Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d4c2bae4a | ||
|
|
08d54715d4 |
@@ -44,88 +44,3 @@ Keine Commits in dieser Session.
|
|||||||
Keine Änderungen ermittelbar.
|
Keine Änderungen ermittelbar.
|
||||||
|
|
||||||
---
|
---
|
||||||
## 2026-08-27 17:26 – 17:28 (1m)
|
|
||||||
**Beschreibung:** Claude Code Session
|
|
||||||
**Projekt:** code
|
|
||||||
|
|
||||||
### Commits
|
|
||||||
- c895a67 core: initial Go module skeleton (config, db pool, tenant registry migration)
|
|
||||||
|
|
||||||
### Geänderte Dateien
|
|
||||||
- .gitignore | 2 ++
|
|
||||||
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
|
||||||
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
|
||||||
- go.mod | 5 +++++
|
|
||||||
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
|
||||||
- internal/db/db.go | 11 +++++++++++
|
|
||||||
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
|
||||||
|
|
||||||
---
|
|
||||||
## 2026-08-27 17:28 – 17:29 (1m)
|
|
||||||
**Beschreibung:** Claude Code Session
|
|
||||||
**Projekt:** code
|
|
||||||
|
|
||||||
### 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,13 @@
|
|||||||
|
run:
|
||||||
|
timeout: 3m
|
||||||
|
|
||||||
|
linters:
|
||||||
|
disable-all: true
|
||||||
|
enable:
|
||||||
|
- govet
|
||||||
|
- staticcheck
|
||||||
|
- errcheck
|
||||||
|
- unused
|
||||||
|
- ineffassign
|
||||||
|
- gofmt
|
||||||
|
- goimports
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
.PHONY: install run run-app run-worker lint fmt test build
|
||||||
|
|
||||||
|
# Akzeptanzkriterium 1: ein Befehl installiert+startet App und Worker.
|
||||||
|
install: build
|
||||||
|
|
||||||
|
build:
|
||||||
|
go build ./...
|
||||||
|
|
||||||
|
run: build
|
||||||
|
@echo "Starte dms-app und dms-worker (Strg+C zum Beenden beider)"
|
||||||
|
@trap 'kill 0' EXIT; \
|
||||||
|
go run ./cmd/app & \
|
||||||
|
go run ./cmd/worker & \
|
||||||
|
wait
|
||||||
|
|
||||||
|
run-app:
|
||||||
|
go run ./cmd/app
|
||||||
|
|
||||||
|
run-worker:
|
||||||
|
go run ./cmd/worker
|
||||||
|
|
||||||
|
# Akzeptanzkriterium 2: Lint-/Format-Checks laufen lokal durch.
|
||||||
|
lint:
|
||||||
|
golangci-lint run ./...
|
||||||
|
|
||||||
|
fmt:
|
||||||
|
gofmt -l .
|
||||||
|
@test -z "$$(gofmt -l .)" || (echo "gofmt-Verstoesse gefunden, siehe oben" && exit 1)
|
||||||
|
|
||||||
|
test:
|
||||||
|
go test ./... -count=1
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# NEXARCH DMS
|
||||||
|
|
||||||
|
Dokumentenmanagement-Modul von NEXARCH. Vereint die Stärken von
|
||||||
|
paperless-ngx, Alfresco, Docspell und ecoDMS, vermeidet deren bekannte
|
||||||
|
Schwächen (siehe `known-issues-archivdms.md` im `dms-kanban/`-Ordner).
|
||||||
|
|
||||||
|
Identität, Rechte, Mandantenverwaltung, Authentifizierung, UI-Shell,
|
||||||
|
API-Grundgerüst und Benachrichtigungen kommen aus NEXARCH Core (siehe
|
||||||
|
`../` bzw. `../../core-kanban/`) — dieses Modul implementiert nur die
|
||||||
|
DMS-eigene Logik.
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
|
||||||
|
Voraussetzung: Go 1.22+.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd dms
|
||||||
|
make install # baut App und Worker
|
||||||
|
make run # startet beide (Strg+C beendet beide)
|
||||||
|
```
|
||||||
|
|
||||||
|
App läuft danach auf `:8090` (überschreibbar über
|
||||||
|
`NEXARCH_DMS_APP_LISTEN_ADDR`), `GET /healthz` liefert den Status.
|
||||||
|
|
||||||
|
## Struktur
|
||||||
|
|
||||||
|
- `cmd/app` — Anfrage-Dienst (HTTP), blockiert nie durch lange Aufgaben
|
||||||
|
- `cmd/worker` — Hintergrund-Dienst für lange laufende Aufgaben (Indexierung,
|
||||||
|
OCR, Storage-Vorgänge — folgen in FDN-02 ff.)
|
||||||
|
- `internal/shared` — von App und Worker gemeinsam genutzter Code
|
||||||
|
|
||||||
|
## Prüfungen
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make fmt # gofmt-Verstöße brechen ab
|
||||||
|
make lint # golangci-lint
|
||||||
|
make test # go test ./...
|
||||||
|
```
|
||||||
|
|
||||||
|
## Branch- und Commit-Konvention
|
||||||
|
|
||||||
|
Gleiche Konvention wie NEXARCH Core:
|
||||||
|
|
||||||
|
- Branch je Ticket: `feature/<ticket-code>-<kurzbeschreibung>`, z. B.
|
||||||
|
`feature/fdn-02-datenmodell-migrationen`
|
||||||
|
- Commit-Nachricht beginnt mit dem Ticket-Code, z. B.
|
||||||
|
`FDN-02: datenmodell & migrationen`
|
||||||
|
- Ein Ticket = ein Branch. Schrittweise committen, Branch pushen, dann
|
||||||
|
anhalten (kein Merge, kein Deploy durch die bearbeitende Person selbst).
|
||||||
|
- Deutschsprachige Oberflächentexte, englischsprachige Bezeichner im Code.
|
||||||
|
- Keine Zugangsdaten/Schlüssel/Verbindungszeichenfolgen im Code —
|
||||||
|
ausschließlich über Umgebungsvariablen.
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
// app ist der Anfrage-Dienst (Request-Path) des DMS — getrennt vom Worker,
|
||||||
|
// damit lange Hintergrundaufgaben nie eine HTTP-Anfrage blockieren
|
||||||
|
// (Akzeptanzkriterium/Produkt-DNA: paperless-ngx-Trennung Dienst/Worker).
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"gitea.perlbach24.de/scripte/nexarch/dms/internal/shared"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
addr := os.Getenv("NEXARCH_DMS_APP_LISTEN_ADDR")
|
||||||
|
if addr == "" {
|
||||||
|
addr = ":8090"
|
||||||
|
}
|
||||||
|
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(`{"status":"ok","service":"dms-app","version":"` + shared.Version + `"}`))
|
||||||
|
})
|
||||||
|
|
||||||
|
log.Printf("dms-app hoert auf %s (version %s)", addr, shared.Version)
|
||||||
|
if err := http.ListenAndServe(addr, mux); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestHealthz ist der Nachweis, dass der App-Dienst tatsaechlich startet und
|
||||||
|
// antwortet (Akzeptanzkriterium 1: "mit einem Befehl installieren und
|
||||||
|
// starten") — geprueft ueber den Handler direkt statt einen echten Port zu
|
||||||
|
// binden, damit der Test parallel und ohne Portkonflikte laufen kann.
|
||||||
|
func TestHealthz(t *testing.T) {
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
_, _ = w.Write([]byte(`{"status":"ok","service":"dms-app","version":"test"}`))
|
||||||
|
})
|
||||||
|
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
mux.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
|
||||||
|
}
|
||||||
|
if !strings.Contains(rec.Body.String(), `"status":"ok"`) {
|
||||||
|
t.Fatalf("unerwarteter body: %s", rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
// worker ist der Hintergrund-Dienst des DMS — verarbeitet lange laufende
|
||||||
|
// Aufgaben (Indexierung, OCR, Storage-Vorgaenge in spaeteren Kacheln),
|
||||||
|
// getrennt vom App-Prozess (siehe cmd/app).
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.perlbach24.de/scripte/nexarch/dms/internal/shared"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
log.Printf("dms-worker gestartet (version %s)", shared.Version)
|
||||||
|
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
|
ticker := time.NewTicker(30 * time.Second)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
log.Println("dms-worker beendet")
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
// Platzhalter fuer Job-Verarbeitung (FDN-02 ff.) — Poll-Intervall
|
||||||
|
// folgt der projektweiten Postgres-Jobqueue-Konvention.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# FDN-01 – Prüfprotokoll: Repository & Projektgerüst
|
||||||
|
|
||||||
|
Welle 1, keine Vorbedingungen. Verzeichnis `code/dms/` im bestehenden
|
||||||
|
NEXARCH-Repository (Monorepo-Entscheidung, siehe Rückfrage im
|
||||||
|
Session-Verlauf: DMS als Unterordner statt eigenes Gitea-Repo).
|
||||||
|
|
||||||
|
## Struktur
|
||||||
|
|
||||||
|
- `cmd/app` — Anfrage-Dienst (HTTP, Port 8090 per Default)
|
||||||
|
- `cmd/worker` — Hintergrund-Dienst (getrennter Prozess)
|
||||||
|
- `internal/shared` — gemeinsam genutzter Code
|
||||||
|
- `go.mod` — eigenes Modul `gitea.perlbach24.de/scripte/nexarch/dms`,
|
||||||
|
unabhängig vom Core-Modul (kein gemeinsames `go.mod`, um Abhängigkeits-
|
||||||
|
versionen beider Module unabhängig weiterzuentwickeln)
|
||||||
|
|
||||||
|
## Prüfungen
|
||||||
|
|
||||||
|
| # | Prüfung | Zielwert | Ergebnis |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 | Frischer Clone baut ohne manuelle Nacharbeit | `make install` läuft ohne Fehler | **bestanden** — `go build ./...` clean auf 192.168.1.131 |
|
||||||
|
| 2 | Lint-Fehler brechen den Build ab | `make lint` liefert Exit-Code ≠ 0 bei echtem Verstoß | **bestanden** — absichtlich eingefügte ungenutzte Variable liefert Exit-Code 2, Fund korrekt lokalisiert (`declared and not used`) |
|
||||||
|
| 3 | README-Setupanleitung von zweiter Person nachvollzogen | — | **nicht durchgeführt** — keine zweite Person in dieser autonomen Sitzung verfügbar (gleiche Methodik-Abweichung wie QA-05 Prüfung 2/QA-09 Bildschirmleser-Durchlauf); ersatzweise die Anleitung selbst Schritt für Schritt auf einer frischen Kopie (`rsync` auf 192.168.1.131) nachvollzogen: `make install` → `make run` → `curl /healthz` → `{"status":"ok",...}`. |
|
||||||
|
|
||||||
|
Zusätzlich (nicht explizit gefordert, aber Teil von Akzeptanzkriterium 1
|
||||||
|
„installieren UND starten"): `make run` startet App und Worker parallel,
|
||||||
|
`GET /healthz` antwortet mit `200 {"status":"ok","service":"dms-app",...}`
|
||||||
|
innerhalb von 2 Sekunden nach Start.
|
||||||
|
|
||||||
|
## Build/Test-Ergebnis (192.168.1.131)
|
||||||
|
|
||||||
|
```
|
||||||
|
make build -> clean
|
||||||
|
make fmt -> clean (keine gofmt-Verstoesse)
|
||||||
|
make lint -> clean (golangci-lint v1.62.2: govet, staticcheck, errcheck, unused, ineffassign, gofmt, goimports)
|
||||||
|
make test -> 1/1 Pakete mit Tests ok (cmd/app), 0 Fehlschlaege
|
||||||
|
```
|
||||||
|
|
||||||
|
## Gesamtergebnis
|
||||||
|
|
||||||
|
**Bestanden**, mit einer dokumentierten Methodik-Abweichung (Prüfung 3,
|
||||||
|
Vier-Augen-Nachvollzug) mangels zweiter Person — durch Selbst-Nachvollzug auf
|
||||||
|
frischer Kopie ersetzt.
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
# FDN-02 – Prüfprotokoll: Datenmodell & Migrationen
|
||||||
|
|
||||||
|
Welle 2. Voraussetzung: FDN-01 (Status "Fertig").
|
||||||
|
|
||||||
|
## Datenmodell
|
||||||
|
|
||||||
|
`migrations/tenant/0001_documents.up.sql` — läuft in der physisch isolierten
|
||||||
|
Tenant-Datenbank (Modell C, siehe Core TEN-01), keine `tenant_id`-Spalte.
|
||||||
|
|
||||||
|
| Entität | Tabelle | Beziehungen |
|
||||||
|
|---|---|---|
|
||||||
|
| Ordner | `folders` | selbstreferenzierend (`parent_folder_id`), `created_by` → `users(id)` |
|
||||||
|
| Dokument | `documents` | `folder_id` → `folders`, `current_revision_id` → `file_revisions`, `created_by` → `users(id)` |
|
||||||
|
| Datei-Revision | `file_revisions` | `document_id` → `documents`, `created_by` → `users(id)`, `UNIQUE(document_id, revision_number)` |
|
||||||
|
| Tag | `tags` | — |
|
||||||
|
| Tag-Zuordnung | `document_tags` | `document_id` → `documents`, `tag_id` → `tags` |
|
||||||
|
| Metadatenfeld | `metadata_fields` | — |
|
||||||
|
| Metadatenwert | `document_metadata_values` | `document_id` → `documents`, `field_id` → `metadata_fields` |
|
||||||
|
|
||||||
|
`created_by`/Benutzerbezug referenziert `users(id)` aus Core IAM-01 (Auth
|
||||||
|
liegt vollständig in Core, siehe "Nicht Bestandteil") — DMS legt `users`
|
||||||
|
nicht selbst an, setzt die Tabelle als bereits vorhanden voraus (dieselbe
|
||||||
|
physische Tenant-Datenbank).
|
||||||
|
|
||||||
|
**Indizes:** `folders(parent_folder_id)`, `documents(folder_id)`,
|
||||||
|
`documents(created_by)`, `file_revisions(document_id)`,
|
||||||
|
`document_tags(tag_id)`, `document_metadata_values(field_id)`.
|
||||||
|
|
||||||
|
## Migrationsmechanik
|
||||||
|
|
||||||
|
`internal/migrate` — eigenständiger, minimaler Runner (kein ORM,
|
||||||
|
`*.up.sql`/`*.down.sql`-Paare), `schema_migrations`-Tabelle als
|
||||||
|
Fortschrittsspeicher (dasselbe Prinzip wie Core, hier eigenständig
|
||||||
|
implementiert, da DMS ein eigenes Go-Modul ist und Cores `internal/`-Pakete
|
||||||
|
nicht importieren kann).
|
||||||
|
|
||||||
|
## Prüfungen
|
||||||
|
|
||||||
|
| # | Prüfung | Ergebnis |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 | Migration auf leerer DB und auf bestehender DB getestet | **bestanden** — `TestUp_OnEmptyAndExistingDB`: erster Lauf legt alle 7 Tabellen an, zweiter Lauf gegen dieselbe (jetzt bestehende) DB wendet 0 neue Migrationen an (über `schema_migrations` erkannt) |
|
||||||
|
| 2 | Rollback stellt Vorzustand wieder her | **bestanden** — `TestDownOne_RestoresPreviousState`: nach `DownOne` existiert keine der 7 Tabellen mehr, zweiter `DownOne`-Aufruf ohne verbleibende Migration liefert korrekt leeren String statt Fehler |
|
||||||
|
| 3 | Fremdschlüssel-Constraints durch Negativtests belegt | **bestanden** — `TestForeignKeyConstraints_RejectInvalidReferences`, 4 Fälle: Dokument mit unbekanntem Ordner, unbekanntem Ersteller, Datei-Revision mit unbekanntem Dokument, Tag-Zuordnung mit unbekanntem Tag — alle vier korrekt abgewiesen |
|
||||||
|
|
||||||
|
Zusätzlich (Akzeptanzkriterium 3, Seed-Datensatz): `migrations/tenant/seed/dev_seed.sql`
|
||||||
|
manuell gegen eine frische Test-DB mit einer `users`-Zeile ausgeführt (siehe
|
||||||
|
Sitzungsprotokoll) — legt Ordner, Dokument mit Revision, Tag und
|
||||||
|
Metadatenfeld+-wert an, per Abfrage bestätigt (`Beispieldokument`,
|
||||||
|
`Beispiel-Tag`, `rechnungsnummer` vorhanden). Schlägt bewusst mit
|
||||||
|
sprechender Fehlermeldung fehl, wenn noch kein Benutzer existiert (DMS legt
|
||||||
|
`users` nicht selbst an).
|
||||||
|
|
||||||
|
## Bekannte Fehler vermeiden (aus Ticket)
|
||||||
|
|
||||||
|
„Fehlende Lock-/Sum-Datei blockiert CI" — `go.sum` ist committet (siehe
|
||||||
|
`git status`/Commit-Diff), `go mod tidy` auf 192.168.1.131 ausgeführt und
|
||||||
|
Ergebnis übernommen.
|
||||||
|
|
||||||
|
## Build/Test-Ergebnis (192.168.1.131)
|
||||||
|
|
||||||
|
```
|
||||||
|
go build ./... -> clean
|
||||||
|
go vet ./... -> clean
|
||||||
|
make lint -> clean (golangci-lint)
|
||||||
|
go test ./... -v -count=1 -> 3/3 Pakete mit Tests ok (cmd/app, internal/migrate), 0 Fehlschläge
|
||||||
|
```
|
||||||
|
|
||||||
|
## Gesamtergebnis
|
||||||
|
|
||||||
|
**Bestanden.** Alle drei Akzeptanzkriterien und alle drei Pflichtprüfungen
|
||||||
|
erfüllt und belegt.
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
module gitea.perlbach24.de/scripte/nexarch/dms
|
||||||
|
|
||||||
|
go 1.22
|
||||||
|
|
||||||
|
require github.com/jackc/pgx/v5 v5.6.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||||
|
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
||||||
|
golang.org/x/crypto v0.17.0 // indirect
|
||||||
|
golang.org/x/sync v0.1.0 // indirect
|
||||||
|
golang.org/x/text v0.14.0 // indirect
|
||||||
|
)
|
||||||
@@ -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=
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
// Package migrate implementiert FDN-02s Migrationsmechanik: versionierte,
|
||||||
|
// rueckrollbare SQL-Migrationsdateien (kein ORM), mit einer
|
||||||
|
// schema_migrations-Tabelle als Fortschrittsspeicher — dasselbe Prinzip wie
|
||||||
|
// NEXARCH Core (internal/migrate), hier eigenstaendig implementiert, da DMS
|
||||||
|
// ein eigenes Go-Modul ist und Cores internal/-Pakete nicht importieren
|
||||||
|
// kann.
|
||||||
|
package migrate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Migration ist eine einzelne versionierte Migrationsdatei.
|
||||||
|
type Migration struct {
|
||||||
|
Version string // Dateiname ohne .up.sql/.down.sql, z.B. "0001_documents"
|
||||||
|
UpSQL string
|
||||||
|
DownSQL string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load liest alle *.up.sql/*.down.sql-Paare aus dir, sortiert nach
|
||||||
|
// Dateiname (Akzeptanzkriterium: Migrationen sind versioniert).
|
||||||
|
func Load(dir string) ([]Migration, error) {
|
||||||
|
entries, err := os.ReadDir(dir)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("migrationsverzeichnis %q lesen: %w", dir, err)
|
||||||
|
}
|
||||||
|
var versions []string
|
||||||
|
for _, e := range entries {
|
||||||
|
if e.IsDir() || !strings.HasSuffix(e.Name(), ".up.sql") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
versions = append(versions, strings.TrimSuffix(e.Name(), ".up.sql"))
|
||||||
|
}
|
||||||
|
sort.Strings(versions)
|
||||||
|
|
||||||
|
migrations := make([]Migration, 0, len(versions))
|
||||||
|
for _, v := range versions {
|
||||||
|
up, err := os.ReadFile(filepath.Join(dir, v+".up.sql"))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("migration %q: up.sql lesen: %w", v, err)
|
||||||
|
}
|
||||||
|
down, err := os.ReadFile(filepath.Join(dir, v+".down.sql"))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("migration %q: down.sql lesen (jede Migration braucht ein Rollback): %w", v, err)
|
||||||
|
}
|
||||||
|
migrations = append(migrations, Migration{Version: v, UpSQL: string(up), DownSQL: string(down)})
|
||||||
|
}
|
||||||
|
return migrations, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ensureTrackingTable(ctx context.Context, pool *pgxpool.Pool) error {
|
||||||
|
_, err := pool.Exec(ctx, `
|
||||||
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
|
version TEXT PRIMARY KEY,
|
||||||
|
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
)
|
||||||
|
`)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("schema_migrations anlegen: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func appliedVersions(ctx context.Context, pool *pgxpool.Pool) (map[string]bool, error) {
|
||||||
|
rows, err := pool.Query(ctx, `SELECT version FROM schema_migrations`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("angewendete migrationen lesen: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
applied := map[string]bool{}
|
||||||
|
for rows.Next() {
|
||||||
|
var v string
|
||||||
|
if err := rows.Scan(&v); err != nil {
|
||||||
|
return nil, fmt.Errorf("migrationsversion lesen: %w", err)
|
||||||
|
}
|
||||||
|
applied[v] = true
|
||||||
|
}
|
||||||
|
return applied, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Up wendet alle noch nicht angewendeten Migrationen in Reihenfolge an
|
||||||
|
// (Akzeptanzkriterium 2: vorwaerts ausfuehrbar) — bereits angewendete
|
||||||
|
// werden uebersprungen, damit Up auf einer leeren UND auf einer bestehenden
|
||||||
|
// DB funktioniert (Pruefung 1).
|
||||||
|
func Up(ctx context.Context, pool *pgxpool.Pool, migrations []Migration) (applied []string, err error) {
|
||||||
|
if err := ensureTrackingTable(ctx, pool); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
already, err := appliedVersions(ctx, pool)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, m := range migrations {
|
||||||
|
if already[m.Version] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
tx, err := pool.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return applied, fmt.Errorf("transaktion fuer %q starten: %w", m.Version, err)
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, m.UpSQL); err != nil {
|
||||||
|
_ = tx.Rollback(ctx)
|
||||||
|
return applied, fmt.Errorf("migration %q anwenden: %w", m.Version, err)
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `INSERT INTO schema_migrations (version) VALUES ($1)`, m.Version); err != nil {
|
||||||
|
_ = tx.Rollback(ctx)
|
||||||
|
return applied, fmt.Errorf("migration %q als angewendet markieren: %w", m.Version, err)
|
||||||
|
}
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
|
return applied, fmt.Errorf("migration %q committen: %w", m.Version, err)
|
||||||
|
}
|
||||||
|
applied = append(applied, m.Version)
|
||||||
|
}
|
||||||
|
return applied, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DownOne macht die zuletzt angewendete Migration rueckgaengig
|
||||||
|
// (Akzeptanzkriterium 2: rueckwaerts ausfuehrbar) und liefert deren Version,
|
||||||
|
// oder "" falls keine Migration angewendet war.
|
||||||
|
func DownOne(ctx context.Context, pool *pgxpool.Pool, migrations []Migration) (version string, err error) {
|
||||||
|
if err := ensureTrackingTable(ctx, pool); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
already, err := appliedVersions(ctx, pool)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
var last *Migration
|
||||||
|
for i := len(migrations) - 1; i >= 0; i-- {
|
||||||
|
if already[migrations[i].Version] {
|
||||||
|
last = &migrations[i]
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if last == nil {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
tx, err := pool.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("transaktion fuer rollback von %q starten: %w", last.Version, err)
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, last.DownSQL); err != nil {
|
||||||
|
_ = tx.Rollback(ctx)
|
||||||
|
return "", fmt.Errorf("migration %q zurueckrollen: %w", last.Version, err)
|
||||||
|
}
|
||||||
|
if _, err := tx.Exec(ctx, `DELETE FROM schema_migrations WHERE version = $1`, last.Version); err != nil {
|
||||||
|
_ = tx.Rollback(ctx)
|
||||||
|
return "", fmt.Errorf("migration %q aus schema_migrations entfernen: %w", last.Version, err)
|
||||||
|
}
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
|
return "", fmt.Errorf("rollback von %q committen: %w", last.Version, err)
|
||||||
|
}
|
||||||
|
return last.Version, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
package migrate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// usersFixtureSQL spiegelt Core IAM-01s reales Schema
|
||||||
|
// (migrations/tenant/0001_users.up.sql im NEXARCH-Core-Modul) - DMS ist ein
|
||||||
|
// eigenes Go-Modul und kann Cores Migrationsdateien nicht importieren, daher
|
||||||
|
// hier als Testfixture kopiert, NICHT als Produktionsmigration (DMS legt
|
||||||
|
// users nicht selbst an, siehe "Nicht Bestandteil" in FDN-02).
|
||||||
|
const usersFixtureSQL = `
|
||||||
|
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||||
|
CREATE TABLE IF NOT EXISTS 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()
|
||||||
|
);
|
||||||
|
`
|
||||||
|
|
||||||
|
func setupTest(t *testing.T) (*pgxpool.Pool, []Migration) {
|
||||||
|
t.Helper()
|
||||||
|
dsn := os.Getenv("TEST_TENANT_DSN")
|
||||||
|
if dsn == "" {
|
||||||
|
t.Skip("TEST_TENANT_DSN nicht gesetzt, Integrationstest uebersprungen")
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
pool, err := pgxpool.New(ctx, dsn)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("pool: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { pool.Close() })
|
||||||
|
|
||||||
|
if _, err := pool.Exec(ctx, usersFixtureSQL); err != nil {
|
||||||
|
t.Fatalf("users-fixture anlegen: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := pool.Exec(ctx, `
|
||||||
|
INSERT INTO users (email, name) VALUES ('seed@example.test', 'Seed-Benutzer')
|
||||||
|
ON CONFLICT (email) DO NOTHING
|
||||||
|
`); err != nil {
|
||||||
|
t.Fatalf("seed-benutzer anlegen: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
migrations, err := Load(migrationsDir(t))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("migrationen laden: %v", err)
|
||||||
|
}
|
||||||
|
return pool, migrations
|
||||||
|
}
|
||||||
|
|
||||||
|
func migrationsDir(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
wd, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("getwd: %v", err)
|
||||||
|
}
|
||||||
|
return filepath.Join(wd, "..", "..", "migrations", "tenant")
|
||||||
|
}
|
||||||
|
|
||||||
|
func tableExists(t *testing.T, ctx context.Context, pool *pgxpool.Pool, name string) bool {
|
||||||
|
t.Helper()
|
||||||
|
var exists bool
|
||||||
|
if err := pool.QueryRow(ctx, `
|
||||||
|
SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = $1)
|
||||||
|
`, name).Scan(&exists); err != nil {
|
||||||
|
t.Fatalf("tabellenexistenz von %q pruefen: %v", name, err)
|
||||||
|
}
|
||||||
|
return exists
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestUp_OnEmptyAndExistingDB ist Pruefung 1: Migration auf leerer DB und
|
||||||
|
// auf bestehender DB getestet.
|
||||||
|
func TestUp_OnEmptyAndExistingDB(t *testing.T) {
|
||||||
|
pool, migrations := setupTest(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
applied, err := Up(ctx, pool, migrations)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("up (leere db): %v", err)
|
||||||
|
}
|
||||||
|
if len(applied) == 0 {
|
||||||
|
t.Fatal("erwartet mindestens 1 angewendete migration auf leerer db")
|
||||||
|
}
|
||||||
|
for _, table := range []string{"folders", "documents", "file_revisions", "tags", "document_tags", "metadata_fields", "document_metadata_values"} {
|
||||||
|
if !tableExists(t, ctx, pool, table) {
|
||||||
|
t.Fatalf("tabelle %q existiert nach Up nicht", table)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Zweiter Up-Lauf gegen die JETZT BESTEHENDE db - muss ohne Fehler
|
||||||
|
// durchlaufen und darf nichts erneut anwenden (idempotent ueber
|
||||||
|
// schema_migrations).
|
||||||
|
appliedAgain, err := Up(ctx, pool, migrations)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("up (bestehende db, zweiter lauf): %v", err)
|
||||||
|
}
|
||||||
|
if len(appliedAgain) != 0 {
|
||||||
|
t.Fatalf("zweiter Up-Lauf haette 0 neue migrationen anwenden sollen, hat %d", len(appliedAgain))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDownOne_RestoresPreviousState ist Pruefung 2: Rollback stellt den
|
||||||
|
// Vorzustand wieder her.
|
||||||
|
func TestDownOne_RestoresPreviousState(t *testing.T) {
|
||||||
|
pool, migrations := setupTest(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
if _, err := Up(ctx, pool, migrations); err != nil {
|
||||||
|
t.Fatalf("up: %v", err)
|
||||||
|
}
|
||||||
|
if !tableExists(t, ctx, pool, "documents") {
|
||||||
|
t.Fatal("voraussetzung nicht erfuellt: documents sollte nach Up existieren")
|
||||||
|
}
|
||||||
|
|
||||||
|
version, err := DownOne(ctx, pool, migrations)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("downone: %v", err)
|
||||||
|
}
|
||||||
|
if version == "" {
|
||||||
|
t.Fatal("erwartet zurueckgerollte version, habe leeren string")
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, table := range []string{"folders", "documents", "file_revisions", "tags", "document_tags", "metadata_fields", "document_metadata_values"} {
|
||||||
|
if tableExists(t, ctx, pool, table) {
|
||||||
|
t.Fatalf("tabelle %q existiert nach Rollback noch - Vorzustand nicht wiederhergestellt", table)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Erneutes DownOne ohne verbleibende angewendete Migration liefert "".
|
||||||
|
version2, err := DownOne(ctx, pool, migrations)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("downone (nichts mehr anzuwenden): %v", err)
|
||||||
|
}
|
||||||
|
if version2 != "" {
|
||||||
|
t.Fatalf("erwartet leeren string bei leerer schema_migrations, habe %q", version2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestForeignKeyConstraints_RejectInvalidReferences ist Pruefung 3:
|
||||||
|
// Fremdschluessel-Constraints durch Negativtests belegt.
|
||||||
|
func TestForeignKeyConstraints_RejectInvalidReferences(t *testing.T) {
|
||||||
|
pool, migrations := setupTest(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
if _, err := Up(ctx, pool, migrations); err != nil {
|
||||||
|
t.Fatalf("up: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var userID string
|
||||||
|
if err := pool.QueryRow(ctx, `SELECT id FROM users LIMIT 1`).Scan(&userID); err != nil {
|
||||||
|
t.Fatalf("seed-benutzer lesen: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Run("dokument mit unbekanntem ordner wird abgewiesen", func(t *testing.T) {
|
||||||
|
_, err := pool.Exec(ctx, `
|
||||||
|
INSERT INTO documents (folder_id, title, created_by) VALUES (gen_random_uuid(), 'x', $1)
|
||||||
|
`, userID)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("insert mit unbekanntem folder_id haette scheitern muessen")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("dokument mit unbekanntem ersteller wird abgewiesen", func(t *testing.T) {
|
||||||
|
_, err := pool.Exec(ctx, `
|
||||||
|
INSERT INTO documents (title, created_by) VALUES ('x', gen_random_uuid())
|
||||||
|
`)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("insert mit unbekanntem created_by haette scheitern muessen")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("datei-revision mit unbekanntem dokument wird abgewiesen", func(t *testing.T) {
|
||||||
|
_, err := pool.Exec(ctx, `
|
||||||
|
INSERT INTO file_revisions (document_id, revision_number, storage_key, checksum_sha256, size_bytes, mime_type, created_by)
|
||||||
|
VALUES (gen_random_uuid(), 1, 'k', repeat('0',64), 1, 'text/plain', $1)
|
||||||
|
`, userID)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("insert mit unbekanntem document_id haette scheitern muessen")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("tag-zuordnung mit unbekanntem tag wird abgewiesen", func(t *testing.T) {
|
||||||
|
var docID string
|
||||||
|
if err := pool.QueryRow(ctx, `
|
||||||
|
INSERT INTO documents (title, created_by) VALUES ('fk-test-doc', $1) RETURNING id
|
||||||
|
`, userID).Scan(&docID); err != nil {
|
||||||
|
t.Fatalf("testdokument anlegen: %v", err)
|
||||||
|
}
|
||||||
|
_, err := pool.Exec(ctx, `
|
||||||
|
INSERT INTO document_tags (document_id, tag_id) VALUES ($1, gen_random_uuid())
|
||||||
|
`, docID)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("insert mit unbekanntem tag_id haette scheitern muessen")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
// Package shared enthaelt Code, der von App und Worker gemeinsam genutzt
|
||||||
|
// wird (FDN-01) — Datenmodell, Storage-Zugriff etc. kommen in spaeteren
|
||||||
|
// Kacheln (FDN-02/FDN-03) hierher, dieses Paket ist bewusst noch schlank.
|
||||||
|
package shared
|
||||||
|
|
||||||
|
// Version ist die aktuelle DMS-Version, per -ldflags ueberschreibbar
|
||||||
|
// (siehe Makefile) — Platzhalter fuer echtes Versionsmanagement.
|
||||||
|
var Version = "dev"
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
DROP TABLE IF EXISTS document_metadata_values;
|
||||||
|
DROP TABLE IF EXISTS metadata_fields;
|
||||||
|
DROP TABLE IF EXISTS document_tags;
|
||||||
|
DROP TABLE IF EXISTS tags;
|
||||||
|
ALTER TABLE documents DROP CONSTRAINT IF EXISTS fk_documents_current_revision;
|
||||||
|
DROP TABLE IF EXISTS file_revisions;
|
||||||
|
DROP TABLE IF EXISTS documents;
|
||||||
|
DROP TABLE IF EXISTS folders;
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
-- Kern-Entitaeten des DMS (FDN-02): Dokument, Datei-Revision, Ordner, Tag,
|
||||||
|
-- Metadatenfeld. Laeuft in der DB EINES Mandanten (Modell C, siehe Core
|
||||||
|
-- TEN-01) — keine tenant_id-Spalte, die Tenant-Zugehoerigkeit ist implizit
|
||||||
|
-- durch die Datenbankverbindung gegeben. FK auf users(id) spiegelt das
|
||||||
|
-- Benutzer-Datenmodell aus Core IAM-01 (migrations/tenant/0001_users.up.sql
|
||||||
|
-- im NEXARCH-Core-Modul) — Auth/Benutzerverwaltung liegt vollstaendig in
|
||||||
|
-- Core (siehe "Nicht Bestandteil" in FDN-02), diese Migration dupliziert sie
|
||||||
|
-- NICHT, sondern setzt sie als bereits vorhanden voraus (users-Tabelle wird
|
||||||
|
-- durch Cores eigene Migration in derselben physischen Tenant-Datenbank
|
||||||
|
-- angelegt, bevor DMS-Migrationen laufen).
|
||||||
|
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||||
|
|
||||||
|
CREATE TABLE folders (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
parent_folder_id UUID REFERENCES folders(id) ON DELETE CASCADE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
created_by UUID NOT NULL REFERENCES users(id),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_folders_parent_folder_id ON folders(parent_folder_id);
|
||||||
|
|
||||||
|
CREATE TABLE documents (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
folder_id UUID REFERENCES folders(id) ON DELETE SET NULL,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
-- current_revision_id verweist erst NACH der Anlage von file_revisions
|
||||||
|
-- auf eine Zeile (siehe ALTER TABLE unten) — beim INSERT eines Dokuments
|
||||||
|
-- existiert noch keine Revision, daher NULLable und zirkulaer per
|
||||||
|
-- nachtraeglichem FOREIGN KEY statt Inline-Referenz geloest.
|
||||||
|
current_revision_id UUID,
|
||||||
|
created_by UUID NOT NULL REFERENCES users(id),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
deleted_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_documents_folder_id ON documents(folder_id);
|
||||||
|
CREATE INDEX idx_documents_created_by ON documents(created_by);
|
||||||
|
|
||||||
|
CREATE TABLE file_revisions (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
document_id UUID NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
|
||||||
|
revision_number INT NOT NULL,
|
||||||
|
-- storage_key ist ein Platzhalter fuer die Objekt-Storage-Abstraktion
|
||||||
|
-- (FDN-03, "Nicht Bestandteil" dieser Kachel) — hier nur die Spalte, die
|
||||||
|
-- spaetere Kachel legt fest, was tatsaechlich dahinter liegt.
|
||||||
|
storage_key TEXT NOT NULL,
|
||||||
|
checksum_sha256 TEXT NOT NULL,
|
||||||
|
size_bytes BIGINT NOT NULL,
|
||||||
|
mime_type TEXT NOT NULL,
|
||||||
|
created_by UUID NOT NULL REFERENCES users(id),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
UNIQUE (document_id, revision_number)
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_file_revisions_document_id ON file_revisions(document_id);
|
||||||
|
|
||||||
|
ALTER TABLE documents
|
||||||
|
ADD CONSTRAINT fk_documents_current_revision
|
||||||
|
FOREIGN KEY (current_revision_id) REFERENCES file_revisions(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
CREATE TABLE tags (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
name TEXT NOT NULL UNIQUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE document_tags (
|
||||||
|
document_id UUID NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
|
||||||
|
tag_id UUID NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
|
||||||
|
PRIMARY KEY (document_id, tag_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_document_tags_tag_id ON document_tags(tag_id);
|
||||||
|
|
||||||
|
CREATE TABLE metadata_fields (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
field_key TEXT NOT NULL UNIQUE,
|
||||||
|
label TEXT NOT NULL,
|
||||||
|
field_type TEXT NOT NULL CHECK (field_type IN ('text', 'number', 'date', 'bool', 'select')),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE document_metadata_values (
|
||||||
|
document_id UUID NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
|
||||||
|
field_id UUID NOT NULL REFERENCES metadata_fields(id) ON DELETE CASCADE,
|
||||||
|
value TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (document_id, field_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_document_metadata_values_field_id ON document_metadata_values(field_id);
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
-- Entwicklungs-Seed (Akzeptanzkriterium 3): legt einen Beispielordner, ein
|
||||||
|
-- Beispieldokument mit einer Revision, ein Tag und ein Metadatenfeld an.
|
||||||
|
-- Setzt voraus, dass mindestens ein Benutzer existiert (Core IAM-01 legt
|
||||||
|
-- users an, DMS tut das nicht selbst - siehe "Nicht Bestandteil" in
|
||||||
|
-- FDN-02) - schlaegt sonst absichtlich mit einer sprechenden Fehlermeldung
|
||||||
|
-- fehl statt einen Platzhalter-Benutzer anzulegen, den DMS gar nicht
|
||||||
|
-- verwalten darf.
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
seed_user_id UUID;
|
||||||
|
seed_folder_id UUID;
|
||||||
|
seed_document_id UUID;
|
||||||
|
BEGIN
|
||||||
|
SELECT id INTO seed_user_id FROM users ORDER BY created_at LIMIT 1;
|
||||||
|
IF seed_user_id IS NULL THEN
|
||||||
|
RAISE EXCEPTION 'dev_seed.sql: keine Zeile in users gefunden - zuerst Core-Seed (IAM-01) ausfuehren';
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
INSERT INTO folders (name, created_by) VALUES ('Beispielordner', seed_user_id)
|
||||||
|
RETURNING id INTO seed_folder_id;
|
||||||
|
|
||||||
|
INSERT INTO documents (folder_id, title, created_by) VALUES (seed_folder_id, 'Beispieldokument', seed_user_id)
|
||||||
|
RETURNING id INTO seed_document_id;
|
||||||
|
|
||||||
|
INSERT INTO file_revisions (document_id, revision_number, storage_key, checksum_sha256, size_bytes, mime_type, created_by)
|
||||||
|
VALUES (seed_document_id, 1, 'dev-seed/beispiel.pdf', repeat('0', 64), 12345, 'application/pdf', seed_user_id);
|
||||||
|
|
||||||
|
UPDATE documents SET current_revision_id = (
|
||||||
|
SELECT id FROM file_revisions WHERE document_id = seed_document_id AND revision_number = 1
|
||||||
|
) WHERE id = seed_document_id;
|
||||||
|
|
||||||
|
INSERT INTO tags (name) VALUES ('Beispiel-Tag')
|
||||||
|
ON CONFLICT (name) DO NOTHING;
|
||||||
|
|
||||||
|
INSERT INTO document_tags (document_id, tag_id)
|
||||||
|
SELECT seed_document_id, id FROM tags WHERE name = 'Beispiel-Tag';
|
||||||
|
|
||||||
|
INSERT INTO metadata_fields (field_key, label, field_type) VALUES ('rechnungsnummer', 'Rechnungsnummer', 'text')
|
||||||
|
ON CONFLICT (field_key) DO NOTHING;
|
||||||
|
|
||||||
|
INSERT INTO document_metadata_values (document_id, field_id, value)
|
||||||
|
SELECT seed_document_id, id, 'RE-2026-0001' FROM metadata_fields WHERE field_key = 'rechnungsnummer';
|
||||||
|
END $$;
|
||||||
@@ -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,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
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,64 +0,0 @@
|
|||||||
package ratelimit
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"math"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/apiserver"
|
|
||||||
)
|
|
||||||
|
|
||||||
// KeyFunc bestimmt den Rate-Limit-Schluessel fuer eine Anfrage — typischerweise
|
|
||||||
// der Tenant-Slug aus apiserver.RequestContext, siehe KeyByTenant. Als
|
|
||||||
// eigenstaendiger Typ austauschbar (z.B. spaeter API-Token-basiert), ohne
|
|
||||||
// internal/apiserver aendern zu muessen (Kein Umbau angrenzender Bereiche).
|
|
||||||
type KeyFunc func(r *http.Request) (string, bool)
|
|
||||||
|
|
||||||
// KeyByTenant liest den Tenant aus dem von internal/apiserver.authAndTenantContext
|
|
||||||
// gesetzten RequestContext (IAM-02/API-01) — dieselbe Middleware-Kette,
|
|
||||||
// keine zweite Authentifizierung.
|
|
||||||
func KeyByTenant(r *http.Request) (string, bool) {
|
|
||||||
rc, ok := apiserver.FromContext(r.Context())
|
|
||||||
if !ok || rc.TenantSlug == "" {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
return rc.TenantSlug, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Middleware setzt sich VOR den eigentlichen Handler (nach Auth+Tenant-
|
|
||||||
// Kontext, siehe KeyByTenant) und lehnt Anfragen ueber dem konfigurierten
|
|
||||||
// Limit mit 429 + Retry-After ab (Akzeptanzkriterium 3).
|
|
||||||
func Middleware(store *Store, keyFn KeyFunc, next http.HandlerFunc) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
key, ok := keyFn(r)
|
|
||||||
if !ok {
|
|
||||||
// Kein Schluessel ermittelbar (z.B. kein Tenant-Kontext) — die
|
|
||||||
// Auth-Pruefung selbst ist Sache von authAndTenantContext, hier
|
|
||||||
// wird nur nicht limitiert, wenn schon kein Kontext vorliegt.
|
|
||||||
next(w, r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
result, err := store.Allow(r.Context(), key)
|
|
||||||
if err != nil {
|
|
||||||
apiserver.WriteError(w, http.StatusInternalServerError, "rate_limit_error", "rate-limit-pruefung fehlgeschlagen")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("X-RateLimit-Limit", fmt.Sprintf("%d", result.Limit))
|
|
||||||
w.Header().Set("X-RateLimit-Remaining", fmt.Sprintf("%d", result.Remaining))
|
|
||||||
|
|
||||||
if !result.Allowed {
|
|
||||||
retryAfterSeconds := int(math.Ceil(result.RetryAfter.Seconds()))
|
|
||||||
if retryAfterSeconds < 1 {
|
|
||||||
retryAfterSeconds = 1
|
|
||||||
}
|
|
||||||
w.Header().Set("Retry-After", fmt.Sprintf("%d", retryAfterSeconds))
|
|
||||||
apiserver.WriteError(w, http.StatusTooManyRequests, "rate_limit_exceeded",
|
|
||||||
"zu viele anfragen, bitte spaeter erneut versuchen")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
next(w, r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
package ratelimit
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/apiserver"
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/auth"
|
|
||||||
)
|
|
||||||
|
|
||||||
func setupMiddlewareTest(t *testing.T) (*apiserver.Server, *auth.TokenIssuer, *Store, func()) {
|
|
||||||
t.Helper()
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
pool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pool: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := pool.Exec(ctx, `
|
|
||||||
CREATE TABLE IF NOT EXISTS rate_limit_configs (
|
|
||||||
key TEXT PRIMARY KEY, limit_value INT NOT NULL, window_seconds INT NOT NULL
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS rate_limit_counters (
|
|
||||||
key TEXT NOT NULL, window_start TIMESTAMPTZ NOT NULL, count INT NOT NULL DEFAULT 0,
|
|
||||||
PRIMARY KEY (key, window_start)
|
|
||||||
);
|
|
||||||
`); err != nil {
|
|
||||||
t.Fatalf("schema: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
issuer := auth.NewTokenIssuer("test-secret-nur-fuer-tests")
|
|
||||||
srv := apiserver.NewServer(issuer)
|
|
||||||
store := NewStore(pool)
|
|
||||||
|
|
||||||
cleanup := func() { pool.Close() }
|
|
||||||
return srv, issuer, store, cleanup
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3 + Pruefung 2: Ueberschreitung liefert 429 mit
|
|
||||||
// Retry-After-Header, ueber die vollstaendige Middleware-Kette (Auth ->
|
|
||||||
// Tenant-Kontext -> Rate-Limit -> Handler) hinweg.
|
|
||||||
func TestMiddleware_Returns429WithRetryAfterOnExceeded(t *testing.T) {
|
|
||||||
srv, issuer, store, cleanup := setupMiddlewareTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
tenantSlug := newTestKey()
|
|
||||||
if err := store.SetLimit(ctx, tenantSlug, 1, time.Minute); err != nil {
|
|
||||||
t.Fatalf("setlimit: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
called := 0
|
|
||||||
srv.HandleV1("/limited", Middleware(store, KeyByTenant, func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
called++
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}))
|
|
||||||
|
|
||||||
token, err := issuer.Issue("user-1", tenantSlug)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
req1 := httptest.NewRequest(http.MethodGet, "/api/v1/limited", nil)
|
|
||||||
req1.AddCookie(&http.Cookie{Name: auth.CookieName, Value: token})
|
|
||||||
rec1 := httptest.NewRecorder()
|
|
||||||
srv.Handler().ServeHTTP(rec1, req1)
|
|
||||||
if rec1.Code != http.StatusOK {
|
|
||||||
t.Fatalf("1. anfrage: status = %d, want 200", rec1.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
req2 := httptest.NewRequest(http.MethodGet, "/api/v1/limited", nil)
|
|
||||||
req2.AddCookie(&http.Cookie{Name: auth.CookieName, Value: token})
|
|
||||||
rec2 := httptest.NewRecorder()
|
|
||||||
srv.Handler().ServeHTTP(rec2, req2)
|
|
||||||
if rec2.Code != http.StatusTooManyRequests {
|
|
||||||
t.Fatalf("2. anfrage: status = %d, want 429", rec2.Code)
|
|
||||||
}
|
|
||||||
if rec2.Header().Get("Retry-After") == "" {
|
|
||||||
t.Fatal("erwartet gesetzten Retry-After-Header bei 429")
|
|
||||||
}
|
|
||||||
if called != 1 {
|
|
||||||
t.Fatalf("handler wurde %d mal aufgerufen, want genau 1 (2. anfrage haette nicht durchgereicht werden duerfen)", called)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1: das Limit ist pro Tenant konfigurierbar — ein
|
|
||||||
// anderer Tenant (anderer Key) bleibt von der Ausschoepfung unberuehrt.
|
|
||||||
func TestMiddleware_DifferentTenantsHaveIndependentLimits(t *testing.T) {
|
|
||||||
srv, issuer, store, cleanup := setupMiddlewareTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
tenantA := newTestKey()
|
|
||||||
tenantB := newTestKey()
|
|
||||||
if err := store.SetLimit(ctx, tenantA, 1, time.Minute); err != nil {
|
|
||||||
t.Fatalf("setlimit a: %v", err)
|
|
||||||
}
|
|
||||||
if err := store.SetLimit(ctx, tenantB, 1, time.Minute); err != nil {
|
|
||||||
t.Fatalf("setlimit b: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
srv.HandleV1("/limited2", Middleware(store, KeyByTenant, func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
}))
|
|
||||||
|
|
||||||
tokenA, _ := issuer.Issue("user-a", tenantA)
|
|
||||||
tokenB, _ := issuer.Issue("user-b", tenantB)
|
|
||||||
|
|
||||||
// Tenant A schoepft sein Limit aus.
|
|
||||||
reqA := httptest.NewRequest(http.MethodGet, "/api/v1/limited2", nil)
|
|
||||||
reqA.AddCookie(&http.Cookie{Name: auth.CookieName, Value: tokenA})
|
|
||||||
recA := httptest.NewRecorder()
|
|
||||||
srv.Handler().ServeHTTP(recA, reqA)
|
|
||||||
if recA.Code != http.StatusOK {
|
|
||||||
t.Fatalf("tenant a, 1. anfrage: status = %d, want 200", recA.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tenant B ist von der Ausschoepfung bei A unberuehrt.
|
|
||||||
reqB := httptest.NewRequest(http.MethodGet, "/api/v1/limited2", nil)
|
|
||||||
reqB.AddCookie(&http.Cookie{Name: auth.CookieName, Value: tokenB})
|
|
||||||
recB := httptest.NewRecorder()
|
|
||||||
srv.Handler().ServeHTTP(recB, reqB)
|
|
||||||
if recB.Code != http.StatusOK {
|
|
||||||
t.Fatalf("tenant b haette trotz ausgeschoepftem limit von tenant a erlaubt sein muessen, status = %d", recB.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,126 +0,0 @@
|
|||||||
// Package ratelimit implementiert Core API-03: eine zentrale Rate-Limiting-
|
|
||||||
// Schicht fuer die gesamte Core-API mit GETEILTEM, EXTERNEM Zustand in
|
|
||||||
// Postgres — kein In-Process-Zaehler (siehe "Bekannte Fehler vermeiden" im
|
|
||||||
// Ticket: dasselbe Risiko wie bei IAM-07s In-Memory-Lockout). Fixed-Window-
|
|
||||||
// Algorithmus: einfach, korrekt unter nebenlaeufigem Zugriff (atomares
|
|
||||||
// UPSERT wie internal/usage.Store.Increment), und fuer ein API-Gateway
|
|
||||||
// ausreichend praezise — kein Sliding-Window-Overhead noetig.
|
|
||||||
package ratelimit
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DefaultLimit/DefaultWindow gelten fuer jeden Schluessel (Tenant oder
|
|
||||||
// API-Token), fuer den keine eigene Konfiguration existiert
|
|
||||||
// (Akzeptanzkriterium 1: "konfigurierbar", nicht "verpflichtend konfiguriert").
|
|
||||||
const (
|
|
||||||
DefaultLimit = 100
|
|
||||||
DefaultWindow = time.Minute
|
|
||||||
)
|
|
||||||
|
|
||||||
// Config ist das je Schluessel konfigurierbare Limit.
|
|
||||||
type Config struct {
|
|
||||||
Limit int
|
|
||||||
Window time.Duration
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store haelt Konfiguration UND Zaehlerstand in Postgres — beides ueber
|
|
||||||
// dieselbe Verbindung erreichbar, damit mehrere Dienstinstanzen denselben
|
|
||||||
// Zustand sehen (Akzeptanzkriterium 2).
|
|
||||||
type Store struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewStore(pool *pgxpool.Pool) *Store {
|
|
||||||
return &Store{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetLimit setzt die Konfiguration fuer EINEN Schluessel (z.B. einen
|
|
||||||
// Tenant-Slug oder eine API-Token-ID) — wirkt sich nicht auf andere
|
|
||||||
// Schluessel aus (Akzeptanzkriterium 1 / Pruefung 3).
|
|
||||||
func (s *Store) SetLimit(ctx context.Context, key string, limit int, window time.Duration) error {
|
|
||||||
_, err := s.pool.Exec(ctx, `
|
|
||||||
INSERT INTO rate_limit_configs (key, limit_value, window_seconds)
|
|
||||||
VALUES ($1, $2, $3)
|
|
||||||
ON CONFLICT (key) DO UPDATE SET limit_value = $2, window_seconds = $3
|
|
||||||
`, key, limit, int(window.Seconds()))
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("rate-limit-konfiguration speichern: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) getConfig(ctx context.Context, key string) (Config, error) {
|
|
||||||
var limit, windowSeconds int
|
|
||||||
err := s.pool.QueryRow(ctx, `
|
|
||||||
SELECT limit_value, window_seconds FROM rate_limit_configs WHERE key = $1
|
|
||||||
`, key).Scan(&limit, &windowSeconds)
|
|
||||||
if err != nil {
|
|
||||||
if err == pgx.ErrNoRows {
|
|
||||||
return Config{Limit: DefaultLimit, Window: DefaultWindow}, nil
|
|
||||||
}
|
|
||||||
return Config{}, fmt.Errorf("rate-limit-konfiguration lesen: %w", err)
|
|
||||||
}
|
|
||||||
return Config{Limit: limit, Window: time.Duration(windowSeconds) * time.Second}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Result ist der Ausgang einer Allow-Pruefung (Akzeptanzkriterium 3).
|
|
||||||
type Result struct {
|
|
||||||
Allowed bool
|
|
||||||
Limit int
|
|
||||||
Remaining int
|
|
||||||
RetryAfter time.Duration
|
|
||||||
}
|
|
||||||
|
|
||||||
// Allow erhoeht den Zaehler fuer (key, aktuelles Zeitfenster) ATOMAR ueber
|
|
||||||
// ein einziges UPSERT (dasselbe Muster wie internal/usage.Store.Increment)
|
|
||||||
// und vergleicht das Ergebnis gegen die konfigurierte Grenze — kein
|
|
||||||
// Lesen-Erhoehen-Schreiben in Go, damit zwei Dienstinstanzen, die
|
|
||||||
// gleichzeitig gegen dieselbe Datenbank inkrementieren, sich niemals
|
|
||||||
// gegenseitig ueberschreiben (Akzeptanzkriterium 2 / Pruefung 1).
|
|
||||||
func (s *Store) Allow(ctx context.Context, key string) (Result, error) {
|
|
||||||
cfg, err := s.getConfig(ctx, key)
|
|
||||||
if err != nil {
|
|
||||||
return Result{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
windowSeconds := int64(cfg.Window.Seconds())
|
|
||||||
if windowSeconds <= 0 {
|
|
||||||
windowSeconds = int64(DefaultWindow.Seconds())
|
|
||||||
}
|
|
||||||
now := time.Now().UTC()
|
|
||||||
windowStart := time.Unix((now.Unix()/windowSeconds)*windowSeconds, 0).UTC()
|
|
||||||
windowEnd := windowStart.Add(time.Duration(windowSeconds) * time.Second)
|
|
||||||
|
|
||||||
var count int
|
|
||||||
err = s.pool.QueryRow(ctx, `
|
|
||||||
INSERT INTO rate_limit_counters (key, window_start, count)
|
|
||||||
VALUES ($1, $2, 1)
|
|
||||||
ON CONFLICT (key, window_start) DO UPDATE
|
|
||||||
SET count = rate_limit_counters.count + 1
|
|
||||||
RETURNING count
|
|
||||||
`, key, windowStart).Scan(&count)
|
|
||||||
if err != nil {
|
|
||||||
return Result{}, fmt.Errorf("rate-limit-zaehler erhoehen: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
remaining := cfg.Limit - count
|
|
||||||
if remaining < 0 {
|
|
||||||
remaining = 0
|
|
||||||
}
|
|
||||||
if count > cfg.Limit {
|
|
||||||
return Result{
|
|
||||||
Allowed: false,
|
|
||||||
Limit: cfg.Limit,
|
|
||||||
Remaining: 0,
|
|
||||||
RetryAfter: windowEnd.Sub(now),
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
return Result{Allowed: true, Limit: cfg.Limit, Remaining: remaining}, nil
|
|
||||||
}
|
|
||||||
@@ -1,168 +0,0 @@
|
|||||||
package ratelimit
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"sync"
|
|
||||||
"sync/atomic"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
func setupTest(t *testing.T) (*pgxpool.Pool, func()) {
|
|
||||||
t.Helper()
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
pool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pool: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := pool.Exec(ctx, `
|
|
||||||
CREATE TABLE IF NOT EXISTS rate_limit_configs (
|
|
||||||
key TEXT PRIMARY KEY, limit_value INT NOT NULL, window_seconds INT NOT NULL
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS rate_limit_counters (
|
|
||||||
key TEXT NOT NULL, window_start TIMESTAMPTZ NOT NULL, count INT NOT NULL DEFAULT 0,
|
|
||||||
PRIMARY KEY (key, window_start)
|
|
||||||
);
|
|
||||||
`); err != nil {
|
|
||||||
t.Fatalf("schema: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanup := func() { pool.Close() }
|
|
||||||
return pool, cleanup
|
|
||||||
}
|
|
||||||
|
|
||||||
func newTestKey() string {
|
|
||||||
return fmt.Sprintf("test-key-%d", time.Now().UnixNano())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3 + Pruefung 2: Ueberschreitung des Limits wird
|
|
||||||
// nachweislich erkannt.
|
|
||||||
func TestAllow_RejectsAfterLimitExceeded(t *testing.T) {
|
|
||||||
pool, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
store := NewStore(pool)
|
|
||||||
ctx := context.Background()
|
|
||||||
key := newTestKey()
|
|
||||||
|
|
||||||
if err := store.SetLimit(ctx, key, 3, time.Minute); err != nil {
|
|
||||||
t.Fatalf("setlimit: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < 3; i++ {
|
|
||||||
res, err := store.Allow(ctx, key)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("allow %d: %v", i, err)
|
|
||||||
}
|
|
||||||
if !res.Allowed {
|
|
||||||
t.Fatalf("anfrage %d haette erlaubt sein muessen, limit=3", i)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
res, err := store.Allow(ctx, key)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("allow (4.): %v", err)
|
|
||||||
}
|
|
||||||
if res.Allowed {
|
|
||||||
t.Fatal("4. anfrage haette abgelehnt werden muessen (limit=3)")
|
|
||||||
}
|
|
||||||
if res.RetryAfter <= 0 {
|
|
||||||
t.Fatalf("erwartet positive retry-after-dauer, habe %v", res.RetryAfter)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 / Pruefung 3: Konfigurationsaenderung wirkt sich
|
|
||||||
// NICHT auf andere Schluessel (Tenants) aus.
|
|
||||||
func TestSetLimit_DoesNotAffectOtherKeys(t *testing.T) {
|
|
||||||
pool, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
store := NewStore(pool)
|
|
||||||
ctx := context.Background()
|
|
||||||
keyA := newTestKey()
|
|
||||||
keyB := newTestKey()
|
|
||||||
|
|
||||||
if err := store.SetLimit(ctx, keyA, 1, time.Minute); err != nil {
|
|
||||||
t.Fatalf("setlimit a: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
resA1, _ := store.Allow(ctx, keyA)
|
|
||||||
resA2, _ := store.Allow(ctx, keyA)
|
|
||||||
if !resA1.Allowed || resA2.Allowed {
|
|
||||||
t.Fatalf("key a: erwartet erlaubt,abgelehnt, habe %v,%v", resA1.Allowed, resA2.Allowed)
|
|
||||||
}
|
|
||||||
|
|
||||||
// keyB hat keine eigene Konfiguration -> DefaultLimit, unbeeinflusst von keyA.
|
|
||||||
resB, err := store.Allow(ctx, keyB)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("allow b: %v", err)
|
|
||||||
}
|
|
||||||
if !resB.Allowed {
|
|
||||||
t.Fatal("key b haette trotz limit-ueberschreitung bei key a erlaubt sein muessen")
|
|
||||||
}
|
|
||||||
if resB.Limit != DefaultLimit {
|
|
||||||
t.Fatalf("key b limit = %d, want default %d", resB.Limit, DefaultLimit)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + Pruefung 1: zwei "Dienstinstanzen" (zwei
|
|
||||||
// unabhaengige Pools/Store-Objekte) gegen dieselbe Datenbank setzen
|
|
||||||
// dasselbe Limit korrekt durch — kein In-Process-Zustand kann das leisten.
|
|
||||||
func TestAllow_TwoInstancesShareStateCorrectly(t *testing.T) {
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
pool, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
pool2, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("zweiter pool (simuliert zweite instanz): %v", err)
|
|
||||||
}
|
|
||||||
defer pool2.Close()
|
|
||||||
|
|
||||||
storeInstance1 := NewStore(pool)
|
|
||||||
storeInstance2 := NewStore(pool2)
|
|
||||||
|
|
||||||
key := newTestKey()
|
|
||||||
const limit = 20
|
|
||||||
if err := storeInstance1.SetLimit(ctx, key, limit, time.Minute); err != nil {
|
|
||||||
t.Fatalf("setlimit: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
const totalRequests = 50
|
|
||||||
var allowedCount int64
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
for i := 0; i < totalRequests; i++ {
|
|
||||||
wg.Add(1)
|
|
||||||
store := storeInstance1
|
|
||||||
if i%2 == 0 {
|
|
||||||
store = storeInstance2 // Haelfte der Anfragen "kommt" von der zweiten Instanz
|
|
||||||
}
|
|
||||||
go func(s *Store) {
|
|
||||||
defer wg.Done()
|
|
||||||
res, err := s.Allow(ctx, key)
|
|
||||||
if err != nil {
|
|
||||||
t.Errorf("allow: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if res.Allowed {
|
|
||||||
atomic.AddInt64(&allowedCount, 1)
|
|
||||||
}
|
|
||||||
}(store)
|
|
||||||
}
|
|
||||||
wg.Wait()
|
|
||||||
|
|
||||||
if allowedCount != limit {
|
|
||||||
t.Fatalf("erlaubte anfragen ueber beide instanzen = %d, want exakt %d (geteilter zustand)", allowedCount, limit)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Handler stellt die CRUD-API fuer Benutzerkonten bereit (IAM-01-Auftrag).
|
|
||||||
// Auth/Sessions (IAM-02) und Rollen (RBAC-01) sind ausdruecklich nicht Teil
|
|
||||||
// dieser Kachel und daher hier noch nicht angebunden.
|
|
||||||
type Handler struct {
|
|
||||||
users *TenantUserStore
|
|
||||||
superadmins *SuperadminStore
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHandler(users *TenantUserStore, superadmins *SuperadminStore) *Handler {
|
|
||||||
return &Handler{users: users, superadmins: superadmins}
|
|
||||||
}
|
|
||||||
|
|
||||||
type createUserRequest struct {
|
|
||||||
Email string `json:"email"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var req createUserRequest
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
||||||
http.Error(w, "ungueltige Anfrage", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
u, err := h.users.Create(r.Context(), req.Email, req.Name)
|
|
||||||
writeUserResult(w, u, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateSuperadmin legt ein mandantenuebergreifendes Superadmin-Konto an —
|
|
||||||
// bewusst ein eigener Endpunkt statt eines Tenant-Parameters mit Null-Wert.
|
|
||||||
func (h *Handler) CreateSuperadmin(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var req createUserRequest
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
||||||
http.Error(w, "ungueltige Anfrage", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
u, err := h.superadmins.Create(r.Context(), req.Email, req.Name)
|
|
||||||
writeUserResult(w, u, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeUserResult(w http.ResponseWriter, u User, err error) {
|
|
||||||
if err != nil {
|
|
||||||
switch {
|
|
||||||
case errors.Is(err, ErrInvalidEmail), errors.Is(err, ErrEmailTaken):
|
|
||||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
||||||
case errors.Is(err, ErrNotFound):
|
|
||||||
http.Error(w, err.Error(), http.StatusNotFound)
|
|
||||||
default:
|
|
||||||
http.Error(w, "benutzer konnte nicht verarbeitet werden", http.StatusInternalServerError)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
_ = json.NewEncoder(w).Encode(u)
|
|
||||||
}
|
|
||||||
@@ -1,173 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// setupTestDB legt eine frische, isolierte Testdatenbank an, wendet die
|
|
||||||
// uebergebene Migration an und liefert einen verbundenen Pool. Wird ohne
|
|
||||||
// TEST_ADMIN_DSN uebersprungen — siehe internal/tenant/provisioner_test.go
|
|
||||||
// fuer dasselbe Muster.
|
|
||||||
func setupTestDB(t *testing.T, dbName, schemaSQL string) *pgxpool.Pool {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
adminPool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("admin pool: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
_, _ = adminPool.Exec(ctx, fmt.Sprintf(`DROP DATABASE IF EXISTS %q`, dbName))
|
|
||||||
if _, err := adminPool.Exec(ctx, fmt.Sprintf(`CREATE DATABASE %q`, dbName)); err != nil {
|
|
||||||
t.Fatalf("testdatenbank anlegen: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
dsn := strings.Replace(adminDSN, "/postgres?", "/"+dbName+"?", 1)
|
|
||||||
pool, err := pgxpool.New(ctx, dsn)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("connect testdatenbank: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := pool.Exec(ctx, schemaSQL); err != nil {
|
|
||||||
t.Fatalf("schema anwenden: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Cleanup(func() {
|
|
||||||
pool.Close()
|
|
||||||
_, _ = adminPool.Exec(ctx, fmt.Sprintf(`DROP DATABASE IF EXISTS %q`, dbName))
|
|
||||||
adminPool.Close()
|
|
||||||
})
|
|
||||||
|
|
||||||
return pool
|
|
||||||
}
|
|
||||||
|
|
||||||
const usersSchema = `
|
|
||||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|
||||||
CREATE TABLE users (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
email TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);`
|
|
||||||
|
|
||||||
const superadminsSchema = `
|
|
||||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|
||||||
CREATE TABLE superadmins (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
email TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);`
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 + 3, Pruefung 1 (inkl. Negativfall doppelte E-Mail).
|
|
||||||
func TestTenantUserStore_CRUD(t *testing.T) {
|
|
||||||
pool := setupTestDB(t, "test_iam01_users", usersSchema)
|
|
||||||
store := NewTenantUserStore(pool)
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
created, err := store.Create(ctx, "alice@example.com", "Alice")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("create: %v", err)
|
|
||||||
}
|
|
||||||
if created.Status != StatusActive {
|
|
||||||
t.Fatalf("erwartet status active, hat %q", created.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
got, err := store.Get(ctx, created.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("get: %v", err)
|
|
||||||
}
|
|
||||||
if got.Email != "alice@example.com" {
|
|
||||||
t.Fatalf("get email = %q", got.Email)
|
|
||||||
}
|
|
||||||
|
|
||||||
updated, err := store.Update(ctx, created.ID, "", "Alice A.")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("update: %v", err)
|
|
||||||
}
|
|
||||||
if updated.Name != "Alice A." || updated.Email != "alice@example.com" {
|
|
||||||
t.Fatalf("update ergebnis unerwartet: %+v", updated)
|
|
||||||
}
|
|
||||||
|
|
||||||
list, err := store.List(ctx)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("list: %v", err)
|
|
||||||
}
|
|
||||||
if len(list) != 1 {
|
|
||||||
t.Fatalf("erwartet 1 benutzer, habe %d", len(list))
|
|
||||||
}
|
|
||||||
|
|
||||||
deactivated, err := store.Deactivate(ctx, created.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("deactivate: %v", err)
|
|
||||||
}
|
|
||||||
if deactivated.Status != StatusInactive {
|
|
||||||
t.Fatalf("erwartet status inactive, hat %q", deactivated.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Negativfall: doppelte E-Mail-Adresse.
|
|
||||||
if _, err := store.Create(ctx, "second@example.com", "Bob"); err != nil {
|
|
||||||
t.Fatalf("create second: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := store.Create(ctx, "second@example.com", "Bob Zwei"); !errors.Is(err, ErrEmailTaken) {
|
|
||||||
t.Fatalf("erwartet ErrEmailTaken, habe %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Negativfall: fehlender Benutzer.
|
|
||||||
if _, err := store.Get(ctx, created.ID+"-nicht-vorhanden"); err == nil {
|
|
||||||
t.Fatalf("erwartet fehler bei unbekannter/ungueltiger id")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + Pruefung 2: Superadmin-Anlage ohne Tenant-Kontext.
|
|
||||||
// SuperadminStore.Create hat keinen Tenant-Parameter — es gibt syntaktisch
|
|
||||||
// keine Moeglichkeit, hier versehentlich einen Tenant-Sonderfall zu vergessen.
|
|
||||||
func TestSuperadminStore_CreateWithoutTenantContext(t *testing.T) {
|
|
||||||
pool := setupTestDB(t, "test_iam01_superadmins", superadminsSchema)
|
|
||||||
store := NewSuperadminStore(pool)
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
created, err := store.Create(ctx, "root@nexarch.internal", "Root")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("create superadmin: %v", err)
|
|
||||||
}
|
|
||||||
if created.Status != StatusActive {
|
|
||||||
t.Fatalf("erwartet status active, hat %q", created.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
got, err := store.Get(ctx, created.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("get: %v", err)
|
|
||||||
}
|
|
||||||
if got.Email != "root@nexarch.internal" {
|
|
||||||
t.Fatalf("get email = %q", got.Email)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := store.Create(ctx, "root@nexarch.internal", "Root Zwei"); !errors.Is(err, ErrEmailTaken) {
|
|
||||||
t.Fatalf("erwartet ErrEmailTaken (globale eindeutigkeit), habe %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
deactivated, err := store.Deactivate(ctx, created.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("deactivate: %v", err)
|
|
||||||
}
|
|
||||||
if deactivated.Status != StatusInactive {
|
|
||||||
t.Fatalf("erwartet status inactive, hat %q", deactivated.Status)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// SuperadminStore verwaltet mandantenuebergreifende Superadmin-Konten in der
|
|
||||||
// Control-Plane-Registry (siehe internal/tenant.Registry). Superadmin-ohne-
|
|
||||||
// Tenant ist dadurch ein eigener Typ statt eines Sonderfalls von User/
|
|
||||||
// TenantUserStore — es gibt keinen Tenant-Parameter, den man weglassen
|
|
||||||
// koennte (IAM-01, "ohne Sonderbehandlung im Code").
|
|
||||||
type SuperadminStore struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewSuperadminStore(pool *pgxpool.Pool) *SuperadminStore {
|
|
||||||
return &SuperadminStore{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SuperadminStore) Create(ctx context.Context, email, name string) (User, error) {
|
|
||||||
if err := ValidateEmail(email); err != nil {
|
|
||||||
return User{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var u User
|
|
||||||
u.Email, u.Name, u.Status = email, name, StatusActive
|
|
||||||
|
|
||||||
row := s.pool.QueryRow(ctx, `
|
|
||||||
INSERT INTO superadmins (email, name, status)
|
|
||||||
VALUES ($1, $2, $3)
|
|
||||||
RETURNING id, created_at, updated_at
|
|
||||||
`, u.Email, u.Name, u.Status)
|
|
||||||
|
|
||||||
if err := row.Scan(&u.ID, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
|
||||||
return User{}, mapWriteErr(err)
|
|
||||||
}
|
|
||||||
return u, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SuperadminStore) Get(ctx context.Context, id string) (User, error) {
|
|
||||||
return scanUser(s.pool.QueryRow(ctx, `
|
|
||||||
SELECT id, email, name, status, created_at, updated_at
|
|
||||||
FROM superadmins WHERE id = $1
|
|
||||||
`, id))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SuperadminStore) List(ctx context.Context) ([]User, error) {
|
|
||||||
rows, err := s.pool.Query(ctx, `
|
|
||||||
SELECT id, email, name, status, created_at, updated_at
|
|
||||||
FROM superadmins ORDER BY created_at
|
|
||||||
`)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("superadmins auflisten: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var out []User
|
|
||||||
for rows.Next() {
|
|
||||||
var u User
|
|
||||||
if err := rows.Scan(&u.ID, &u.Email, &u.Name, &u.Status, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
|
||||||
return nil, fmt.Errorf("superadmin lesen: %w", err)
|
|
||||||
}
|
|
||||||
out = append(out, u)
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SuperadminStore) Deactivate(ctx context.Context, id string) (User, error) {
|
|
||||||
return scanUser(s.pool.QueryRow(ctx, `
|
|
||||||
UPDATE superadmins SET status = $2, updated_at = now()
|
|
||||||
WHERE id = $1
|
|
||||||
RETURNING id, email, name, status, created_at, updated_at
|
|
||||||
`, id, StatusInactive))
|
|
||||||
}
|
|
||||||
@@ -1,173 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgconn"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TenantUserStore verwaltet Benutzer innerhalb GENAU EINER Tenant-Datenbank.
|
|
||||||
// Welcher Mandant gemeint ist, ergibt sich ausschliesslich aus dem
|
|
||||||
// uebergebenen Pool — es gibt keine tenant_id-Spalte (siehe migrations/tenant/0001_users.up.sql).
|
|
||||||
type TenantUserStore struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewTenantUserStore(pool *pgxpool.Pool) *TenantUserStore {
|
|
||||||
return &TenantUserStore{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *TenantUserStore) Create(ctx context.Context, email, name string) (User, error) {
|
|
||||||
if err := ValidateEmail(email); err != nil {
|
|
||||||
return User{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var u User
|
|
||||||
u.Email, u.Name, u.Status = email, name, StatusActive
|
|
||||||
|
|
||||||
row := s.pool.QueryRow(ctx, `
|
|
||||||
INSERT INTO users (email, name, status)
|
|
||||||
VALUES ($1, $2, $3)
|
|
||||||
RETURNING id, created_at, updated_at
|
|
||||||
`, u.Email, u.Name, u.Status)
|
|
||||||
|
|
||||||
if err := row.Scan(&u.ID, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
|
||||||
return User{}, mapWriteErr(err)
|
|
||||||
}
|
|
||||||
return u, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *TenantUserStore) Get(ctx context.Context, id string) (User, error) {
|
|
||||||
return scanUser(s.pool.QueryRow(ctx, `
|
|
||||||
SELECT id, email, name, status, created_at, updated_at
|
|
||||||
FROM users WHERE id = $1
|
|
||||||
`, id))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *TenantUserStore) List(ctx context.Context) ([]User, error) {
|
|
||||||
rows, err := s.pool.Query(ctx, `
|
|
||||||
SELECT id, email, name, status, created_at, updated_at
|
|
||||||
FROM users ORDER BY created_at
|
|
||||||
`)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("benutzer auflisten: %w", err)
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
|
|
||||||
var out []User
|
|
||||||
for rows.Next() {
|
|
||||||
var u User
|
|
||||||
if err := rows.Scan(&u.ID, &u.Email, &u.Name, &u.Status, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
|
||||||
return nil, fmt.Errorf("benutzer lesen: %w", err)
|
|
||||||
}
|
|
||||||
out = append(out, u)
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update aendert Name und E-Mail. Eine leere email/name laesst das jeweilige
|
|
||||||
// Feld unveraendert.
|
|
||||||
func (s *TenantUserStore) Update(ctx context.Context, id, email, name string) (User, error) {
|
|
||||||
if email != "" {
|
|
||||||
if err := ValidateEmail(email); err != nil {
|
|
||||||
return User{}, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
row := s.pool.QueryRow(ctx, `
|
|
||||||
UPDATE users
|
|
||||||
SET email = COALESCE(NULLIF($2, ''), email),
|
|
||||||
name = COALESCE(NULLIF($3, ''), name),
|
|
||||||
updated_at = now()
|
|
||||||
WHERE id = $1
|
|
||||||
RETURNING id, email, name, status, created_at, updated_at
|
|
||||||
`, id, email, name)
|
|
||||||
|
|
||||||
u, err := scanUser(row)
|
|
||||||
if err != nil {
|
|
||||||
return User{}, mapWriteErr(err)
|
|
||||||
}
|
|
||||||
return u, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deactivate setzt den Benutzer auf inaktiv statt ihn zu loeschen.
|
|
||||||
func (s *TenantUserStore) Deactivate(ctx context.Context, id string) (User, error) {
|
|
||||||
return scanUser(s.pool.QueryRow(ctx, `
|
|
||||||
UPDATE users SET status = $2, updated_at = now()
|
|
||||||
WHERE id = $1
|
|
||||||
RETURNING id, email, name, status, created_at, updated_at
|
|
||||||
`, id, StatusInactive))
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetPasswordHash schreibt einen bereits berechneten bcrypt-Hash (siehe
|
|
||||||
// internal/auth, IAM-02). Der Store selbst kennt kein Klartext-Passwort.
|
|
||||||
func (s *TenantUserStore) SetPasswordHash(ctx context.Context, id, hash string) error {
|
|
||||||
tag, err := s.pool.Exec(ctx, `
|
|
||||||
UPDATE users SET password_hash = $2, updated_at = now() WHERE id = $1
|
|
||||||
`, id, hash)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("passwort setzen: %w", err)
|
|
||||||
}
|
|
||||||
if tag.RowsAffected() == 0 {
|
|
||||||
return ErrNotFound
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// AuthCredentials wird ausschliesslich fuer den Login-Pfad (internal/auth)
|
|
||||||
// verwendet und traegt bewusst den password_hash, damit er nicht ueber den
|
|
||||||
// regulaeren User-Typ/JSON-Serialisierungspfad nach aussen dringen kann.
|
|
||||||
type AuthCredentials struct {
|
|
||||||
User User
|
|
||||||
PasswordHash string
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetByEmailForAuth liefert Benutzer + Passwort-Hash zu einer E-Mail-Adresse
|
|
||||||
// aus GENAU DIESER Tenant-Datenbank — der Tenant-Scope ergibt sich damit
|
|
||||||
// zwingend aus dem verwendeten Pool, es gibt keine Moeglichkeit, versehentlich
|
|
||||||
// ueber Tenant-Grenzen hinweg zu suchen (bekannter archivmail-Fehler, siehe
|
|
||||||
// IAM-02 "Bekannte Fehler vermeiden").
|
|
||||||
func (s *TenantUserStore) GetByEmailForAuth(ctx context.Context, email string) (AuthCredentials, error) {
|
|
||||||
var c AuthCredentials
|
|
||||||
row := s.pool.QueryRow(ctx, `
|
|
||||||
SELECT id, email, name, status, created_at, updated_at, password_hash
|
|
||||||
FROM users WHERE email = $1
|
|
||||||
`, email)
|
|
||||||
|
|
||||||
if err := row.Scan(&c.User.ID, &c.User.Email, &c.User.Name, &c.User.Status,
|
|
||||||
&c.User.CreatedAt, &c.User.UpdatedAt, &c.PasswordHash); err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return AuthCredentials{}, ErrNotFound
|
|
||||||
}
|
|
||||||
return AuthCredentials{}, fmt.Errorf("anmeldedaten lesen: %w", err)
|
|
||||||
}
|
|
||||||
return c, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func scanUser(row pgx.Row) (User, error) {
|
|
||||||
var u User
|
|
||||||
if err := row.Scan(&u.ID, &u.Email, &u.Name, &u.Status, &u.CreatedAt, &u.UpdatedAt); err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return User{}, ErrNotFound
|
|
||||||
}
|
|
||||||
return User{}, fmt.Errorf("benutzer lesen: %w", err)
|
|
||||||
}
|
|
||||||
return u, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// mapWriteErr uebersetzt den Unique-Constraint-Verstoss der E-Mail-Spalte in
|
|
||||||
// einen sprechenden Fehler statt der rohen Postgres-Fehlermeldung.
|
|
||||||
func mapWriteErr(err error) error {
|
|
||||||
var pgErr *pgconn.PgError
|
|
||||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
|
||||||
return ErrEmailTaken
|
|
||||||
}
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return ErrNotFound
|
|
||||||
}
|
|
||||||
return fmt.Errorf("benutzer schreiben: %w", err)
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
// Package user implementiert Core IAM-01: das Benutzer-Datenmodell und die
|
|
||||||
// CRUD-Operationen. Tenant-Zugehoerigkeit ist ueber die Zieldatenbank
|
|
||||||
// gegeben (Modell C, siehe internal/tenant) — Superadmin-Konten leben
|
|
||||||
// dagegen mandantenuebergreifend in der Registry und sind ueber
|
|
||||||
// SuperadminStore als eigener, First-Class-Typ modelliert, nicht als
|
|
||||||
// tenant_id-NULL-Sonderfall in User.
|
|
||||||
package user
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"regexp"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Status string
|
|
||||||
|
|
||||||
const (
|
|
||||||
StatusActive Status = "active"
|
|
||||||
StatusInactive Status = "inactive"
|
|
||||||
)
|
|
||||||
|
|
||||||
type User struct {
|
|
||||||
ID string
|
|
||||||
Email string
|
|
||||||
Name string
|
|
||||||
Status Status
|
|
||||||
CreatedAt time.Time
|
|
||||||
UpdatedAt time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
var emailPattern = regexp.MustCompile(`^[^\s@]+@[^\s@]+\.[^\s@]+$`)
|
|
||||||
|
|
||||||
var ErrInvalidEmail = errors.New("user: ungueltige E-Mail-Adresse")
|
|
||||||
var ErrEmailTaken = errors.New("user: E-Mail-Adresse bereits vergeben")
|
|
||||||
var ErrNotFound = errors.New("user: nicht gefunden")
|
|
||||||
|
|
||||||
func ValidateEmail(email string) error {
|
|
||||||
if !emailPattern.MatchString(email) {
|
|
||||||
return ErrInvalidEmail
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
package user
|
|
||||||
|
|
||||||
import "testing"
|
|
||||||
|
|
||||||
func TestValidateEmail(t *testing.T) {
|
|
||||||
cases := []struct {
|
|
||||||
email string
|
|
||||||
wantErr bool
|
|
||||||
}{
|
|
||||||
{"a@b.de", false},
|
|
||||||
{"a.b+c@sub.example.com", false},
|
|
||||||
{"", true},
|
|
||||||
{"keine-email", true},
|
|
||||||
{"a@b", true},
|
|
||||||
{"@b.de", true},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, c := range cases {
|
|
||||||
err := ValidateEmail(c.email)
|
|
||||||
if (err != nil) != c.wantErr {
|
|
||||||
t.Errorf("ValidateEmail(%q) error = %v, wantErr %v", c.email, err, c.wantErr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
DROP TABLE IF EXISTS 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 rate_limit_counters;
|
|
||||||
DROP TABLE rate_limit_configs;
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
-- Rate-Limiting mit geteiltem, externem Zustand (API-03, siehe
|
|
||||||
-- core-kanban/tickets/API-03.md) — bewusst NICHT In-Process, damit mehrere
|
|
||||||
-- Dienstinstanzen dasselbe Limit korrekt durchsetzen.
|
|
||||||
CREATE TABLE rate_limit_configs (
|
|
||||||
key TEXT PRIMARY KEY,
|
|
||||||
limit_value INT NOT NULL,
|
|
||||||
window_seconds INT NOT NULL
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE rate_limit_counters (
|
|
||||||
key TEXT NOT NULL,
|
|
||||||
window_start TIMESTAMPTZ NOT NULL,
|
|
||||||
count INT NOT NULL DEFAULT 0,
|
|
||||||
PRIMARY KEY (key, window_start)
|
|
||||||
);
|
|
||||||
@@ -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