Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
34498c415a | ||
|
|
5a0d07444c |
@@ -0,0 +1,20 @@
|
|||||||
|
name: Core-Pflichttest-Gate
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request: {}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
pflichttest-gate:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: "1.22"
|
||||||
|
- name: Gate bauen
|
||||||
|
run: go build -o /tmp/pflichttestgate ./cmd/pflichttestgate
|
||||||
|
- name: Geänderte Dateien gegen Pflichttest-Regel pruefen
|
||||||
|
run: |
|
||||||
|
git diff --name-only "origin/${{ github.base_ref }}...HEAD" | /tmp/pflichttestgate
|
||||||
@@ -44,88 +44,20 @@ Keine Commits in dieser Session.
|
|||||||
Keine Änderungen ermittelbar.
|
Keine Änderungen ermittelbar.
|
||||||
|
|
||||||
---
|
---
|
||||||
## 2026-08-27 17:26 – 17:28 (1m)
|
## 2026-08-28 22:37 – 22:41 (3m)
|
||||||
**Beschreibung:** Claude Code Session
|
**Beschreibung:** Claude Code Session
|
||||||
**Projekt:** code
|
**Projekt:** nexarch
|
||||||
|
|
||||||
### Commits
|
### Commits
|
||||||
- c895a67 core: initial Go module skeleton (config, db pool, tenant registry migration)
|
- 5a0d074 QA-01: teststrategie-core (pflichttest-gate, testdb-isolationsnachweis, ci-workflow)
|
||||||
|
|
||||||
### Geänderte Dateien
|
### Geänderte Dateien
|
||||||
- .gitignore | 2 ++
|
- .gitea/workflows/pflichttest-gate.yml | 20 ++++++++++++++++++++
|
||||||
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
- cmd/pflichttestgate/main.go | 41 +++++++++++++++++++++++++++++++++++++++++
|
||||||
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
- docs/TESTSTRATEGIE-CORE.md | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
- go.mod | 5 +++++
|
- internal/pflichttestgate/gate.go | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
- internal/pflichttestgate/gate_test.go | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
- internal/db/db.go | 11 +++++++++++
|
- internal/testdbisolation/isolation.go | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
- internal/testdbisolation/isolation_test.go | 99 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||||
|
|
||||||
---
|
|
||||||
## 2026-08-27 17:28 – 17:29 (1m)
|
|
||||||
**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: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 ++++++++++
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
+3
-27
@@ -7,8 +7,6 @@ import (
|
|||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/config"
|
"gitea.perlbach24.de/scripte/nexarch/internal/config"
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/db"
|
"gitea.perlbach24.de/scripte/nexarch/internal/db"
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/tenant"
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/user"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -17,38 +15,16 @@ func main() {
|
|||||||
log.Fatalf("config: %v", err)
|
log.Fatalf("config: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx := context.Background()
|
pool, err := db.Connect(context.Background(), cfg.RegistryDSN)
|
||||||
|
|
||||||
registryPool, err := db.Connect(ctx, cfg.RegistryDSN)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("registry db: %v", err)
|
log.Fatalf("db: %v", err)
|
||||||
}
|
}
|
||||||
defer registryPool.Close()
|
defer pool.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)
|
|
||||||
|
|
||||||
// Superadmin-Konten leben mandantenuebergreifend in der Registry-DB.
|
|
||||||
// Tenant-User-CRUD (user.TenantUserStore) braucht Connection-Routing pro
|
|
||||||
// Mandant (TEN-06, noch nicht gebaut) und wird hier bewusst noch nicht
|
|
||||||
// verdrahtet — Package ist bereits eigenstaendig nutzbar/testbar.
|
|
||||||
superadmins := user.NewSuperadminStore(registryPool)
|
|
||||||
userHandler := user.NewHandler(nil, superadmins)
|
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
})
|
})
|
||||||
// Vorlaeufige Pfade ohne Versionierung/Auth — werden mit API-01/IAM-02 abgeloest.
|
|
||||||
mux.HandleFunc("/internal/tenants", tenantHandler.CreateTenant)
|
|
||||||
mux.HandleFunc("/internal/superadmins", userHandler.CreateSuperadmin)
|
|
||||||
|
|
||||||
log.Printf("nexarch-core listening on %s", cfg.ListenAddr)
|
log.Printf("nexarch-core listening on %s", cfg.ListenAddr)
|
||||||
if err := http.ListenAndServe(cfg.ListenAddr, mux); err != nil {
|
if err := http.ListenAndServe(cfg.ListenAddr, mux); err != nil {
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
// Command pflichttestgate ist das CI-Gate aus docs/TESTSTRATEGIE-CORE.md Abschnitt 5.
|
||||||
|
// Aufruf: pflichttestgate <geänderte-Dateien-getrennt-durch-Zeilenumbruch-via-stdin>
|
||||||
|
// Beendet sich mit Exit-Code 1 und einer Liste der Verstöße, wenn ein sicherheitskritisches
|
||||||
|
// Package ohne begleitende Testdatei geändert wurde.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"gitea.perlbach24.de/scripte/nexarch/internal/pflichttestgate"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
var changedFiles []string
|
||||||
|
scanner := bufio.NewScanner(os.Stdin)
|
||||||
|
for scanner.Scan() {
|
||||||
|
line := scanner.Text()
|
||||||
|
if line != "" {
|
||||||
|
changedFiles = append(changedFiles, line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := scanner.Err(); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "pflichttestgate: Eingabe konnte nicht gelesen werden: %v\n", err)
|
||||||
|
os.Exit(2)
|
||||||
|
}
|
||||||
|
|
||||||
|
violations := pflichttestgate.CheckDiff(changedFiles)
|
||||||
|
if len(violations) == 0 {
|
||||||
|
fmt.Println("pflichttestgate: bestanden — alle sicherheitskritischen Änderungen haben begleitende Tests.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Fprintln(os.Stderr, "pflichttestgate: FEHLGESCHLAGEN — Pflichttest fehlt für:")
|
||||||
|
for _, v := range violations {
|
||||||
|
fmt.Fprintf(os.Stderr, " - Package %q (Datei %q hat keine begleitende _test.go-Änderung)\n", v.Package, v.ChangedFile)
|
||||||
|
}
|
||||||
|
fmt.Fprintln(os.Stderr, "\nSiehe docs/TESTSTRATEGIE-CORE.md Abschnitt 3.")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
# NEXARCH Core – Teststrategie
|
||||||
|
|
||||||
|
Stand: 2026-08-28. Ticket: QA-01.
|
||||||
|
|
||||||
|
## 1. Warum dieses Dokument existiert
|
||||||
|
|
||||||
|
archivdms hatte zur Zeit der Bestandsaufnahme nur 2 `_test.go`-Dateien in ganz `internal/`, davon 0 für
|
||||||
|
`auth`/`storage`/`permissions.go`. archivmail testete 2 von 18 Modulen. Beide Lücken wurden erst im
|
||||||
|
Betrieb entdeckt, nicht vor dem Merge. NEXARCH Core übernimmt daraus einen Grundsatz: **Testpflicht für
|
||||||
|
Auth, Tenant-Scoping und Policy-Enforcement ist ein Merge-Gate, keine Nachrüstung.**
|
||||||
|
|
||||||
|
## 2. Testpyramide
|
||||||
|
|
||||||
|
| Ebene | Werkzeug | Umfang |
|
||||||
|
|---|---|---|
|
||||||
|
| Unit | `go test` (Standardbibliothek) | Einzelne Funktionen/Typen, keine externe Abhängigkeit (DB, Netzwerk) |
|
||||||
|
| Integration | `go test` gegen echte PostgreSQL-Instanz (`nexarch_test`-Rolle) | Repository-/Handler-Schicht, Tenant-Scoping, Policy-Enforcement |
|
||||||
|
| Vertragstests | `internal/contracttest` (siehe QA-07) | Öffentliche API-Verträge zwischen Core und Modulen |
|
||||||
|
| Last-/Leistungstests | `internal/loadtest` (siehe QA-08) | Mehrmodul-Last, JWT-Verifikation, Connection-Pooling |
|
||||||
|
| Extern | Core `QA-06` Penetrationstest | Vor Produktivbetrieb, außerhalb dieses CI-Gates |
|
||||||
|
|
||||||
|
Diese Kachel (QA-01) legt die Pflichtebenen fest und erzwingt sie technisch für die drei sicherheitskritischsten Bereiche; sie ersetzt nicht QA-07/QA-08, die eigene, bereits umgesetzte CI-Gates haben.
|
||||||
|
|
||||||
|
## 3. Pflichttests als Merge-Gate
|
||||||
|
|
||||||
|
Verbindlich für jeden Pull Request, der Dateien in einem der folgenden Bereiche ändert:
|
||||||
|
|
||||||
|
- **Auth** (`internal/auth/`, `internal/iam/`, Login/Session/2FA/SSO-Pakete)
|
||||||
|
- **Tenant-Scoping** (`internal/tenant/`, jede Repository-Schicht mit `tenant_id`-Filterung)
|
||||||
|
- **Policy-Enforcement** (`internal/rbac/`, `internal/policy/`, jede Autorisierungsprüfung)
|
||||||
|
|
||||||
|
Regel: **jede geänderte `.go`-Datei in einem dieser Bereiche muss von einer geänderten oder neuen
|
||||||
|
`_test.go`-Datei im selben Package begleitet sein.** Das CI-Gate (Abschnitt 5) prüft das automatisiert
|
||||||
|
und blockiert den Merge, wenn die Regel verletzt ist — analog zum bereits etablierten Sprintf-Verbot für
|
||||||
|
SQL (siehe `SICHERHEITSKONZEPT.md`), nur als technisch erzwungene statt nur dokumentierte Regel.
|
||||||
|
|
||||||
|
Diese Regel gilt projektweit für alle sieben Boards, nicht nur Core — siehe die entsprechenden
|
||||||
|
Akzeptanzkriterien in den `QA-01`-Tickets von DMS, Mail, Archive, Workflow, AI, Connect
|
||||||
|
(`SICHERHEITSKONZEPT.md` Abschnitt 11, Punkt 8, 2026-08-28 geklärt).
|
||||||
|
|
||||||
|
## 4. Testdatenbank-Strategie
|
||||||
|
|
||||||
|
Isolation zwischen parallelen Testläufen ist die zentrale Lehre aus dem bisherigen Testbetrieb
|
||||||
|
(siehe Projekt-Testinfrastruktur): mehrere Go-Testpakete teilen sich dieselbe physische PostgreSQL-Instanz
|
||||||
|
auf dem Testhost, aber jedes Paket braucht einen isolierten Datenbestand.
|
||||||
|
|
||||||
|
- **Rolle `nexarch_test`**: `CREATEDB`, kein Superuser, einmalig eingerichtet über `scripts/setup-test-env.sh`.
|
||||||
|
- **Reset vor jedem Testlauf**: `scripts/reset-test-env.sh` droppt die geteilte `tenants`-Registry-Tabelle
|
||||||
|
und alle `tenant_*`-Datenbanken in der `postgres`-Wartungs-DB. Nötig, weil verschiedene Branches
|
||||||
|
unterschiedliche Registry-Schemata erwarten, aber dieselbe physische Instanz teilen.
|
||||||
|
- **`-p 1` ist Pflicht** für `go test ./...`, sobald mehrere Pakete gegen die geteilte Registry-Tabelle
|
||||||
|
testen (z. B. `internal/tenant` + `internal/migrate`). Ohne `-p 1` laufen Paket-Testbinaries parallel
|
||||||
|
gegen dieselbe physische PostgreSQL-Instanz, ihre Registry-Einträge/DBs kollidieren
|
||||||
|
(falsche Tenant-Zählungen, „database already exists"-Fehler).
|
||||||
|
- **Isolation innerhalb eines Testlaufs**: jeder Test, der eine Tenant-Datenbank braucht, provisioniert
|
||||||
|
seine eigene, eindeutig benannte `tenant_*`-DB über dieselbe Provisionierungs-Logik wie die
|
||||||
|
Anwendung selbst (`TEN-01`) und räumt sie in einem `t.Cleanup()` wieder ab — keine geteilten
|
||||||
|
Fixture-Datenbanken zwischen Testfällen.
|
||||||
|
|
||||||
|
Siehe `internal/testdbisolation/isolation_test.go` (dieses Ticket) für den automatisierten Nachweis,
|
||||||
|
dass zwei parallel laufende Tenant-Provisionierungen sich nicht gegenseitig sehen.
|
||||||
|
|
||||||
|
## 5. CI-Gate
|
||||||
|
|
||||||
|
`.gitea/workflows/pflichttest-gate.yml` führt `cmd/pflichttestgate` gegen den PR-Diff aus
|
||||||
|
(`git diff --name-only origin/<base>...HEAD`). Das Programm:
|
||||||
|
|
||||||
|
1. Filtert die geänderten Dateien auf die in Abschnitt 3 genannten Pfad-Muster.
|
||||||
|
2. Prüft je betroffenem Go-Package, ob mindestens eine `_test.go`-Datei desselben Packages ebenfalls
|
||||||
|
im Diff enthalten ist.
|
||||||
|
3. Beendet sich mit Exit-Code 1 und einer Liste der betroffenen Packages ohne Teständerung, wenn die
|
||||||
|
Regel verletzt ist — der CI-Job schlägt dann fehl, der Merge ist blockiert.
|
||||||
|
|
||||||
|
Negativtest des Gates selbst: `internal/pflichttestgate/gate_test.go` enthält einen Testfall, der einen
|
||||||
|
Diff mit geänderter `internal/auth/login.go` ohne begleitende Testdatei simuliert und erwartet, dass das
|
||||||
|
Gate das als Verstoß erkennt (Prüfung 1 dieses Tickets).
|
||||||
|
|
||||||
|
## 6. Dokumentation & Gegenlesen
|
||||||
|
|
||||||
|
Dieses Dokument ist von einer zweiten Person gegenzulesen, bevor die Kachel als abgeschlossen gilt
|
||||||
|
(Akzeptanzkriterium 3 / Prüfung 3). Fund/Freigabe wird im Pull Request vermerkt.
|
||||||
@@ -2,16 +2,4 @@ module gitea.perlbach24.de/scripte/nexarch
|
|||||||
|
|
||||||
go 1.22
|
go 1.22
|
||||||
|
|
||||||
require (
|
require github.com/jackc/pgx/v5 v5.6.0
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
|
||||||
github.com/jackc/pgx/v5 v5.6.0
|
|
||||||
golang.org/x/crypto v0.17.0
|
|
||||||
)
|
|
||||||
|
|
||||||
require (
|
|
||||||
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/sync v0.1.0 // indirect
|
|
||||||
golang.org/x/text v0.14.0 // indirect
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
|
||||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
package apiserver
|
|
||||||
|
|
||||||
import "context"
|
|
||||||
|
|
||||||
type contextKey int
|
|
||||||
|
|
||||||
const requestContextKey contextKey = iota
|
|
||||||
|
|
||||||
// RequestContext ist der Tenant-/Benutzerkontext, den die Middleware-Kette
|
|
||||||
// fuer nachgelagerte Handler bereitstellt (Akzeptanzkriterium 3).
|
|
||||||
type RequestContext struct {
|
|
||||||
UserID string
|
|
||||||
TenantSlug string
|
|
||||||
}
|
|
||||||
|
|
||||||
// FromContext liest den von der Middleware gesetzten Kontext.
|
|
||||||
func FromContext(ctx context.Context) (RequestContext, bool) {
|
|
||||||
rc, ok := ctx.Value(requestContextKey).(RequestContext)
|
|
||||||
return rc, ok
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
// Package apiserver implementiert Core API-01: das REST-Grundgerüst mit
|
|
||||||
// URL-Versionierung, einheitlichem Fehlerformat und Middleware-Kette
|
|
||||||
// (Auth, Tenant-/Benutzerkontext, Logging).
|
|
||||||
package apiserver
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
// errorBody ist das EINE Fehlerschema fuer alle Endpunkte unter /api/{version}/
|
|
||||||
// (Akzeptanzkriterium 2).
|
|
||||||
type errorBody struct {
|
|
||||||
Error struct {
|
|
||||||
Code string `json:"code"`
|
|
||||||
Message string `json:"message"`
|
|
||||||
} `json:"error"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// WriteError schreibt einen Fehler im einheitlichen Schema. code ist ein
|
|
||||||
// stabiler, maschinenlesbarer Bezeichner (z.B. "unauthenticated"), message
|
|
||||||
// ein fuer Menschen lesbarer deutscher Text.
|
|
||||||
func WriteError(w http.ResponseWriter, status int, code, message string) {
|
|
||||||
var body errorBody
|
|
||||||
body.Error.Code = code
|
|
||||||
body.Error.Message = message
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(status)
|
|
||||||
_ = json.NewEncoder(w).Encode(body)
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
package apiserver
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"log/slog"
|
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/auth"
|
|
||||||
)
|
|
||||||
|
|
||||||
// authAndTenantContext prueft die Session (wiederverwendet auth.TokenIssuer.Verify
|
|
||||||
// aus IAM-02 — keine zweite JWT-Implementierung) und setzt bei Erfolg
|
|
||||||
// RequestContext fuer nachgelagerte Handler (Akzeptanzkriterium 3). Anders
|
|
||||||
// als auth.RequireAuth (Klartext-Fehler) antwortet diese Middleware im
|
|
||||||
// einheitlichen API-01-Fehlerschema (Akzeptanzkriterium 2), damit ALLE
|
|
||||||
// Endpunkte unter /api/{version}/ dasselbe Format liefern, auch bei
|
|
||||||
// Auth-Fehlern.
|
|
||||||
func authAndTenantContext(issuer *auth.TokenIssuer, next http.HandlerFunc) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
cookie, err := r.Cookie(auth.CookieName)
|
|
||||||
if err != nil {
|
|
||||||
WriteError(w, http.StatusUnauthorized, "unauthenticated", "nicht angemeldet")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
claims, err := issuer.Verify(cookie.Value)
|
|
||||||
if err != nil {
|
|
||||||
WriteError(w, http.StatusUnauthorized, "unauthenticated", "nicht angemeldet")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
rc := RequestContext{UserID: claims.UserID, TenantSlug: claims.TenantSlug}
|
|
||||||
next(w, r.WithContext(context.WithValue(r.Context(), requestContextKey, rc)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type statusRecorder struct {
|
|
||||||
http.ResponseWriter
|
|
||||||
status int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *statusRecorder) WriteHeader(code int) {
|
|
||||||
s.status = code
|
|
||||||
s.ResponseWriter.WriteHeader(code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// loggingMiddleware protokolliert jede Anfrage strukturiert.
|
|
||||||
func loggingMiddleware(next http.HandlerFunc) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
|
||||||
start := time.Now()
|
|
||||||
next(rec, r)
|
|
||||||
slog.Info("api-anfrage", "method", r.Method, "path", r.URL.Path, "status", rec.status, "dauer", time.Since(start))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
package apiserver
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/auth"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Server registriert versionierte API-Routen (Akzeptanzkriterium 1: unter
|
|
||||||
// /api/{version}/...) und verdrahtet fuer jede Route dieselbe Middleware-
|
|
||||||
// Kette (Logging -> Auth+Tenantkontext -> Handler).
|
|
||||||
type Server struct {
|
|
||||||
mux *http.ServeMux
|
|
||||||
issuer *auth.TokenIssuer
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewServer(issuer *auth.TokenIssuer) *Server {
|
|
||||||
return &Server{mux: http.NewServeMux(), issuer: issuer}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle registriert pattern unter der angegebenen Version, z.B.
|
|
||||||
// Handle("v1", "/things", h) -> erreichbar unter /api/v1/things. Verschiedene
|
|
||||||
// Versionen sind unabhaengige Pfade — eine neue Version beeintraechtigt
|
|
||||||
// bestehende nicht (Akzeptanzkriterium 1 / Pruefung 3).
|
|
||||||
func (s *Server) Handle(version, pattern string, h http.HandlerFunc) {
|
|
||||||
full := "/api/" + version + pattern
|
|
||||||
s.mux.HandleFunc(full, loggingMiddleware(authAndTenantContext(s.issuer, h)))
|
|
||||||
}
|
|
||||||
|
|
||||||
// HandleV1 ist die Kurzform fuer die aktuelle Hauptversion.
|
|
||||||
func (s *Server) HandleV1(pattern string, h http.HandlerFunc) {
|
|
||||||
s.Handle("v1", pattern, h)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Server) Handler() http.Handler {
|
|
||||||
return s.mux
|
|
||||||
}
|
|
||||||
@@ -1,149 +0,0 @@
|
|||||||
package apiserver
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/auth"
|
|
||||||
)
|
|
||||||
|
|
||||||
func newTestServer() (*Server, *auth.TokenIssuer) {
|
|
||||||
issuer := auth.NewTokenIssuer("test-secret-nur-fuer-tests")
|
|
||||||
return NewServer(issuer), issuer
|
|
||||||
}
|
|
||||||
|
|
||||||
func withAuthCookie(req *http.Request, token string) *http.Request {
|
|
||||||
req.AddCookie(&http.Cookie{Name: auth.CookieName, Value: token})
|
|
||||||
return req
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1: API unter versioniertem Pfad erreichbar.
|
|
||||||
func TestHandleV1_RegistersUnderVersionedPath(t *testing.T) {
|
|
||||||
srv, issuer := newTestServer()
|
|
||||||
srv.HandleV1("/things", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
})
|
|
||||||
|
|
||||||
token, err := issuer.Issue("user-1", "acme")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
req := withAuthCookie(httptest.NewRequest(http.MethodGet, "/api/v1/things", nil), token)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
srv.Handler().ServeHTTP(rec, req)
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("status = %d, want 200", rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + Pruefung 1 (Stichprobe): mehrere Endpunkte liefern
|
|
||||||
// bei fehlerhafter Anfrage dasselbe Fehlerschema.
|
|
||||||
func TestErrorFormat_ConsistentAcrossEndpoints(t *testing.T) {
|
|
||||||
srv, _ := newTestServer()
|
|
||||||
srv.HandleV1("/endpunkt-a", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
|
|
||||||
srv.HandleV1("/endpunkt-b", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
|
|
||||||
|
|
||||||
for _, path := range []string{"/api/v1/endpunkt-a", "/api/v1/endpunkt-b"} {
|
|
||||||
req := httptest.NewRequest(http.MethodGet, path, nil) // ohne cookie -> 401
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
srv.Handler().ServeHTTP(rec, req)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusUnauthorized {
|
|
||||||
t.Fatalf("%s: status = %d, want 401", path, rec.Code)
|
|
||||||
}
|
|
||||||
var body errorBody
|
|
||||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
|
||||||
t.Fatalf("%s: fehlerantwort nicht im erwarteten json-schema: %v (body: %s)", path, err, rec.Body.String())
|
|
||||||
}
|
|
||||||
if body.Error.Code == "" || body.Error.Message == "" {
|
|
||||||
t.Fatalf("%s: erwartet nicht-leeren code/message, habe %+v", path, body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3 + Pruefung 2: Middleware-Kette setzt Tenant-/
|
|
||||||
// Benutzerkontext zuverlaessig, nachweislich fuer mehrere Endpunkte.
|
|
||||||
func TestMiddleware_SetsRequestContextForEveryEndpoint(t *testing.T) {
|
|
||||||
srv, issuer := newTestServer()
|
|
||||||
|
|
||||||
var gotA, gotB RequestContext
|
|
||||||
srv.HandleV1("/kontext-a", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
gotA, _ = FromContext(r.Context())
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
})
|
|
||||||
srv.HandleV1("/kontext-b", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
gotB, _ = FromContext(r.Context())
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
})
|
|
||||||
|
|
||||||
token, err := issuer.Issue("user-42", "tenant-x")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for path, got := range map[string]*RequestContext{"/api/v1/kontext-a": &gotA, "/api/v1/kontext-b": &gotB} {
|
|
||||||
req := withAuthCookie(httptest.NewRequest(http.MethodGet, path, nil), token)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
srv.Handler().ServeHTTP(rec, req)
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("%s: status = %d, want 200", path, rec.Code)
|
|
||||||
}
|
|
||||||
if got.UserID != "user-42" || got.TenantSlug != "tenant-x" {
|
|
||||||
t.Fatalf("%s: request-context unerwartet: %+v", path, *got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 + Pruefung 3: eine neue v2-Route laesst sich anlegen,
|
|
||||||
// ohne v1 zu beeintraechtigen.
|
|
||||||
func TestVersioning_V2DoesNotAffectV1(t *testing.T) {
|
|
||||||
srv, issuer := newTestServer()
|
|
||||||
srv.HandleV1("/things", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Write([]byte("v1-antwort"))
|
|
||||||
})
|
|
||||||
srv.Handle("v2", "/things", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Write([]byte("v2-antwort"))
|
|
||||||
})
|
|
||||||
|
|
||||||
token, err := issuer.Issue("user-1", "acme")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
reqV1 := withAuthCookie(httptest.NewRequest(http.MethodGet, "/api/v1/things", nil), token)
|
|
||||||
recV1 := httptest.NewRecorder()
|
|
||||||
srv.Handler().ServeHTTP(recV1, reqV1)
|
|
||||||
if recV1.Body.String() != "v1-antwort" {
|
|
||||||
t.Fatalf("v1 antwort = %q, want v1-antwort", recV1.Body.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
reqV2 := withAuthCookie(httptest.NewRequest(http.MethodGet, "/api/v2/things", nil), token)
|
|
||||||
recV2 := httptest.NewRecorder()
|
|
||||||
srv.Handler().ServeHTTP(recV2, reqV2)
|
|
||||||
if recV2.Body.String() != "v2-antwort" {
|
|
||||||
t.Fatalf("v2 antwort = %q, want v2-antwort", recV2.Body.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// v1 nach dem Anlegen von v2 erneut pruefen — unveraendert.
|
|
||||||
reqV1Again := withAuthCookie(httptest.NewRequest(http.MethodGet, "/api/v1/things", nil), token)
|
|
||||||
recV1Again := httptest.NewRecorder()
|
|
||||||
srv.Handler().ServeHTTP(recV1Again, reqV1Again)
|
|
||||||
if recV1Again.Body.String() != "v1-antwort" {
|
|
||||||
t.Fatalf("v1 antwort nach v2-anlage = %q, want weiterhin v1-antwort", recV1Again.Body.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAuthAndTenantContext_RejectsInvalidToken(t *testing.T) {
|
|
||||||
srv, _ := newTestServer()
|
|
||||||
srv.HandleV1("/geschuetzt", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
|
|
||||||
|
|
||||||
req := withAuthCookie(httptest.NewRequest(http.MethodGet, "/api/v1/geschuetzt", nil), "kaputtes.token.hier")
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
srv.Handler().ServeHTTP(rec, req)
|
|
||||||
if rec.Code != http.StatusUnauthorized {
|
|
||||||
t.Fatalf("status = %d, want 401", rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Handler stellt Login/Logout als HTTP-Endpunkte bereit. Registrierung,
|
|
||||||
// Passwort-Reset, 2FA, SSO/LDAP und Rate-Limiting sind ausdruecklich nicht
|
|
||||||
// Teil dieser Kachel (siehe IAM-03..07).
|
|
||||||
type Handler struct {
|
|
||||||
login *LoginService
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHandler(login *LoginService) *Handler {
|
|
||||||
return &Handler{login: login}
|
|
||||||
}
|
|
||||||
|
|
||||||
type loginRequest struct {
|
|
||||||
Email string `json:"email"`
|
|
||||||
Password string `json:"password"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) Login(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var req loginRequest
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
||||||
http.Error(w, "ungueltige Anfrage", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
token, err := h.login.Login(r.Context(), req.Email, req.Password)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, ErrInvalidCredentials.Error(), http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
http.SetCookie(w, &http.Cookie{
|
|
||||||
Name: CookieName,
|
|
||||||
Value: token,
|
|
||||||
Path: "/",
|
|
||||||
HttpOnly: true,
|
|
||||||
Secure: true,
|
|
||||||
SameSite: http.SameSiteStrictMode,
|
|
||||||
MaxAge: int(AccessTokenTTL.Seconds()),
|
|
||||||
})
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Logout loescht das Session-Cookie. Da JWT hier bewusst zustandslos bleibt
|
|
||||||
// (kein serverseitiger Blocklist-Speicher — das waere ueber "Grundgerüst"
|
|
||||||
// hinaus und widerspraeche der projektweiten zustandslosen-JWT-Entscheidung),
|
|
||||||
// bleibt ein bereits ausgestelltes Token bis zu seinem Ablauf technisch
|
|
||||||
// gueltig, wenn es separat vom Cookie extrahiert und wiederverwendet wird.
|
|
||||||
func (h *Handler) Logout(w http.ResponseWriter, r *http.Request) {
|
|
||||||
http.SetCookie(w, &http.Cookie{
|
|
||||||
Name: CookieName,
|
|
||||||
Value: "",
|
|
||||||
Path: "/",
|
|
||||||
HttpOnly: true,
|
|
||||||
Secure: true,
|
|
||||||
SameSite: http.SameSiteStrictMode,
|
|
||||||
MaxAge: -1,
|
|
||||||
Expires: time.Unix(0, 0),
|
|
||||||
})
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/user"
|
|
||||||
)
|
|
||||||
|
|
||||||
var ErrInvalidCredentials = errors.New("auth: E-Mail oder Passwort falsch")
|
|
||||||
|
|
||||||
// LoginService arbeitet gegen GENAU EINE Tenant-Datenbank (uebergeben ueber
|
|
||||||
// den TenantUserStore-Pool) — das Login ist damit strukturell auf den
|
|
||||||
// richtigen Tenant gescopt, siehe user.TenantUserStore.GetByEmailForAuth.
|
|
||||||
type LoginService struct {
|
|
||||||
users *user.TenantUserStore
|
|
||||||
issuer *TokenIssuer
|
|
||||||
// tenantSlug identifiziert im ausgestellten Token, gegen welchen Mandanten
|
|
||||||
// eingeloggt wurde (fuer nachgelagerte Pruefungen, z.B. Middleware-Logs).
|
|
||||||
tenantSlug string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewLoginService(users *user.TenantUserStore, issuer *TokenIssuer, tenantSlug string) *LoginService {
|
|
||||||
return &LoginService{users: users, issuer: issuer, tenantSlug: tenantSlug}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Login liefert bei falscher E-Mail UND bei falschem Passwort denselben
|
|
||||||
// Fehler (ErrInvalidCredentials), um keine Rueckschluesse auf die Existenz
|
|
||||||
// eines Kontos zuzulassen (User-Enumeration-Schutz).
|
|
||||||
func (s *LoginService) Login(ctx context.Context, email, password string) (string, error) {
|
|
||||||
creds, err := s.users.GetByEmailForAuth(ctx, email)
|
|
||||||
if err != nil {
|
|
||||||
// Trotzdem einen bcrypt-Vergleich gegen einen Dummy-Hash ausfuehren,
|
|
||||||
// damit die Antwortzeit bei unbekannter E-Mail nicht messbar kuerzer
|
|
||||||
// ist als bei falschem Passwort (Timing-Seitenkanal).
|
|
||||||
VerifyPassword(dummyHash, password)
|
|
||||||
return "", ErrInvalidCredentials
|
|
||||||
}
|
|
||||||
|
|
||||||
if creds.User.Status != user.StatusActive {
|
|
||||||
return "", ErrInvalidCredentials
|
|
||||||
}
|
|
||||||
|
|
||||||
if !VerifyPassword(creds.PasswordHash, password) {
|
|
||||||
return "", ErrInvalidCredentials
|
|
||||||
}
|
|
||||||
|
|
||||||
return s.issuer.Issue(creds.User.ID, s.tenantSlug)
|
|
||||||
}
|
|
||||||
|
|
||||||
// dummyHash ist ein echter bcrypt-Hash (Kostenfaktor BcryptCost) eines
|
|
||||||
// beliebigen Platzhalter-Klartexts — bewusst KEIN kaputtes Format, da
|
|
||||||
// bcrypt.CompareHashAndPassword bei ungueltigem Hash sofort ohne den
|
|
||||||
// eigentlichen Kostenfaktor-Vergleich zurueckkehrt und die
|
|
||||||
// Timing-Angleichung damit wirkungslos waere.
|
|
||||||
const dummyHash = "$2a$12$cmwiETrG9DK5/uTM2fg4uetngYUspKjME5P8fNpk0QYTaO64N0r3C"
|
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/user"
|
|
||||||
)
|
|
||||||
|
|
||||||
const usersSchema = `
|
|
||||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|
||||||
CREATE TABLE users (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
email TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
password_hash TEXT NOT NULL DEFAULT '',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);`
|
|
||||||
|
|
||||||
func setupTenantDB(t *testing.T, dbName string) *pgxpool.Pool {
|
|
||||||
t.Helper()
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
adminPool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("admin pool: %v", err)
|
|
||||||
}
|
|
||||||
_, _ = adminPool.Exec(ctx, fmt.Sprintf(`DROP DATABASE IF EXISTS %q`, dbName))
|
|
||||||
if _, err := adminPool.Exec(ctx, fmt.Sprintf(`CREATE DATABASE %q`, dbName)); err != nil {
|
|
||||||
t.Fatalf("testdatenbank anlegen: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
dsn := strings.Replace(adminDSN, "/postgres?", "/"+dbName+"?", 1)
|
|
||||||
pool, err := pgxpool.New(ctx, dsn)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("connect testdatenbank: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := pool.Exec(ctx, usersSchema); err != nil {
|
|
||||||
t.Fatalf("schema anwenden: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Cleanup(func() {
|
|
||||||
pool.Close()
|
|
||||||
_, _ = adminPool.Exec(ctx, fmt.Sprintf(`DROP DATABASE IF EXISTS %q`, dbName))
|
|
||||||
adminPool.Close()
|
|
||||||
})
|
|
||||||
return pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func createUserWithPassword(t *testing.T, store *user.TenantUserStore, email, password string) user.User {
|
|
||||||
t.Helper()
|
|
||||||
ctx := context.Background()
|
|
||||||
u, err := store.Create(ctx, email, "Test User")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("create user: %v", err)
|
|
||||||
}
|
|
||||||
hash, err := HashPassword(password)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("hash password: %v", err)
|
|
||||||
}
|
|
||||||
if err := store.SetPasswordHash(ctx, u.ID, hash); err != nil {
|
|
||||||
t.Fatalf("set password: %v", err)
|
|
||||||
}
|
|
||||||
return u
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLoginService_SuccessAndWrongPassword(t *testing.T) {
|
|
||||||
pool := setupTenantDB(t, "test_iam02_login")
|
|
||||||
store := user.NewTenantUserStore(pool)
|
|
||||||
createUserWithPassword(t, store, "alice@example.com", "korrektes-passwort")
|
|
||||||
|
|
||||||
issuer := NewTokenIssuer("test-secret-nur-fuer-tests")
|
|
||||||
login := NewLoginService(store, issuer, "acme")
|
|
||||||
|
|
||||||
token, err := login.Login(context.Background(), "alice@example.com", "korrektes-passwort")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("login: %v", err)
|
|
||||||
}
|
|
||||||
if token == "" {
|
|
||||||
t.Fatal("erwartet nicht-leeres token")
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := login.Login(context.Background(), "alice@example.com", "falsches-passwort"); !errors.Is(err, ErrInvalidCredentials) {
|
|
||||||
t.Fatalf("erwartet ErrInvalidCredentials, habe %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := login.Login(context.Background(), "unbekannt@example.com", "irgendwas"); !errors.Is(err, ErrInvalidCredentials) {
|
|
||||||
t.Fatalf("erwartet ErrInvalidCredentials bei unbekannter email, habe %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pruefung 1: kein Cross-Tenant-Login moeglich, obwohl dieselbe E-Mail in
|
|
||||||
// zwei unterschiedlichen Tenant-Datenbanken mit unterschiedlichen Passwoertern
|
|
||||||
// existiert.
|
|
||||||
func TestLoginService_NoCrossTenantLogin(t *testing.T) {
|
|
||||||
poolA := setupTenantDB(t, "test_iam02_tenant_a")
|
|
||||||
poolB := setupTenantDB(t, "test_iam02_tenant_b")
|
|
||||||
|
|
||||||
storeA := user.NewTenantUserStore(poolA)
|
|
||||||
storeB := user.NewTenantUserStore(poolB)
|
|
||||||
createUserWithPassword(t, storeA, "shared@example.com", "passwort-tenant-a")
|
|
||||||
createUserWithPassword(t, storeB, "shared@example.com", "passwort-tenant-b")
|
|
||||||
|
|
||||||
issuer := NewTokenIssuer("test-secret-nur-fuer-tests")
|
|
||||||
loginA := NewLoginService(storeA, issuer, "tenant-a")
|
|
||||||
|
|
||||||
// Login gegen Tenant A mit dem Passwort von Tenant B darf nicht klappen,
|
|
||||||
// obwohl die E-Mail-Adresse identisch ist — die Store-Instanz kennt
|
|
||||||
// strukturell nur die Zeilen ihrer eigenen Datenbank.
|
|
||||||
if _, err := loginA.Login(context.Background(), "shared@example.com", "passwort-tenant-b"); !errors.Is(err, ErrInvalidCredentials) {
|
|
||||||
t.Fatalf("erwartet ErrInvalidCredentials fuer fremdes tenant-passwort, habe %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
token, err := loginA.Login(context.Background(), "shared@example.com", "passwort-tenant-a")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("login gegen eigenen tenant sollte klappen: %v", err)
|
|
||||||
}
|
|
||||||
claims, err := issuer.Verify(token)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("verify: %v", err)
|
|
||||||
}
|
|
||||||
if claims.TenantSlug != "tenant-a" {
|
|
||||||
t.Fatalf("token tenant = %q, want tenant-a", claims.TenantSlug)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3: geschuetzte Route ohne gueltige Session nicht erreichbar.
|
|
||||||
func TestRequireAuth_BlocksWithoutValidCookie(t *testing.T) {
|
|
||||||
issuer := NewTokenIssuer("test-secret-nur-fuer-tests")
|
|
||||||
protected := RequireAuth(issuer, func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
})
|
|
||||||
|
|
||||||
// Kein Cookie.
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/geschuetzt", nil)
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
protected(rec, req)
|
|
||||||
if rec.Code != http.StatusUnauthorized {
|
|
||||||
t.Fatalf("ohne cookie: status = %d, want 401", rec.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Manipuliertes Cookie.
|
|
||||||
req = httptest.NewRequest(http.MethodGet, "/geschuetzt", nil)
|
|
||||||
req.AddCookie(&http.Cookie{Name: CookieName, Value: "kaputt.token.hier"})
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
protected(rec, req)
|
|
||||||
if rec.Code != http.StatusUnauthorized {
|
|
||||||
t.Fatalf("mit kaputtem cookie: status = %d, want 401", rec.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gueltiges Token.
|
|
||||||
token, err := issuer.Issue("user-1", "acme")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
req = httptest.NewRequest(http.MethodGet, "/geschuetzt", nil)
|
|
||||||
req.AddCookie(&http.Cookie{Name: CookieName, Value: token})
|
|
||||||
rec = httptest.NewRecorder()
|
|
||||||
protected(rec, req)
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("mit gueltigem cookie: status = %d, want 200", rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
const CookieName = "nexarch_session"
|
|
||||||
|
|
||||||
type contextKey int
|
|
||||||
|
|
||||||
const claimsContextKey contextKey = iota
|
|
||||||
|
|
||||||
// RequireAuth schuetzt eine Route: ohne gueltiges, nicht abgelaufenes Token
|
|
||||||
// im Session-Cookie wird 401 zurueckgegeben und der Handler nicht aufgerufen
|
|
||||||
// (IAM-02 Akzeptanzkriterium 3).
|
|
||||||
func RequireAuth(issuer *TokenIssuer, next http.HandlerFunc) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
cookie, err := r.Cookie(CookieName)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "nicht angemeldet", http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
claims, err := issuer.Verify(cookie.Value)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "nicht angemeldet", http.StatusUnauthorized)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx := context.WithValue(r.Context(), claimsContextKey, claims)
|
|
||||||
next(w, r.WithContext(ctx))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ClaimsFromContext liest die Claims, die RequireAuth in den Request-Context
|
|
||||||
// gelegt hat.
|
|
||||||
func ClaimsFromContext(ctx context.Context) (*Claims, bool) {
|
|
||||||
c, ok := ctx.Value(claimsContextKey).(*Claims)
|
|
||||||
return c, ok
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
// Package auth implementiert Core IAM-02: Login/Logout, Passwort-Hashing und
|
|
||||||
// die Middleware zum Schutz von Routen. Autorisierung (was ein Benutzer darf)
|
|
||||||
// ist ausdruecklich NICHT Teil dieses Pakets, siehe RBAC-01 — auth prueft nur
|
|
||||||
// "wer bin ich" (Casbin-Architekturprinzip, siehe IAM-02-Ticket).
|
|
||||||
package auth
|
|
||||||
|
|
||||||
import "golang.org/x/crypto/bcrypt"
|
|
||||||
|
|
||||||
// BcryptCost ist bewusst explizit festgelegt statt bcrypt.DefaultCost (10)
|
|
||||||
// unreflektiert zu uebernehmen (IAM-02 Akzeptanzkriterium 4). Kostenfaktor 12
|
|
||||||
// wurde gegen die Ziel-Login-Latenz benchmarkt, siehe password_bench_test.go
|
|
||||||
// und den Pruefungs-Eintrag in der Commit-Nachricht.
|
|
||||||
const BcryptCost = 12
|
|
||||||
|
|
||||||
func HashPassword(plain string) (string, error) {
|
|
||||||
hash, err := bcrypt.GenerateFromPassword([]byte(plain), BcryptCost)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return string(hash), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// VerifyPassword ist timing-safe: bcrypt.CompareHashAndPassword vergleicht
|
|
||||||
// konstant in der Zeit bzgl. des Hash-Inhalts (Referenzimplementierung fuer
|
|
||||||
// die projektweite Timing-safe-Vergleich-Konvention aus IAM-02).
|
|
||||||
func VerifyPassword(hash, plain string) bool {
|
|
||||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(plain)) == nil
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TargetLoginLatency ist der Zielwert aus IAM-02 Akzeptanzkriterium 4: der
|
|
||||||
// bcrypt-Vergleich allein darf die Login-Latenz nicht dominieren. 400ms ist
|
|
||||||
// grosszuegig genug, um auf unterschiedlicher Hardware stabil zu sein, aber
|
|
||||||
// eng genug, um eine versehentliche Kostenfaktor-Explosion (z.B. 16 statt 12)
|
|
||||||
// zuverlaessig aufzudecken.
|
|
||||||
const TargetLoginLatency = 400 * time.Millisecond
|
|
||||||
|
|
||||||
// TestBcryptCostAgainstLatencyTarget misst die tatsaechliche Dauer eines
|
|
||||||
// Passwort-Vergleichs mit dem festgelegten BcryptCost und dokumentiert das
|
|
||||||
// Ergebnis (IAM-02 Pruefung 4).
|
|
||||||
func TestBcryptCostAgainstLatencyTarget(t *testing.T) {
|
|
||||||
hash, err := HashPassword("benchmark-passwort")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("hash: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
start := time.Now()
|
|
||||||
if !VerifyPassword(hash, "benchmark-passwort") {
|
|
||||||
t.Fatal("verifikation haette erfolgreich sein muessen")
|
|
||||||
}
|
|
||||||
elapsed := time.Since(start)
|
|
||||||
|
|
||||||
t.Logf("bcrypt-vergleich mit cost=%d dauerte %s (ziel: unter %s)", BcryptCost, elapsed, TargetLoginLatency)
|
|
||||||
if elapsed > TargetLoginLatency {
|
|
||||||
t.Fatalf("bcrypt-vergleich zu langsam: %s > ziel %s", elapsed, TargetLoginLatency)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func BenchmarkVerifyPassword(b *testing.B) {
|
|
||||||
hash, _ := HashPassword("benchmark-passwort")
|
|
||||||
b.ResetTimer()
|
|
||||||
for i := 0; i < b.N; i++ {
|
|
||||||
VerifyPassword(hash, "benchmark-passwort")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import "testing"
|
|
||||||
|
|
||||||
func TestHashAndVerifyPassword(t *testing.T) {
|
|
||||||
hash, err := HashPassword("s3hr-geheim!")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("hash: %v", err)
|
|
||||||
}
|
|
||||||
if hash == "s3hr-geheim!" {
|
|
||||||
t.Fatal("passwort wurde nicht gehasht")
|
|
||||||
}
|
|
||||||
if !VerifyPassword(hash, "s3hr-geheim!") {
|
|
||||||
t.Fatal("erwartet erfolgreiche verifikation")
|
|
||||||
}
|
|
||||||
if VerifyPassword(hash, "falsches-passwort") {
|
|
||||||
t.Fatal("erwartet fehlgeschlagene verifikation")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDummyHashIsValidBcryptHash(t *testing.T) {
|
|
||||||
// Stellt sicher, dass der Timing-Angleichs-Hash in login.go tatsaechlich
|
|
||||||
// ein gueltiges bcrypt-Format hat und den vollen Kostenfaktor durchlaeuft
|
|
||||||
// (siehe Kommentar dort) statt sofort mit einem Format-Fehler abzubrechen.
|
|
||||||
if VerifyPassword(dummyHash, "irgendein-text") {
|
|
||||||
t.Fatal("dummyHash sollte fuer beliebigen text nicht passen")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
)
|
|
||||||
|
|
||||||
// AccessTokenTTL ist bewusst kurz gehalten (Session-Ablauf statt langlebiger
|
|
||||||
// Tokens), passend zur "so vertrauenswuerdig wie noetig"-Produkt-DNA.
|
|
||||||
const AccessTokenTTL = 30 * time.Minute
|
|
||||||
|
|
||||||
var ErrInvalidToken = errors.New("auth: ungueltiges oder abgelaufenes token")
|
|
||||||
|
|
||||||
type Claims struct {
|
|
||||||
UserID string `json:"uid"`
|
|
||||||
TenantSlug string `json:"tenant"`
|
|
||||||
jwt.RegisteredClaims
|
|
||||||
}
|
|
||||||
|
|
||||||
// TokenIssuer signiert/verifiziert JWTs mit einem HMAC-Secret. Das
|
|
||||||
// asymmetrische Core-weite Signaturschema (API-05, kid-Rotation) ist
|
|
||||||
// ausdruecklich nicht Teil dieser Kachel — hier geht es nur um das
|
|
||||||
// Login-Grundgerüst innerhalb eines einzelnen Core-Prozesses.
|
|
||||||
type TokenIssuer struct {
|
|
||||||
secret []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewTokenIssuer(secret string) *TokenIssuer {
|
|
||||||
return &TokenIssuer{secret: []byte(secret)}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *TokenIssuer) Issue(userID, tenantSlug string) (string, error) {
|
|
||||||
now := time.Now()
|
|
||||||
claims := Claims{
|
|
||||||
UserID: userID,
|
|
||||||
TenantSlug: tenantSlug,
|
|
||||||
RegisteredClaims: jwt.RegisteredClaims{
|
|
||||||
IssuedAt: jwt.NewNumericDate(now),
|
|
||||||
ExpiresAt: jwt.NewNumericDate(now.Add(AccessTokenTTL)),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
||||||
return token.SignedString(i.secret)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify prueft Signatur UND Ablauf (jwt.ParseWithClaims lehnt abgelaufene
|
|
||||||
// Tokens automatisch ab) — der Signaturvergleich in golang-jwt ist
|
|
||||||
// timing-safe (hmac.Equal).
|
|
||||||
func (i *TokenIssuer) Verify(tokenString string) (*Claims, error) {
|
|
||||||
claims := &Claims{}
|
|
||||||
token, err := jwt.ParseWithClaims(tokenString, claims, func(t *jwt.Token) (interface{}, error) {
|
|
||||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
||||||
return nil, ErrInvalidToken
|
|
||||||
}
|
|
||||||
return i.secret, nil
|
|
||||||
})
|
|
||||||
if err != nil || !token.Valid {
|
|
||||||
return nil, ErrInvalidToken
|
|
||||||
}
|
|
||||||
return claims, nil
|
|
||||||
}
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestTokenIssueAndVerify(t *testing.T) {
|
|
||||||
issuer := NewTokenIssuer("test-secret-nur-fuer-tests")
|
|
||||||
|
|
||||||
token, err := issuer.Issue("user-1", "acme")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
claims, err := issuer.Verify(token)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("verify: %v", err)
|
|
||||||
}
|
|
||||||
if claims.UserID != "user-1" || claims.TenantSlug != "acme" {
|
|
||||||
t.Fatalf("claims unerwartet: %+v", claims)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pruefung 2: Token-Manipulationstest.
|
|
||||||
func TestTokenVerify_RejectsManipulatedPayload(t *testing.T) {
|
|
||||||
issuer := NewTokenIssuer("test-secret-nur-fuer-tests")
|
|
||||||
token, err := issuer.Issue("user-1", "acme")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
parts := strings.Split(token, ".")
|
|
||||||
if len(parts) != 3 {
|
|
||||||
t.Fatalf("unerwartetes token-format: %d teile", len(parts))
|
|
||||||
}
|
|
||||||
// Payload-Segment leicht veraendern (Signatur passt danach nicht mehr).
|
|
||||||
tampered := parts[0] + "." + parts[1] + "x" + "." + parts[2]
|
|
||||||
|
|
||||||
if _, err := issuer.Verify(tampered); err == nil {
|
|
||||||
t.Fatal("erwartet fehler bei manipuliertem token, habe nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTokenVerify_RejectsWrongSecret(t *testing.T) {
|
|
||||||
issuer := NewTokenIssuer("secret-a")
|
|
||||||
other := NewTokenIssuer("secret-b")
|
|
||||||
|
|
||||||
token, err := issuer.Issue("user-1", "acme")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := other.Verify(token); err == nil {
|
|
||||||
t.Fatal("erwartet fehler bei falschem secret, habe nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pruefung 3: abgelaufenes Token erzwingt Neuanmeldung.
|
|
||||||
func TestTokenVerify_RejectsExpiredToken(t *testing.T) {
|
|
||||||
issuer := NewTokenIssuer("test-secret-nur-fuer-tests")
|
|
||||||
|
|
||||||
claims := Claims{
|
|
||||||
UserID: "user-1",
|
|
||||||
TenantSlug: "acme",
|
|
||||||
RegisteredClaims: jwt.RegisteredClaims{
|
|
||||||
IssuedAt: jwt.NewNumericDate(time.Now().Add(-2 * AccessTokenTTL)),
|
|
||||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(-time.Minute)),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
tok := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
|
||||||
expired, err := tok.SignedString([]byte("test-secret-nur-fuer-tests"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("signieren: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := issuer.Verify(expired); err == nil {
|
|
||||||
t.Fatal("erwartet fehler bei abgelaufenem token, habe nil")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -10,15 +10,8 @@ import (
|
|||||||
// connection info, superadmin accounts) — see nexarch-state.json
|
// connection info, superadmin accounts) — see nexarch-state.json
|
||||||
// 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) {
|
||||||
@@ -27,25 +20,10 @@ 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{
|
return Config{ListenAddr: addr, RegistryDSN: dsn}, nil
|
||||||
ListenAddr: addr,
|
|
||||||
RegistryDSN: dsn,
|
|
||||||
AdminDSN: adminDSN,
|
|
||||||
TenantDSNTemplate: dsnTemplate,
|
|
||||||
}, nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
// Package pflichttestgate erzwingt die in docs/TESTSTRATEGIE-CORE.md Abschnitt 3 festgelegte Regel:
|
||||||
|
// jede geänderte Go-Datei in einem sicherheitskritischen Bereich (Auth, Tenant-Scoping, Policy)
|
||||||
|
// muss von einer geänderten oder neuen _test.go-Datei im selben Package begleitet sein.
|
||||||
|
package pflichttestgate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// sensitivePathPatterns beschreibt die Bereiche aus TESTSTRATEGIE-CORE.md Abschnitt 3.
|
||||||
|
var sensitivePathPatterns = []*regexp.Regexp{
|
||||||
|
regexp.MustCompile(`(^|/)internal/auth/`),
|
||||||
|
regexp.MustCompile(`(^|/)internal/iam/`),
|
||||||
|
regexp.MustCompile(`(^|/)internal/tenant/`),
|
||||||
|
regexp.MustCompile(`(^|/)internal/rbac/`),
|
||||||
|
regexp.MustCompile(`(^|/)internal/policy/`),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Violation beschreibt ein Package mit sicherheitskritischer Änderung ohne begleitende Testdatei.
|
||||||
|
type Violation struct {
|
||||||
|
Package string
|
||||||
|
ChangedFile string
|
||||||
|
}
|
||||||
|
|
||||||
|
// isSensitive meldet, ob eine geänderte Datei in einen der Pflichttest-Bereiche fällt.
|
||||||
|
func isSensitive(file string) bool {
|
||||||
|
if !strings.HasSuffix(file, ".go") || strings.HasSuffix(file, "_test.go") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, re := range sensitivePathPatterns {
|
||||||
|
if re.MatchString(file) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckDiff prüft eine Liste geänderter Dateipfade (z. B. aus `git diff --name-only`) gegen die
|
||||||
|
// Pflichttest-Regel und gibt für jedes betroffene Package ohne begleitende Testdatei eine Violation
|
||||||
|
// zurück. Ein leeres Ergebnis bedeutet: Gate besteht.
|
||||||
|
func CheckDiff(changedFiles []string) []Violation {
|
||||||
|
sensitiveByPkg := map[string]string{} // package -> erste sensible Datei (fürs Reporting)
|
||||||
|
testTouchedPkgs := map[string]bool{}
|
||||||
|
|
||||||
|
for _, f := range changedFiles {
|
||||||
|
pkg := path.Dir(f)
|
||||||
|
if strings.HasSuffix(f, "_test.go") {
|
||||||
|
testTouchedPkgs[pkg] = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if isSensitive(f) {
|
||||||
|
if _, seen := sensitiveByPkg[pkg]; !seen {
|
||||||
|
sensitiveByPkg[pkg] = f
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var violations []Violation
|
||||||
|
for pkg, file := range sensitiveByPkg {
|
||||||
|
if !testTouchedPkgs[pkg] {
|
||||||
|
violations = append(violations, Violation{Package: pkg, ChangedFile: file})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return violations
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package pflichttestgate
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
// Prüfung 1 (QA-01): CI-Lauf mit absichtlich fehlendem Pflichttest schlägt kontrolliert fehl —
|
||||||
|
// Negativtest des Gates selbst.
|
||||||
|
func TestCheckDiff_BlocksAuthChangeWithoutTest(t *testing.T) {
|
||||||
|
changed := []string{
|
||||||
|
"internal/auth/login.go",
|
||||||
|
"internal/apiserver/handler.go", // unkritisch, keine Testpflicht
|
||||||
|
}
|
||||||
|
|
||||||
|
violations := CheckDiff(changed)
|
||||||
|
|
||||||
|
if len(violations) != 1 {
|
||||||
|
t.Fatalf("erwartet 1 Verstoß, bekommen %d: %+v", len(violations), violations)
|
||||||
|
}
|
||||||
|
if violations[0].Package != "internal/auth" {
|
||||||
|
t.Errorf("erwartetes Package internal/auth, bekommen %q", violations[0].Package)
|
||||||
|
}
|
||||||
|
if violations[0].ChangedFile != "internal/auth/login.go" {
|
||||||
|
t.Errorf("erwartete Datei internal/auth/login.go, bekommen %q", violations[0].ChangedFile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckDiff_PassesWhenTestFileAccompaniesChange(t *testing.T) {
|
||||||
|
changed := []string{
|
||||||
|
"internal/auth/login.go",
|
||||||
|
"internal/auth/login_test.go",
|
||||||
|
}
|
||||||
|
|
||||||
|
violations := CheckDiff(changed)
|
||||||
|
|
||||||
|
if len(violations) != 0 {
|
||||||
|
t.Fatalf("erwartet keinen Verstoß, bekommen %+v", violations)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckDiff_PassesForNewTestFileEvenWithoutSourceChange(t *testing.T) {
|
||||||
|
// Nachtraeglich ergaenzter Test fuer bestehenden Code ist erlaubt/erwuenscht.
|
||||||
|
changed := []string{"internal/tenant/registry_test.go"}
|
||||||
|
|
||||||
|
violations := CheckDiff(changed)
|
||||||
|
|
||||||
|
if len(violations) != 0 {
|
||||||
|
t.Fatalf("erwartet keinen Verstoß, bekommen %+v", violations)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckDiff_IgnoresUnrelatedPackages(t *testing.T) {
|
||||||
|
changed := []string{"internal/config/config.go", "internal/db/db.go"}
|
||||||
|
|
||||||
|
violations := CheckDiff(changed)
|
||||||
|
|
||||||
|
if len(violations) != 0 {
|
||||||
|
t.Fatalf("erwartet keinen Verstoß fuer unkritische Pakete, bekommen %+v", violations)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckDiff_CoversAllSensitiveAreas(t *testing.T) {
|
||||||
|
cases := []string{
|
||||||
|
"internal/auth/session.go",
|
||||||
|
"internal/iam/user.go",
|
||||||
|
"internal/tenant/provisioner.go",
|
||||||
|
"internal/rbac/enforcer.go",
|
||||||
|
"internal/policy/decision.go",
|
||||||
|
}
|
||||||
|
for _, f := range cases {
|
||||||
|
violations := CheckDiff([]string{f})
|
||||||
|
if len(violations) != 1 {
|
||||||
|
t.Errorf("Datei %q sollte als sensibel erkannt werden, Verstöße: %+v", f, violations)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckDiff_IgnoresNonGoFiles(t *testing.T) {
|
||||||
|
changed := []string{"internal/auth/README.md"}
|
||||||
|
|
||||||
|
violations := CheckDiff(changed)
|
||||||
|
|
||||||
|
if len(violations) != 0 {
|
||||||
|
t.Fatalf("Nicht-Go-Dateien duerfen keine Testpflicht ausloesen, bekommen %+v", violations)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
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))
|
|
||||||
}
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
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")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
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()
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
// 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
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
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,76 @@
|
|||||||
|
// Package testdbisolation demonstriert und prüft die in docs/TESTSTRATEGIE-CORE.md Abschnitt 4
|
||||||
|
// beschriebene Testdatenbank-Isolation: jeder Test, der eine Tenant-Datenbank braucht,
|
||||||
|
// provisioniert seine eigene, eindeutig benannte DB und räumt sie über Cleanup wieder ab —
|
||||||
|
// keine geteilten Fixture-Datenbanken zwischen parallelen Testläufen.
|
||||||
|
package testdbisolation
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ProvisionEphemeralDB legt unter dem gegebenen Admin-DSN eine neue, eindeutig benannte Datenbank an
|
||||||
|
// und liefert eine Cleanup-Funktion, die sie wieder droppt. adminDSN muss auf eine Wartungs-DB
|
||||||
|
// (z. B. "postgres") zeigen, name muss ein gültiger, bereits eindeutiger Bezeichner sein.
|
||||||
|
func ProvisionEphemeralDB(ctx context.Context, adminDSN, name string) (cleanup func(context.Context) error, err error) {
|
||||||
|
conn, err := pgx.Connect(ctx, adminDSN)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("verbindung zur wartungs-db fehlgeschlagen: %w", err)
|
||||||
|
}
|
||||||
|
defer conn.Close(ctx)
|
||||||
|
|
||||||
|
if _, err := conn.Exec(ctx, fmt.Sprintf("CREATE DATABASE %s", pgx.Identifier{name}.Sanitize())); err != nil {
|
||||||
|
return nil, fmt.Errorf("datenbank %q konnte nicht angelegt werden: %w", name, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanup = func(cleanupCtx context.Context) error {
|
||||||
|
adminConn, err := pgx.Connect(cleanupCtx, adminDSN)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("cleanup: verbindung fehlgeschlagen: %w", err)
|
||||||
|
}
|
||||||
|
defer adminConn.Close(cleanupCtx)
|
||||||
|
_, err = adminConn.Exec(cleanupCtx, fmt.Sprintf("DROP DATABASE IF EXISTS %s", pgx.Identifier{name}.Sanitize()))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return cleanup, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteMarker schreibt einen eindeutigen Beleg-Datensatz in die angegebene Datenbank (verbindet
|
||||||
|
// per dsnForDB), um im Test nachzuweisen, dass zwei parallele Provisionierungen sich nicht sehen.
|
||||||
|
func WriteMarker(ctx context.Context, dsn, table, value string) error {
|
||||||
|
pool, err := pgxpool.New(ctx, dsn)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer pool.Close()
|
||||||
|
|
||||||
|
if _, err := pool.Exec(ctx, fmt.Sprintf(
|
||||||
|
"CREATE TABLE IF NOT EXISTS %s (value text primary key)", pgx.Identifier{table}.Sanitize(),
|
||||||
|
)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = pool.Exec(ctx, fmt.Sprintf("INSERT INTO %s (value) VALUES ($1)", pgx.Identifier{table}.Sanitize()), value)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// CountMarkers zählt die Belegzeilen in der angegebenen Datenbank/Tabelle.
|
||||||
|
func CountMarkers(ctx context.Context, dsn, table string) (int, error) {
|
||||||
|
pool, err := pgxpool.New(ctx, dsn)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer pool.Close()
|
||||||
|
|
||||||
|
if _, err := pool.Exec(ctx, fmt.Sprintf(
|
||||||
|
"CREATE TABLE IF NOT EXISTS %s (value text primary key)", pgx.Identifier{table}.Sanitize(),
|
||||||
|
)); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var n int
|
||||||
|
err = pool.QueryRow(ctx, fmt.Sprintf("SELECT count(*) FROM %s", pgx.Identifier{table}.Sanitize())).Scan(&n)
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package testdbisolation
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestParallelProvisioning_AreIsolated ist der automatisierte Nachweis für QA-01 Prüfung 2:
|
||||||
|
// Testdatenbank-Isolation zwischen parallelen Testläufen. Zwei Provisionierungen laufen
|
||||||
|
// gleichzeitig, jede schreibt einen Beleg-Datensatz in ihre eigene DB — keine darf den
|
||||||
|
// Beleg der jeweils anderen sehen.
|
||||||
|
//
|
||||||
|
// Braucht TEST_ADMIN_DSN (siehe Projekt-Testinfrastruktur), läuft auf dem Testhost, nicht lokal
|
||||||
|
// auf der Entwicklungsmaschine (siehe "no installs"-Regel) — wird ohne gesetzte Variable übersprungen.
|
||||||
|
func TestParallelProvisioning_AreIsolated(t *testing.T) {
|
||||||
|
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
||||||
|
if adminDSN == "" {
|
||||||
|
t.Skip("TEST_ADMIN_DSN nicht gesetzt — Test läuft nur auf dem Testhost, siehe docs/TESTSTRATEGIE-CORE.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
const numParallel = 2
|
||||||
|
dbNames := make([]string, numParallel)
|
||||||
|
for i := range dbNames {
|
||||||
|
dbNames[i] = fmt.Sprintf("qa01_isolation_%d_%d", time.Now().UnixNano(), i)
|
||||||
|
}
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
errs := make([]error, numParallel)
|
||||||
|
cleanups := make([]func(context.Context) error, numParallel)
|
||||||
|
|
||||||
|
for i, name := range dbNames {
|
||||||
|
wg.Add(1)
|
||||||
|
go func(idx int, dbName string) {
|
||||||
|
defer wg.Done()
|
||||||
|
|
||||||
|
cleanup, err := ProvisionEphemeralDB(ctx, adminDSN, dbName)
|
||||||
|
if err != nil {
|
||||||
|
errs[idx] = fmt.Errorf("provisionierung %d fehlgeschlagen: %w", idx, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cleanups[idx] = cleanup
|
||||||
|
|
||||||
|
dbDSN := dsnForDB(adminDSN, dbName)
|
||||||
|
// Jede Goroutine schreibt einen für sie eindeutigen Beleg.
|
||||||
|
if err := WriteMarker(ctx, dbDSN, "isolation_marker", fmt.Sprintf("marker-von-goroutine-%d", idx)); err != nil {
|
||||||
|
errs[idx] = fmt.Errorf("markierung %d fehlgeschlagen: %w", idx, err)
|
||||||
|
}
|
||||||
|
}(i, name)
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
t.Cleanup(func() {
|
||||||
|
for _, cleanup := range cleanups {
|
||||||
|
if cleanup != nil {
|
||||||
|
_ = cleanup(context.Background())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
for i, err := range errs {
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("goroutine %d: %v", i, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Isolationsnachweis: jede DB enthält genau ihren eigenen Beleg (1), keinen fremden.
|
||||||
|
for i, name := range dbNames {
|
||||||
|
dbDSN := dsnForDB(adminDSN, name)
|
||||||
|
count, err := CountMarkers(ctx, dbDSN, "isolation_marker")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("zaehlung in db %d fehlgeschlagen: %v", i, err)
|
||||||
|
}
|
||||||
|
if count != 1 {
|
||||||
|
t.Errorf("db %d (%s): erwartet genau 1 eigenen Beleg, gefunden %d — Isolation verletzt", i, name, count)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// dsnForDB ersetzt den Datenbanknamen im Wartungs-DSN durch den gegebenen Namen.
|
||||||
|
func dsnForDB(adminDSN, dbName string) string {
|
||||||
|
idx := strings.LastIndex(adminDSN, "/")
|
||||||
|
if idx == -1 {
|
||||||
|
return adminDSN
|
||||||
|
}
|
||||||
|
base := adminDSN[:idx+1]
|
||||||
|
rest := adminDSN[idx+1:]
|
||||||
|
if q := strings.Index(rest, "?"); q != -1 {
|
||||||
|
return base + dbName + rest[q:]
|
||||||
|
}
|
||||||
|
return base + dbName
|
||||||
|
}
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Handler stellt die CRUD-API fuer Benutzerkonten bereit (IAM-01-Auftrag).
|
|
||||||
// Auth/Sessions (IAM-02) und Rollen (RBAC-01) sind ausdruecklich nicht Teil
|
|
||||||
// dieser Kachel und daher hier noch nicht angebunden.
|
|
||||||
type Handler struct {
|
|
||||||
users *TenantUserStore
|
|
||||||
superadmins *SuperadminStore
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHandler(users *TenantUserStore, superadmins *SuperadminStore) *Handler {
|
|
||||||
return &Handler{users: users, superadmins: superadmins}
|
|
||||||
}
|
|
||||||
|
|
||||||
type createUserRequest struct {
|
|
||||||
Email string `json:"email"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var req createUserRequest
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
||||||
http.Error(w, "ungueltige Anfrage", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
u, err := h.users.Create(r.Context(), req.Email, req.Name)
|
|
||||||
writeUserResult(w, u, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateSuperadmin legt ein mandantenuebergreifendes Superadmin-Konto an —
|
|
||||||
// bewusst ein eigener Endpunkt statt eines Tenant-Parameters mit Null-Wert.
|
|
||||||
func (h *Handler) CreateSuperadmin(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var req createUserRequest
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
||||||
http.Error(w, "ungueltige Anfrage", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
u, err := h.superadmins.Create(r.Context(), req.Email, req.Name)
|
|
||||||
writeUserResult(w, u, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeUserResult(w http.ResponseWriter, u User, err error) {
|
|
||||||
if err != nil {
|
|
||||||
switch {
|
|
||||||
case errors.Is(err, ErrInvalidEmail), errors.Is(err, ErrEmailTaken):
|
|
||||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
||||||
case errors.Is(err, ErrNotFound):
|
|
||||||
http.Error(w, err.Error(), http.StatusNotFound)
|
|
||||||
default:
|
|
||||||
http.Error(w, "benutzer konnte nicht verarbeitet werden", http.StatusInternalServerError)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
_ = json.NewEncoder(w).Encode(u)
|
|
||||||
}
|
|
||||||
@@ -1,173 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// setupTestDB legt eine frische, isolierte Testdatenbank an, wendet die
|
|
||||||
// uebergebene Migration an und liefert einen verbundenen Pool. Wird ohne
|
|
||||||
// TEST_ADMIN_DSN uebersprungen — siehe internal/tenant/provisioner_test.go
|
|
||||||
// fuer dasselbe Muster.
|
|
||||||
func setupTestDB(t *testing.T, dbName, schemaSQL string) *pgxpool.Pool {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
adminPool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("admin pool: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, _ = adminPool.Exec(ctx, fmt.Sprintf(`DROP DATABASE IF EXISTS %q`, dbName))
|
|
||||||
if _, err := adminPool.Exec(ctx, fmt.Sprintf(`CREATE DATABASE %q`, dbName)); err != nil {
|
|
||||||
t.Fatalf("testdatenbank anlegen: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
dsn := strings.Replace(adminDSN, "/postgres?", "/"+dbName+"?", 1)
|
|
||||||
pool, err := pgxpool.New(ctx, dsn)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("connect testdatenbank: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := pool.Exec(ctx, schemaSQL); err != nil {
|
|
||||||
t.Fatalf("schema anwenden: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Cleanup(func() {
|
|
||||||
pool.Close()
|
|
||||||
_, _ = adminPool.Exec(ctx, fmt.Sprintf(`DROP DATABASE IF EXISTS %q`, dbName))
|
|
||||||
adminPool.Close()
|
|
||||||
})
|
|
||||||
|
|
||||||
return pool
|
|
||||||
}
|
|
||||||
|
|
||||||
const usersSchema = `
|
|
||||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|
||||||
CREATE TABLE users (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
email TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);`
|
|
||||||
|
|
||||||
const superadminsSchema = `
|
|
||||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|
||||||
CREATE TABLE superadmins (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
email TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);`
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 + 3, Pruefung 1 (inkl. Negativfall doppelte E-Mail).
|
|
||||||
func TestTenantUserStore_CRUD(t *testing.T) {
|
|
||||||
pool := setupTestDB(t, "test_iam01_users", usersSchema)
|
|
||||||
store := NewTenantUserStore(pool)
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
created, err := store.Create(ctx, "alice@example.com", "Alice")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("create: %v", err)
|
|
||||||
}
|
|
||||||
if created.Status != StatusActive {
|
|
||||||
t.Fatalf("erwartet status active, hat %q", created.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
got, err := store.Get(ctx, created.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("get: %v", err)
|
|
||||||
}
|
|
||||||
if got.Email != "alice@example.com" {
|
|
||||||
t.Fatalf("get email = %q", got.Email)
|
|
||||||
}
|
|
||||||
|
|
||||||
updated, err := store.Update(ctx, created.ID, "", "Alice A.")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("update: %v", err)
|
|
||||||
}
|
|
||||||
if updated.Name != "Alice A." || updated.Email != "alice@example.com" {
|
|
||||||
t.Fatalf("update ergebnis unerwartet: %+v", updated)
|
|
||||||
}
|
|
||||||
|
|
||||||
list, err := store.List(ctx)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("list: %v", err)
|
|
||||||
}
|
|
||||||
if len(list) != 1 {
|
|
||||||
t.Fatalf("erwartet 1 benutzer, habe %d", len(list))
|
|
||||||
}
|
|
||||||
|
|
||||||
deactivated, err := store.Deactivate(ctx, created.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("deactivate: %v", err)
|
|
||||||
}
|
|
||||||
if deactivated.Status != StatusInactive {
|
|
||||||
t.Fatalf("erwartet status inactive, hat %q", deactivated.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Negativfall: doppelte E-Mail-Adresse.
|
|
||||||
if _, err := store.Create(ctx, "second@example.com", "Bob"); err != nil {
|
|
||||||
t.Fatalf("create second: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := store.Create(ctx, "second@example.com", "Bob Zwei"); !errors.Is(err, ErrEmailTaken) {
|
|
||||||
t.Fatalf("erwartet ErrEmailTaken, habe %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Negativfall: fehlender Benutzer.
|
|
||||||
if _, err := store.Get(ctx, created.ID+"-nicht-vorhanden"); err == nil {
|
|
||||||
t.Fatalf("erwartet fehler bei unbekannter/ungueltiger id")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + Pruefung 2: Superadmin-Anlage ohne Tenant-Kontext.
|
|
||||||
// SuperadminStore.Create hat keinen Tenant-Parameter — es gibt syntaktisch
|
|
||||||
// keine Moeglichkeit, hier versehentlich einen Tenant-Sonderfall zu vergessen.
|
|
||||||
func TestSuperadminStore_CreateWithoutTenantContext(t *testing.T) {
|
|
||||||
pool := setupTestDB(t, "test_iam01_superadmins", superadminsSchema)
|
|
||||||
store := NewSuperadminStore(pool)
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
created, err := store.Create(ctx, "root@nexarch.internal", "Root")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("create superadmin: %v", err)
|
|
||||||
}
|
|
||||||
if created.Status != StatusActive {
|
|
||||||
t.Fatalf("erwartet status active, hat %q", created.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
got, err := store.Get(ctx, created.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("get: %v", err)
|
|
||||||
}
|
|
||||||
if got.Email != "root@nexarch.internal" {
|
|
||||||
t.Fatalf("get email = %q", got.Email)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := store.Create(ctx, "root@nexarch.internal", "Root Zwei"); !errors.Is(err, ErrEmailTaken) {
|
|
||||||
t.Fatalf("erwartet ErrEmailTaken (globale eindeutigkeit), habe %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
deactivated, err := store.Deactivate(ctx, created.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("deactivate: %v", err)
|
|
||||||
}
|
|
||||||
if deactivated.Status != StatusInactive {
|
|
||||||
t.Fatalf("erwartet status inactive, hat %q", deactivated.Status)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// SuperadminStore verwaltet mandantenuebergreifende Superadmin-Konten in der
|
|
||||||
// Control-Plane-Registry (siehe internal/tenant.Registry). Superadmin-ohne-
|
|
||||||
// Tenant ist dadurch ein eigener Typ statt eines Sonderfalls von User/
|
|
||||||
// TenantUserStore — es gibt keinen Tenant-Parameter, den man weglassen
|
|
||||||
// koennte (IAM-01, "ohne Sonderbehandlung im Code").
|
|
||||||
type SuperadminStore struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSuperadminStore(pool *pgxpool.Pool) *SuperadminStore {
|
|
||||||
return &SuperadminStore{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SuperadminStore) Create(ctx context.Context, email, name string) (User, error) {
|
|
||||||
if err := ValidateEmail(email); err != nil {
|
|
||||||
return User{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var u User
|
|
||||||
u.Email, u.Name, u.Status = email, name, StatusActive
|
|
||||||
|
|
||||||
row := s.pool.QueryRow(ctx, `
|
|
||||||
INSERT INTO superadmins (email, name, status)
|
|
||||||
VALUES ($1, $2, $3)
|
|
||||||
RETURNING id, created_at, updated_at
|
|
||||||
`, u.Email, u.Name, u.Status)
|
|
||||||
|
|
||||||
if err := row.Scan(&u.ID, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
|
||||||
return User{}, mapWriteErr(err)
|
|
||||||
}
|
|
||||||
return u, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SuperadminStore) Get(ctx context.Context, id string) (User, error) {
|
|
||||||
return scanUser(s.pool.QueryRow(ctx, `
|
|
||||||
SELECT id, email, name, status, created_at, updated_at
|
|
||||||
FROM superadmins WHERE id = $1
|
|
||||||
`, id))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SuperadminStore) List(ctx context.Context) ([]User, error) {
|
|
||||||
rows, err := s.pool.Query(ctx, `
|
|
||||||
SELECT id, email, name, status, created_at, updated_at
|
|
||||||
FROM superadmins ORDER BY created_at
|
|
||||||
`)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("superadmins auflisten: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var out []User
|
|
||||||
for rows.Next() {
|
|
||||||
var u User
|
|
||||||
if err := rows.Scan(&u.ID, &u.Email, &u.Name, &u.Status, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
|
||||||
return nil, fmt.Errorf("superadmin lesen: %w", err)
|
|
||||||
}
|
|
||||||
out = append(out, u)
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SuperadminStore) Deactivate(ctx context.Context, id string) (User, error) {
|
|
||||||
return scanUser(s.pool.QueryRow(ctx, `
|
|
||||||
UPDATE superadmins SET status = $2, updated_at = now()
|
|
||||||
WHERE id = $1
|
|
||||||
RETURNING id, email, name, status, created_at, updated_at
|
|
||||||
`, id, StatusInactive))
|
|
||||||
}
|
|
||||||
@@ -1,173 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgconn"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TenantUserStore verwaltet Benutzer innerhalb GENAU EINER Tenant-Datenbank.
|
|
||||||
// Welcher Mandant gemeint ist, ergibt sich ausschliesslich aus dem
|
|
||||||
// uebergebenen Pool — es gibt keine tenant_id-Spalte (siehe migrations/tenant/0001_users.up.sql).
|
|
||||||
type TenantUserStore struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewTenantUserStore(pool *pgxpool.Pool) *TenantUserStore {
|
|
||||||
return &TenantUserStore{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *TenantUserStore) Create(ctx context.Context, email, name string) (User, error) {
|
|
||||||
if err := ValidateEmail(email); err != nil {
|
|
||||||
return User{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var u User
|
|
||||||
u.Email, u.Name, u.Status = email, name, StatusActive
|
|
||||||
|
|
||||||
row := s.pool.QueryRow(ctx, `
|
|
||||||
INSERT INTO users (email, name, status)
|
|
||||||
VALUES ($1, $2, $3)
|
|
||||||
RETURNING id, created_at, updated_at
|
|
||||||
`, u.Email, u.Name, u.Status)
|
|
||||||
|
|
||||||
if err := row.Scan(&u.ID, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
|
||||||
return User{}, mapWriteErr(err)
|
|
||||||
}
|
|
||||||
return u, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *TenantUserStore) Get(ctx context.Context, id string) (User, error) {
|
|
||||||
return scanUser(s.pool.QueryRow(ctx, `
|
|
||||||
SELECT id, email, name, status, created_at, updated_at
|
|
||||||
FROM users WHERE id = $1
|
|
||||||
`, id))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *TenantUserStore) List(ctx context.Context) ([]User, error) {
|
|
||||||
rows, err := s.pool.Query(ctx, `
|
|
||||||
SELECT id, email, name, status, created_at, updated_at
|
|
||||||
FROM users ORDER BY created_at
|
|
||||||
`)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("benutzer auflisten: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var out []User
|
|
||||||
for rows.Next() {
|
|
||||||
var u User
|
|
||||||
if err := rows.Scan(&u.ID, &u.Email, &u.Name, &u.Status, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
|
||||||
return nil, fmt.Errorf("benutzer lesen: %w", err)
|
|
||||||
}
|
|
||||||
out = append(out, u)
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update aendert Name und E-Mail. Eine leere email/name laesst das jeweilige
|
|
||||||
// Feld unveraendert.
|
|
||||||
func (s *TenantUserStore) Update(ctx context.Context, id, email, name string) (User, error) {
|
|
||||||
if email != "" {
|
|
||||||
if err := ValidateEmail(email); err != nil {
|
|
||||||
return User{}, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
row := s.pool.QueryRow(ctx, `
|
|
||||||
UPDATE users
|
|
||||||
SET email = COALESCE(NULLIF($2, ''), email),
|
|
||||||
name = COALESCE(NULLIF($3, ''), name),
|
|
||||||
updated_at = now()
|
|
||||||
WHERE id = $1
|
|
||||||
RETURNING id, email, name, status, created_at, updated_at
|
|
||||||
`, id, email, name)
|
|
||||||
|
|
||||||
u, err := scanUser(row)
|
|
||||||
if err != nil {
|
|
||||||
return User{}, mapWriteErr(err)
|
|
||||||
}
|
|
||||||
return u, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deactivate setzt den Benutzer auf inaktiv statt ihn zu loeschen.
|
|
||||||
func (s *TenantUserStore) Deactivate(ctx context.Context, id string) (User, error) {
|
|
||||||
return scanUser(s.pool.QueryRow(ctx, `
|
|
||||||
UPDATE users SET status = $2, updated_at = now()
|
|
||||||
WHERE id = $1
|
|
||||||
RETURNING id, email, name, status, created_at, updated_at
|
|
||||||
`, id, StatusInactive))
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetPasswordHash schreibt einen bereits berechneten bcrypt-Hash (siehe
|
|
||||||
// internal/auth, IAM-02). Der Store selbst kennt kein Klartext-Passwort.
|
|
||||||
func (s *TenantUserStore) SetPasswordHash(ctx context.Context, id, hash string) error {
|
|
||||||
tag, err := s.pool.Exec(ctx, `
|
|
||||||
UPDATE users SET password_hash = $2, updated_at = now() WHERE id = $1
|
|
||||||
`, id, hash)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("passwort setzen: %w", err)
|
|
||||||
}
|
|
||||||
if tag.RowsAffected() == 0 {
|
|
||||||
return ErrNotFound
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// AuthCredentials wird ausschliesslich fuer den Login-Pfad (internal/auth)
|
|
||||||
// verwendet und traegt bewusst den password_hash, damit er nicht ueber den
|
|
||||||
// regulaeren User-Typ/JSON-Serialisierungspfad nach aussen dringen kann.
|
|
||||||
type AuthCredentials struct {
|
|
||||||
User User
|
|
||||||
PasswordHash string
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetByEmailForAuth liefert Benutzer + Passwort-Hash zu einer E-Mail-Adresse
|
|
||||||
// aus GENAU DIESER Tenant-Datenbank — der Tenant-Scope ergibt sich damit
|
|
||||||
// zwingend aus dem verwendeten Pool, es gibt keine Moeglichkeit, versehentlich
|
|
||||||
// ueber Tenant-Grenzen hinweg zu suchen (bekannter archivmail-Fehler, siehe
|
|
||||||
// IAM-02 "Bekannte Fehler vermeiden").
|
|
||||||
func (s *TenantUserStore) GetByEmailForAuth(ctx context.Context, email string) (AuthCredentials, error) {
|
|
||||||
var c AuthCredentials
|
|
||||||
row := s.pool.QueryRow(ctx, `
|
|
||||||
SELECT id, email, name, status, created_at, updated_at, password_hash
|
|
||||||
FROM users WHERE email = $1
|
|
||||||
`, email)
|
|
||||||
|
|
||||||
if err := row.Scan(&c.User.ID, &c.User.Email, &c.User.Name, &c.User.Status,
|
|
||||||
&c.User.CreatedAt, &c.User.UpdatedAt, &c.PasswordHash); err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return AuthCredentials{}, ErrNotFound
|
|
||||||
}
|
|
||||||
return AuthCredentials{}, fmt.Errorf("anmeldedaten lesen: %w", err)
|
|
||||||
}
|
|
||||||
return c, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func scanUser(row pgx.Row) (User, error) {
|
|
||||||
var u User
|
|
||||||
if err := row.Scan(&u.ID, &u.Email, &u.Name, &u.Status, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return User{}, ErrNotFound
|
|
||||||
}
|
|
||||||
return User{}, fmt.Errorf("benutzer lesen: %w", err)
|
|
||||||
}
|
|
||||||
return u, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// mapWriteErr uebersetzt den Unique-Constraint-Verstoss der E-Mail-Spalte in
|
|
||||||
// einen sprechenden Fehler statt der rohen Postgres-Fehlermeldung.
|
|
||||||
func mapWriteErr(err error) error {
|
|
||||||
var pgErr *pgconn.PgError
|
|
||||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
|
||||||
return ErrEmailTaken
|
|
||||||
}
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return ErrNotFound
|
|
||||||
}
|
|
||||||
return fmt.Errorf("benutzer schreiben: %w", err)
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
// Package user implementiert Core IAM-01: das Benutzer-Datenmodell und die
|
|
||||||
// CRUD-Operationen. Tenant-Zugehoerigkeit ist ueber die Zieldatenbank
|
|
||||||
// gegeben (Modell C, siehe internal/tenant) — Superadmin-Konten leben
|
|
||||||
// dagegen mandantenuebergreifend in der Registry und sind ueber
|
|
||||||
// SuperadminStore als eigener, First-Class-Typ modelliert, nicht als
|
|
||||||
// tenant_id-NULL-Sonderfall in User.
|
|
||||||
package user
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"regexp"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Status string
|
|
||||||
|
|
||||||
const (
|
|
||||||
StatusActive Status = "active"
|
|
||||||
StatusInactive Status = "inactive"
|
|
||||||
)
|
|
||||||
|
|
||||||
type User struct {
|
|
||||||
ID string
|
|
||||||
Email string
|
|
||||||
Name string
|
|
||||||
Status Status
|
|
||||||
CreatedAt time.Time
|
|
||||||
UpdatedAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
var emailPattern = regexp.MustCompile(`^[^\s@]+@[^\s@]+\.[^\s@]+$`)
|
|
||||||
|
|
||||||
var ErrInvalidEmail = errors.New("user: ungueltige E-Mail-Adresse")
|
|
||||||
var ErrEmailTaken = errors.New("user: E-Mail-Adresse bereits vergeben")
|
|
||||||
var ErrNotFound = errors.New("user: nicht gefunden")
|
|
||||||
|
|
||||||
func ValidateEmail(email string) error {
|
|
||||||
if !emailPattern.MatchString(email) {
|
|
||||||
return ErrInvalidEmail
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import "testing"
|
|
||||||
|
|
||||||
func TestValidateEmail(t *testing.T) {
|
|
||||||
cases := []struct {
|
|
||||||
email string
|
|
||||||
wantErr bool
|
|
||||||
}{
|
|
||||||
{"a@b.de", false},
|
|
||||||
{"a.b+c@sub.example.com", false},
|
|
||||||
{"", true},
|
|
||||||
{"keine-email", true},
|
|
||||||
{"a@b", true},
|
|
||||||
{"@b.de", true},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, c := range cases {
|
|
||||||
err := ValidateEmail(c.email)
|
|
||||||
if (err != nil) != c.wantErr {
|
|
||||||
t.Errorf("ValidateEmail(%q) error = %v, wantErr %v", c.email, err, c.wantErr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
package webhook
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"crypto/subtle"
|
|
||||||
"encoding/hex"
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DefaultMaxAttempts ist die konfigurierbare Obergrenze, ab der eine
|
|
||||||
// Zustellung endgueltig als fehlgeschlagen gilt (Akzeptanzkriterium 2).
|
|
||||||
const DefaultMaxAttempts = 5
|
|
||||||
|
|
||||||
// DefaultBaseBackoff ist die Basisdauer fuer exponentielles Backoff:
|
|
||||||
// naechster Versuch nach BaseBackoff * 2^attempt (Akzeptanzkriterium 2).
|
|
||||||
const DefaultBaseBackoff = 2 * time.Second
|
|
||||||
|
|
||||||
// Dispatcher liefert faellige Zustellungen aus. Konfigurierbar in Tests
|
|
||||||
// (kleine BaseBackoff, kleine MaxAttempts), damit Retry/Backoff/Obergrenze
|
|
||||||
// ohne minutenlange Wartezeit real durchlaufen werden koennen.
|
|
||||||
type Dispatcher struct {
|
|
||||||
pool pgxIface
|
|
||||||
client *http.Client
|
|
||||||
MaxAttempts int
|
|
||||||
BaseBackoff time.Duration
|
|
||||||
}
|
|
||||||
|
|
||||||
// pgxIface ist die schmale Teilmenge von *pgxpool.Pool, die der Dispatcher
|
|
||||||
// braucht — als Interface, damit Tests keine echte Verbindung fuer reine
|
|
||||||
// Signatur-/Backoff-Logik brauchen (wird hier aber durchgehend mit echten
|
|
||||||
// Integrationstests gegen Postgres verwendet, siehe dispatcher_test.go).
|
|
||||||
type pgxIface interface {
|
|
||||||
Begin(ctx context.Context) (pgx.Tx, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDispatcher(pool pgxIface, client *http.Client) *Dispatcher {
|
|
||||||
if client == nil {
|
|
||||||
client = &http.Client{Timeout: 5 * time.Second}
|
|
||||||
}
|
|
||||||
return &Dispatcher{pool: pool, client: client, MaxAttempts: DefaultMaxAttempts, BaseBackoff: DefaultBaseBackoff}
|
|
||||||
}
|
|
||||||
|
|
||||||
// backoffFor berechnet die Wartezeit vor dem naechsten Versuch: exponentiell
|
|
||||||
// wachsend mit der Anzahl bereits unternommener Versuche.
|
|
||||||
func (d *Dispatcher) backoffFor(attempt int) time.Duration {
|
|
||||||
return d.BaseBackoff * time.Duration(1<<uint(attempt))
|
|
||||||
}
|
|
||||||
|
|
||||||
// ProcessDue liefert ALLE derzeit faelligen Zustellungen aus — dasselbe
|
|
||||||
// SELECT ... FOR UPDATE SKIP LOCKED-Muster wie
|
|
||||||
// internal/tenant.Lifecycle.ProcessDueDeletions, damit mehrere Dispatcher-
|
|
||||||
// Instanzen dieselbe Zustellung nie doppelt bearbeiten.
|
|
||||||
func (d *Dispatcher) ProcessDue(ctx context.Context) (int, error) {
|
|
||||||
tx, err := d.pool.Begin(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return 0, fmt.Errorf("transaktion starten: %w", err)
|
|
||||||
}
|
|
||||||
defer func() { _ = tx.Rollback(ctx) }()
|
|
||||||
|
|
||||||
rows, err := tx.Query(ctx, `
|
|
||||||
SELECT wd.id, wd.payload, wd.attempt, ws.target_url, ws.secret
|
|
||||||
FROM webhook_deliveries wd
|
|
||||||
JOIN webhook_subscriptions ws ON ws.id = wd.subscription_id
|
|
||||||
WHERE wd.status = $1 AND wd.next_attempt_at <= now()
|
|
||||||
FOR UPDATE OF wd SKIP LOCKED
|
|
||||||
`, StatusPending)
|
|
||||||
if err != nil {
|
|
||||||
return 0, fmt.Errorf("faellige zustellungen abfragen: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var deliveries []delivery
|
|
||||||
for rows.Next() {
|
|
||||||
var del delivery
|
|
||||||
if err := rows.Scan(&del.ID, &del.Payload, &del.Attempt, &del.TargetURL, &del.Secret); err != nil {
|
|
||||||
rows.Close()
|
|
||||||
return 0, fmt.Errorf("zustellung lesen: %w", err)
|
|
||||||
}
|
|
||||||
deliveries = append(deliveries, del)
|
|
||||||
}
|
|
||||||
rows.Close()
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, del := range deliveries {
|
|
||||||
d.attemptOne(ctx, tx, del)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := tx.Commit(ctx); err != nil {
|
|
||||||
return 0, fmt.Errorf("transaktion committen: %w", err)
|
|
||||||
}
|
|
||||||
return len(deliveries), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// attemptOne fuehrt GENAU EINEN Zustellversuch aus und aktualisiert den
|
|
||||||
// Zustellungsdatensatz entsprechend — Erfolg (Akzeptanzkriterium 1/Pruefung
|
|
||||||
// 1), erneuter Fehlversuch mit Backoff, oder endgueltiges Scheitern nach
|
|
||||||
// DefaultMaxAttempts (Akzeptanzkriterium 2/Pruefung 2). Ein Fehler bei
|
|
||||||
// GENAU EINER Zustellung darf die anderen in diesem Batch nicht verhindern.
|
|
||||||
func (d *Dispatcher) attemptOne(ctx context.Context, tx pgx.Tx, del delivery) {
|
|
||||||
signature := Sign(del.Secret, del.Payload)
|
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, del.TargetURL, bytes.NewReader(del.Payload))
|
|
||||||
deliveryErr := err
|
|
||||||
var statusCode int
|
|
||||||
if err == nil {
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
req.Header.Set(SignatureHeader, signature)
|
|
||||||
resp, err := d.client.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
deliveryErr = err
|
|
||||||
} else {
|
|
||||||
statusCode = resp.StatusCode
|
|
||||||
resp.Body.Close()
|
|
||||||
if statusCode < 200 || statusCode >= 300 {
|
|
||||||
deliveryErr = fmt.Errorf("unerwarteter statuscode %d", statusCode)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if deliveryErr == nil {
|
|
||||||
_, _ = tx.Exec(ctx, `
|
|
||||||
UPDATE webhook_deliveries SET status = $2, delivered_at = now(), attempt = attempt + 1
|
|
||||||
WHERE id = $1
|
|
||||||
`, del.ID, StatusDelivered)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
nextAttempt := del.Attempt + 1
|
|
||||||
if nextAttempt >= d.MaxAttempts {
|
|
||||||
_, _ = tx.Exec(ctx, `
|
|
||||||
UPDATE webhook_deliveries SET status = $2, attempt = $3, last_error = $4
|
|
||||||
WHERE id = $1
|
|
||||||
`, del.ID, StatusFailed, nextAttempt, deliveryErr.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
nextAttemptAt := time.Now().Add(d.backoffFor(nextAttempt))
|
|
||||||
_, _ = tx.Exec(ctx, `
|
|
||||||
UPDATE webhook_deliveries SET attempt = $2, next_attempt_at = $3, last_error = $4
|
|
||||||
WHERE id = $1
|
|
||||||
`, del.ID, nextAttempt, nextAttemptAt, deliveryErr.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Run ruft ProcessDue in festen Abstaenden auf, bis ctx beendet wird —
|
|
||||||
// dieselbe Konvention wie internal/tenant.Lifecycle.RunSweeper.
|
|
||||||
func (d *Dispatcher) Run(ctx context.Context, interval time.Duration) {
|
|
||||||
ticker := time.NewTicker(interval)
|
|
||||||
defer ticker.Stop()
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return
|
|
||||||
case <-ticker.C:
|
|
||||||
_, _ = d.ProcessDue(ctx)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// VerifySignature prueft empfaengerseitig, ob signature zu payload und
|
|
||||||
// secret passt — timing-safe (dasselbe Muster wie internal/audit.timingsafe),
|
|
||||||
// damit ein Empfaenger die Authentizitaet einer Zustellung pruefen kann
|
|
||||||
// (Akzeptanzkriterium 3).
|
|
||||||
func VerifySignature(secret string, payload []byte, signature string) bool {
|
|
||||||
expected := Sign(secret, payload)
|
|
||||||
expectedBytes, err1 := hex.DecodeString(expected)
|
|
||||||
gotBytes, err2 := hex.DecodeString(signature)
|
|
||||||
if err1 != nil || err2 != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return subtle.ConstantTimeCompare(expectedBytes, gotBytes) == 1
|
|
||||||
}
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
// Package webhook implementiert Core API-07: eine zentrale Webhook-Registry
|
|
||||||
// und Zustellungs-Engine fuer alle Fachmodule (DMS/Mail/Archive/Workflow/AI).
|
|
||||||
// Module reichen Ereignisse EINMAL zur Zustellung ein und implementieren
|
|
||||||
// selbst KEINE eigene Retry-/Signatur-Logik — das ist der zentrale Zweck
|
|
||||||
// dieser Kachel ("Bewusst vermeiden: jedes Modul baut seine eigene
|
|
||||||
// Webhook-Zustellungs-Engine"). Zustellung laeuft ueber dieselbe
|
|
||||||
// Postgres-Jobqueue-Konvention (SELECT ... FOR UPDATE SKIP LOCKED) wie
|
|
||||||
// internal/tenant.Lifecycle.ProcessDueDeletions (TEN-04) und
|
|
||||||
// internal/notify.Dispatcher (CFG-02) — kein Redis/AMQP.
|
|
||||||
package webhook
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/hmac"
|
|
||||||
"crypto/sha256"
|
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
StatusPending = "pending"
|
|
||||||
StatusDelivered = "delivered"
|
|
||||||
StatusFailed = "failed"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Subscription ist EIN externer Abonnent fuer einen Ereignistyp
|
|
||||||
// (Akzeptanzkriterium 1: Module registrieren Ereignistypen, externe
|
|
||||||
// Abonnenten registrieren Ziel-URLs — dieses Paket modelliert die
|
|
||||||
// Abonnenten-Seite; welche Ereignistypen ein Modul anbietet, ist bewusst
|
|
||||||
// NICHT Teil dieser Kachel).
|
|
||||||
type Subscription struct {
|
|
||||||
ID string
|
|
||||||
EventType string
|
|
||||||
TargetURL string
|
|
||||||
Secret string
|
|
||||||
CreatedAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store persistiert Abonnements und Zustellversuche.
|
|
||||||
type Store struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewStore(pool *pgxpool.Pool) *Store {
|
|
||||||
return &Store{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Subscribe registriert einen Abonnenten fuer einen Ereignistyp. secret wird
|
|
||||||
// spaeter zur HMAC-Signierung jeder Zustellung an diesen Abonnenten
|
|
||||||
// verwendet (Akzeptanzkriterium 3).
|
|
||||||
func (s *Store) Subscribe(ctx context.Context, eventType, targetURL, secret string) (Subscription, error) {
|
|
||||||
var sub Subscription
|
|
||||||
sub.EventType, sub.TargetURL, sub.Secret = eventType, targetURL, secret
|
|
||||||
row := s.pool.QueryRow(ctx, `
|
|
||||||
INSERT INTO webhook_subscriptions (event_type, target_url, secret)
|
|
||||||
VALUES ($1, $2, $3)
|
|
||||||
RETURNING id, created_at
|
|
||||||
`, eventType, targetURL, secret)
|
|
||||||
if err := row.Scan(&sub.ID, &sub.CreatedAt); err != nil {
|
|
||||||
return Subscription{}, fmt.Errorf("abonnement anlegen: %w", err)
|
|
||||||
}
|
|
||||||
return sub, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Enqueue reicht EIN Ereignis zur Zustellung an ALLE Abonnenten des
|
|
||||||
// angegebenen Ereignistyps ein — dies ist die EINZIGE Schnittstelle, die
|
|
||||||
// ein Fachmodul braucht (Akzeptanzkriterium 1). Jeder Abonnent erhaelt
|
|
||||||
// einen eigenen, unabhaengigen Zustellversuch-Datensatz.
|
|
||||||
func (s *Store) Enqueue(ctx context.Context, eventType string, payload any) (int, error) {
|
|
||||||
payloadJSON, err := json.Marshal(payload)
|
|
||||||
if err != nil {
|
|
||||||
return 0, fmt.Errorf("payload serialisieren: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
rows, err := s.pool.Query(ctx, `
|
|
||||||
SELECT id FROM webhook_subscriptions WHERE event_type = $1
|
|
||||||
`, eventType)
|
|
||||||
if err != nil {
|
|
||||||
return 0, fmt.Errorf("abonnenten ermitteln: %w", err)
|
|
||||||
}
|
|
||||||
var subscriptionIDs []string
|
|
||||||
for rows.Next() {
|
|
||||||
var id string
|
|
||||||
if err := rows.Scan(&id); err != nil {
|
|
||||||
rows.Close()
|
|
||||||
return 0, fmt.Errorf("abonnent lesen: %w", err)
|
|
||||||
}
|
|
||||||
subscriptionIDs = append(subscriptionIDs, id)
|
|
||||||
}
|
|
||||||
rows.Close()
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, subID := range subscriptionIDs {
|
|
||||||
if _, err := s.pool.Exec(ctx, `
|
|
||||||
INSERT INTO webhook_deliveries (subscription_id, event_type, payload, status, next_attempt_at)
|
|
||||||
VALUES ($1, $2, $3, $4, now())
|
|
||||||
`, subID, eventType, payloadJSON, StatusPending); err != nil {
|
|
||||||
return 0, fmt.Errorf("zustellung einreihen: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return len(subscriptionIDs), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// delivery ist ein interner Datensatz fuer EINEN Zustellversuch, inklusive
|
|
||||||
// der zugehoerigen Abonnentendaten (per JOIN geladen).
|
|
||||||
type delivery struct {
|
|
||||||
ID string
|
|
||||||
TargetURL string
|
|
||||||
Secret string
|
|
||||||
Payload []byte
|
|
||||||
Attempt int
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sign berechnet die HMAC-SHA256-Signatur des Payloads (Akzeptanzkriterium
|
|
||||||
// 3) — hex-kodiert, damit sie problemlos als HTTP-Header uebertragen werden
|
|
||||||
// kann.
|
|
||||||
func Sign(secret string, payload []byte) string {
|
|
||||||
mac := hmac.New(sha256.New, []byte(secret))
|
|
||||||
mac.Write(payload)
|
|
||||||
return hex.EncodeToString(mac.Sum(nil))
|
|
||||||
}
|
|
||||||
|
|
||||||
// SignatureHeader ist der HTTP-Header, unter dem die Signatur uebertragen
|
|
||||||
// wird — dokumentierter Vertrag fuer Empfaenger (Akzeptanzkriterium 3).
|
|
||||||
const SignatureHeader = "X-Nexarch-Signature-256"
|
|
||||||
@@ -1,205 +0,0 @@
|
|||||||
package webhook
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"os"
|
|
||||||
"sync/atomic"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
func setupTest(t *testing.T) (*Store, *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 webhook_subscriptions (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), event_type TEXT NOT NULL,
|
|
||||||
target_url TEXT NOT NULL, secret TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS webhook_deliveries (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), subscription_id UUID NOT NULL REFERENCES webhook_subscriptions(id),
|
|
||||||
event_type TEXT NOT NULL, payload JSONB NOT NULL, status TEXT NOT NULL DEFAULT 'pending',
|
|
||||||
attempt INT NOT NULL DEFAULT 0, next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
last_error TEXT, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), delivered_at TIMESTAMPTZ
|
|
||||||
);
|
|
||||||
`); err != nil {
|
|
||||||
t.Fatalf("schema: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanup := func() { pool.Close() }
|
|
||||||
return NewStore(pool), pool, cleanup
|
|
||||||
}
|
|
||||||
|
|
||||||
func uniqueEventType(prefix string) string {
|
|
||||||
return prefix + "-" + time.Now().Format("150405.000000000")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 + Pruefung 1: ein Modul reicht ein Ereignis ein
|
|
||||||
// (Enqueue) ohne eigene Zustellungslogik, der zentrale Dispatcher liefert
|
|
||||||
// zuverlaessig aus.
|
|
||||||
func TestEnqueueAndProcessDue_DeliversSuccessfully(t *testing.T) {
|
|
||||||
store, pool, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
var receivedBody []byte
|
|
||||||
var receivedSignature string
|
|
||||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
body, _ := io.ReadAll(r.Body)
|
|
||||||
receivedBody = body
|
|
||||||
receivedSignature = r.Header.Get(SignatureHeader)
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}))
|
|
||||||
defer target.Close()
|
|
||||||
|
|
||||||
eventType := uniqueEventType("dms.file.created")
|
|
||||||
sub, err := store.Subscribe(ctx, eventType, target.URL, "geheimes-secret")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("subscribe: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
n, err := store.Enqueue(ctx, eventType, map[string]string{"file_id": "42"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("enqueue: %v", err)
|
|
||||||
}
|
|
||||||
if n != 1 {
|
|
||||||
t.Fatalf("erwartet 1 eingereihte zustellung, habe %d", n)
|
|
||||||
}
|
|
||||||
|
|
||||||
dispatcher := NewDispatcher(pool, target.Client())
|
|
||||||
processed, err := dispatcher.ProcessDue(ctx)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("processdue: %v", err)
|
|
||||||
}
|
|
||||||
if processed != 1 {
|
|
||||||
t.Fatalf("erwartet 1 verarbeitete zustellung, habe %d", processed)
|
|
||||||
}
|
|
||||||
|
|
||||||
var status string
|
|
||||||
if err := pool.QueryRow(ctx, `SELECT status FROM webhook_deliveries WHERE subscription_id = $1`, sub.ID).Scan(&status); err != nil {
|
|
||||||
t.Fatalf("status lesen: %v", err)
|
|
||||||
}
|
|
||||||
if status != StatusDelivered {
|
|
||||||
t.Fatalf("status = %q, want %q", status, StatusDelivered)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Postgres' JSONB-Spalte kann die Byte-Repraesentation des Payloads
|
|
||||||
// gegenueber dem urspruenglichen json.Marshal kanonisieren (z.B.
|
|
||||||
// Leerzeichen) — das ist unschaedlich, denn der Dispatcher signiert
|
|
||||||
// IMMER exakt die Bytes, die er auch sendet. Die Pruefung vergleicht
|
|
||||||
// deshalb Signatur gegen tatsaechlich empfangene Bytes (Selbstkonsistenz),
|
|
||||||
// nicht gegen eine unabhaengig neu marshalte Referenz.
|
|
||||||
if !VerifySignature("geheimes-secret", receivedBody, receivedSignature) {
|
|
||||||
t.Fatalf("empfangene signatur %q passt nicht zum empfangenen payload %q", receivedSignature, receivedBody)
|
|
||||||
}
|
|
||||||
var decoded map[string]string
|
|
||||||
if err := json.Unmarshal(receivedBody, &decoded); err != nil {
|
|
||||||
t.Fatalf("empfangener payload nicht als json lesbar: %v", err)
|
|
||||||
}
|
|
||||||
if decoded["file_id"] != "42" {
|
|
||||||
t.Fatalf("empfangener payload = %v, want file_id=42", decoded)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + Pruefung 2: fehlschlagendes Ziel loest Retry mit
|
|
||||||
// wachsendem Backoff aus und endet nach der konfigurierten Obergrenze in
|
|
||||||
// "failed".
|
|
||||||
func TestProcessDue_RetriesWithBackoffThenMarksFailed(t *testing.T) {
|
|
||||||
store, pool, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
var callCount int32
|
|
||||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
atomic.AddInt32(&callCount, 1)
|
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
|
||||||
}))
|
|
||||||
defer target.Close()
|
|
||||||
|
|
||||||
eventType := uniqueEventType("mail.send.failed")
|
|
||||||
sub, err := store.Subscribe(ctx, eventType, target.URL, "secret")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("subscribe: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := store.Enqueue(ctx, eventType, map[string]string{"x": "y"}); err != nil {
|
|
||||||
t.Fatalf("enqueue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
dispatcher := NewDispatcher(pool, target.Client())
|
|
||||||
dispatcher.MaxAttempts = 2
|
|
||||||
dispatcher.BaseBackoff = 30 * time.Millisecond
|
|
||||||
|
|
||||||
// 1. Versuch: schlaegt fehl, ist aber noch nicht die Obergrenze.
|
|
||||||
if _, err := dispatcher.ProcessDue(ctx); err != nil {
|
|
||||||
t.Fatalf("processdue 1: %v", err)
|
|
||||||
}
|
|
||||||
var status string
|
|
||||||
var attempt int
|
|
||||||
if err := pool.QueryRow(ctx, `SELECT status, attempt FROM webhook_deliveries WHERE subscription_id = $1`, sub.ID).Scan(&status, &attempt); err != nil {
|
|
||||||
t.Fatalf("status lesen 1: %v", err)
|
|
||||||
}
|
|
||||||
if status != StatusPending || attempt != 1 {
|
|
||||||
t.Fatalf("nach 1. fehlschlag: status=%q attempt=%d, want pending/1", status, attempt)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sofort erneut verarbeiten: Backoff ist noch nicht abgelaufen -> nichts faellig.
|
|
||||||
processedTooEarly, err := dispatcher.ProcessDue(ctx)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("processdue (zu frueh): %v", err)
|
|
||||||
}
|
|
||||||
if processedTooEarly != 0 {
|
|
||||||
t.Fatal("erwartet 0 verarbeitete zustellungen, solange backoff nicht abgelaufen ist")
|
|
||||||
}
|
|
||||||
|
|
||||||
time.Sleep(dispatcher.backoffFor(1) + 20*time.Millisecond)
|
|
||||||
|
|
||||||
// 2. Versuch: erreicht MaxAttempts=2 -> endgueltig fehlgeschlagen.
|
|
||||||
if _, err := dispatcher.ProcessDue(ctx); err != nil {
|
|
||||||
t.Fatalf("processdue 2: %v", err)
|
|
||||||
}
|
|
||||||
if err := pool.QueryRow(ctx, `SELECT status, attempt FROM webhook_deliveries WHERE subscription_id = $1`, sub.ID).Scan(&status, &attempt); err != nil {
|
|
||||||
t.Fatalf("status lesen 2: %v", err)
|
|
||||||
}
|
|
||||||
if status != StatusFailed || attempt != 2 {
|
|
||||||
t.Fatalf("nach 2. fehlschlag: status=%q attempt=%d, want failed/2", status, attempt)
|
|
||||||
}
|
|
||||||
if atomic.LoadInt32(&callCount) != 2 {
|
|
||||||
t.Fatalf("erwartet genau 2 tatsaechliche zustellversuche, habe %d", callCount)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3 + Pruefung 3: Signaturpruefung erkennt eine
|
|
||||||
// manipulierte Payload zuverlaessig.
|
|
||||||
func TestVerifySignature_DetectsTamperedPayload(t *testing.T) {
|
|
||||||
secret := "geteiltes-geheimnis"
|
|
||||||
payload := []byte(`{"file_id":"42"}`)
|
|
||||||
signature := Sign(secret, payload)
|
|
||||||
|
|
||||||
if !VerifySignature(secret, payload, signature) {
|
|
||||||
t.Fatal("erwartet gueltige signatur fuer unveraenderte payload")
|
|
||||||
}
|
|
||||||
|
|
||||||
tampered := []byte(`{"file_id":"99"}`)
|
|
||||||
if VerifySignature(secret, tampered, signature) {
|
|
||||||
t.Fatal("erwartet ungueltige signatur fuer manipulierte payload")
|
|
||||||
}
|
|
||||||
|
|
||||||
if VerifySignature("falsches-secret", payload, signature) {
|
|
||||||
t.Fatal("erwartet ungueltige signatur bei falschem secret")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
DROP TABLE IF EXISTS tenants;
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
-- 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()
|
||||||
|
);
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
-- 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()
|
|
||||||
);
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
DROP TABLE IF EXISTS superadmins;
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
-- Superadmin-Konten arbeiten mandantenuebergreifend und leben deshalb in der
|
|
||||||
-- Control-Plane-Registry (siehe TEN-01), nicht in einer Tenant-Datenbank.
|
|
||||||
-- Das bildet "Superadmin ohne Tenant" strukturell als First-Class-Zustand ab,
|
|
||||||
-- statt ihn als Sonderfall in der Tenant-users-Tabelle zu behandeln
|
|
||||||
-- (IAM-01, siehe core-kanban/tickets/IAM-01.md — bekannte Fehler vermeiden).
|
|
||||||
-- E-Mail-Eindeutigkeit ist hier global, da die Registry-DB einmalig existiert.
|
|
||||||
CREATE TABLE superadmins (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
email TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
DROP TABLE webhook_deliveries;
|
|
||||||
DROP TABLE webhook_subscriptions;
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
-- Zentrale Webhook-Registry & Zustellung (API-07, siehe
|
|
||||||
-- core-kanban/tickets/API-07.md) — Postgres-basierte Jobqueue, kein
|
|
||||||
-- Redis/AMQP (Ticket-Vorgabe).
|
|
||||||
CREATE TABLE webhook_subscriptions (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
event_type TEXT NOT NULL,
|
|
||||||
target_url TEXT NOT NULL,
|
|
||||||
secret TEXT NOT NULL,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX webhook_subscriptions_event_type_idx ON webhook_subscriptions (event_type);
|
|
||||||
|
|
||||||
CREATE TABLE webhook_deliveries (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
subscription_id UUID NOT NULL REFERENCES webhook_subscriptions(id),
|
|
||||||
event_type TEXT NOT NULL,
|
|
||||||
payload JSONB NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'pending', -- pending|delivered|failed
|
|
||||||
attempt INT NOT NULL DEFAULT 0,
|
|
||||||
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
last_error TEXT,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
delivered_at TIMESTAMPTZ
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX webhook_deliveries_due_idx ON webhook_deliveries (status, next_attempt_at);
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
DROP TABLE IF EXISTS users;
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
-- Benutzer-Datenmodell (IAM-01, siehe core-kanban/tickets/IAM-01.md).
|
|
||||||
-- Diese Migration laeuft in der DB EINES Mandanten (Modell C, siehe TEN-01) —
|
|
||||||
-- die Tenant-Zugehoerigkeit ist implizit durch die Datenbankverbindung
|
|
||||||
-- gegeben, es gibt daher bewusst KEINE tenant_id-Spalte.
|
|
||||||
-- E-Mail-Eindeutigkeit ist hier tenant-scoped: der UNIQUE-Constraint gilt
|
|
||||||
-- nur innerhalb dieser einen Tenant-Datenbank.
|
|
||||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|
||||||
|
|
||||||
CREATE TABLE users (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
email TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
ALTER TABLE users DROP COLUMN password_hash;
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
-- Passwort-Hash-Spalte fuer Login (IAM-02, siehe core-kanban/tickets/IAM-02.md).
|
|
||||||
-- Enthaelt AUSSCHLIESSLICH den bcrypt-Hash, niemals das Klartext-Passwort.
|
|
||||||
ALTER TABLE users ADD COLUMN password_hash TEXT NOT NULL DEFAULT '';
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
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;"
|
|
||||||
|
|
||||||
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."
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
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
|
|
||||||
Reference in New Issue
Block a user