Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6537888da6 | ||
|
|
bfa5c61db5 | ||
|
|
554c9aae66 | ||
|
|
1ba90319a2 | ||
|
|
3c226dab12 | ||
|
|
f344f79326 | ||
|
|
c4bcfa8caf | ||
|
|
584cefa388 | ||
|
|
00665592f6 | ||
|
|
3b96d8ef41 | ||
|
|
c9e8edbbf0 | ||
|
|
b12d53f469 | ||
|
|
8da9c67d08 |
@@ -1,2 +1,4 @@
|
|||||||
*.log
|
*.log
|
||||||
.env
|
.env
|
||||||
|
web/*/node_modules/
|
||||||
|
web/*/.next/
|
||||||
|
|||||||
@@ -44,3 +44,118 @@ Keine Commits in dieser Session.
|
|||||||
Keine Änderungen ermittelbar.
|
Keine Änderungen ermittelbar.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
## 2026-08-27 17:26 – 17:28 (1m)
|
||||||
|
**Beschreibung:** Claude Code Session
|
||||||
|
**Projekt:** code
|
||||||
|
|
||||||
|
### Commits
|
||||||
|
- c895a67 core: initial Go module skeleton (config, db pool, tenant registry migration)
|
||||||
|
|
||||||
|
### Geänderte Dateien
|
||||||
|
- .gitignore | 2 ++
|
||||||
|
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
||||||
|
- go.mod | 5 +++++
|
||||||
|
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
||||||
|
- internal/db/db.go | 11 +++++++++++
|
||||||
|
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
||||||
|
|
||||||
|
---
|
||||||
|
## 2026-08-27 17:28 – 17:29 (1m)
|
||||||
|
**Beschreibung:** Claude Code Session
|
||||||
|
**Projekt:** code
|
||||||
|
## 2026-08-28 21:44 – 21:44 (0m)
|
||||||
|
**Beschreibung:** Claude Code Session
|
||||||
|
**Projekt:** nexarch
|
||||||
|
|
||||||
|
### Commits
|
||||||
|
Keine Commits in dieser Session.
|
||||||
|
|
||||||
|
### Geänderte Dateien
|
||||||
|
- .gitignore | 2 ++
|
||||||
|
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
||||||
|
- go.mod | 5 +++++
|
||||||
|
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
||||||
|
- internal/db/db.go | 11 +++++++++++
|
||||||
|
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
||||||
|
|
||||||
|
---
|
||||||
|
## 2026-08-27 17:31 – 17:31 (0m)
|
||||||
|
**Beschreibung:** Claude Code Session
|
||||||
|
**Projekt:** code
|
||||||
|
|
||||||
|
### Commits
|
||||||
|
Keine Commits in dieser Session.
|
||||||
|
|
||||||
|
### Geänderte Dateien
|
||||||
|
- .gitignore | 2 ++
|
||||||
|
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
||||||
|
- go.mod | 5 +++++
|
||||||
|
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
||||||
|
- internal/db/db.go | 11 +++++++++++
|
||||||
|
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
||||||
|
|
||||||
|
---
|
||||||
|
## 2026-08-27 17:36 – 17:36 (0m)
|
||||||
|
**Beschreibung:** Claude Code Session
|
||||||
|
**Projekt:** code
|
||||||
|
|
||||||
|
### Commits
|
||||||
|
Keine Commits in dieser Session.
|
||||||
|
|
||||||
|
### Geänderte Dateien
|
||||||
|
- .gitignore | 2 ++
|
||||||
|
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
||||||
|
- go.mod | 5 +++++
|
||||||
|
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
||||||
|
- internal/db/db.go | 11 +++++++++++
|
||||||
|
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
||||||
|
|
||||||
|
---
|
||||||
|
## 2026-08-27 17:36 – 17:37 (0m)
|
||||||
|
**Beschreibung:** Claude Code Session
|
||||||
|
**Projekt:** code
|
||||||
|
|
||||||
|
### Commits
|
||||||
|
Keine Commits in dieser Session.
|
||||||
|
|
||||||
|
### Geänderte Dateien
|
||||||
|
- .gitignore | 2 ++
|
||||||
|
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
||||||
|
- go.mod | 5 +++++
|
||||||
|
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
||||||
|
- internal/db/db.go | 11 +++++++++++
|
||||||
|
- 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 +
|
||||||
|
|
||||||
|
---
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
// auditlog-devserver stellt AUD-03s ExportHandler (internal/audit) fuer die
|
||||||
|
// Next.js-Audit-Log-Ansicht (AUD-04) bereit. Getrennt von cmd/core aus
|
||||||
|
// demselben Grund wie die anderen *-devserver (siehe LIC-04/TEN-05): echte
|
||||||
|
// Auth/RBAC ist noch nicht in die zentrale Server-Topologie verdrahtet.
|
||||||
|
//
|
||||||
|
// Authorize wird hier mit einem geteilten Admin-Token ueber
|
||||||
|
// crypto/subtle.ConstantTimeCompare umgesetzt — demselben Timing-safe-Muster
|
||||||
|
// wie internal/audit.timingsafe (AUD-02), NICHT ueber eine neue
|
||||||
|
// Rollen-/Rechteschicht, da diese Kachel ausdruecklich nur von AUD-03
|
||||||
|
// abhaengt und keine Rechteverwaltung duplizieren soll.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"gitea.perlbach24.de/scripte/nexarch/internal/audit"
|
||||||
|
"gitea.perlbach24.de/scripte/nexarch/internal/auditadmin"
|
||||||
|
"gitea.perlbach24.de/scripte/nexarch/internal/db"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
dsn := os.Getenv("NEXARCH_REGISTRY_DSN")
|
||||||
|
if dsn == "" {
|
||||||
|
log.Fatal("NEXARCH_REGISTRY_DSN nicht gesetzt")
|
||||||
|
}
|
||||||
|
adminToken := os.Getenv("NEXARCH_AUDIT_ADMIN_TOKEN")
|
||||||
|
if adminToken == "" {
|
||||||
|
log.Fatal("NEXARCH_AUDIT_ADMIN_TOKEN nicht gesetzt")
|
||||||
|
}
|
||||||
|
addr := os.Getenv("NEXARCH_AUDITLOG_LISTEN_ADDR")
|
||||||
|
if addr == "" {
|
||||||
|
addr = ":8083"
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
pool, err := db.Connect(ctx, dsn)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("db: %v", err)
|
||||||
|
}
|
||||||
|
defer pool.Close()
|
||||||
|
|
||||||
|
auditLog := audit.NewLog(pool)
|
||||||
|
tokenAuthorize := auditadmin.NewTokenAuthorizer(adminToken)
|
||||||
|
authorize := func(_ context.Context, caller string) bool { return tokenAuthorize(caller) }
|
||||||
|
handler := audit.NewExportHandler(auditLog, authorize)
|
||||||
|
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("/audit/export", withCORS(handler.Export))
|
||||||
|
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
|
||||||
|
|
||||||
|
log.Printf("auditlog-devserver listening on %s", addr)
|
||||||
|
log.Fatal(http.ListenAndServe(addr, mux))
|
||||||
|
}
|
||||||
|
|
||||||
|
func withCORS(next http.HandlerFunc) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||||
|
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||||
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||||
|
if r.Method == http.MethodOptions {
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next(w, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
+18
-3
@@ -7,6 +7,7 @@ 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"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -15,16 +16,30 @@ func main() {
|
|||||||
log.Fatalf("config: %v", err)
|
log.Fatalf("config: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
pool, err := db.Connect(context.Background(), cfg.RegistryDSN)
|
ctx := context.Background()
|
||||||
|
|
||||||
|
registryPool, err := db.Connect(ctx, cfg.RegistryDSN)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("db: %v", err)
|
log.Fatalf("registry db: %v", err)
|
||||||
}
|
}
|
||||||
defer pool.Close()
|
defer registryPool.Close()
|
||||||
|
|
||||||
|
adminPool, err := db.Connect(ctx, cfg.AdminDSN)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("admin db: %v", err)
|
||||||
|
}
|
||||||
|
defer adminPool.Close()
|
||||||
|
|
||||||
|
registry := tenant.NewRegistry(registryPool)
|
||||||
|
provisioner := tenant.NewProvisioner(adminPool, registry, cfg.TenantDSNTemplate)
|
||||||
|
tenantHandler := tenant.NewHandler(provisioner)
|
||||||
|
|
||||||
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)
|
||||||
})
|
})
|
||||||
|
// Vorlaeufiger Pfad ohne Versionierung/Auth — wird mit API-01/IAM-01 abgeloest.
|
||||||
|
mux.HandleFunc("/internal/tenants", tenantHandler.CreateTenant)
|
||||||
|
|
||||||
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 {
|
||||||
|
|||||||
@@ -3,3 +3,12 @@ module gitea.perlbach24.de/scripte/nexarch
|
|||||||
go 1.22
|
go 1.22
|
||||||
|
|
||||||
require github.com/jackc/pgx/v5 v5.6.0
|
require github.com/jackc/pgx/v5 v5.6.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // 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/text v0.14.0 // indirect
|
||||||
|
)
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
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/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
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/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||||
|
github.com/jackc/pgx/v5 v5.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY=
|
||||||
|
github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
||||||
|
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||||
|
golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k=
|
||||||
|
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
|
||||||
|
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
|
||||||
|
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||||
|
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
// Package audit implementiert Core AUD-01: das zentrale, vom allgemeinen
|
||||||
|
// Anwendungs-Log getrennte Audit-Datenmodell fuer sicherheits- und
|
||||||
|
// compliancerelevante Ereignisse (wer, was, wann, an welchem Tenant).
|
||||||
|
// Unveraenderlichkeit (Append-only) ist AUD-02, Export/Filter-API ist AUD-03
|
||||||
|
// — dieses Paket liefert nur das Datenmodell und den EINEN zentralen
|
||||||
|
// Schreibpfad (Akzeptanzkriterium 3).
|
||||||
|
package audit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SystemTenant ist der reservierte Tenant-Bezug fuer mandantenuebergreifende
|
||||||
|
// Ereignisse (z.B. Superadmin-Aktionen) — es gibt bewusst KEINEN Weg, ein
|
||||||
|
// Ereignis ganz ohne Tenant-Bezug zu schreiben (Akzeptanzkriterium 2).
|
||||||
|
const SystemTenant = "system"
|
||||||
|
|
||||||
|
var ErrMissingTenant = errors.New("audit: tenant_slug darf nicht leer sein")
|
||||||
|
var ErrMissingActor = errors.New("audit: actor darf nicht leer sein")
|
||||||
|
var ErrMissingAction = errors.New("audit: action darf nicht leer sein")
|
||||||
|
|
||||||
|
// Event ist ein strukturiertes Audit-Ereignis (Akzeptanzkriterium 1: Akteur,
|
||||||
|
// Aktion, Zielobjekt, Zeitpunkt, Tenant).
|
||||||
|
type Event struct {
|
||||||
|
TenantSlug string
|
||||||
|
Actor string
|
||||||
|
Action string
|
||||||
|
Target string
|
||||||
|
Metadata map[string]any
|
||||||
|
OccurredAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// Log ist der EINE zentrale Schreibpfad fuer Audit-Ereignisse — es gibt
|
||||||
|
// bewusst keine zweite Schreibmoeglichkeit, damit kein Handler versehentlich
|
||||||
|
// direkt in audit_events schreibt und dabei die Validierung umgeht
|
||||||
|
// (Akzeptanzkriterium 3).
|
||||||
|
type Log struct {
|
||||||
|
pool *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLog(pool *pgxpool.Pool) *Log {
|
||||||
|
return &Log{pool: pool}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Record persistiert genau einen Audit-Eintrag. Fehlender Tenant-Bezug wird
|
||||||
|
// bereits hier abgewiesen (klarer Fehler statt Constraint-Verletzung im
|
||||||
|
// Normalfall) — die Datenbank-CHECK-Constraint aus der Migration ist die
|
||||||
|
// zweite, unumgehbare Verteidigungslinie (Akzeptanzkriterium 2 / Pruefung 2).
|
||||||
|
func (l *Log) Record(ctx context.Context, e Event) error {
|
||||||
|
if e.TenantSlug == "" {
|
||||||
|
return ErrMissingTenant
|
||||||
|
}
|
||||||
|
if e.Actor == "" {
|
||||||
|
return ErrMissingActor
|
||||||
|
}
|
||||||
|
if e.Action == "" {
|
||||||
|
return ErrMissingAction
|
||||||
|
}
|
||||||
|
if e.Metadata == nil {
|
||||||
|
e.Metadata = map[string]any{}
|
||||||
|
}
|
||||||
|
metadataJSON, err := json.Marshal(e.Metadata)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("metadaten serialisieren: %w", err)
|
||||||
|
}
|
||||||
|
if e.OccurredAt.IsZero() {
|
||||||
|
e.OccurredAt = time.Now()
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = l.pool.Exec(ctx, `
|
||||||
|
INSERT INTO audit_events (occurred_at, tenant_slug, actor, action, target, metadata)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6)
|
||||||
|
`, e.OccurredAt, e.TenantSlug, e.Actor, e.Action, e.Target, metadataJSON)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("audit-ereignis schreiben: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CountByTenant ist eine schlanke Lesehilfe fuer Tests/Diagnose — die
|
||||||
|
// eigentliche Filter-/Export-API ist AUD-03, hier bewusst nicht vorgezogen.
|
||||||
|
func (l *Log) CountByTenant(ctx context.Context, tenantSlug string) (int, error) {
|
||||||
|
var n int
|
||||||
|
if err := l.pool.QueryRow(ctx, `
|
||||||
|
SELECT count(*) FROM audit_events WHERE tenant_slug = $1
|
||||||
|
`, tenantSlug).Scan(&n); err != nil {
|
||||||
|
return 0, fmt.Errorf("audit-ereignisse zaehlen: %w", err)
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
func setupAuditTest(t *testing.T) (*Log, *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 audit_events (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
tenant_slug TEXT NOT NULL CHECK (tenant_slug <> ''),
|
||||||
|
actor TEXT NOT NULL CHECK (actor <> ''),
|
||||||
|
action TEXT NOT NULL CHECK (action <> ''),
|
||||||
|
target TEXT NOT NULL,
|
||||||
|
metadata JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||||
|
)`); err != nil {
|
||||||
|
t.Fatalf("schema: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanup := func() {
|
||||||
|
_, _ = pool.Exec(ctx, `DELETE FROM audit_events WHERE tenant_slug LIKE 'test\_%' ESCAPE '\' OR tenant_slug = $1`, SystemTenant)
|
||||||
|
pool.Close()
|
||||||
|
}
|
||||||
|
return NewLog(pool), pool, cleanup
|
||||||
|
}
|
||||||
|
|
||||||
|
// Akzeptanzkriterium 1 + Pruefung 1: ein sicherheitsrelevanter Vorgang
|
||||||
|
// (hier: fehlgeschlagener Login) erzeugt zuverlaessig genau einen Eintrag.
|
||||||
|
func TestRecord_PersistsExactlyOneEventPerSecurityIncident(t *testing.T) {
|
||||||
|
log, pool, cleanup := setupAuditTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
err := log.Record(ctx, Event{
|
||||||
|
TenantSlug: "test_acme",
|
||||||
|
Actor: "alice@example.com",
|
||||||
|
Action: "iam.login_failed",
|
||||||
|
Target: "user:alice@example.com",
|
||||||
|
Metadata: map[string]any{"reason": "falsches passwort"},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("record: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
count, err := log.CountByTenant(ctx, "test_acme")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("count: %v", err)
|
||||||
|
}
|
||||||
|
if count != 1 {
|
||||||
|
t.Fatalf("erwartet genau 1 audit-eintrag, habe %d", count)
|
||||||
|
}
|
||||||
|
|
||||||
|
var actor, action, target string
|
||||||
|
if err := pool.QueryRow(ctx, `
|
||||||
|
SELECT actor, action, target FROM audit_events WHERE tenant_slug = 'test_acme'
|
||||||
|
`).Scan(&actor, &action, &target); err != nil {
|
||||||
|
t.Fatalf("eintrag lesen: %v", err)
|
||||||
|
}
|
||||||
|
if actor != "alice@example.com" || action != "iam.login_failed" || target != "user:alice@example.com" {
|
||||||
|
t.Fatalf("eintrag unerwartet: actor=%q action=%q target=%q", actor, action, target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Akzeptanzkriterium 2 + Pruefung 2 (App-Ebene): fehlender Tenant-Bezug wird
|
||||||
|
// bereits vom zentralen Schreibpfad abgewiesen.
|
||||||
|
func TestRecord_RejectsMissingTenant(t *testing.T) {
|
||||||
|
log, _, cleanup := setupAuditTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
err := log.Record(ctx, Event{TenantSlug: "", Actor: "alice", Action: "irgendwas"})
|
||||||
|
if !errors.Is(err, ErrMissingTenant) {
|
||||||
|
t.Fatalf("erwartet ErrMissingTenant, habe %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Akzeptanzkriterium 2 + Pruefung 2 (DB-Ebene): selbst ein direkter INSERT,
|
||||||
|
// der Log.Record umgeht, wird durch die CHECK-Constraint verhindert — der
|
||||||
|
// Schutz haengt nicht allein von der Go-Validierung ab.
|
||||||
|
func TestConstraint_RejectsMissingTenantAtDatabaseLevel(t *testing.T) {
|
||||||
|
_, pool, cleanup := setupAuditTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
_, err := pool.Exec(ctx, `
|
||||||
|
INSERT INTO audit_events (tenant_slug, actor, action, target)
|
||||||
|
VALUES ('', 'alice', 'irgendwas', 'ziel')
|
||||||
|
`)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("erwartet fehler durch CHECK-constraint bei leerem tenant_slug, habe nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRecord_RejectsMissingActorAndAction(t *testing.T) {
|
||||||
|
log, _, cleanup := setupAuditTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
if err := log.Record(ctx, Event{TenantSlug: "test_acme", Actor: "", Action: "x"}); !errors.Is(err, ErrMissingActor) {
|
||||||
|
t.Fatalf("erwartet ErrMissingActor, habe %v", err)
|
||||||
|
}
|
||||||
|
if err := log.Record(ctx, Event{TenantSlug: "test_acme", Actor: "alice", Action: ""}); !errors.Is(err, ErrMissingAction) {
|
||||||
|
t.Fatalf("erwartet ErrMissingAction, habe %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRecord_SystemTenantForCrossTenantEvents(t *testing.T) {
|
||||||
|
log, _, cleanup := setupAuditTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
if err := log.Record(ctx, Event{TenantSlug: SystemTenant, Actor: "superadmin", Action: "tenant.provisioned", Target: "tenant:acme"}); err != nil {
|
||||||
|
t.Fatalf("record mit SystemTenant: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/csv"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Filter grenzt einen Export ein (Akzeptanzkriterium 1). Leere/Nil-Felder
|
||||||
|
// bedeuten "kein Filter auf diesem Feld".
|
||||||
|
type Filter struct {
|
||||||
|
TenantSlug string
|
||||||
|
Actor string
|
||||||
|
Action string
|
||||||
|
From *time.Time
|
||||||
|
To *time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildFilterQuery(f Filter) (string, []any) {
|
||||||
|
query := `SELECT occurred_at, tenant_slug, actor, action, target, metadata FROM audit_events WHERE 1=1`
|
||||||
|
var args []any
|
||||||
|
|
||||||
|
if f.TenantSlug != "" {
|
||||||
|
args = append(args, f.TenantSlug)
|
||||||
|
query += fmt.Sprintf(" AND tenant_slug = $%d", len(args))
|
||||||
|
}
|
||||||
|
if f.Actor != "" {
|
||||||
|
args = append(args, f.Actor)
|
||||||
|
query += fmt.Sprintf(" AND actor = $%d", len(args))
|
||||||
|
}
|
||||||
|
if f.Action != "" {
|
||||||
|
args = append(args, f.Action)
|
||||||
|
query += fmt.Sprintf(" AND action = $%d", len(args))
|
||||||
|
}
|
||||||
|
if f.From != nil {
|
||||||
|
args = append(args, *f.From)
|
||||||
|
query += fmt.Sprintf(" AND occurred_at >= $%d", len(args))
|
||||||
|
}
|
||||||
|
if f.To != nil {
|
||||||
|
args = append(args, *f.To)
|
||||||
|
query += fmt.Sprintf(" AND occurred_at <= $%d", len(args))
|
||||||
|
}
|
||||||
|
query += " ORDER BY occurred_at"
|
||||||
|
return query, args
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamCSV schreibt gefilterte Audit-Eintraege direkt als CSV in w, Zeile
|
||||||
|
// fuer Zeile ueber rows.Next() — es wird zu keinem Zeitpunkt das gesamte
|
||||||
|
// Ergebnis im Speicher aufgebaut (Akzeptanzkriterium 3 / Pruefung 1).
|
||||||
|
func (l *Log) StreamCSV(ctx context.Context, filter Filter, w io.Writer) error {
|
||||||
|
query, args := buildFilterQuery(filter)
|
||||||
|
rows, err := l.pool.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("export abfragen: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
cw := csv.NewWriter(w)
|
||||||
|
if err := cw.Write([]string{"occurred_at", "tenant_slug", "actor", "action", "target", "metadata"}); err != nil {
|
||||||
|
return fmt.Errorf("csv-header schreiben: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
var occurredAt time.Time
|
||||||
|
var tenantSlug, actor, action, target string
|
||||||
|
var metadataJSON []byte
|
||||||
|
if err := rows.Scan(&occurredAt, &tenantSlug, &actor, &action, &target, &metadataJSON); err != nil {
|
||||||
|
return fmt.Errorf("zeile lesen: %w", err)
|
||||||
|
}
|
||||||
|
if err := cw.Write([]string{
|
||||||
|
occurredAt.Format(time.RFC3339), tenantSlug, actor, action, target, string(metadataJSON),
|
||||||
|
}); err != nil {
|
||||||
|
return fmt.Errorf("csv-zeile schreiben: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cw.Flush()
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return fmt.Errorf("export lesen: %w", err)
|
||||||
|
}
|
||||||
|
return cw.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
// exportRecord ist die JSON-Repraesentation einer exportierten Zeile.
|
||||||
|
type exportRecord struct {
|
||||||
|
OccurredAt time.Time `json:"occurred_at"`
|
||||||
|
TenantSlug string `json:"tenant_slug"`
|
||||||
|
Actor string `json:"actor"`
|
||||||
|
Action string `json:"action"`
|
||||||
|
Target string `json:"target"`
|
||||||
|
Metadata json.RawMessage `json:"metadata"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// StreamJSON schreibt gefilterte Audit-Eintraege als JSON Lines (ein
|
||||||
|
// JSON-Objekt pro Zeile) — bewusst kein einzelnes grosses JSON-Array, da
|
||||||
|
// dessen korrektes Streaming (Kommas/Klammern ohne Zwischenpufferung)
|
||||||
|
// unnoetige Komplexitaet fuer denselben Zweck waere. Wie StreamCSV
|
||||||
|
// zeilenweise ueber rows.Next(), kein Aufbau im Speicher.
|
||||||
|
func (l *Log) StreamJSON(ctx context.Context, filter Filter, w io.Writer) error {
|
||||||
|
query, args := buildFilterQuery(filter)
|
||||||
|
rows, err := l.pool.Query(ctx, query, args...)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("export abfragen: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
enc := json.NewEncoder(w)
|
||||||
|
for rows.Next() {
|
||||||
|
var rec exportRecord
|
||||||
|
var metadataJSON []byte
|
||||||
|
if err := rows.Scan(&rec.OccurredAt, &rec.TenantSlug, &rec.Actor, &rec.Action, &rec.Target, &metadataJSON); err != nil {
|
||||||
|
return fmt.Errorf("zeile lesen: %w", err)
|
||||||
|
}
|
||||||
|
rec.Metadata = metadataJSON
|
||||||
|
if err := enc.Encode(rec); err != nil {
|
||||||
|
return fmt.Errorf("json-zeile schreiben: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return rows.Err()
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Authorize entscheidet, ob caller den Export ausfuehren darf. Die
|
||||||
|
// eigentliche Rollen-/Rechtepruefung (RBAC-02 Policy-Enforcement) ist nicht
|
||||||
|
// Teil dieser Kachel — ExportHandler kennt nur diese schmale Schnittstelle,
|
||||||
|
// analog zum RetentionRegistrar-Muster aus AUD-05.
|
||||||
|
type Authorize func(ctx context.Context, caller string) bool
|
||||||
|
|
||||||
|
// ExportHandler stellt den Export als HTTP-Endpunkt bereit
|
||||||
|
// (Akzeptanzkriterium 2: fuer berechtigte Rollen verfuegbar).
|
||||||
|
type ExportHandler struct {
|
||||||
|
log *Log
|
||||||
|
authorize Authorize
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewExportHandler(log *Log, authorize Authorize) *ExportHandler {
|
||||||
|
return &ExportHandler{log: log, authorize: authorize}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Export liest Filter-Query-Parameter (tenant, actor, action, from, to,
|
||||||
|
// format) und schreibt DIREKT auf den ResponseWriter (io.Writer) — dieselbe
|
||||||
|
// Streaming-Funktion wie in export.go, kein zusaetzlicher Pufferungsschritt.
|
||||||
|
func (h *ExportHandler) Export(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// "caller" identifiziert die anfragende Person fuer die Berechtigungs-
|
||||||
|
// pruefung — bewusst getrennt vom Filterfeld "actor" (das den
|
||||||
|
// AUDIT-Akteur meint, ueber den gefiltert wird).
|
||||||
|
caller := r.URL.Query().Get("caller")
|
||||||
|
if caller == "" || !h.authorize(r.Context(), caller) {
|
||||||
|
http.Error(w, "keine berechtigung fuer audit-log-export", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
filter := Filter{
|
||||||
|
TenantSlug: r.URL.Query().Get("tenant"),
|
||||||
|
Actor: r.URL.Query().Get("actor"),
|
||||||
|
Action: r.URL.Query().Get("action"),
|
||||||
|
}
|
||||||
|
if from := r.URL.Query().Get("from"); from != "" {
|
||||||
|
t, err := time.Parse(time.RFC3339, from)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "ungueltiges from-datum, erwartet RFC3339", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
filter.From = &t
|
||||||
|
}
|
||||||
|
if to := r.URL.Query().Get("to"); to != "" {
|
||||||
|
t, err := time.Parse(time.RFC3339, to)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "ungueltiges to-datum, erwartet RFC3339", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
filter.To = &t
|
||||||
|
}
|
||||||
|
|
||||||
|
switch r.URL.Query().Get("format") {
|
||||||
|
case "json":
|
||||||
|
w.Header().Set("Content-Type", "application/x-ndjson")
|
||||||
|
if err := h.log.StreamJSON(r.Context(), filter, w); err != nil {
|
||||||
|
http.Error(w, "export fehlgeschlagen", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
w.Header().Set("Content-Type", "text/csv")
|
||||||
|
if err := h.log.StreamCSV(r.Context(), filter, w); err != nil {
|
||||||
|
http.Error(w, "export fehlgeschlagen", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/csv"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
func setupExportTest(t *testing.T) (*Log, 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 audit_events (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
tenant_slug TEXT NOT NULL CHECK (tenant_slug <> ''),
|
||||||
|
actor TEXT NOT NULL CHECK (actor <> ''),
|
||||||
|
action TEXT NOT NULL CHECK (action <> ''),
|
||||||
|
target TEXT NOT NULL,
|
||||||
|
metadata JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||||
|
)`); err != nil {
|
||||||
|
t.Fatalf("schema: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanup := func() { pool.Close() }
|
||||||
|
return NewLog(pool), cleanup
|
||||||
|
}
|
||||||
|
|
||||||
|
// Akzeptanzkriterium 1 + Pruefung 2: Filterkombinationen liefern korrekte
|
||||||
|
// Teilmengen.
|
||||||
|
func TestExport_FilterCombinations(t *testing.T) {
|
||||||
|
log, cleanup := setupExportTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
run := fmt.Sprintf("_%d", time.Now().UnixNano())
|
||||||
|
tenantA, tenantB := "test_fa"+run, "test_fb"+run
|
||||||
|
alice, bob := "alice"+run, "bob"+run
|
||||||
|
|
||||||
|
events := []Event{
|
||||||
|
{TenantSlug: tenantA, Actor: alice, Action: "login", Target: "x"},
|
||||||
|
{TenantSlug: tenantA, Actor: bob, Action: "login", Target: "x"},
|
||||||
|
{TenantSlug: tenantA, Actor: alice, Action: "logout", Target: "x"},
|
||||||
|
{TenantSlug: tenantB, Actor: alice, Action: "login", Target: "x"},
|
||||||
|
}
|
||||||
|
for _, e := range events {
|
||||||
|
if err := log.Record(ctx, e); err != nil {
|
||||||
|
t.Fatalf("record: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
filter Filter
|
||||||
|
wantLen int
|
||||||
|
}{
|
||||||
|
{"nach tenant", Filter{TenantSlug: tenantA}, 3},
|
||||||
|
{"nach tenant+actor", Filter{TenantSlug: tenantA, Actor: alice}, 2},
|
||||||
|
{"nach tenant+actor+action", Filter{TenantSlug: tenantA, Actor: alice, Action: "login"}, 1},
|
||||||
|
{"nach actor ueber beide tenants", Filter{Actor: alice, Action: "login"}, 2},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, c := range cases {
|
||||||
|
t.Run(c.name, func(t *testing.T) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := log.StreamCSV(ctx, c.filter, &buf); err != nil {
|
||||||
|
t.Fatalf("stream: %v", err)
|
||||||
|
}
|
||||||
|
rows, err := csv.NewReader(&buf).ReadAll()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("csv parsen: %v", err)
|
||||||
|
}
|
||||||
|
got := len(rows) - 1 // Header abziehen
|
||||||
|
if got != c.wantLen {
|
||||||
|
t.Fatalf("erwartet %d zeilen, habe %d", c.wantLen, got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Akzeptanzkriterium 1 + Pruefung 2: Zeitraum-Filter.
|
||||||
|
func TestExport_TimeRangeFilter(t *testing.T) {
|
||||||
|
log, cleanup := setupExportTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
tenant := fmt.Sprintf("test_tr_%d", time.Now().UnixNano())
|
||||||
|
past := time.Now().Add(-48 * time.Hour)
|
||||||
|
future := time.Now().Add(48 * time.Hour)
|
||||||
|
|
||||||
|
if err := log.Record(ctx, Event{TenantSlug: tenant, Actor: "a", Action: "x", Target: "t", OccurredAt: time.Now()}); err != nil {
|
||||||
|
t.Fatalf("record: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := log.StreamCSV(ctx, Filter{TenantSlug: tenant, From: &past, To: &future}, &buf); err != nil {
|
||||||
|
t.Fatalf("stream (innerhalb range): %v", err)
|
||||||
|
}
|
||||||
|
if got := countLines(buf.String()) - 1; got != 1 {
|
||||||
|
t.Fatalf("erwartet 1 eintrag innerhalb des zeitraums, habe %d", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
farPast := time.Now().Add(-96 * time.Hour)
|
||||||
|
buf.Reset()
|
||||||
|
if err := log.StreamCSV(ctx, Filter{TenantSlug: tenant, From: &farPast, To: &past}, &buf); err != nil {
|
||||||
|
t.Fatalf("stream (ausserhalb range): %v", err)
|
||||||
|
}
|
||||||
|
if got := countLines(buf.String()) - 1; got != 0 {
|
||||||
|
t.Fatalf("erwartet 0 eintraege ausserhalb des zeitraums, habe %d", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func countLines(s string) int {
|
||||||
|
s = strings.TrimRight(s, "\n")
|
||||||
|
if s == "" {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return len(strings.Split(s, "\n"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Akzeptanzkriterium 3 + Pruefung 1: Export mit hoher Eintragszahl ohne
|
||||||
|
// uebermaessigen Speicherverbrauch — Stichprobe per runtime.MemStats.
|
||||||
|
func TestExport_StreamsLargeResultWithoutExcessiveMemory(t *testing.T) {
|
||||||
|
log, cleanup := setupExportTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
tenant := fmt.Sprintf("test_large_%d", time.Now().UnixNano())
|
||||||
|
const n = 20000
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
if err := log.Record(ctx, Event{TenantSlug: tenant, Actor: "bulk", Action: "test.bulk", Target: fmt.Sprintf("obj-%d", i)}); err != nil {
|
||||||
|
t.Fatalf("record %d: %v", i, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
runtime.GC()
|
||||||
|
var before runtime.MemStats
|
||||||
|
runtime.ReadMemStats(&before)
|
||||||
|
|
||||||
|
lineCount := 0
|
||||||
|
cw := &countingWriter{onWrite: func(p []byte) { lineCount += strings.Count(string(p), "\n") }}
|
||||||
|
if err := log.StreamCSV(ctx, Filter{TenantSlug: tenant}, cw); err != nil {
|
||||||
|
t.Fatalf("stream: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
runtime.GC()
|
||||||
|
var after runtime.MemStats
|
||||||
|
runtime.ReadMemStats(&after)
|
||||||
|
|
||||||
|
if lineCount != n+1 { // +1 Header
|
||||||
|
t.Fatalf("erwartet %d zeilen (inkl. header), habe %d", n+1, lineCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Grobe Stichprobe: ein NICHT streamender Export haette hier locker
|
||||||
|
// mehrere MB an einmal gehaltenen Zeilen/Strings erzeugt. Grosszuegige
|
||||||
|
// Schwelle, da Go-Heap-Messungen naturgemaess rauschen.
|
||||||
|
const maxAcceptableGrowth = 3 * 1024 * 1024 // 3 MB
|
||||||
|
growth := int64(after.HeapAlloc) - int64(before.HeapAlloc)
|
||||||
|
t.Logf("heap-wachstum waehrend export von %d zeilen: %d bytes (schwelle: %d)", n, growth, maxAcceptableGrowth)
|
||||||
|
if growth > maxAcceptableGrowth {
|
||||||
|
t.Fatalf("heap ist um %d bytes gewachsen, erwartet unter %d (hinweis auf vollstaendige pufferung statt streaming)", growth, maxAcceptableGrowth)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type countingWriter struct {
|
||||||
|
onWrite func(p []byte)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *countingWriter) Write(p []byte) (int, error) {
|
||||||
|
w.onWrite(p)
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Akzeptanzkriterium 2 + Pruefung 3: Zugriff ohne passende Berechtigung wird abgewiesen.
|
||||||
|
func TestExportHandler_RejectsWithoutAuthorization(t *testing.T) {
|
||||||
|
log, cleanup := setupExportTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
handler := NewExportHandler(log, func(ctx context.Context, caller string) bool {
|
||||||
|
return caller == "berechtigte-person@example.com"
|
||||||
|
})
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/audit/export?caller=unberechtigt@example.com", nil)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
handler.Export(rec, req)
|
||||||
|
if rec.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("unberechtigt: status = %d, want 403", rec.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
reqNoCaller := httptest.NewRequest(http.MethodGet, "/audit/export", nil)
|
||||||
|
recNoCaller := httptest.NewRecorder()
|
||||||
|
handler.Export(recNoCaller, reqNoCaller)
|
||||||
|
if recNoCaller.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("ohne caller: status = %d, want 403", recNoCaller.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
reqOK := httptest.NewRequest(http.MethodGet, "/audit/export?caller=berechtigte-person@example.com", nil)
|
||||||
|
recOK := httptest.NewRecorder()
|
||||||
|
handler.Export(recOK, reqOK)
|
||||||
|
if recOK.Code != http.StatusOK {
|
||||||
|
t.Fatalf("berechtigt: status = %d, want 200", recOK.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
// Package auditadmin implementiert Core AUD-04: die Berechtigungspruefung
|
||||||
|
// fuer die Audit-Log-Ansicht. Enthaelt bewusst KEINE eigene Filter-/
|
||||||
|
// Export-Logik — die Ansicht ist "reiner Konsument der Export-API" (AUD-03,
|
||||||
|
// internal/audit.ExportHandler); dieses Paket liefert nur die
|
||||||
|
// audit.Authorize-Implementierung, die der Entwicklungs-/Testserver
|
||||||
|
// (cmd/auditlog-devserver) einhaengt.
|
||||||
|
package auditadmin
|
||||||
|
|
||||||
|
import "crypto/subtle"
|
||||||
|
|
||||||
|
// NewTokenAuthorizer liefert eine audit.Authorize-Funktion, die den
|
||||||
|
// aufrufenden "caller"-Wert timing-safe gegen ein geteiltes Admin-Token
|
||||||
|
// vergleicht — dasselbe Muster wie internal/audit.timingsafe (AUD-02),
|
||||||
|
// NICHT ueber eine neue Rollen-/Rechteschicht, da AUD-04 ausdruecklich nur
|
||||||
|
// von AUD-03 abhaengt.
|
||||||
|
func NewTokenAuthorizer(adminToken string) func(caller string) bool {
|
||||||
|
return func(caller string) bool {
|
||||||
|
if caller == "" || adminToken == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return subtle.ConstantTimeCompare([]byte(caller), []byte(adminToken)) == 1
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package auditadmin
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
// Grundlage fuer Akzeptanzkriterium 1/2: die Oberflaeche darf Daten und den
|
||||||
|
// Export nur bei korrektem Admin-Token abrufen.
|
||||||
|
func TestNewTokenAuthorizer_AcceptsCorrectToken(t *testing.T) {
|
||||||
|
authorize := NewTokenAuthorizer("geheimes-token")
|
||||||
|
if !authorize("geheimes-token") {
|
||||||
|
t.Fatal("erwartet true fuer korrektes token")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewTokenAuthorizer_RejectsWrongToken(t *testing.T) {
|
||||||
|
authorize := NewTokenAuthorizer("geheimes-token")
|
||||||
|
if authorize("falsches-token") {
|
||||||
|
t.Fatal("erwartet false fuer falsches token")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewTokenAuthorizer_RejectsEmptyCaller(t *testing.T) {
|
||||||
|
authorize := NewTokenAuthorizer("geheimes-token")
|
||||||
|
if authorize("") {
|
||||||
|
t.Fatal("erwartet false fuer leeren aufrufer")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewTokenAuthorizer_RejectsWhenNoTokenConfigured(t *testing.T) {
|
||||||
|
authorize := NewTokenAuthorizer("")
|
||||||
|
if authorize("irgendwas") {
|
||||||
|
t.Fatal("erwartet false, wenn kein admin-token konfiguriert ist (fail-safe-default)")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,7 +11,14 @@ import (
|
|||||||
// multi_tenancy: Modell C (physisch getrennte DB pro Mandant).
|
// multi_tenancy: Modell C (physisch getrennte DB pro Mandant).
|
||||||
type Config struct {
|
type Config struct {
|
||||||
ListenAddr string
|
ListenAddr string
|
||||||
|
// RegistryDSN verbindet zur Control-Plane-Registry-Datenbank.
|
||||||
RegistryDSN string
|
RegistryDSN string
|
||||||
|
// AdminDSN verbindet zur Wartungsdatenbank (z.B. "postgres") und wird nur
|
||||||
|
// fuer CREATE/DROP DATABASE beim Tenant-Provisioning verwendet.
|
||||||
|
AdminDSN string
|
||||||
|
// TenantDSNTemplate enthaelt genau ein "%s" als Platzhalter fuer den
|
||||||
|
// Datenbanknamen einer neu provisionierten Tenant-Datenbank.
|
||||||
|
TenantDSNTemplate string
|
||||||
}
|
}
|
||||||
|
|
||||||
func Load() (Config, error) {
|
func Load() (Config, error) {
|
||||||
@@ -20,10 +27,25 @@ func Load() (Config, error) {
|
|||||||
return Config{}, fmt.Errorf("NEXARCH_REGISTRY_DSN not set")
|
return Config{}, fmt.Errorf("NEXARCH_REGISTRY_DSN not set")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
adminDSN := os.Getenv("NEXARCH_ADMIN_DSN")
|
||||||
|
if adminDSN == "" {
|
||||||
|
return Config{}, fmt.Errorf("NEXARCH_ADMIN_DSN not set")
|
||||||
|
}
|
||||||
|
|
||||||
|
dsnTemplate := os.Getenv("NEXARCH_TENANT_DSN_TEMPLATE")
|
||||||
|
if dsnTemplate == "" {
|
||||||
|
return Config{}, fmt.Errorf("NEXARCH_TENANT_DSN_TEMPLATE not set")
|
||||||
|
}
|
||||||
|
|
||||||
addr := os.Getenv("NEXARCH_LISTEN_ADDR")
|
addr := os.Getenv("NEXARCH_LISTEN_ADDR")
|
||||||
if addr == "" {
|
if addr == "" {
|
||||||
addr = ":8080"
|
addr = ":8080"
|
||||||
}
|
}
|
||||||
|
|
||||||
return Config{ListenAddr: addr, RegistryDSN: dsn}, nil
|
return Config{
|
||||||
|
ListenAddr: addr,
|
||||||
|
RegistryDSN: dsn,
|
||||||
|
AdminDSN: adminDSN,
|
||||||
|
TenantDSNTemplate: dsnTemplate,
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package tenant
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Handler ist eine schlanke Vorbereitung der Schnittstelle fuer API-01
|
||||||
|
// (REST-API-Grundgerüst & Versionierung) und TEN-02 (Self-Service-Onboarding).
|
||||||
|
// Auth/Rate-Limiting/Versionierung selbst sind ausdruecklich nicht Teil von
|
||||||
|
// TEN-01 und werden dort nachgezogen.
|
||||||
|
type Handler struct {
|
||||||
|
provisioner *Provisioner
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(p *Provisioner) *Handler {
|
||||||
|
return &Handler{provisioner: p}
|
||||||
|
}
|
||||||
|
|
||||||
|
type createTenantRequest struct {
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) CreateTenant(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req createTenantRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
http.Error(w, "ungueltige Anfrage", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
t, err := h.provisioner.Provision(r.Context(), req.Slug, req.Name)
|
||||||
|
if err != nil {
|
||||||
|
if err == ErrInvalidSlug {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.Error(w, "tenant konnte nicht angelegt werden", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
_ = json.NewEncoder(w).Encode(t)
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package tenant
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Provisioner legt fuer jeden neuen Mandanten eine vollstaendig isolierte
|
||||||
|
// PostgreSQL-Datenbank an und registriert sie transaktional in der Registry
|
||||||
|
// (Akzeptanzkriterium 2). Zwei Mandanten-Datenbanken sind danach auf
|
||||||
|
// Infrastrukturebene komplett getrennt (Akzeptanzkriterium 3).
|
||||||
|
type Provisioner struct {
|
||||||
|
// adminPool ist mit der Wartungsdatenbank (z. B. "postgres") verbunden
|
||||||
|
// und wird ausschliesslich fuer CREATE/DROP DATABASE verwendet, da diese
|
||||||
|
// Befehle in PostgreSQL nicht in einer Transaktion laufen koennen.
|
||||||
|
adminPool *pgxpool.Pool
|
||||||
|
registry *Registry
|
||||||
|
// dsnTemplate enthaelt genau ein "%s" als Platzhalter fuer den
|
||||||
|
// Datenbanknamen, z. B. "postgresql://user:pass@host:5432/%s?sslmode=disable".
|
||||||
|
dsnTemplate string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewProvisioner(adminPool *pgxpool.Pool, registry *Registry, dsnTemplate string) *Provisioner {
|
||||||
|
return &Provisioner{adminPool: adminPool, registry: registry, dsnTemplate: dsnTemplate}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Provision legt die Tenant-Datenbank an und registriert sie. Schlaegt die
|
||||||
|
// Registrierung fehl, wird die bereits angelegte Datenbank wieder entfernt,
|
||||||
|
// damit kein verwaister, unregistrierter Tenant zurueckbleibt.
|
||||||
|
func (p *Provisioner) Provision(ctx context.Context, slug, name string) (Tenant, error) {
|
||||||
|
if err := ValidateSlug(slug); err != nil {
|
||||||
|
return Tenant{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
dbName := dbNameForSlug(slug)
|
||||||
|
|
||||||
|
// CREATE DATABASE erlaubt keine Parameter-Platzhalter; slug ist durch
|
||||||
|
// ValidateSlug bereits auf [a-z0-9_] beschraenkt, Injektion ausgeschlossen.
|
||||||
|
if _, err := p.adminPool.Exec(ctx, fmt.Sprintf(`CREATE DATABASE %q`, dbName)); err != nil {
|
||||||
|
return Tenant{}, fmt.Errorf("tenant-datenbank anlegen: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
t := Tenant{
|
||||||
|
Slug: slug,
|
||||||
|
Name: name,
|
||||||
|
DBName: dbName,
|
||||||
|
DBDSN: fmt.Sprintf(p.dsnTemplate, dbName),
|
||||||
|
Status: StatusActive,
|
||||||
|
}
|
||||||
|
|
||||||
|
tx, err := p.registry.pool.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
p.rollbackDatabase(ctx, dbName)
|
||||||
|
return Tenant{}, fmt.Errorf("registry-transaktion starten: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
created, err := p.registry.insertTx(ctx, tx, t)
|
||||||
|
if err != nil {
|
||||||
|
_ = tx.Rollback(ctx)
|
||||||
|
p.rollbackDatabase(ctx, dbName)
|
||||||
|
return Tenant{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
|
p.rollbackDatabase(ctx, dbName)
|
||||||
|
return Tenant{}, fmt.Errorf("registry-transaktion committen: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return created, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// rollbackDatabase entfernt eine bereits angelegte Tenant-Datenbank, wenn die
|
||||||
|
// Registrierung fehlschlug, damit Provisioning insgesamt atomar wirkt.
|
||||||
|
func (p *Provisioner) rollbackDatabase(ctx context.Context, dbName string) {
|
||||||
|
_, _ = p.adminPool.Exec(ctx, fmt.Sprintf(`DROP DATABASE IF EXISTS %q`, dbName))
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package tenant
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Integrationstest fuer Akzeptanzkriterien 2 und 3. Benoetigt eine echte
|
||||||
|
// Postgres-Instanz und wird ohne TEST_ADMIN_DSN uebersprungen, nicht als
|
||||||
|
// fehlgeschlagen gewertet — siehe Pruefungen-Ergebnis im PR.
|
||||||
|
//
|
||||||
|
// TEST_ADMIN_DSN muss auf die Wartungsdatenbank zeigen, z. B.:
|
||||||
|
//
|
||||||
|
// postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable
|
||||||
|
func TestProvision_CreatesIsolatedDatabases(t *testing.T) {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
defer adminPool.Close()
|
||||||
|
|
||||||
|
registryPool, err := pgxpool.New(ctx, adminDSN)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("registry pool: %v", err)
|
||||||
|
}
|
||||||
|
defer registryPool.Close()
|
||||||
|
|
||||||
|
if _, err := registryPool.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()
|
||||||
|
)`); err != nil {
|
||||||
|
t.Fatalf("registry-schema: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
dsnTemplate := strings.Replace(adminDSN, "/postgres?", "/%s?", 1)
|
||||||
|
registry := NewRegistry(registryPool)
|
||||||
|
provisioner := NewProvisioner(adminPool, registry, dsnTemplate)
|
||||||
|
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_, _ = registryPool.Exec(ctx, `DELETE FROM tenants WHERE slug IN ('acme','globex')`)
|
||||||
|
_, _ = adminPool.Exec(ctx, `DROP DATABASE IF EXISTS tenant_acme`)
|
||||||
|
_, _ = adminPool.Exec(ctx, `DROP DATABASE IF EXISTS tenant_globex`)
|
||||||
|
})
|
||||||
|
|
||||||
|
tenantA, err := provisioner.Provision(ctx, "acme", "Acme GmbH")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("provision acme: %v", err)
|
||||||
|
}
|
||||||
|
tenantB, err := provisioner.Provision(ctx, "globex", "Globex AG")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("provision globex: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if tenantA.DBName == tenantB.DBName {
|
||||||
|
t.Fatalf("erwartet unterschiedliche db_name, beide sind %q", tenantA.DBName)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Akzeptanzkriterium 3 / Pruefung 3: In der Datenbank von Tenant A existiert
|
||||||
|
// keine Verbindungsmoeglichkeit zu Tenant B, weil beide physisch getrennte
|
||||||
|
// Datenbanken sind, statt sich auf einen Query-Filter zu verlassen.
|
||||||
|
poolA, err := pgxpool.New(ctx, tenantA.DBDSN)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("connect tenant a: %v", err)
|
||||||
|
}
|
||||||
|
defer poolA.Close()
|
||||||
|
|
||||||
|
var globexVisible bool
|
||||||
|
err = poolA.QueryRow(ctx, `
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT 1 FROM pg_catalog.pg_database WHERE datname = $1
|
||||||
|
)
|
||||||
|
`, tenantB.DBName).Scan(&globexVisible)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("pruefung tenant-trennung: %v", err)
|
||||||
|
}
|
||||||
|
// pg_database ist clusterweit sichtbar (Existenz der DB), aber die
|
||||||
|
// eigentliche Pruefung ist: aus poolA (verbunden mit tenant_acme) ist keine
|
||||||
|
// Tabelle/Zeile aus tenant_globex erreichbar, da current_database() getrennt ist.
|
||||||
|
var currentDB string
|
||||||
|
if err := poolA.QueryRow(ctx, `SELECT current_database()`).Scan(¤tDB); err != nil {
|
||||||
|
t.Fatalf("current_database: %v", err)
|
||||||
|
}
|
||||||
|
if currentDB != tenantA.DBName {
|
||||||
|
t.Fatalf("current_database() = %q, want %q — keine physische Trennung", currentDB, tenantA.DBName)
|
||||||
|
}
|
||||||
|
if currentDB == tenantB.DBName {
|
||||||
|
t.Fatalf("tenant a verbindung zeigt auf tenant b datenbank")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package tenant
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Registry kapselt den Zugriff auf die Control-Plane-Registry-Datenbank.
|
||||||
|
// Sie enthaelt ausschliesslich Tenant-Metadaten (Akzeptanzkriterium 1) —
|
||||||
|
// niemals Geschaeftsdaten eines Mandanten.
|
||||||
|
type Registry struct {
|
||||||
|
pool *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRegistry(pool *pgxpool.Pool) *Registry {
|
||||||
|
return &Registry{pool: pool}
|
||||||
|
}
|
||||||
|
|
||||||
|
// insertTx schreibt den Tenant-Datensatz innerhalb einer laufenden Transaktion,
|
||||||
|
// damit Provisioner.Provision DB-Anlage und Registrierung atomar behandeln kann.
|
||||||
|
func (r *Registry) insertTx(ctx context.Context, tx pgx.Tx, t Tenant) (Tenant, error) {
|
||||||
|
row := tx.QueryRow(ctx, `
|
||||||
|
INSERT INTO tenants (slug, name, db_name, db_dsn, status)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
|
RETURNING id, created_at
|
||||||
|
`, t.Slug, t.Name, t.DBName, t.DBDSN, t.Status)
|
||||||
|
|
||||||
|
if err := row.Scan(&t.ID, &t.CreatedAt); err != nil {
|
||||||
|
return Tenant{}, fmt.Errorf("tenant registrieren: %w", err)
|
||||||
|
}
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) GetBySlug(ctx context.Context, slug string) (Tenant, error) {
|
||||||
|
var t Tenant
|
||||||
|
row := r.pool.QueryRow(ctx, `
|
||||||
|
SELECT id, slug, name, db_name, db_dsn, status, created_at
|
||||||
|
FROM tenants WHERE slug = $1
|
||||||
|
`, slug)
|
||||||
|
|
||||||
|
if err := row.Scan(&t.ID, &t.Slug, &t.Name, &t.DBName, &t.DBDSN, &t.Status, &t.CreatedAt); err != nil {
|
||||||
|
return Tenant{}, fmt.Errorf("tenant laden: %w", err)
|
||||||
|
}
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) List(ctx context.Context) ([]Tenant, error) {
|
||||||
|
rows, err := r.pool.Query(ctx, `
|
||||||
|
SELECT id, slug, name, db_name, db_dsn, status, created_at
|
||||||
|
FROM tenants ORDER BY created_at
|
||||||
|
`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("tenants auflisten: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var out []Tenant
|
||||||
|
for rows.Next() {
|
||||||
|
var t Tenant
|
||||||
|
if err := rows.Scan(&t.ID, &t.Slug, &t.Name, &t.DBName, &t.DBDSN, &t.Status, &t.CreatedAt); err != nil {
|
||||||
|
return nil, fmt.Errorf("tenant lesen: %w", err)
|
||||||
|
}
|
||||||
|
out = append(out, t)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
// Package tenant implements Core TEN-01: die Control-Plane-Registry und die
|
||||||
|
// Provisioning-Routine fuer physisch getrennte Mandanten-Datenbanken (Modell C).
|
||||||
|
package tenant
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"regexp"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status string
|
||||||
|
|
||||||
|
const (
|
||||||
|
StatusActive Status = "active"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Tenant struct {
|
||||||
|
ID string
|
||||||
|
Slug string
|
||||||
|
Name string
|
||||||
|
DBName string
|
||||||
|
DBDSN string
|
||||||
|
Status Status
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// slugPattern erzwingt sichere, als SQL-Identifier verwendbare Slugs, damit
|
||||||
|
// der Datenbankname niemals aus unkontrolliertem Nutzereingabe-Text gebaut wird.
|
||||||
|
var slugPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{1,48}$`)
|
||||||
|
|
||||||
|
var ErrInvalidSlug = errors.New("tenant: slug muss mit Kleinbuchstaben beginnen und darf nur [a-z0-9_] enthalten (2-49 Zeichen)")
|
||||||
|
|
||||||
|
func ValidateSlug(slug string) error {
|
||||||
|
if !slugPattern.MatchString(slug) {
|
||||||
|
return ErrInvalidSlug
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func dbNameForSlug(slug string) string {
|
||||||
|
return "tenant_" + slug
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package tenant
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestValidateSlug(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
slug string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{"acme", false},
|
||||||
|
{"acme_gmbh", false},
|
||||||
|
{"a1", false},
|
||||||
|
{"", true},
|
||||||
|
{"a", true},
|
||||||
|
{"1acme", true},
|
||||||
|
{"Acme", true},
|
||||||
|
{"acme-gmbh", true},
|
||||||
|
{"acme;drop table tenants", true},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, c := range cases {
|
||||||
|
err := ValidateSlug(c.slug)
|
||||||
|
if (err != nil) != c.wantErr {
|
||||||
|
t.Errorf("ValidateSlug(%q) error = %v, wantErr %v", c.slug, err, c.wantErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDBNameForSlug(t *testing.T) {
|
||||||
|
got := dbNameForSlug("acme")
|
||||||
|
want := "tenant_acme"
|
||||||
|
if got != want {
|
||||||
|
t.Errorf("dbNameForSlug() = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
DROP TABLE IF EXISTS tenants;
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
-- Control-plane registry: tenant list + connection info (Modell C).
|
|
||||||
-- Core TEN-01 (siehe core-kanban).
|
|
||||||
CREATE TABLE tenants (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
slug TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
db_dsn TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
-- Control-plane registry: Tenant-Liste + Verbindungsinformationen (Modell C).
|
||||||
|
-- Enthaelt AUSSCHLIESSLICH Tenant-Metadaten, keine Geschaeftsdaten eines Mandanten.
|
||||||
|
-- Core TEN-01 (siehe core-kanban/tickets/TEN-01.md).
|
||||||
|
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||||
|
|
||||||
|
CREATE TABLE 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()
|
||||||
|
);
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
DROP TABLE IF EXISTS audit_events;
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
-- Zentrales Audit-Log-Modell (AUD-01, siehe core-kanban/tickets/AUD-01.md).
|
||||||
|
-- Getrennt vom allgemeinen Anwendungs-Log (Akzeptanzkriterium 2): eigene
|
||||||
|
-- Tabelle, eigenes Paket (internal/audit), kein Log-Framework.
|
||||||
|
-- tenant_slug ist NOT NULL + darf nicht leer sein (Akzeptanzkriterium 2 /
|
||||||
|
-- Pruefung 2) — mandantenuebergreifende Ereignisse nutzen den reservierten
|
||||||
|
-- Wert 'system', niemals NULL oder leeren String.
|
||||||
|
CREATE TABLE audit_events (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
tenant_slug TEXT NOT NULL CHECK (tenant_slug <> ''),
|
||||||
|
actor TEXT NOT NULL CHECK (actor <> ''),
|
||||||
|
action TEXT NOT NULL CHECK (action <> ''),
|
||||||
|
target TEXT NOT NULL,
|
||||||
|
metadata JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX audit_events_tenant_slug_idx ON audit_events (tenant_slug, occurred_at);
|
||||||
Executable
+24
@@ -0,0 +1,24 @@
|
|||||||
|
#!/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
|
||||||
|
|
||||||
|
PASS="${NEXARCH_TEST_DB_PASSWORD:?Setze NEXARCH_TEST_DB_PASSWORD vor dem Aufruf}"
|
||||||
|
ROLE="nexarch_test"
|
||||||
|
|
||||||
|
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 audit_events CASCADE;"
|
||||||
|
|
||||||
|
dbs=$(psql -h localhost -U "$ROLE" -d postgres -tAc "SELECT datname FROM pg_database WHERE datname LIKE 'tenant\_%' ESCAPE '\'")
|
||||||
|
for db in $dbs; do
|
||||||
|
psql -h localhost -U "$ROLE" -d postgres -v ON_ERROR_STOP=1 -c "DROP DATABASE IF EXISTS \"${db}\";"
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "Testumgebung zurueckgesetzt: registry-tabelle + $(echo "$dbs" | grep -c . || true) tenant-datenbank(en) entfernt."
|
||||||
Executable
+24
@@ -0,0 +1,24 @@
|
|||||||
|
#!/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
|
||||||
|
|
||||||
|
PASS="${NEXARCH_TEST_DB_PASSWORD:?Setze NEXARCH_TEST_DB_PASSWORD vor dem Aufruf}"
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
NEXARCH_TEST_DB_PASSWORD="$PASS" bash scripts/reset-test-env.sh
|
||||||
|
|
||||||
|
export TEST_ADMIN_DSN="postgresql://nexarch_test:${PASS}@localhost:5432/postgres?sslmode=disable"
|
||||||
|
|
||||||
|
echo "== go build =="
|
||||||
|
go build ./...
|
||||||
|
|
||||||
|
echo "== go vet =="
|
||||||
|
go vet ./...
|
||||||
|
|
||||||
|
echo "== go test (-p 1) =="
|
||||||
|
go test ./... -p 1 -count=1
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { ThemeProvider, I18nProvider, ToastProvider, typography } from "@nexarch/shl";
|
||||||
|
|
||||||
|
export const metadata = {
|
||||||
|
title: "NEXARCH Audit-Log",
|
||||||
|
};
|
||||||
|
|
||||||
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { fetchRecords, exportURL, type AuditRecord, type AuditFilter } from "@/lib/api";
|
||||||
|
|
||||||
|
const EMPTY_FILTER: AuditFilter = { tenant: "", actor: "", action: "", from: "", to: "" };
|
||||||
|
|
||||||
|
export default function Page() {
|
||||||
|
const [caller, setCaller] = useState("");
|
||||||
|
const [filter, setFilter] = useState<AuditFilter>(EMPTY_FILTER);
|
||||||
|
const [records, setRecords] = useState<AuditRecord[] | null>(null);
|
||||||
|
const [selected, setSelected] = useState<AuditRecord | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
async function onSearch() {
|
||||||
|
setError(null);
|
||||||
|
setSelected(null);
|
||||||
|
try {
|
||||||
|
const data = await fetchRecords(caller.trim(), filter);
|
||||||
|
setRecords(data);
|
||||||
|
} catch (e: any) {
|
||||||
|
setError(e.message ?? "Unbekannter Fehler");
|
||||||
|
setRecords(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onExport(format: "csv" | "json") {
|
||||||
|
const url = exportURL(caller.trim(), filter, format);
|
||||||
|
// Echter Datei-Download ueber Browser-Navigation, KEIN erneutes Parsen
|
||||||
|
// im Frontend (Akzeptanzkriterium 2: Export aus AUD-03 direkt ausloesbar).
|
||||||
|
window.open(url, "_blank");
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main style={{ maxWidth: 1000, margin: "0 auto", padding: "2rem 1rem" }}>
|
||||||
|
<h1>Audit-Log</h1>
|
||||||
|
|
||||||
|
<div style={{ display: "grid", gap: "0.5rem", gridTemplateColumns: "repeat(3, 1fr)", marginBottom: "1rem" }}>
|
||||||
|
<input
|
||||||
|
value={caller}
|
||||||
|
onChange={(e) => setCaller(e.target.value)}
|
||||||
|
placeholder="Admin-Token (Berechtigung)"
|
||||||
|
style={{ padding: "0.5rem", gridColumn: "span 3" }}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
value={filter.tenant}
|
||||||
|
onChange={(e) => setFilter({ ...filter, tenant: e.target.value })}
|
||||||
|
placeholder="Tenant"
|
||||||
|
style={{ padding: "0.5rem" }}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
value={filter.actor}
|
||||||
|
onChange={(e) => setFilter({ ...filter, actor: e.target.value })}
|
||||||
|
placeholder="Akteur"
|
||||||
|
style={{ padding: "0.5rem" }}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
value={filter.action}
|
||||||
|
onChange={(e) => setFilter({ ...filter, action: e.target.value })}
|
||||||
|
placeholder="Aktion"
|
||||||
|
style={{ padding: "0.5rem" }}
|
||||||
|
/>
|
||||||
|
<label>
|
||||||
|
Von
|
||||||
|
<input
|
||||||
|
type="datetime-local"
|
||||||
|
value={filter.from}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilter({ ...filter, from: e.target.value ? new Date(e.target.value).toISOString() : "" })
|
||||||
|
}
|
||||||
|
style={{ width: "100%", padding: "0.4rem" }}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
Bis
|
||||||
|
<input
|
||||||
|
type="datetime-local"
|
||||||
|
value={filter.to}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFilter({ ...filter, to: e.target.value ? new Date(e.target.value).toISOString() : "" })
|
||||||
|
}
|
||||||
|
style={{ width: "100%", padding: "0.4rem" }}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style={{ display: "flex", gap: "0.5rem", marginBottom: "1rem" }}>
|
||||||
|
<button onClick={onSearch}>Suchen</button>
|
||||||
|
<button onClick={() => onExport("csv")}>Export als CSV</button>
|
||||||
|
<button onClick={() => onExport("json")}>Export als JSON</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<p style={{ color: "#c62828" }} role="alert">
|
||||||
|
Fehler: {error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{records && (
|
||||||
|
<table style={{ width: "100%", borderCollapse: "collapse", background: "white" }}>
|
||||||
|
<thead>
|
||||||
|
<tr style={{ textAlign: "left", borderBottom: "2px solid #ddd" }}>
|
||||||
|
<th style={{ padding: "0.5rem" }}>Zeitpunkt</th>
|
||||||
|
<th style={{ padding: "0.5rem" }}>Tenant</th>
|
||||||
|
<th style={{ padding: "0.5rem" }}>Akteur</th>
|
||||||
|
<th style={{ padding: "0.5rem" }}>Aktion</th>
|
||||||
|
<th style={{ padding: "0.5rem" }}></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{records.map((r, i) => (
|
||||||
|
<tr key={i} style={{ borderBottom: "1px solid #eee" }}>
|
||||||
|
<td style={{ padding: "0.5rem" }}>{new Date(r.occurred_at).toLocaleString("de-DE")}</td>
|
||||||
|
<td style={{ padding: "0.5rem" }}>{r.tenant_slug}</td>
|
||||||
|
<td style={{ padding: "0.5rem" }}>{r.actor}</td>
|
||||||
|
<td style={{ padding: "0.5rem" }}>{r.action}</td>
|
||||||
|
<td style={{ padding: "0.5rem" }}>
|
||||||
|
<button onClick={() => setSelected(r)}>Details</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{records.length === 0 && (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={5} style={{ padding: "0.5rem" }}>
|
||||||
|
Keine Einträge gefunden.
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{selected && (
|
||||||
|
<section style={{ background: "white", padding: "1rem", borderRadius: 8, marginTop: "1.5rem" }}>
|
||||||
|
<h2>Eintrag-Details</h2>
|
||||||
|
<dl>
|
||||||
|
<dt>Zeitpunkt</dt>
|
||||||
|
<dd>{new Date(selected.occurred_at).toLocaleString("de-DE")}</dd>
|
||||||
|
<dt>Tenant</dt>
|
||||||
|
<dd>{selected.tenant_slug}</dd>
|
||||||
|
<dt>Akteur</dt>
|
||||||
|
<dd>{selected.actor}</dd>
|
||||||
|
<dt>Aktion</dt>
|
||||||
|
<dd>{selected.action}</dd>
|
||||||
|
<dt>Ziel</dt>
|
||||||
|
<dd>{selected.target}</dd>
|
||||||
|
<dt>Metadaten</dt>
|
||||||
|
<dd>
|
||||||
|
<pre style={{ whiteSpace: "pre-wrap", background: "#f5f6f8", padding: "0.5rem" }}>
|
||||||
|
{JSON.stringify(selected.metadata, null, 2)}
|
||||||
|
</pre>
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
<button onClick={() => setSelected(null)}>Schließen</button>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
// Duenner Client der AUD-03-Export-API (internal/audit.ExportHandler) —
|
||||||
|
// keine eigene Aggregations-/Filterlogik im Frontend (Ticket-Vorgabe:
|
||||||
|
// "reiner Konsument der Export-API"). Die JSON-Lines-Antwort wird nur
|
||||||
|
// dekodiert, nicht neu berechnet oder gefiltert.
|
||||||
|
export type AuditRecord = {
|
||||||
|
occurred_at: string;
|
||||||
|
tenant_slug: string;
|
||||||
|
actor: string;
|
||||||
|
action: string;
|
||||||
|
target: string;
|
||||||
|
metadata: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AuditFilter = {
|
||||||
|
tenant: string;
|
||||||
|
actor: string;
|
||||||
|
action: string;
|
||||||
|
from: string; // RFC3339, leer = kein Filter
|
||||||
|
to: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function apiBase(): string {
|
||||||
|
const base = process.env.NEXT_PUBLIC_AUDITLOG_API_URL;
|
||||||
|
if (!base) {
|
||||||
|
throw new Error(
|
||||||
|
"NEXT_PUBLIC_AUDITLOG_API_URL ist nicht gesetzt (Umgebungsvariable erforderlich)"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildParams(caller: string, filter: AuditFilter, format: "json" | "csv"): URLSearchParams {
|
||||||
|
const params = new URLSearchParams({ caller, format });
|
||||||
|
if (filter.tenant) params.set("tenant", filter.tenant);
|
||||||
|
if (filter.actor) params.set("actor", filter.actor);
|
||||||
|
if (filter.action) params.set("action", filter.action);
|
||||||
|
if (filter.from) params.set("from", filter.from);
|
||||||
|
if (filter.to) params.set("to", filter.to);
|
||||||
|
return params;
|
||||||
|
}
|
||||||
|
|
||||||
|
// exportURL liefert die Adresse desselben Endpunkts, den auch die
|
||||||
|
// Export-Datei-Funktion (Akzeptanzkriterium 2) verwendet — Liste und Export
|
||||||
|
// sind bewusst DERSELBE API-Aufruf mit unterschiedlichem "format".
|
||||||
|
export function exportURL(caller: string, filter: AuditFilter, format: "json" | "csv"): string {
|
||||||
|
return `${apiBase()}/audit/export?${buildParams(caller, filter, format)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetchRecords laedt die Liste als JSON-Lines und dekodiert Zeile fuer
|
||||||
|
// Zeile — dieselben Filterparameter wie ein direkter API-Aufruf
|
||||||
|
// (Akzeptanzkriterium 1 / Pruefung 1).
|
||||||
|
export async function fetchRecords(caller: string, filter: AuditFilter): Promise<AuditRecord[]> {
|
||||||
|
const res = await fetch(exportURL(caller, filter, "json"), { cache: "no-store" });
|
||||||
|
if (!res.ok) {
|
||||||
|
const text = await res.text().catch(() => "");
|
||||||
|
throw new Error(text || `Anfrage fehlgeschlagen (${res.status})`);
|
||||||
|
}
|
||||||
|
const text = await res.text();
|
||||||
|
return text
|
||||||
|
.split("\n")
|
||||||
|
.filter((line) => line.trim() !== "")
|
||||||
|
.map((line) => JSON.parse(line) as AuditRecord);
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
/** @type {import('next').NextConfig} */
|
||||||
|
const nextConfig = {
|
||||||
|
// @nexarch/shl liegt als file:-Dependency mit TS-Quellen in node_modules —
|
||||||
|
// Next.js transpiliert node_modules standardmäßig nicht, siehe web/shl/README.md.
|
||||||
|
transpilePackages: ["@nexarch/shl"],
|
||||||
|
};
|
||||||
|
export default nextConfig;
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"name": "nexarch-audit-log",
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "es2017",
|
||||||
|
"lib": ["dom", "dom.iterable", "esnext"],
|
||||||
|
"allowJs": true,
|
||||||
|
"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"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# @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
|
||||||
|
```
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
// 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");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// 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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
// 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
// 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
"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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
"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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
// Ö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";
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
"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];
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
// 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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"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"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { defineConfig } from "vitest/config";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
environment: "jsdom",
|
||||||
|
setupFiles: ["./vitest.setup.ts"],
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
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