Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b12d53f469 | ||
|
|
8da9c67d08 |
@@ -44,3 +44,88 @@ 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 ++++++++++
|
||||||
|
|
||||||
|
---
|
||||||
|
|||||||
+18
-3
@@ -7,6 +7,7 @@ import (
|
|||||||
|
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/config"
|
"gitea.perlbach24.de/scripte/nexarch/internal/config"
|
||||||
"gitea.perlbach24.de/scripte/nexarch/internal/db"
|
"gitea.perlbach24.de/scripte/nexarch/internal/db"
|
||||||
|
"gitea.perlbach24.de/scripte/nexarch/internal/tenant"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -15,16 +16,30 @@ func main() {
|
|||||||
log.Fatalf("config: %v", err)
|
log.Fatalf("config: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
pool, err := db.Connect(context.Background(), cfg.RegistryDSN)
|
ctx := context.Background()
|
||||||
|
|
||||||
|
registryPool, err := db.Connect(ctx, cfg.RegistryDSN)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("db: %v", err)
|
log.Fatalf("registry db: %v", err)
|
||||||
}
|
}
|
||||||
defer pool.Close()
|
defer registryPool.Close()
|
||||||
|
|
||||||
|
adminPool, err := db.Connect(ctx, cfg.AdminDSN)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("admin db: %v", err)
|
||||||
|
}
|
||||||
|
defer adminPool.Close()
|
||||||
|
|
||||||
|
registry := tenant.NewRegistry(registryPool)
|
||||||
|
provisioner := tenant.NewProvisioner(adminPool, registry, cfg.TenantDSNTemplate)
|
||||||
|
tenantHandler := tenant.NewHandler(provisioner)
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
})
|
})
|
||||||
|
// Vorlaeufiger Pfad ohne Versionierung/Auth — wird mit API-01/IAM-01 abgeloest.
|
||||||
|
mux.HandleFunc("/internal/tenants", tenantHandler.CreateTenant)
|
||||||
|
|
||||||
log.Printf("nexarch-core listening on %s", cfg.ListenAddr)
|
log.Printf("nexarch-core listening on %s", cfg.ListenAddr)
|
||||||
if err := http.ListenAndServe(cfg.ListenAddr, mux); err != nil {
|
if err := http.ListenAndServe(cfg.ListenAddr, mux); err != nil {
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
run:
|
|
||||||
timeout: 3m
|
|
||||||
|
|
||||||
linters:
|
|
||||||
disable-all: true
|
|
||||||
enable:
|
|
||||||
- govet
|
|
||||||
- staticcheck
|
|
||||||
- errcheck
|
|
||||||
- unused
|
|
||||||
- ineffassign
|
|
||||||
- gofmt
|
|
||||||
- goimports
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
.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
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
# 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.
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
// 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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
// 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.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
# 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.
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
# 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
@@ -1,14 +0,0 @@
|
|||||||
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,165 +0,0 @@
|
|||||||
// 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
|
|
||||||
}
|
|
||||||
@@ -1,204 +0,0 @@
|
|||||||
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")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
// 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"
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
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;
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
-- 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);
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
-- 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 $$;
|
|
||||||
@@ -3,3 +3,12 @@ module gitea.perlbach24.de/scripte/nexarch
|
|||||||
go 1.22
|
go 1.22
|
||||||
|
|
||||||
require github.com/jackc/pgx/v5 v5.6.0
|
require github.com/jackc/pgx/v5 v5.6.0
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||||
|
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
||||||
|
golang.org/x/crypto v0.17.0 // indirect
|
||||||
|
golang.org/x/sync v0.1.0 // indirect
|
||||||
|
golang.org/x/text v0.14.0 // indirect
|
||||||
|
)
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
// Package audit implementiert Core AUD-01: das zentrale, vom allgemeinen
|
||||||
|
// Anwendungs-Log getrennte Audit-Datenmodell fuer sicherheits- und
|
||||||
|
// compliancerelevante Ereignisse (wer, was, wann, an welchem Tenant).
|
||||||
|
// Unveraenderlichkeit (Append-only) ist AUD-02, Export/Filter-API ist AUD-03
|
||||||
|
// — dieses Paket liefert nur das Datenmodell und den EINEN zentralen
|
||||||
|
// Schreibpfad (Akzeptanzkriterium 3).
|
||||||
|
package audit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SystemTenant ist der reservierte Tenant-Bezug fuer mandantenuebergreifende
|
||||||
|
// Ereignisse (z.B. Superadmin-Aktionen) — es gibt bewusst KEINEN Weg, ein
|
||||||
|
// Ereignis ganz ohne Tenant-Bezug zu schreiben (Akzeptanzkriterium 2).
|
||||||
|
const SystemTenant = "system"
|
||||||
|
|
||||||
|
var ErrMissingTenant = errors.New("audit: tenant_slug darf nicht leer sein")
|
||||||
|
var ErrMissingActor = errors.New("audit: actor darf nicht leer sein")
|
||||||
|
var ErrMissingAction = errors.New("audit: action darf nicht leer sein")
|
||||||
|
|
||||||
|
// Event ist ein strukturiertes Audit-Ereignis (Akzeptanzkriterium 1: Akteur,
|
||||||
|
// Aktion, Zielobjekt, Zeitpunkt, Tenant).
|
||||||
|
type Event struct {
|
||||||
|
TenantSlug string
|
||||||
|
Actor string
|
||||||
|
Action string
|
||||||
|
Target string
|
||||||
|
Metadata map[string]any
|
||||||
|
OccurredAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// Log ist der EINE zentrale Schreibpfad fuer Audit-Ereignisse — es gibt
|
||||||
|
// bewusst keine zweite Schreibmoeglichkeit, damit kein Handler versehentlich
|
||||||
|
// direkt in audit_events schreibt und dabei die Validierung umgeht
|
||||||
|
// (Akzeptanzkriterium 3).
|
||||||
|
type Log struct {
|
||||||
|
pool *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLog(pool *pgxpool.Pool) *Log {
|
||||||
|
return &Log{pool: pool}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Record persistiert genau einen Audit-Eintrag. Fehlender Tenant-Bezug wird
|
||||||
|
// bereits hier abgewiesen (klarer Fehler statt Constraint-Verletzung im
|
||||||
|
// Normalfall) — die Datenbank-CHECK-Constraint aus der Migration ist die
|
||||||
|
// zweite, unumgehbare Verteidigungslinie (Akzeptanzkriterium 2 / Pruefung 2).
|
||||||
|
func (l *Log) Record(ctx context.Context, e Event) error {
|
||||||
|
if e.TenantSlug == "" {
|
||||||
|
return ErrMissingTenant
|
||||||
|
}
|
||||||
|
if e.Actor == "" {
|
||||||
|
return ErrMissingActor
|
||||||
|
}
|
||||||
|
if e.Action == "" {
|
||||||
|
return ErrMissingAction
|
||||||
|
}
|
||||||
|
if e.Metadata == nil {
|
||||||
|
e.Metadata = map[string]any{}
|
||||||
|
}
|
||||||
|
metadataJSON, err := json.Marshal(e.Metadata)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("metadaten serialisieren: %w", err)
|
||||||
|
}
|
||||||
|
if e.OccurredAt.IsZero() {
|
||||||
|
e.OccurredAt = time.Now()
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = l.pool.Exec(ctx, `
|
||||||
|
INSERT INTO audit_events (occurred_at, tenant_slug, actor, action, target, metadata)
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6)
|
||||||
|
`, e.OccurredAt, e.TenantSlug, e.Actor, e.Action, e.Target, metadataJSON)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("audit-ereignis schreiben: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CountByTenant ist eine schlanke Lesehilfe fuer Tests/Diagnose — die
|
||||||
|
// eigentliche Filter-/Export-API ist AUD-03, hier bewusst nicht vorgezogen.
|
||||||
|
func (l *Log) CountByTenant(ctx context.Context, tenantSlug string) (int, error) {
|
||||||
|
var n int
|
||||||
|
if err := l.pool.QueryRow(ctx, `
|
||||||
|
SELECT count(*) FROM audit_events WHERE tenant_slug = $1
|
||||||
|
`, tenantSlug).Scan(&n); err != nil {
|
||||||
|
return 0, fmt.Errorf("audit-ereignisse zaehlen: %w", err)
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
package audit
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
func setupAuditTest(t *testing.T) (*Log, *pgxpool.Pool, func()) {
|
||||||
|
t.Helper()
|
||||||
|
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
||||||
|
if adminDSN == "" {
|
||||||
|
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
pool, err := pgxpool.New(ctx, adminDSN)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("pool: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := pool.Exec(ctx, `
|
||||||
|
CREATE TABLE IF NOT EXISTS audit_events (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
tenant_slug TEXT NOT NULL CHECK (tenant_slug <> ''),
|
||||||
|
actor TEXT NOT NULL CHECK (actor <> ''),
|
||||||
|
action TEXT NOT NULL CHECK (action <> ''),
|
||||||
|
target TEXT NOT NULL,
|
||||||
|
metadata JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||||
|
)`); err != nil {
|
||||||
|
t.Fatalf("schema: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cleanup := func() {
|
||||||
|
_, _ = pool.Exec(ctx, `DELETE FROM audit_events WHERE tenant_slug LIKE 'test\_%' ESCAPE '\' OR tenant_slug = $1`, SystemTenant)
|
||||||
|
pool.Close()
|
||||||
|
}
|
||||||
|
return NewLog(pool), pool, cleanup
|
||||||
|
}
|
||||||
|
|
||||||
|
// Akzeptanzkriterium 1 + Pruefung 1: ein sicherheitsrelevanter Vorgang
|
||||||
|
// (hier: fehlgeschlagener Login) erzeugt zuverlaessig genau einen Eintrag.
|
||||||
|
func TestRecord_PersistsExactlyOneEventPerSecurityIncident(t *testing.T) {
|
||||||
|
log, pool, cleanup := setupAuditTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
err := log.Record(ctx, Event{
|
||||||
|
TenantSlug: "test_acme",
|
||||||
|
Actor: "alice@example.com",
|
||||||
|
Action: "iam.login_failed",
|
||||||
|
Target: "user:alice@example.com",
|
||||||
|
Metadata: map[string]any{"reason": "falsches passwort"},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("record: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
count, err := log.CountByTenant(ctx, "test_acme")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("count: %v", err)
|
||||||
|
}
|
||||||
|
if count != 1 {
|
||||||
|
t.Fatalf("erwartet genau 1 audit-eintrag, habe %d", count)
|
||||||
|
}
|
||||||
|
|
||||||
|
var actor, action, target string
|
||||||
|
if err := pool.QueryRow(ctx, `
|
||||||
|
SELECT actor, action, target FROM audit_events WHERE tenant_slug = 'test_acme'
|
||||||
|
`).Scan(&actor, &action, &target); err != nil {
|
||||||
|
t.Fatalf("eintrag lesen: %v", err)
|
||||||
|
}
|
||||||
|
if actor != "alice@example.com" || action != "iam.login_failed" || target != "user:alice@example.com" {
|
||||||
|
t.Fatalf("eintrag unerwartet: actor=%q action=%q target=%q", actor, action, target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Akzeptanzkriterium 2 + Pruefung 2 (App-Ebene): fehlender Tenant-Bezug wird
|
||||||
|
// bereits vom zentralen Schreibpfad abgewiesen.
|
||||||
|
func TestRecord_RejectsMissingTenant(t *testing.T) {
|
||||||
|
log, _, cleanup := setupAuditTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
err := log.Record(ctx, Event{TenantSlug: "", Actor: "alice", Action: "irgendwas"})
|
||||||
|
if !errors.Is(err, ErrMissingTenant) {
|
||||||
|
t.Fatalf("erwartet ErrMissingTenant, habe %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Akzeptanzkriterium 2 + Pruefung 2 (DB-Ebene): selbst ein direkter INSERT,
|
||||||
|
// der Log.Record umgeht, wird durch die CHECK-Constraint verhindert — der
|
||||||
|
// Schutz haengt nicht allein von der Go-Validierung ab.
|
||||||
|
func TestConstraint_RejectsMissingTenantAtDatabaseLevel(t *testing.T) {
|
||||||
|
_, pool, cleanup := setupAuditTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
_, err := pool.Exec(ctx, `
|
||||||
|
INSERT INTO audit_events (tenant_slug, actor, action, target)
|
||||||
|
VALUES ('', 'alice', 'irgendwas', 'ziel')
|
||||||
|
`)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("erwartet fehler durch CHECK-constraint bei leerem tenant_slug, habe nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRecord_RejectsMissingActorAndAction(t *testing.T) {
|
||||||
|
log, _, cleanup := setupAuditTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
if err := log.Record(ctx, Event{TenantSlug: "test_acme", Actor: "", Action: "x"}); !errors.Is(err, ErrMissingActor) {
|
||||||
|
t.Fatalf("erwartet ErrMissingActor, habe %v", err)
|
||||||
|
}
|
||||||
|
if err := log.Record(ctx, Event{TenantSlug: "test_acme", Actor: "alice", Action: ""}); !errors.Is(err, ErrMissingAction) {
|
||||||
|
t.Fatalf("erwartet ErrMissingAction, habe %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRecord_SystemTenantForCrossTenantEvents(t *testing.T) {
|
||||||
|
log, _, cleanup := setupAuditTest(t)
|
||||||
|
defer cleanup()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
if err := log.Record(ctx, Event{TenantSlug: SystemTenant, Actor: "superadmin", Action: "tenant.provisioned", Target: "tenant:acme"}); err != nil {
|
||||||
|
t.Fatalf("record mit SystemTenant: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,8 +10,15 @@ 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) {
|
||||||
@@ -20,10 +27,25 @@ func Load() (Config, error) {
|
|||||||
return Config{}, fmt.Errorf("NEXARCH_REGISTRY_DSN not set")
|
return Config{}, fmt.Errorf("NEXARCH_REGISTRY_DSN not set")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
adminDSN := os.Getenv("NEXARCH_ADMIN_DSN")
|
||||||
|
if adminDSN == "" {
|
||||||
|
return Config{}, fmt.Errorf("NEXARCH_ADMIN_DSN not set")
|
||||||
|
}
|
||||||
|
|
||||||
|
dsnTemplate := os.Getenv("NEXARCH_TENANT_DSN_TEMPLATE")
|
||||||
|
if dsnTemplate == "" {
|
||||||
|
return Config{}, fmt.Errorf("NEXARCH_TENANT_DSN_TEMPLATE not set")
|
||||||
|
}
|
||||||
|
|
||||||
addr := os.Getenv("NEXARCH_LISTEN_ADDR")
|
addr := os.Getenv("NEXARCH_LISTEN_ADDR")
|
||||||
if addr == "" {
|
if addr == "" {
|
||||||
addr = ":8080"
|
addr = ":8080"
|
||||||
}
|
}
|
||||||
|
|
||||||
return Config{ListenAddr: addr, RegistryDSN: dsn}, nil
|
return Config{
|
||||||
|
ListenAddr: addr,
|
||||||
|
RegistryDSN: dsn,
|
||||||
|
AdminDSN: adminDSN,
|
||||||
|
TenantDSNTemplate: dsnTemplate,
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package tenant
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Handler ist eine schlanke Vorbereitung der Schnittstelle fuer API-01
|
||||||
|
// (REST-API-Grundgerüst & Versionierung) und TEN-02 (Self-Service-Onboarding).
|
||||||
|
// Auth/Rate-Limiting/Versionierung selbst sind ausdruecklich nicht Teil von
|
||||||
|
// TEN-01 und werden dort nachgezogen.
|
||||||
|
type Handler struct {
|
||||||
|
provisioner *Provisioner
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(p *Provisioner) *Handler {
|
||||||
|
return &Handler{provisioner: p}
|
||||||
|
}
|
||||||
|
|
||||||
|
type createTenantRequest struct {
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) CreateTenant(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var req createTenantRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||||
|
http.Error(w, "ungueltige Anfrage", http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
t, err := h.provisioner.Provision(r.Context(), req.Slug, req.Name)
|
||||||
|
if err != nil {
|
||||||
|
if err == ErrInvalidSlug {
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
http.Error(w, "tenant konnte nicht angelegt werden", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(http.StatusCreated)
|
||||||
|
_ = json.NewEncoder(w).Encode(t)
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package tenant
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Provisioner legt fuer jeden neuen Mandanten eine vollstaendig isolierte
|
||||||
|
// PostgreSQL-Datenbank an und registriert sie transaktional in der Registry
|
||||||
|
// (Akzeptanzkriterium 2). Zwei Mandanten-Datenbanken sind danach auf
|
||||||
|
// Infrastrukturebene komplett getrennt (Akzeptanzkriterium 3).
|
||||||
|
type Provisioner struct {
|
||||||
|
// adminPool ist mit der Wartungsdatenbank (z. B. "postgres") verbunden
|
||||||
|
// und wird ausschliesslich fuer CREATE/DROP DATABASE verwendet, da diese
|
||||||
|
// Befehle in PostgreSQL nicht in einer Transaktion laufen koennen.
|
||||||
|
adminPool *pgxpool.Pool
|
||||||
|
registry *Registry
|
||||||
|
// dsnTemplate enthaelt genau ein "%s" als Platzhalter fuer den
|
||||||
|
// Datenbanknamen, z. B. "postgresql://user:pass@host:5432/%s?sslmode=disable".
|
||||||
|
dsnTemplate string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewProvisioner(adminPool *pgxpool.Pool, registry *Registry, dsnTemplate string) *Provisioner {
|
||||||
|
return &Provisioner{adminPool: adminPool, registry: registry, dsnTemplate: dsnTemplate}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Provision legt die Tenant-Datenbank an und registriert sie. Schlaegt die
|
||||||
|
// Registrierung fehl, wird die bereits angelegte Datenbank wieder entfernt,
|
||||||
|
// damit kein verwaister, unregistrierter Tenant zurueckbleibt.
|
||||||
|
func (p *Provisioner) Provision(ctx context.Context, slug, name string) (Tenant, error) {
|
||||||
|
if err := ValidateSlug(slug); err != nil {
|
||||||
|
return Tenant{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
dbName := dbNameForSlug(slug)
|
||||||
|
|
||||||
|
// CREATE DATABASE erlaubt keine Parameter-Platzhalter; slug ist durch
|
||||||
|
// ValidateSlug bereits auf [a-z0-9_] beschraenkt, Injektion ausgeschlossen.
|
||||||
|
if _, err := p.adminPool.Exec(ctx, fmt.Sprintf(`CREATE DATABASE %q`, dbName)); err != nil {
|
||||||
|
return Tenant{}, fmt.Errorf("tenant-datenbank anlegen: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
t := Tenant{
|
||||||
|
Slug: slug,
|
||||||
|
Name: name,
|
||||||
|
DBName: dbName,
|
||||||
|
DBDSN: fmt.Sprintf(p.dsnTemplate, dbName),
|
||||||
|
Status: StatusActive,
|
||||||
|
}
|
||||||
|
|
||||||
|
tx, err := p.registry.pool.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
p.rollbackDatabase(ctx, dbName)
|
||||||
|
return Tenant{}, fmt.Errorf("registry-transaktion starten: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
created, err := p.registry.insertTx(ctx, tx, t)
|
||||||
|
if err != nil {
|
||||||
|
_ = tx.Rollback(ctx)
|
||||||
|
p.rollbackDatabase(ctx, dbName)
|
||||||
|
return Tenant{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Commit(ctx); err != nil {
|
||||||
|
p.rollbackDatabase(ctx, dbName)
|
||||||
|
return Tenant{}, fmt.Errorf("registry-transaktion committen: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return created, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// rollbackDatabase entfernt eine bereits angelegte Tenant-Datenbank, wenn die
|
||||||
|
// Registrierung fehlschlug, damit Provisioning insgesamt atomar wirkt.
|
||||||
|
func (p *Provisioner) rollbackDatabase(ctx context.Context, dbName string) {
|
||||||
|
_, _ = p.adminPool.Exec(ctx, fmt.Sprintf(`DROP DATABASE IF EXISTS %q`, dbName))
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package tenant
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Integrationstest fuer Akzeptanzkriterien 2 und 3. Benoetigt eine echte
|
||||||
|
// Postgres-Instanz und wird ohne TEST_ADMIN_DSN uebersprungen, nicht als
|
||||||
|
// fehlgeschlagen gewertet — siehe Pruefungen-Ergebnis im PR.
|
||||||
|
//
|
||||||
|
// TEST_ADMIN_DSN muss auf die Wartungsdatenbank zeigen, z. B.:
|
||||||
|
//
|
||||||
|
// postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable
|
||||||
|
func TestProvision_CreatesIsolatedDatabases(t *testing.T) {
|
||||||
|
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
||||||
|
if adminDSN == "" {
|
||||||
|
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
adminPool, err := pgxpool.New(ctx, adminDSN)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("admin pool: %v", err)
|
||||||
|
}
|
||||||
|
defer adminPool.Close()
|
||||||
|
|
||||||
|
registryPool, err := pgxpool.New(ctx, adminDSN)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("registry pool: %v", err)
|
||||||
|
}
|
||||||
|
defer registryPool.Close()
|
||||||
|
|
||||||
|
if _, err := registryPool.Exec(ctx, `
|
||||||
|
CREATE TABLE IF NOT EXISTS tenants (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
slug TEXT NOT NULL UNIQUE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
db_name TEXT NOT NULL UNIQUE,
|
||||||
|
db_dsn TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'active',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
)`); err != nil {
|
||||||
|
t.Fatalf("registry-schema: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
dsnTemplate := strings.Replace(adminDSN, "/postgres?", "/%s?", 1)
|
||||||
|
registry := NewRegistry(registryPool)
|
||||||
|
provisioner := NewProvisioner(adminPool, registry, dsnTemplate)
|
||||||
|
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_, _ = registryPool.Exec(ctx, `DELETE FROM tenants WHERE slug IN ('acme','globex')`)
|
||||||
|
_, _ = adminPool.Exec(ctx, `DROP DATABASE IF EXISTS tenant_acme`)
|
||||||
|
_, _ = adminPool.Exec(ctx, `DROP DATABASE IF EXISTS tenant_globex`)
|
||||||
|
})
|
||||||
|
|
||||||
|
tenantA, err := provisioner.Provision(ctx, "acme", "Acme GmbH")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("provision acme: %v", err)
|
||||||
|
}
|
||||||
|
tenantB, err := provisioner.Provision(ctx, "globex", "Globex AG")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("provision globex: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if tenantA.DBName == tenantB.DBName {
|
||||||
|
t.Fatalf("erwartet unterschiedliche db_name, beide sind %q", tenantA.DBName)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Akzeptanzkriterium 3 / Pruefung 3: In der Datenbank von Tenant A existiert
|
||||||
|
// keine Verbindungsmoeglichkeit zu Tenant B, weil beide physisch getrennte
|
||||||
|
// Datenbanken sind, statt sich auf einen Query-Filter zu verlassen.
|
||||||
|
poolA, err := pgxpool.New(ctx, tenantA.DBDSN)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("connect tenant a: %v", err)
|
||||||
|
}
|
||||||
|
defer poolA.Close()
|
||||||
|
|
||||||
|
var globexVisible bool
|
||||||
|
err = poolA.QueryRow(ctx, `
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT 1 FROM pg_catalog.pg_database WHERE datname = $1
|
||||||
|
)
|
||||||
|
`, tenantB.DBName).Scan(&globexVisible)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("pruefung tenant-trennung: %v", err)
|
||||||
|
}
|
||||||
|
// pg_database ist clusterweit sichtbar (Existenz der DB), aber die
|
||||||
|
// eigentliche Pruefung ist: aus poolA (verbunden mit tenant_acme) ist keine
|
||||||
|
// Tabelle/Zeile aus tenant_globex erreichbar, da current_database() getrennt ist.
|
||||||
|
var currentDB string
|
||||||
|
if err := poolA.QueryRow(ctx, `SELECT current_database()`).Scan(¤tDB); err != nil {
|
||||||
|
t.Fatalf("current_database: %v", err)
|
||||||
|
}
|
||||||
|
if currentDB != tenantA.DBName {
|
||||||
|
t.Fatalf("current_database() = %q, want %q — keine physische Trennung", currentDB, tenantA.DBName)
|
||||||
|
}
|
||||||
|
if currentDB == tenantB.DBName {
|
||||||
|
t.Fatalf("tenant a verbindung zeigt auf tenant b datenbank")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package tenant
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Registry kapselt den Zugriff auf die Control-Plane-Registry-Datenbank.
|
||||||
|
// Sie enthaelt ausschliesslich Tenant-Metadaten (Akzeptanzkriterium 1) —
|
||||||
|
// niemals Geschaeftsdaten eines Mandanten.
|
||||||
|
type Registry struct {
|
||||||
|
pool *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRegistry(pool *pgxpool.Pool) *Registry {
|
||||||
|
return &Registry{pool: pool}
|
||||||
|
}
|
||||||
|
|
||||||
|
// insertTx schreibt den Tenant-Datensatz innerhalb einer laufenden Transaktion,
|
||||||
|
// damit Provisioner.Provision DB-Anlage und Registrierung atomar behandeln kann.
|
||||||
|
func (r *Registry) insertTx(ctx context.Context, tx pgx.Tx, t Tenant) (Tenant, error) {
|
||||||
|
row := tx.QueryRow(ctx, `
|
||||||
|
INSERT INTO tenants (slug, name, db_name, db_dsn, status)
|
||||||
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
|
RETURNING id, created_at
|
||||||
|
`, t.Slug, t.Name, t.DBName, t.DBDSN, t.Status)
|
||||||
|
|
||||||
|
if err := row.Scan(&t.ID, &t.CreatedAt); err != nil {
|
||||||
|
return Tenant{}, fmt.Errorf("tenant registrieren: %w", err)
|
||||||
|
}
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) GetBySlug(ctx context.Context, slug string) (Tenant, error) {
|
||||||
|
var t Tenant
|
||||||
|
row := r.pool.QueryRow(ctx, `
|
||||||
|
SELECT id, slug, name, db_name, db_dsn, status, created_at
|
||||||
|
FROM tenants WHERE slug = $1
|
||||||
|
`, slug)
|
||||||
|
|
||||||
|
if err := row.Scan(&t.ID, &t.Slug, &t.Name, &t.DBName, &t.DBDSN, &t.Status, &t.CreatedAt); err != nil {
|
||||||
|
return Tenant{}, fmt.Errorf("tenant laden: %w", err)
|
||||||
|
}
|
||||||
|
return t, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) List(ctx context.Context) ([]Tenant, error) {
|
||||||
|
rows, err := r.pool.Query(ctx, `
|
||||||
|
SELECT id, slug, name, db_name, db_dsn, status, created_at
|
||||||
|
FROM tenants ORDER BY created_at
|
||||||
|
`)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("tenants auflisten: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var out []Tenant
|
||||||
|
for rows.Next() {
|
||||||
|
var t Tenant
|
||||||
|
if err := rows.Scan(&t.ID, &t.Slug, &t.Name, &t.DBName, &t.DBDSN, &t.Status, &t.CreatedAt); err != nil {
|
||||||
|
return nil, fmt.Errorf("tenant lesen: %w", err)
|
||||||
|
}
|
||||||
|
out = append(out, t)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
// Package tenant implements Core TEN-01: die Control-Plane-Registry und die
|
||||||
|
// Provisioning-Routine fuer physisch getrennte Mandanten-Datenbanken (Modell C).
|
||||||
|
package tenant
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"regexp"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Status string
|
||||||
|
|
||||||
|
const (
|
||||||
|
StatusActive Status = "active"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Tenant struct {
|
||||||
|
ID string
|
||||||
|
Slug string
|
||||||
|
Name string
|
||||||
|
DBName string
|
||||||
|
DBDSN string
|
||||||
|
Status Status
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// slugPattern erzwingt sichere, als SQL-Identifier verwendbare Slugs, damit
|
||||||
|
// der Datenbankname niemals aus unkontrolliertem Nutzereingabe-Text gebaut wird.
|
||||||
|
var slugPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{1,48}$`)
|
||||||
|
|
||||||
|
var ErrInvalidSlug = errors.New("tenant: slug muss mit Kleinbuchstaben beginnen und darf nur [a-z0-9_] enthalten (2-49 Zeichen)")
|
||||||
|
|
||||||
|
func ValidateSlug(slug string) error {
|
||||||
|
if !slugPattern.MatchString(slug) {
|
||||||
|
return ErrInvalidSlug
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func dbNameForSlug(slug string) string {
|
||||||
|
return "tenant_" + slug
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package tenant
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestValidateSlug(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
slug string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{"acme", false},
|
||||||
|
{"acme_gmbh", false},
|
||||||
|
{"a1", false},
|
||||||
|
{"", true},
|
||||||
|
{"a", true},
|
||||||
|
{"1acme", true},
|
||||||
|
{"Acme", true},
|
||||||
|
{"acme-gmbh", true},
|
||||||
|
{"acme;drop table tenants", true},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, c := range cases {
|
||||||
|
err := ValidateSlug(c.slug)
|
||||||
|
if (err != nil) != c.wantErr {
|
||||||
|
t.Errorf("ValidateSlug(%q) error = %v, wantErr %v", c.slug, err, c.wantErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDBNameForSlug(t *testing.T) {
|
||||||
|
got := dbNameForSlug("acme")
|
||||||
|
want := "tenant_acme"
|
||||||
|
if got != want {
|
||||||
|
t.Errorf("dbNameForSlug() = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
DROP TABLE IF EXISTS tenants;
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
-- Control-plane registry: tenant list + connection info (Modell C).
|
|
||||||
-- Core TEN-01 (siehe core-kanban).
|
|
||||||
CREATE TABLE tenants (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
slug TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
db_dsn TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
-- Control-plane registry: Tenant-Liste + Verbindungsinformationen (Modell C).
|
||||||
|
-- Enthaelt AUSSCHLIESSLICH Tenant-Metadaten, keine Geschaeftsdaten eines Mandanten.
|
||||||
|
-- Core TEN-01 (siehe core-kanban/tickets/TEN-01.md).
|
||||||
|
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||||
|
|
||||||
|
CREATE TABLE tenants (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
slug TEXT NOT NULL UNIQUE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
db_name TEXT NOT NULL UNIQUE,
|
||||||
|
db_dsn TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'active',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
DROP TABLE IF EXISTS audit_events;
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
-- Zentrales Audit-Log-Modell (AUD-01, siehe core-kanban/tickets/AUD-01.md).
|
||||||
|
-- Getrennt vom allgemeinen Anwendungs-Log (Akzeptanzkriterium 2): eigene
|
||||||
|
-- Tabelle, eigenes Paket (internal/audit), kein Log-Framework.
|
||||||
|
-- tenant_slug ist NOT NULL + darf nicht leer sein (Akzeptanzkriterium 2 /
|
||||||
|
-- Pruefung 2) — mandantenuebergreifende Ereignisse nutzen den reservierten
|
||||||
|
-- Wert 'system', niemals NULL oder leeren String.
|
||||||
|
CREATE TABLE audit_events (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
tenant_slug TEXT NOT NULL CHECK (tenant_slug <> ''),
|
||||||
|
actor TEXT NOT NULL CHECK (actor <> ''),
|
||||||
|
action TEXT NOT NULL CHECK (action <> ''),
|
||||||
|
target TEXT NOT NULL,
|
||||||
|
metadata JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX audit_events_tenant_slug_idx ON audit_events (tenant_slug, occurred_at);
|
||||||
Executable
+24
@@ -0,0 +1,24 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Setzt die nexarch-Testumgebung zurueck: loescht die geteilte
|
||||||
|
# Registry-Tabelle "tenants" in der postgres-Wartungsdatenbank sowie alle
|
||||||
|
# tenant_*-Datenbanken. Noetig, weil verschiedene Feature-Branches
|
||||||
|
# unterschiedliche Registry-Schemata erwarten, aber dieselbe physische
|
||||||
|
# Postgres-Instanz auf dem Testhost teilen (siehe [[project-nexarch-test-infra]]).
|
||||||
|
#
|
||||||
|
# Aufruf: NEXARCH_TEST_DB_PASSWORD=... ./scripts/reset-test-env.sh
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
PASS="${NEXARCH_TEST_DB_PASSWORD:?Setze NEXARCH_TEST_DB_PASSWORD vor dem Aufruf}"
|
||||||
|
ROLE="nexarch_test"
|
||||||
|
|
||||||
|
export PGPASSWORD="$PASS"
|
||||||
|
|
||||||
|
psql -h localhost -U "$ROLE" -d postgres -v ON_ERROR_STOP=1 -c "DROP TABLE IF EXISTS tenants CASCADE;"
|
||||||
|
psql -h localhost -U "$ROLE" -d postgres -v ON_ERROR_STOP=1 -c "DROP TABLE IF EXISTS audit_events CASCADE;"
|
||||||
|
|
||||||
|
dbs=$(psql -h localhost -U "$ROLE" -d postgres -tAc "SELECT datname FROM pg_database WHERE datname LIKE 'tenant\_%' ESCAPE '\'")
|
||||||
|
for db in $dbs; do
|
||||||
|
psql -h localhost -U "$ROLE" -d postgres -v ON_ERROR_STOP=1 -c "DROP DATABASE IF EXISTS \"${db}\";"
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "Testumgebung zurueckgesetzt: registry-tabelle + $(echo "$dbs" | grep -c . || true) tenant-datenbank(en) entfernt."
|
||||||
Executable
+24
@@ -0,0 +1,24 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Ein-Kommando-Pruefung fuer den aktuellen Code-Stand auf dem Testhost:
|
||||||
|
# Registry+Tenant-DBs zuruecksetzen, dann build/vet/test in einem Rutsch.
|
||||||
|
# -p 1 ist Pflicht, da mehrere Pakete dieselbe physische Registry-Tabelle auf
|
||||||
|
# dem Testhost teilen (siehe [[project-nexarch-test-infra]]).
|
||||||
|
#
|
||||||
|
# Aufruf: NEXARCH_TEST_DB_PASSWORD=... ./scripts/run-checks.sh
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
PASS="${NEXARCH_TEST_DB_PASSWORD:?Setze NEXARCH_TEST_DB_PASSWORD vor dem Aufruf}"
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
NEXARCH_TEST_DB_PASSWORD="$PASS" bash scripts/reset-test-env.sh
|
||||||
|
|
||||||
|
export TEST_ADMIN_DSN="postgresql://nexarch_test:${PASS}@localhost:5432/postgres?sslmode=disable"
|
||||||
|
|
||||||
|
echo "== go build =="
|
||||||
|
go build ./...
|
||||||
|
|
||||||
|
echo "== go vet =="
|
||||||
|
go vet ./...
|
||||||
|
|
||||||
|
echo "== go test (-p 1) =="
|
||||||
|
go test ./... -p 1 -count=1
|
||||||
Reference in New Issue
Block a user