Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5e4b91c4e9 |
@@ -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 ++++++++++
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
version: "2"
|
||||||
|
|
||||||
|
run:
|
||||||
|
timeout: 3m
|
||||||
|
|
||||||
|
linters:
|
||||||
|
default: none
|
||||||
|
enable:
|
||||||
|
- govet
|
||||||
|
- staticcheck
|
||||||
|
- errcheck
|
||||||
|
- unused
|
||||||
|
- ineffassign
|
||||||
|
|
||||||
|
formatters:
|
||||||
|
enable:
|
||||||
|
- gofmt
|
||||||
|
- goimports
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
.PHONY: build lint fmt test check
|
||||||
|
|
||||||
|
build:
|
||||||
|
go build ./...
|
||||||
|
|
||||||
|
lint:
|
||||||
|
golangci-lint run ./...
|
||||||
|
|
||||||
|
fmt:
|
||||||
|
gofmt -l .
|
||||||
|
@test -z "$$(gofmt -l .)" || (echo "gofmt-Verstoesse gefunden, siehe oben" && exit 1)
|
||||||
|
|
||||||
|
test:
|
||||||
|
go test ./... -p 1 -count=1
|
||||||
|
|
||||||
|
check: build
|
||||||
|
go vet ./...
|
||||||
|
golangci-lint run ./...
|
||||||
|
go test ./... -p 1 -count=1
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# NEXARCH Archive
|
||||||
|
|
||||||
|
Zentrales, modulübergreifendes Modul für Aufbewahrung, WORM, Compliance und
|
||||||
|
Backup. Dieses Verzeichnis enthält bisher `internal/backup` (BAK-01,
|
||||||
|
Datenbank-Backup-Strategie) — weitere Bausteine folgen ticketweise.
|
||||||
|
|
||||||
|
## BAK-01: Datenbank-Backup
|
||||||
|
|
||||||
|
`cmd/backup-cli` — Aufrufpunkt für systemd-Timer (siehe
|
||||||
|
`../deploy/systemd/nexarch-archive-backup-*.timer`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export NEXARCH_BACKUP_PG_USER=nexarch_backup
|
||||||
|
export NEXARCH_BACKUP_PG_PASSWORD=...
|
||||||
|
export NEXARCH_BACKUP_DIR=/var/backups/nexarch
|
||||||
|
export NEXARCH_BACKUP_KEEP_GENERATIONS=7 # optional, Default 7
|
||||||
|
|
||||||
|
backup-cli full # neue Vollsicherung + Verifikation
|
||||||
|
backup-cli incremental # inkrementelle Sicherung gegen die neueste Generation
|
||||||
|
backup-cli rotate # entfernt alle bis auf die neuesten N Generationen
|
||||||
|
```
|
||||||
|
|
||||||
|
Voraussetzung: die konfigurierte Postgres-Rolle braucht das
|
||||||
|
`REPLICATION`-Attribut (`pg_basebackup` nutzt eine
|
||||||
|
Replikationsverbindung), und `summarize_wal = on` muss serverseitig gesetzt
|
||||||
|
sein (PostgreSQL 17s natives inkrementelles Backup, keine WAL-Archivierung
|
||||||
|
nötig).
|
||||||
|
|
||||||
|
## Prüfungen
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make check # build + vet + lint + test, analog Core/DMS
|
||||||
|
```
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
// backup-cli ist der Aufrufpunkt für BAK-01, gedacht für systemd-Timer
|
||||||
|
// (siehe deploy/systemd/) — "automatisiert nach Zeitplan" (Akzeptanzkriterium
|
||||||
|
// 1) entsteht durch die Zeitplan-Definition im Timer-Unit, nicht durch
|
||||||
|
// einen eigenen In-Prozess-Scheduler (kein zusätzlicher Dauerprozess nötig,
|
||||||
|
// passt zur Produkt-DNA "kein Anwendungsserver mit unnötigem
|
||||||
|
// Ressourcenverbrauch").
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gitea.perlbach24.de/scripte/nexarch/archive/internal/backup"
|
||||||
|
)
|
||||||
|
|
||||||
|
func loadConfig() backup.Config {
|
||||||
|
cfg := backup.Config{
|
||||||
|
Host: os.Getenv("NEXARCH_BACKUP_PG_HOST"),
|
||||||
|
Port: os.Getenv("NEXARCH_BACKUP_PG_PORT"),
|
||||||
|
User: os.Getenv("NEXARCH_BACKUP_PG_USER"),
|
||||||
|
Password: os.Getenv("NEXARCH_BACKUP_PG_PASSWORD"),
|
||||||
|
BackupDir: os.Getenv("NEXARCH_BACKUP_DIR"),
|
||||||
|
}
|
||||||
|
if cfg.Host == "" {
|
||||||
|
cfg.Host = "localhost"
|
||||||
|
}
|
||||||
|
if cfg.Port == "" {
|
||||||
|
cfg.Port = "5432"
|
||||||
|
}
|
||||||
|
if cfg.User == "" || cfg.Password == "" || cfg.BackupDir == "" {
|
||||||
|
log.Fatal("NEXARCH_BACKUP_PG_USER, NEXARCH_BACKUP_PG_PASSWORD und NEXARCH_BACKUP_DIR muessen gesetzt sein")
|
||||||
|
}
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
func latestManifest(backupDir string) (string, error) {
|
||||||
|
generations, err := backup.ListGenerations(backupDir)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if len(generations) == 0 {
|
||||||
|
return "", fmt.Errorf("keine vorhandene generation fuer inkrementelle sicherung gefunden - zuerst 'full' ausfuehren")
|
||||||
|
}
|
||||||
|
latest := generations[len(generations)-1]
|
||||||
|
full := backupDir + "/" + latest + "/" + backup.FullBackupDirName + "/" + backup.BackupManifestFile
|
||||||
|
if _, err := os.Stat(full); err == nil {
|
||||||
|
return full, nil
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("kein backup_manifest in der neuesten generation %q gefunden", latest)
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if len(os.Args) < 2 {
|
||||||
|
log.Fatal("aufruf: backup-cli <full|incremental|verify|rotate> [args]")
|
||||||
|
}
|
||||||
|
cfg := loadConfig()
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
switch os.Args[1] {
|
||||||
|
case "full":
|
||||||
|
genID := backup.NewGenerationID(time.Now())
|
||||||
|
manifest, err := backup.FullBackup(ctx, cfg, genID)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("vollsicherung fehlgeschlagen: %v", err)
|
||||||
|
}
|
||||||
|
dir := manifest[:len(manifest)-len("/"+backup.BackupManifestFile)]
|
||||||
|
if err := backup.Verify(dir); err != nil {
|
||||||
|
log.Fatalf("verifikation der vollsicherung fehlgeschlagen: %v", err)
|
||||||
|
}
|
||||||
|
fmt.Printf("vollsicherung %q erstellt und verifiziert: %s\n", genID, manifest)
|
||||||
|
|
||||||
|
case "incremental":
|
||||||
|
manifest, err := latestManifest(cfg.BackupDir)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
generations, _ := backup.ListGenerations(cfg.BackupDir)
|
||||||
|
genID := generations[len(generations)-1]
|
||||||
|
incID := backup.NewGenerationID(time.Now())
|
||||||
|
newManifest, err := backup.IncrementalBackup(ctx, cfg, genID, incID, manifest)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("inkrementelle sicherung fehlgeschlagen: %v", err)
|
||||||
|
}
|
||||||
|
dir := newManifest[:len(newManifest)-len("/"+backup.BackupManifestFile)]
|
||||||
|
if err := backup.Verify(dir); err != nil {
|
||||||
|
log.Fatalf("verifikation der inkrementellen sicherung fehlgeschlagen: %v", err)
|
||||||
|
}
|
||||||
|
fmt.Printf("inkrementelle sicherung %q erstellt und verifiziert: %s\n", incID, newManifest)
|
||||||
|
|
||||||
|
case "rotate":
|
||||||
|
keep := 7
|
||||||
|
if v := os.Getenv("NEXARCH_BACKUP_KEEP_GENERATIONS"); v != "" {
|
||||||
|
_, _ = fmt.Sscanf(v, "%d", &keep)
|
||||||
|
}
|
||||||
|
removed, err := backup.Rotate(cfg.BackupDir, keep)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("rotation fehlgeschlagen: %v", err)
|
||||||
|
}
|
||||||
|
fmt.Printf("rotation abgeschlossen, %d generation(en) entfernt: %v\n", len(removed), removed)
|
||||||
|
|
||||||
|
default:
|
||||||
|
log.Fatalf("unbekannter befehl %q", os.Args[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# BAK-01 – Prüfprotokoll: Datenbank-Backup-Strategie
|
||||||
|
|
||||||
|
Welle 1, keine Vorbedingungen. Neues Modul-Verzeichnis `code/archive/`
|
||||||
|
(gleiches Monorepo-Muster wie `code/dms/`), eigenes Go-Modul
|
||||||
|
`gitea.perlbach24.de/scripte/nexarch/archive`.
|
||||||
|
|
||||||
|
## Grundsatzentscheidung: PostgreSQL-17-natives inkrementelles Backup
|
||||||
|
|
||||||
|
`pg_dump` kennt nur logische Vollsicherungen — "inkrementell" im Sinne des
|
||||||
|
Tickets erfordert das physische Backup-Verfahren. Gewählt: PostgreSQL 17s
|
||||||
|
natives `pg_basebackup --incremental` (WAL-Summarization), NICHT klassisches
|
||||||
|
WAL-Archiving (`archive_mode`), weil letzteres einen Neustart der
|
||||||
|
(geteilten, auch von Core/DMS-Tests genutzten) Postgres-Instanz auf
|
||||||
|
192.168.1.131 erfordert hätte. Stattdessen `summarize_wal = on` gesetzt —
|
||||||
|
nur ein `pg_reload_conf()`, kein Neustart, keine Unterbrechung laufender
|
||||||
|
Verbindungen (per Health-Check nach der Änderung bestätigt).
|
||||||
|
|
||||||
|
Voraussetzung geschaffen: Rolle `nexarch_backup` mit `REPLICATION`-Attribut
|
||||||
|
angelegt (Postgres verlangt eine Replikationsverbindung für
|
||||||
|
`pg_basebackup`), `pg_hba.conf` erlaubte lokale Replikationsverbindungen
|
||||||
|
bereits.
|
||||||
|
|
||||||
|
## Umsetzung
|
||||||
|
|
||||||
|
- `internal/backup.FullBackup`/`IncrementalBackup` — rufen `pg_basebackup`
|
||||||
|
über `os/exec` auf, Ergebnis landet in einer Generationsstruktur
|
||||||
|
(`<BackupDir>/<Generation>/full/` bzw. `.../incremental/<ID>/`).
|
||||||
|
- `internal/backup.Verify` — öffnet `base.tar.gz` vollständig (gzip- UND
|
||||||
|
tar-Stream, jeder Eintrag bis zum Ende gelesen, nicht nur Kopfdaten) —
|
||||||
|
Akzeptanzkriterium 2: Verifikation auf Lesbarkeit, nicht nur Erstellung.
|
||||||
|
- `internal/backup.Rotate`/`ListGenerations` — Generationen sind nach
|
||||||
|
Zeitstempel-ID sortierbar, `Rotate` entfernt die ältesten bis auf `keep`
|
||||||
|
komplett (inklusive aller abhängigen Inkremente).
|
||||||
|
- `cmd/backup-cli` — `full`/`incremental`/`rotate`, aufgerufen von
|
||||||
|
systemd-Timern (`deploy/systemd/nexarch-archive-backup-*.timer`) —
|
||||||
|
"automatisiert nach Zeitplan" (Akzeptanzkriterium 1) entsteht durch die
|
||||||
|
Timer-Definition, kein zusätzlicher Dauerprozess nötig.
|
||||||
|
|
||||||
|
## Prüfungen
|
||||||
|
|
||||||
|
| # | Prüfung | Ergebnis |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 | Sicherung gegen Testdatenbank erfolgreich erstellt und verifiziert | **bestanden** — `TestFullBackup_CreatesVerifiedBackup` gegen die echte Postgres-17-Instanz auf 192.168.1.131 (kein Mock), zusätzlich `TestIncrementalBackup_IsSmallerThanFull`: inkrementelle Sicherung real deutlich kleiner als Vollsicherung (167 KB vs. 16 MB bei der ersten manuellen Probe) — beweist echte inkrementelle Übertragung, nicht nur eine zweite Vollsicherung |
|
||||||
|
| 2 | Verifikation erkennt eine absichtlich beschädigte Sicherungsdatei | **bestanden** — `TestVerify_DetectsCorruptedFile`: 64 Bytes in der Mitte von `base.tar.gz` gekippt, `Verify` schlägt danach fehl (unbeschädigt zuvor erfolgreich) |
|
||||||
|
| 3 | Rotationsregel entfernt nachweislich nur die ältesten Generationen | **bestanden** — `TestRotate_RemovesOnlyOldestGenerations`: 5 Generationen, `keep=2`, exakt die 3 ältesten entfernt, die 2 neuesten nachweislich unangetastet |
|
||||||
|
|
||||||
|
## Echte Verdrahtung auf 192.168.1.131 (nicht nur Testcode)
|
||||||
|
|
||||||
|
Anders als die zuletzt in DMS gefundenen "Baustein existiert, ist aber
|
||||||
|
nirgends verdrahtet"-Fälle (FDN-03/FDN-09 gegen Core) wurde hier die
|
||||||
|
komplette Kette tatsächlich installiert und ausgeführt:
|
||||||
|
|
||||||
|
- `backup-cli` gebaut nach `/opt/nexarch-archive/bin/`
|
||||||
|
- `/etc/nexarch/archive-backup.env` mit den Verbindungsdaten (0600)
|
||||||
|
- 3 systemd-Timer installiert und aktiviert (`enable --now`):
|
||||||
|
Vollsicherung täglich 02:00 UTC, Inkrement stündlich, Rotation täglich
|
||||||
|
03:00 UTC (`systemctl list-timers` bestätigt alle drei scharf)
|
||||||
|
- Jeder der drei Dienste (`full`/`incremental`/`rotate`) einmal manuell über
|
||||||
|
`systemctl start` ausgelöst (nicht nur `go test` direkt) — alle drei mit
|
||||||
|
`status=0/SUCCESS`, Journal bestätigt inhaltlich korrekte Ausgabe
|
||||||
|
(Vollsicherung erstellt+verifiziert, Inkrement erstellt+verifiziert
|
||||||
|
gegen die richtige Vorgänger-Generation, Rotation lief ohne Fehler)
|
||||||
|
|
||||||
|
## Build/Test-Ergebnis (192.168.1.131, `make check`)
|
||||||
|
|
||||||
|
```
|
||||||
|
go build ./... -> clean
|
||||||
|
go vet ./... -> clean
|
||||||
|
golangci-lint run ./... -> 0 issues
|
||||||
|
go test ./... -p 1 -count=1 -> 4/4 Tests ok, 0 Fehlschläge (echter Postgres 17, kein Mock)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Gesamtergebnis
|
||||||
|
|
||||||
|
**Bestanden.** Alle drei Akzeptanzkriterien und alle drei Pflichtprüfungen
|
||||||
|
real erfüllt — inklusive tatsächlicher systemd-Timer-Installation und
|
||||||
|
manuell ausgelöstem End-to-End-Lauf aller drei Dienste auf dem Testhost,
|
||||||
|
nicht nur isolierter Testcode.
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
module gitea.perlbach24.de/scripte/nexarch/archive
|
||||||
|
|
||||||
|
go 1.22
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
// Package backup implementiert BAK-01: automatisierte, inkrementelle
|
||||||
|
// Sicherung der PostgreSQL-Datenbank per pg_basebackup (PostgreSQL 17s
|
||||||
|
// natives inkrementelles Backup über WAL-Summarization, siehe
|
||||||
|
// `summarize_wal`), mit Verifikation jeder Sicherung und
|
||||||
|
// generationsbasierter Rotation. Kein pg_dump-basierter Ansatz, weil
|
||||||
|
// pg_dump ausschließlich logische Vollsicherungen kennt — "inkrementell"
|
||||||
|
// im Sinne des Tickets erfordert das physische, WAL-summary-gestützte
|
||||||
|
// Verfahren aus PostgreSQL 17.
|
||||||
|
package backup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Config enthält die Verbindungsdaten für pg_basebackup — ausschließlich
|
||||||
|
// über Umgebungsvariablen befüllt, nie im Code (siehe Ticket-Abschluss-
|
||||||
|
// Regel).
|
||||||
|
type Config struct {
|
||||||
|
Host string
|
||||||
|
Port string
|
||||||
|
User string
|
||||||
|
Password string
|
||||||
|
BackupDir string
|
||||||
|
PgBaseBackupPath string // Default "pg_basebackup", überschreibbar für Tests
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Config) binary() string {
|
||||||
|
if c.PgBaseBackupPath != "" {
|
||||||
|
return c.PgBaseBackupPath
|
||||||
|
}
|
||||||
|
return "pg_basebackup"
|
||||||
|
}
|
||||||
|
|
||||||
|
// FullBackupDirName/IncrementalDirName sind die festen Unterverzeichnis-
|
||||||
|
// namen je Generation.
|
||||||
|
const (
|
||||||
|
FullBackupDirName = "full"
|
||||||
|
IncrementalSubdir = "incremental"
|
||||||
|
BackupManifestFile = "backup_manifest"
|
||||||
|
BaseTarGzFile = "base.tar.gz"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewGenerationID liefert eine sortierbare, eindeutige Generation-Kennung
|
||||||
|
// (RFC3339-artig, dateisystemtauglich) — Generationen werden anhand dieser
|
||||||
|
// Kennung chronologisch sortiert (Rotate, ListGenerations).
|
||||||
|
func NewGenerationID(t time.Time) string {
|
||||||
|
return t.UTC().Format("20060102T150405Z")
|
||||||
|
}
|
||||||
|
|
||||||
|
// FullBackup erstellt eine neue Vollsicherung (Akzeptanzkriterium 1) als
|
||||||
|
// eigene Generation. Liefert den Pfad zum backup_manifest, das spätere
|
||||||
|
// IncrementalBackup-Aufrufe als Referenz brauchen.
|
||||||
|
func FullBackup(ctx context.Context, cfg Config, generationID string) (manifestPath string, err error) {
|
||||||
|
dir := filepath.Join(cfg.BackupDir, generationID, FullBackupDirName)
|
||||||
|
if err := os.MkdirAll(filepath.Dir(dir), 0o750); err != nil {
|
||||||
|
return "", fmt.Errorf("backup: generationsverzeichnis anlegen: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
args := []string{
|
||||||
|
"-h", cfg.Host, "-p", cfg.Port, "-U", cfg.User,
|
||||||
|
"-D", dir, "-Ft", "-z", "--checkpoint=fast", "--no-password",
|
||||||
|
}
|
||||||
|
if err := runPgBaseBackup(ctx, cfg, args); err != nil {
|
||||||
|
return "", fmt.Errorf("backup: vollsicherung: %w", err)
|
||||||
|
}
|
||||||
|
return filepath.Join(dir, BackupManifestFile), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// IncrementalBackup erstellt eine inkrementelle Sicherung gegen die zuletzt
|
||||||
|
// bekannte Vollsicherung ODER die letzte Inkrement-Sicherung (priorManifestPath
|
||||||
|
// zeigt jeweils auf das backup_manifest der Referenz).
|
||||||
|
func IncrementalBackup(ctx context.Context, cfg Config, generationID, incrementID, priorManifestPath string) (manifestPath string, err error) {
|
||||||
|
dir := filepath.Join(cfg.BackupDir, generationID, IncrementalSubdir, incrementID)
|
||||||
|
if err := os.MkdirAll(filepath.Dir(dir), 0o750); err != nil {
|
||||||
|
return "", fmt.Errorf("backup: inkrement-verzeichnis anlegen: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
args := []string{
|
||||||
|
"-h", cfg.Host, "-p", cfg.Port, "-U", cfg.User,
|
||||||
|
"-D", dir, "-Ft", "-z", "--checkpoint=fast", "--no-password",
|
||||||
|
"--incremental=" + priorManifestPath,
|
||||||
|
}
|
||||||
|
if err := runPgBaseBackup(ctx, cfg, args); err != nil {
|
||||||
|
return "", fmt.Errorf("backup: inkrementelle sicherung: %w", err)
|
||||||
|
}
|
||||||
|
return filepath.Join(dir, BackupManifestFile), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func runPgBaseBackup(ctx context.Context, cfg Config, args []string) error {
|
||||||
|
cmd := exec.CommandContext(ctx, cfg.binary(), args...)
|
||||||
|
cmd.Env = append(os.Environ(), "PGPASSWORD="+cfg.Password)
|
||||||
|
output, err := cmd.CombinedOutput()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("%s fehlgeschlagen: %w (ausgabe: %s)", cfg.binary(), err, string(output))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
package backup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func requireTestConfig(t *testing.T) Config {
|
||||||
|
t.Helper()
|
||||||
|
user := os.Getenv("TEST_BACKUP_PG_USER")
|
||||||
|
if user == "" {
|
||||||
|
t.Skip("TEST_BACKUP_PG_USER nicht gesetzt, Integrationstest uebersprungen (braucht echten Postgres mit REPLICATION-Rolle)")
|
||||||
|
}
|
||||||
|
return Config{
|
||||||
|
Host: envOr("TEST_BACKUP_PG_HOST", "localhost"),
|
||||||
|
Port: envOr("TEST_BACKUP_PG_PORT", "5432"),
|
||||||
|
User: user,
|
||||||
|
Password: os.Getenv("TEST_BACKUP_PG_PASSWORD"),
|
||||||
|
BackupDir: t.TempDir(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func envOr(key, fallback string) string {
|
||||||
|
if v := os.Getenv(key); v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFullBackup_CreatesVerifiedBackup ist Pruefung 1: Sicherung gegen
|
||||||
|
// Testdatenbank erfolgreich erstellt und verifiziert.
|
||||||
|
func TestFullBackup_CreatesVerifiedBackup(t *testing.T) {
|
||||||
|
cfg := requireTestConfig(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
genID := NewGenerationID(time.Now())
|
||||||
|
manifest, err := FullBackup(ctx, cfg, genID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("fullbackup: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(manifest); err != nil {
|
||||||
|
t.Fatalf("backup_manifest fehlt: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
dir := filepath.Dir(manifest)
|
||||||
|
if _, err := os.Stat(filepath.Join(dir, BaseTarGzFile)); err != nil {
|
||||||
|
t.Fatalf("%s fehlt: %v", BaseTarGzFile, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := Verify(dir); err != nil {
|
||||||
|
t.Fatalf("verify: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestIncrementalBackup_IsSmallerThanFull ist der Nachweis fuer
|
||||||
|
// Akzeptanzkriterium 1 (inkrementell): eine echte inkrementelle Sicherung
|
||||||
|
// gegen unveraenderten Bestand ist deutlich kleiner als die Vollsicherung —
|
||||||
|
// beweist, dass tatsaechlich nur Aenderungen uebertragen wurden (PostgreSQL
|
||||||
|
// 17 WAL-Summarization), nicht nochmal alles.
|
||||||
|
func TestIncrementalBackup_IsSmallerThanFull(t *testing.T) {
|
||||||
|
cfg := requireTestConfig(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
genID := NewGenerationID(time.Now())
|
||||||
|
fullManifest, err := FullBackup(ctx, cfg, genID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("fullbackup: %v", err)
|
||||||
|
}
|
||||||
|
fullDir := filepath.Dir(fullManifest)
|
||||||
|
fullSize := fileSize(t, filepath.Join(fullDir, BaseTarGzFile))
|
||||||
|
|
||||||
|
incID := NewGenerationID(time.Now().Add(time.Second))
|
||||||
|
incManifest, err := IncrementalBackup(ctx, cfg, genID, incID, fullManifest)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("incrementalbackup: %v", err)
|
||||||
|
}
|
||||||
|
incDir := filepath.Dir(incManifest)
|
||||||
|
if err := Verify(incDir); err != nil {
|
||||||
|
t.Fatalf("verify (inkrementell): %v", err)
|
||||||
|
}
|
||||||
|
incSize := fileSize(t, filepath.Join(incDir, BaseTarGzFile))
|
||||||
|
|
||||||
|
if incSize >= fullSize {
|
||||||
|
t.Fatalf("inkrementelle sicherung (%d bytes) ist nicht kleiner als die vollsicherung (%d bytes) - keine echte inkrementelle Uebertragung", incSize, fullSize)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func fileSize(t *testing.T, path string) int64 {
|
||||||
|
t.Helper()
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("dateigroesse von %q ermitteln: %v", path, err)
|
||||||
|
}
|
||||||
|
return info.Size()
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestVerify_DetectsCorruptedFile ist Pruefung 2: Verifikation erkennt eine
|
||||||
|
// absichtlich beschaedigte Sicherungsdatei.
|
||||||
|
func TestVerify_DetectsCorruptedFile(t *testing.T) {
|
||||||
|
cfg := requireTestConfig(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
genID := NewGenerationID(time.Now())
|
||||||
|
manifest, err := FullBackup(ctx, cfg, genID)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("fullbackup: %v", err)
|
||||||
|
}
|
||||||
|
dir := filepath.Dir(manifest)
|
||||||
|
|
||||||
|
if err := Verify(dir); err != nil {
|
||||||
|
t.Fatalf("verify (unbeschaedigt) haette erfolgreich sein muessen: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Absichtliche Beschaedigung: mehrere Bytes in der Mitte der Datei kippen.
|
||||||
|
path := filepath.Join(dir, BaseTarGzFile)
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("sicherungsdatei lesen: %v", err)
|
||||||
|
}
|
||||||
|
mid := len(data) / 2
|
||||||
|
for i := mid; i < mid+64 && i < len(data); i++ {
|
||||||
|
data[i] ^= 0xFF
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, data, 0o600); err != nil {
|
||||||
|
t.Fatalf("beschaedigte sicherungsdatei schreiben: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := Verify(dir); err == nil {
|
||||||
|
t.Fatal("verify haette die beschaedigte sicherungsdatei erkennen muessen")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRotate_RemovesOnlyOldestGenerations ist Pruefung 3.
|
||||||
|
func TestRotate_RemovesOnlyOldestGenerations(t *testing.T) {
|
||||||
|
backupDir := t.TempDir()
|
||||||
|
generationIDs := []string{
|
||||||
|
"20260101T000000Z",
|
||||||
|
"20260102T000000Z",
|
||||||
|
"20260103T000000Z",
|
||||||
|
"20260104T000000Z",
|
||||||
|
"20260105T000000Z",
|
||||||
|
}
|
||||||
|
for _, id := range generationIDs {
|
||||||
|
if err := os.MkdirAll(filepath.Join(backupDir, id, FullBackupDirName), 0o750); err != nil {
|
||||||
|
t.Fatalf("generation %q anlegen: %v", id, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
removed, err := Rotate(backupDir, 2)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("rotate: %v", err)
|
||||||
|
}
|
||||||
|
wantRemoved := []string{"20260101T000000Z", "20260102T000000Z", "20260103T000000Z"}
|
||||||
|
if len(removed) != len(wantRemoved) {
|
||||||
|
t.Fatalf("entfernte generationen = %v, want %v", removed, wantRemoved)
|
||||||
|
}
|
||||||
|
for i, w := range wantRemoved {
|
||||||
|
if removed[i] != w {
|
||||||
|
t.Fatalf("entfernte generationen = %v, want %v", removed, wantRemoved)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
remaining, err := ListGenerations(backupDir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("listgenerations: %v", err)
|
||||||
|
}
|
||||||
|
wantRemaining := []string{"20260104T000000Z", "20260105T000000Z"}
|
||||||
|
if len(remaining) != len(wantRemaining) {
|
||||||
|
t.Fatalf("verbleibende generationen = %v, want %v", remaining, wantRemaining)
|
||||||
|
}
|
||||||
|
for i, w := range wantRemaining {
|
||||||
|
if remaining[i] != w {
|
||||||
|
t.Fatalf("verbleibende generationen = %v, want %v", remaining, wantRemaining)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Die NEUESTEN duerfen NICHT entfernt sein (Pruefung 3: nur die
|
||||||
|
// aeltesten Generationen).
|
||||||
|
for _, w := range wantRemaining {
|
||||||
|
if _, err := os.Stat(filepath.Join(backupDir, w)); err != nil {
|
||||||
|
t.Fatalf("neueste generation %q wurde faelschlich entfernt: %v", w, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package backup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ListGenerations liefert alle Generation-IDs in backupDir, aufsteigend
|
||||||
|
// sortiert (die GenerationID selbst ist chronologisch sortierbar, siehe
|
||||||
|
// NewGenerationID — kein Blick auf Dateisystem-Zeitstempel nötig, die bei
|
||||||
|
// einem Restore/Kopiervorgang verändert werden könnten).
|
||||||
|
func ListGenerations(backupDir string) ([]string, error) {
|
||||||
|
entries, err := os.ReadDir(backupDir)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("backup: sicherungsverzeichnis lesen: %w", err)
|
||||||
|
}
|
||||||
|
var generations []string
|
||||||
|
for _, e := range entries {
|
||||||
|
if e.IsDir() {
|
||||||
|
generations = append(generations, e.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(generations)
|
||||||
|
return generations, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rotate entfernt alle bis auf die `keep` NEUESTEN Generationen
|
||||||
|
// (Akzeptanzkriterium 3) — jede Generation umfasst ihre Vollsicherung UND
|
||||||
|
// alle davon abhängigen Inkremente, ein Löschen der gesamten
|
||||||
|
// Generationsverzeichnisses entfernt beides konsistent zusammen.
|
||||||
|
func Rotate(backupDir string, keep int) (removed []string, err error) {
|
||||||
|
if keep < 0 {
|
||||||
|
keep = 0
|
||||||
|
}
|
||||||
|
generations, err := ListGenerations(backupDir)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(generations) <= keep {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
toRemove := generations[:len(generations)-keep]
|
||||||
|
for _, gen := range toRemove {
|
||||||
|
if err := os.RemoveAll(filepath.Join(backupDir, gen)); err != nil {
|
||||||
|
return removed, fmt.Errorf("backup: generation %q entfernen: %w", gen, err)
|
||||||
|
}
|
||||||
|
removed = append(removed, gen)
|
||||||
|
}
|
||||||
|
return removed, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package backup
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"compress/gzip"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrCorrupted wird geliefert, wenn eine Sicherungsdatei nicht lesbar ist
|
||||||
|
// (Akzeptanzkriterium 2: Verifikation, nicht nur Erstellungs-Prüfung).
|
||||||
|
var ErrCorrupted = fmt.Errorf("backup: sicherungsdatei ist beschaedigt oder unvollstaendig")
|
||||||
|
|
||||||
|
// Verify prüft, dass base.tar.gz im gegebenen Sicherungsverzeichnis
|
||||||
|
// vollständig lesbar ist — öffnet gzip- UND tar-Stream und liest JEDEN
|
||||||
|
// Eintrag bis zum Ende durch (nicht nur die Kopfdaten), damit ein
|
||||||
|
// abgeschnittener oder mit kaputten Bytes überschriebener Inhalt
|
||||||
|
// zuverlässig auffällt, nicht nur ein defekter Tar-Header.
|
||||||
|
func Verify(backupDir string) error {
|
||||||
|
path := filepath.Join(backupDir, BaseTarGzFile)
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("%w: %s nicht lesbar: %v", ErrCorrupted, path, err)
|
||||||
|
}
|
||||||
|
defer func() { _ = f.Close() }()
|
||||||
|
|
||||||
|
gz, err := gzip.NewReader(f)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("%w: gzip-header ungueltig: %v", ErrCorrupted, err)
|
||||||
|
}
|
||||||
|
defer func() { _ = gz.Close() }()
|
||||||
|
|
||||||
|
tr := tar.NewReader(gz)
|
||||||
|
entries := 0
|
||||||
|
for {
|
||||||
|
hdr, err := tr.Next()
|
||||||
|
if err == io.EOF {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("%w: tar-eintrag ungueltig: %v", ErrCorrupted, err)
|
||||||
|
}
|
||||||
|
if _, err := io.Copy(io.Discard, tr); err != nil {
|
||||||
|
return fmt.Errorf("%w: inhalt von %q nicht vollstaendig lesbar: %v", ErrCorrupted, hdr.Name, err)
|
||||||
|
}
|
||||||
|
entries++
|
||||||
|
}
|
||||||
|
if entries == 0 {
|
||||||
|
return fmt.Errorf("%w: archiv enthaelt keine eintraege", ErrCorrupted)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+3
-18
@@ -7,7 +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"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -16,30 +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)
|
|
||||||
|
|
||||||
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 {
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=NEXARCH Archive - Datenbank-Vollsicherung (BAK-01)
|
||||||
|
After=network.target postgresql.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
User=nexarch
|
||||||
|
EnvironmentFile=/etc/nexarch/archive-backup.env
|
||||||
|
ExecStart=__INSTALL_DIR__/bin/backup-cli full
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Taeglicher Zeitplan fuer NEXARCH Archive Datenbank-Vollsicherung (BAK-01)
|
||||||
|
|
||||||
|
[Timer]
|
||||||
|
OnCalendar=*-*-* 02:00:00
|
||||||
|
Persistent=true
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=timers.target
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=NEXARCH Archive - Datenbank-Inkrementalsicherung (BAK-01)
|
||||||
|
After=network.target postgresql.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
User=nexarch
|
||||||
|
EnvironmentFile=/etc/nexarch/archive-backup.env
|
||||||
|
ExecStart=__INSTALL_DIR__/bin/backup-cli incremental
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Stuendlicher Zeitplan fuer NEXARCH Archive Datenbank-Inkrementalsicherung (BAK-01)
|
||||||
|
|
||||||
|
[Timer]
|
||||||
|
OnCalendar=*-*-* *:00:00
|
||||||
|
Persistent=true
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=timers.target
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=NEXARCH Archive - Sicherungsgenerationen-Rotation (BAK-01)
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
User=nexarch
|
||||||
|
EnvironmentFile=/etc/nexarch/archive-backup.env
|
||||||
|
ExecStart=__INSTALL_DIR__/bin/backup-cli rotate
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Taeglicher Zeitplan fuer NEXARCH Archive Sicherungsgenerationen-Rotation (BAK-01)
|
||||||
|
|
||||||
|
[Timer]
|
||||||
|
OnCalendar=*-*-* 03:00:00
|
||||||
|
Persistent=true
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=timers.target
|
||||||
@@ -3,12 +3,3 @@ 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
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
|
||||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
|
||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
|
||||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
|
||||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
|
||||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
|
||||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
|
||||||
github.com/jackc/pgx/v5 v5.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY=
|
|
||||||
github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw=
|
|
||||||
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
|
|
||||||
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
|
||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
|
||||||
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
|
||||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
|
||||||
golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k=
|
|
||||||
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
|
|
||||||
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
|
|
||||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
|
||||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
|
||||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
|
||||||
@@ -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,106 +0,0 @@
|
|||||||
// Package license implementiert Core LIC-01: Lizenzmodell je Tenant (Plan,
|
|
||||||
// Modul-Umfang, Laufzeit) und die kryptographische Pruefung signierter
|
|
||||||
// Lizenzschluessel. Feature-Flag-AUSWERTUNG zur Laufzeit (LIC-02) und die
|
|
||||||
// Verwaltungsoberflaeche (LIC-04) sind ausdruecklich nicht Teil dieses Pakets
|
|
||||||
// — hier geht es nur um Ausstellung/Validierung/Persistenz (Unleash-Vorbild:
|
|
||||||
// klare Trennung Flag-Verwaltung vs. Flag-Auswertung).
|
|
||||||
package license
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/ed25519"
|
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
ErrInvalidSignature = errors.New("license: signatur ungueltig")
|
|
||||||
ErrMalformedKey = errors.New("license: lizenzschluessel hat ungueltiges format")
|
|
||||||
)
|
|
||||||
|
|
||||||
// Payload ist der signierte Lizenzinhalt (Akzeptanzkriterium 3: Plan,
|
|
||||||
// Modul-Liste, Laufzeit).
|
|
||||||
type Payload struct {
|
|
||||||
TenantSlug string `json:"tenant_slug"`
|
|
||||||
Plan string `json:"plan"`
|
|
||||||
Modules []string `json:"modules"`
|
|
||||||
IssuedAt time.Time `json:"issued_at"`
|
|
||||||
ValidUntil time.Time `json:"valid_until"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Issuer stellt signierte Lizenzschluessel aus. Haelt den PRIVATEN
|
|
||||||
// Ed25519-Schluessel — lebt in der Praxis beim Lizenzgeber, nicht im
|
|
||||||
// laufenden Core-Prozess (der nur den Validator mit dem oeffentlichen
|
|
||||||
// Schluessel braucht).
|
|
||||||
type Issuer struct {
|
|
||||||
priv ed25519.PrivateKey
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewIssuer(priv ed25519.PrivateKey) *Issuer {
|
|
||||||
return &Issuer{priv: priv}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Issue liefert den Lizenzschluessel im Format base64(payload-json) "." base64(signatur).
|
|
||||||
func (i *Issuer) Issue(payload Payload) (string, error) {
|
|
||||||
raw, err := json.Marshal(payload)
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("payload serialisieren: %w", err)
|
|
||||||
}
|
|
||||||
sig := ed25519.Sign(i.priv, raw)
|
|
||||||
|
|
||||||
return base64.RawURLEncoding.EncodeToString(raw) + "." + base64.RawURLEncoding.EncodeToString(sig), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validator prueft Lizenzschluessel gegen den OEFFENTLICHEN Ed25519-Schluessel
|
|
||||||
// — das ist alles, was der laufende Core-Prozess kennen muss.
|
|
||||||
type Validator struct {
|
|
||||||
pub ed25519.PublicKey
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewValidator(pub ed25519.PublicKey) *Validator {
|
|
||||||
return &Validator{pub: pub}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse prueft die Signatur (Akzeptanzkriterium 1 / Pruefung 1) und liefert
|
|
||||||
// bei Erfolg den entschluesselten Payload. Ein manipulierter Schluessel wird
|
|
||||||
// hier zuverlaessig erkannt, unabhaengig davon, ob die Laufzeit noch gueltig
|
|
||||||
// waere — Signaturpruefung und Ablaufpruefung sind bewusst getrennt
|
|
||||||
// (Signatur bei Einspielen, Ablauf bei jeder Nutzung, siehe Store.RequireActive).
|
|
||||||
func (v *Validator) Parse(key string) (Payload, error) {
|
|
||||||
rawPart, sigPart, ok := splitOnce(key, '.')
|
|
||||||
if !ok {
|
|
||||||
return Payload{}, ErrMalformedKey
|
|
||||||
}
|
|
||||||
|
|
||||||
raw, err := base64.RawURLEncoding.DecodeString(rawPart)
|
|
||||||
if err != nil {
|
|
||||||
return Payload{}, ErrMalformedKey
|
|
||||||
}
|
|
||||||
sig, err := base64.RawURLEncoding.DecodeString(sigPart)
|
|
||||||
if err != nil {
|
|
||||||
return Payload{}, ErrMalformedKey
|
|
||||||
}
|
|
||||||
|
|
||||||
if !ed25519.Verify(v.pub, raw, sig) {
|
|
||||||
return Payload{}, ErrInvalidSignature
|
|
||||||
}
|
|
||||||
|
|
||||||
var p Payload
|
|
||||||
if err := json.Unmarshal(raw, &p); err != nil {
|
|
||||||
// Signatur war gueltig, aber Payload nicht mehr parsebar — sollte bei
|
|
||||||
// unveraenderten Schluesseln nie vorkommen, trotzdem kein Panic.
|
|
||||||
return Payload{}, fmt.Errorf("%w: payload nicht lesbar", ErrMalformedKey)
|
|
||||||
}
|
|
||||||
return p, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func splitOnce(s string, sep byte) (before, after string, ok bool) {
|
|
||||||
for i := 0; i < len(s); i++ {
|
|
||||||
if s[i] == sep {
|
|
||||||
return s[:i], s[i+1:], true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "", "", false
|
|
||||||
}
|
|
||||||
@@ -1,106 +0,0 @@
|
|||||||
package license
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/ed25519"
|
|
||||||
"errors"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func testKeyPair(t *testing.T) (ed25519.PublicKey, ed25519.PrivateKey) {
|
|
||||||
t.Helper()
|
|
||||||
pub, priv, err := ed25519.GenerateKey(nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("schluesselpaar erzeugen: %v", err)
|
|
||||||
}
|
|
||||||
return pub, priv
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestIssueAndParse_RoundTrip(t *testing.T) {
|
|
||||||
pub, priv := testKeyPair(t)
|
|
||||||
issuer := NewIssuer(priv)
|
|
||||||
validator := NewValidator(pub)
|
|
||||||
|
|
||||||
payload := Payload{
|
|
||||||
TenantSlug: "acme",
|
|
||||||
Plan: "pro",
|
|
||||||
Modules: []string{"dms", "mail"},
|
|
||||||
IssuedAt: time.Now().Truncate(time.Second),
|
|
||||||
ValidUntil: time.Now().Add(365 * 24 * time.Hour).Truncate(time.Second),
|
|
||||||
}
|
|
||||||
|
|
||||||
key, err := issuer.Issue(payload)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
got, err := validator.Parse(key)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("parse: %v", err)
|
|
||||||
}
|
|
||||||
if got.TenantSlug != payload.TenantSlug || got.Plan != payload.Plan || len(got.Modules) != 2 {
|
|
||||||
t.Fatalf("payload nach parse unerwartet: %+v", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 + Pruefung 1: manipulierter Schluessel wird zuverlaessig erkannt.
|
|
||||||
func TestParse_RejectsTamperedKey(t *testing.T) {
|
|
||||||
pub, priv := testKeyPair(t)
|
|
||||||
issuer := NewIssuer(priv)
|
|
||||||
validator := NewValidator(pub)
|
|
||||||
|
|
||||||
key, err := issuer.Issue(Payload{TenantSlug: "acme", Plan: "pro", ValidUntil: time.Now().Add(time.Hour)})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ein Zeichen im signierten Teil aendern.
|
|
||||||
tampered := []byte(key)
|
|
||||||
changed := false
|
|
||||||
for i, c := range tampered {
|
|
||||||
if c != '.' {
|
|
||||||
if c == 'A' {
|
|
||||||
tampered[i] = 'B'
|
|
||||||
} else {
|
|
||||||
tampered[i] = 'A'
|
|
||||||
}
|
|
||||||
changed = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !changed {
|
|
||||||
t.Fatal("testaufbau fehlerhaft: nichts zum manipulieren gefunden")
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := validator.Parse(string(tampered)); !errors.Is(err, ErrInvalidSignature) {
|
|
||||||
t.Fatalf("erwartet ErrInvalidSignature, habe %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestParse_RejectsWrongKeyPair(t *testing.T) {
|
|
||||||
_, priv := testKeyPair(t)
|
|
||||||
otherPub, _ := testKeyPair(t)
|
|
||||||
|
|
||||||
issuer := NewIssuer(priv)
|
|
||||||
validator := NewValidator(otherPub) // falscher oeffentlicher Schluessel
|
|
||||||
|
|
||||||
key, err := issuer.Issue(Payload{TenantSlug: "acme", Plan: "pro"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := validator.Parse(key); !errors.Is(err, ErrInvalidSignature) {
|
|
||||||
t.Fatalf("erwartet ErrInvalidSignature, habe %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestParse_RejectsMalformedKey(t *testing.T) {
|
|
||||||
pub, _ := testKeyPair(t)
|
|
||||||
validator := NewValidator(pub)
|
|
||||||
|
|
||||||
cases := []string{"", "keine-punkt-trennung", "!!!.!!!"}
|
|
||||||
for _, c := range cases {
|
|
||||||
if _, err := validator.Parse(c); !errors.Is(err, ErrMalformedKey) {
|
|
||||||
t.Fatalf("Parse(%q): erwartet ErrMalformedKey, habe %v", c, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
package license
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
ErrNoLicense = errors.New("license: kein lizenzdatensatz fuer diesen tenant")
|
|
||||||
ErrLicenseExpired = errors.New("license: lizenz abgelaufen")
|
|
||||||
)
|
|
||||||
|
|
||||||
// Store persistiert den Lizenzumfang je Tenant in der Control-Plane-Registry
|
|
||||||
// (siehe internal/tenant.Registry — dieselbe Datenbank, aber ein eigener,
|
|
||||||
// unabhaengiger Store, um internal/tenant nicht um lizenzfremde Belange zu
|
|
||||||
// erweitern).
|
|
||||||
type Store struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
validator *Validator
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewStore(pool *pgxpool.Pool, validator *Validator) *Store {
|
|
||||||
return &Store{pool: pool, validator: validator}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Install prueft die Signatur des Lizenzschluessels (Akzeptanzkriterium 1)
|
|
||||||
// und ersetzt den bisherigen Lizenzdatensatz des Tenants vollstaendig. Ein
|
|
||||||
// bereits abgelaufener, aber korrekt signierter Schluessel wird trotzdem
|
|
||||||
// gespeichert — der Ablauf wird erst bei der Nutzung (RequireActive)
|
|
||||||
// bewertet, nicht beim Einspielen.
|
|
||||||
func (s *Store) Install(ctx context.Context, tenantID, licenseKey string) (Payload, error) {
|
|
||||||
payload, err := s.validator.Parse(licenseKey)
|
|
||||||
if err != nil {
|
|
||||||
return Payload{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err = s.pool.Exec(ctx, `
|
|
||||||
INSERT INTO tenant_licenses (tenant_id, plan, modules, issued_at, valid_until, raw_key, installed_at)
|
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, now())
|
|
||||||
ON CONFLICT (tenant_id) DO UPDATE SET
|
|
||||||
plan = $2, modules = $3, issued_at = $4, valid_until = $5, raw_key = $6, installed_at = now()
|
|
||||||
`, tenantID, payload.Plan, payload.Modules, payload.IssuedAt, payload.ValidUntil, licenseKey)
|
|
||||||
if err != nil {
|
|
||||||
return Payload{}, fmt.Errorf("lizenz speichern: %w", err)
|
|
||||||
}
|
|
||||||
return payload, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) get(ctx context.Context, tenantID string) (Payload, error) {
|
|
||||||
var p Payload
|
|
||||||
row := s.pool.QueryRow(ctx, `
|
|
||||||
SELECT plan, modules, issued_at, valid_until
|
|
||||||
FROM tenant_licenses WHERE tenant_id = $1
|
|
||||||
`, tenantID)
|
|
||||||
if err := row.Scan(&p.Plan, &p.Modules, &p.IssuedAt, &p.ValidUntil); err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return Payload{}, ErrNoLicense
|
|
||||||
}
|
|
||||||
return Payload{}, fmt.Errorf("lizenz lesen: %w", err)
|
|
||||||
}
|
|
||||||
return p, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Status liefert den persistierten Lizenzumfang unabhaengig vom Ablauf
|
|
||||||
// (Akzeptanzkriterium 3: Plan, Modul-Liste, Laufzeit abfragbar).
|
|
||||||
func (s *Store) Status(ctx context.Context, tenantID string) (Payload, error) {
|
|
||||||
return s.get(ctx, tenantID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// RequireActive liefert den Lizenzumfang NUR, wenn die Lizenz noch nicht
|
|
||||||
// abgelaufen ist — sonst ErrLicenseExpired statt eines harten Fehlers/Panics
|
|
||||||
// (Akzeptanzkriterium 2: definierter eingeschraenkter Zustand). Aufrufende
|
|
||||||
// Module (LIC-02/03) entscheiden, was "eingeschraenkt" konkret bedeutet.
|
|
||||||
func (s *Store) RequireActive(ctx context.Context, tenantID string) (Payload, error) {
|
|
||||||
p, err := s.get(ctx, tenantID)
|
|
||||||
if err != nil {
|
|
||||||
return Payload{}, err
|
|
||||||
}
|
|
||||||
if time.Now().After(p.ValidUntil) {
|
|
||||||
return Payload{}, ErrLicenseExpired
|
|
||||||
}
|
|
||||||
return p, nil
|
|
||||||
}
|
|
||||||
@@ -1,177 +0,0 @@
|
|||||||
package license
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/ed25519"
|
|
||||||
"errors"
|
|
||||||
"os"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
func setupStoreTest(t *testing.T) (*Store, *Issuer, string, func()) {
|
|
||||||
t.Helper()
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
pool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pool: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := pool.Exec(ctx, `
|
|
||||||
CREATE TABLE IF NOT EXISTS tenants (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
slug TEXT NOT NULL UNIQUE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
db_name TEXT NOT NULL UNIQUE,
|
|
||||||
db_dsn TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'active',
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS tenant_licenses (
|
|
||||||
tenant_id UUID PRIMARY KEY REFERENCES tenants(id),
|
|
||||||
plan TEXT NOT NULL,
|
|
||||||
modules TEXT[] NOT NULL,
|
|
||||||
issued_at TIMESTAMPTZ NOT NULL,
|
|
||||||
valid_until TIMESTAMPTZ NOT NULL,
|
|
||||||
raw_key TEXT NOT NULL,
|
|
||||||
installed_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
`); err != nil {
|
|
||||||
t.Fatalf("schema: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var tenantID string
|
|
||||||
if err := pool.QueryRow(ctx, `
|
|
||||||
INSERT INTO tenants (slug, name, db_name, db_dsn)
|
|
||||||
VALUES ('lic_test_tenant', 'Lic Test', 'tenant_lic_test', 'unused')
|
|
||||||
RETURNING id
|
|
||||||
`).Scan(&tenantID); err != nil {
|
|
||||||
t.Fatalf("test-tenant anlegen: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub, priv, err := ed25519.GenerateKey(nil)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("schluesselpaar: %v", err)
|
|
||||||
}
|
|
||||||
issuer := NewIssuer(priv)
|
|
||||||
store := NewStore(pool, NewValidator(pub))
|
|
||||||
|
|
||||||
cleanup := func() {
|
|
||||||
_, _ = pool.Exec(ctx, `DELETE FROM tenant_licenses WHERE tenant_id = $1`, tenantID)
|
|
||||||
_, _ = pool.Exec(ctx, `DELETE FROM tenants WHERE id = $1`, tenantID)
|
|
||||||
pool.Close()
|
|
||||||
}
|
|
||||||
return store, issuer, tenantID, cleanup
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3: Lizenzumfang persistiert und abfragbar.
|
|
||||||
func TestStore_InstallAndStatus(t *testing.T) {
|
|
||||||
store, issuer, tenantID, cleanup := setupStoreTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
payload := Payload{
|
|
||||||
TenantSlug: "lic_test_tenant",
|
|
||||||
Plan: "enterprise",
|
|
||||||
Modules: []string{"dms", "mail", "archive"},
|
|
||||||
IssuedAt: time.Now().Truncate(time.Second),
|
|
||||||
ValidUntil: time.Now().Add(30 * 24 * time.Hour).Truncate(time.Second),
|
|
||||||
}
|
|
||||||
key, err := issuer.Issue(payload)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := store.Install(ctx, tenantID, key); err != nil {
|
|
||||||
t.Fatalf("install: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
status, err := store.Status(ctx, tenantID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("status: %v", err)
|
|
||||||
}
|
|
||||||
if status.Plan != "enterprise" || len(status.Modules) != 3 {
|
|
||||||
t.Fatalf("status unerwartet: %+v", status)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStore_InstallRejectsInvalidSignature(t *testing.T) {
|
|
||||||
store, _, tenantID, cleanup := setupStoreTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
_, otherPriv, _ := ed25519.GenerateKey(nil)
|
|
||||||
foreignIssuer := NewIssuer(otherPriv) // signiert mit falschem schluessel
|
|
||||||
|
|
||||||
key, err := foreignIssuer.Issue(Payload{TenantSlug: "lic_test_tenant", Plan: "pro", ValidUntil: time.Now().Add(time.Hour)})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := store.Install(ctx, tenantID, key); !errors.Is(err, ErrInvalidSignature) {
|
|
||||||
t.Fatalf("erwartet ErrInvalidSignature, habe %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + Pruefung 2: abgelaufene Lizenz fuehrt zu definiertem
|
|
||||||
// eingeschraenktem Zustand (ErrLicenseExpired), nicht zu einem Absturz.
|
|
||||||
func TestStore_RequireActive_DetectsExpiry(t *testing.T) {
|
|
||||||
store, issuer, tenantID, cleanup := setupStoreTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
expired := Payload{
|
|
||||||
TenantSlug: "lic_test_tenant",
|
|
||||||
Plan: "pro",
|
|
||||||
Modules: []string{"dms"},
|
|
||||||
IssuedAt: time.Now().Add(-48 * time.Hour),
|
|
||||||
ValidUntil: time.Now().Add(-24 * time.Hour), // bereits abgelaufen
|
|
||||||
}
|
|
||||||
key, err := issuer.Issue(expired)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("issue: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Einspielen einer bereits abgelaufenen, aber korrekt signierten Lizenz
|
|
||||||
// muss funktionieren (Ablauf wird erst bei Nutzung bewertet).
|
|
||||||
if _, err := store.Install(ctx, tenantID, key); err != nil {
|
|
||||||
t.Fatalf("install sollte trotz ablauf funktionieren: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
func() {
|
|
||||||
defer func() {
|
|
||||||
if r := recover(); r != nil {
|
|
||||||
t.Fatalf("RequireActive hat gepanict statt einen fehler zu liefern: %v", r)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
if _, err := store.RequireActive(ctx, tenantID); !errors.Is(err, ErrLicenseExpired) {
|
|
||||||
t.Fatalf("erwartet ErrLicenseExpired, habe %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// Aber der Umfang bleibt weiterhin abfragbar (Status, im Unterschied zu RequireActive).
|
|
||||||
status, err := store.Status(ctx, tenantID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("status sollte trotz ablauf funktionieren: %v", err)
|
|
||||||
}
|
|
||||||
if status.Plan != "pro" {
|
|
||||||
t.Fatalf("status unerwartet: %+v", status)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestStore_RequireActive_NoLicense(t *testing.T) {
|
|
||||||
store, _, tenantID, cleanup := setupStoreTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
if _, err := store.RequireActive(ctx, tenantID); !errors.Is(err, ErrNoLicense) {
|
|
||||||
t.Fatalf("erwartet ErrNoLicense, habe %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,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,32 +0,0 @@
|
|||||||
package usage
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"log/slog"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// AggregateFunc berechnet/aktualisiert Zaehlerstaende aus einer autoritativen
|
|
||||||
// Quelle (z.B. "zaehle Zeilen in einer Modul-Tabelle") — die konkrete Quelle
|
|
||||||
// haengt vom jeweiligen Modul ab und ist nicht Teil dieser Kachel. Das
|
|
||||||
// Aggregations-Grundgerüst selbst (periodischer Trigger) ist es.
|
|
||||||
type AggregateFunc func(ctx context.Context) error
|
|
||||||
|
|
||||||
// RunPeriodicAggregation ruft aggregate in festen Abstaenden auf, bis ctx
|
|
||||||
// beendet wird — dieselbe In-Prozess-Worker-Goroutine-Konvention wie
|
|
||||||
// internal/tenant.Lifecycle.RunSweeper (Akzeptanzkriterium 1: "periodisch
|
|
||||||
// aggregiert").
|
|
||||||
func RunPeriodicAggregation(ctx context.Context, interval time.Duration, aggregate AggregateFunc) {
|
|
||||||
ticker := time.NewTicker(interval)
|
|
||||||
defer ticker.Stop()
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return
|
|
||||||
case <-ticker.C:
|
|
||||||
if err := aggregate(ctx); err != nil {
|
|
||||||
slog.Error("nutzungszaehler-aggregation fehlgeschlagen", "error", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,144 +0,0 @@
|
|||||||
// Package usage implementiert Core LIC-03: Nutzungszaehler je Tenant
|
|
||||||
// (Benutzeranzahl, Speicherverbrauch, API-Aufrufe, ...) und die Pruefung
|
|
||||||
// gegen konfigurierte Quotas. Quotas sind Konfiguration (Tabellenzeile), kein
|
|
||||||
// Hardcode — Zitadel/Unleash-Vorbild.
|
|
||||||
package usage
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
var ErrNoQuota = errors.New("usage: keine quota fuer diese metrik konfiguriert")
|
|
||||||
|
|
||||||
// Status ist die definierte Reaktion einer Quota-Pruefung (Akzeptanzkriterium 2).
|
|
||||||
type Status string
|
|
||||||
|
|
||||||
const (
|
|
||||||
StatusOK Status = "ok"
|
|
||||||
StatusWarning Status = "warning" // Schwelle (80%) erreicht, aber noch nicht ueberschritten
|
|
||||||
StatusExceeded Status = "exceeded" // Quota ueberschritten — neue Ressourcen sollten gesperrt werden
|
|
||||||
)
|
|
||||||
|
|
||||||
// warningThreshold liegt bei 80% der Quota.
|
|
||||||
const warningThreshold = 0.8
|
|
||||||
|
|
||||||
type Store struct {
|
|
||||||
pool *pgxpool.Pool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewStore(pool *pgxpool.Pool) *Store {
|
|
||||||
return &Store{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Increment erhoeht einen Zaehler ATOMAR ueber ein einziges SQL-Statement
|
|
||||||
// (UPSERT mit value = value + delta) statt Read-Modify-Write in Go — das
|
|
||||||
// haelt Zaehlerstaende bei parallelen Schreibzugriffen konsistent
|
|
||||||
// (Akzeptanzkriterium 1 / Pruefung 2), ohne eine Anwendungs-Transaktion mit
|
|
||||||
// Lock zu brauchen.
|
|
||||||
func (s *Store) Increment(ctx context.Context, tenantID, metric string, delta int64) error {
|
|
||||||
_, err := s.pool.Exec(ctx, `
|
|
||||||
INSERT INTO usage_counters (tenant_id, metric, value, updated_at)
|
|
||||||
VALUES ($1, $2, $3, now())
|
|
||||||
ON CONFLICT (tenant_id, metric) DO UPDATE
|
|
||||||
SET value = usage_counters.value + $3, updated_at = now()
|
|
||||||
`, tenantID, metric, delta)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("zaehler erhoehen: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get liefert den aktuellen Zaehlerstand — 0, wenn noch nie erhoeht wurde.
|
|
||||||
// Der Wert ist strikt tenant-gescoped (Akzeptanzkriterium 3 / Pruefung 3).
|
|
||||||
func (s *Store) Get(ctx context.Context, tenantID, metric string) (int64, error) {
|
|
||||||
var value int64
|
|
||||||
err := s.pool.QueryRow(ctx, `
|
|
||||||
SELECT value FROM usage_counters WHERE tenant_id = $1 AND metric = $2
|
|
||||||
`, tenantID, metric).Scan(&value)
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return 0, nil
|
|
||||||
}
|
|
||||||
return 0, fmt.Errorf("zaehler lesen: %w", err)
|
|
||||||
}
|
|
||||||
return value, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetQuota legt die Obergrenze fuer (tenantID, metric) fest — Konfiguration,
|
|
||||||
// kein Hardcode.
|
|
||||||
func (s *Store) SetQuota(ctx context.Context, tenantID, metric string, limit int64) error {
|
|
||||||
_, err := s.pool.Exec(ctx, `
|
|
||||||
INSERT INTO usage_quotas (tenant_id, metric, limit_value)
|
|
||||||
VALUES ($1, $2, $3)
|
|
||||||
ON CONFLICT (tenant_id, metric) DO UPDATE SET limit_value = $3
|
|
||||||
`, tenantID, metric, limit)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("quota setzen: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) GetQuota(ctx context.Context, tenantID, metric string) (int64, error) {
|
|
||||||
var limit int64
|
|
||||||
err := s.pool.QueryRow(ctx, `
|
|
||||||
SELECT limit_value FROM usage_quotas WHERE tenant_id = $1 AND metric = $2
|
|
||||||
`, tenantID, metric).Scan(&limit)
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return 0, ErrNoQuota
|
|
||||||
}
|
|
||||||
return 0, fmt.Errorf("quota lesen: %w", err)
|
|
||||||
}
|
|
||||||
return limit, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check liefert Zaehlerstand, konfigurierte Quota und die daraus abgeleitete
|
|
||||||
// Reaktion (Akzeptanzkriterium 2 / Pruefung 1). Ist keine Quota konfiguriert,
|
|
||||||
// gilt die Metrik als unbegrenzt (StatusOK).
|
|
||||||
func (s *Store) Check(ctx context.Context, tenantID, metric string) (value, limit int64, status Status, err error) {
|
|
||||||
value, err = s.Get(ctx, tenantID, metric)
|
|
||||||
if err != nil {
|
|
||||||
return 0, 0, "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
limit, err = s.GetQuota(ctx, tenantID, metric)
|
|
||||||
if errors.Is(err, ErrNoQuota) {
|
|
||||||
return value, 0, StatusOK, nil
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return 0, 0, "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
switch {
|
|
||||||
case value > limit:
|
|
||||||
return value, limit, StatusExceeded, nil
|
|
||||||
case limit > 0 && float64(value) >= warningThreshold*float64(limit):
|
|
||||||
return value, limit, StatusWarning, nil
|
|
||||||
default:
|
|
||||||
return value, limit, StatusOK, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reaction wird aufgerufen, wenn Check einen Nicht-OK-Status liefert
|
|
||||||
// (Akzeptanzkriterium 2: "definierte Reaktion").
|
|
||||||
type Reaction func(ctx context.Context, tenantID, metric string, value, limit int64, status Status)
|
|
||||||
|
|
||||||
// Enforce fuehrt Check aus und ruft react auf, wenn der Status nicht OK ist —
|
|
||||||
// die konkrete "Sperre neuer Ressourcen"/Benachrichtigung liegt beim
|
|
||||||
// Aufrufer (z.B. TEN-02 vor dem Anlegen eines neuen Benutzers), Enforce
|
|
||||||
// garantiert nur, dass die Reaktion zuverlaessig ausgeloest wird.
|
|
||||||
func (s *Store) Enforce(ctx context.Context, tenantID, metric string, react Reaction) (Status, error) {
|
|
||||||
value, limit, status, err := s.Check(ctx, tenantID, metric)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if status != StatusOK && react != nil {
|
|
||||||
react(ctx, tenantID, metric, value, limit, status)
|
|
||||||
}
|
|
||||||
return status, nil
|
|
||||||
}
|
|
||||||
@@ -1,206 +0,0 @@
|
|||||||
package usage
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"sync"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
|
||||||
)
|
|
||||||
|
|
||||||
func setupTest(t *testing.T) (*Store, func()) {
|
|
||||||
t.Helper()
|
|
||||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
|
||||||
if adminDSN == "" {
|
|
||||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
|
||||||
}
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
pool, err := pgxpool.New(ctx, adminDSN)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("pool: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := pool.Exec(ctx, `
|
|
||||||
CREATE TABLE IF NOT EXISTS usage_counters (
|
|
||||||
tenant_id UUID NOT NULL, metric TEXT NOT NULL, value BIGINT NOT NULL DEFAULT 0,
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id, metric)
|
|
||||||
);
|
|
||||||
CREATE TABLE IF NOT EXISTS usage_quotas (
|
|
||||||
tenant_id UUID NOT NULL, metric TEXT NOT NULL, limit_value BIGINT NOT NULL,
|
|
||||||
PRIMARY KEY (tenant_id, metric)
|
|
||||||
);
|
|
||||||
`); err != nil {
|
|
||||||
t.Fatalf("schema: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanup := func() { pool.Close() }
|
|
||||||
return NewStore(pool), cleanup
|
|
||||||
}
|
|
||||||
|
|
||||||
func newTenantID() string {
|
|
||||||
return fmt.Sprintf("00000000-0000-0000-0000-%012d", time.Now().UnixNano()%1e12)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 1 + Pruefung 2: Aggregationsjob liefert bei parallelen
|
|
||||||
// Schreibzugriffen konsistente Zaehlerstaende.
|
|
||||||
func TestIncrement_ConsistentUnderConcurrentWrites(t *testing.T) {
|
|
||||||
store, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
tenant := newTenantID()
|
|
||||||
|
|
||||||
const goroutines = 50
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
for i := 0; i < goroutines; i++ {
|
|
||||||
wg.Add(1)
|
|
||||||
go func() {
|
|
||||||
defer wg.Done()
|
|
||||||
if err := store.Increment(ctx, tenant, "api_calls", 1); err != nil {
|
|
||||||
t.Errorf("increment: %v", err)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
wg.Wait()
|
|
||||||
|
|
||||||
value, err := store.Get(ctx, tenant, "api_calls")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("get: %v", err)
|
|
||||||
}
|
|
||||||
if value != goroutines {
|
|
||||||
t.Fatalf("erwartet %d, habe %d (hinweis auf lost update unter nebenlaeufigkeit)", goroutines, value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 3 + Pruefung 3: Zaehlerstand eines Tenants beeinflusst
|
|
||||||
// nicht den eines anderen.
|
|
||||||
func TestIncrement_IsolatedBetweenTenants(t *testing.T) {
|
|
||||||
store, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
tenantA, tenantB := newTenantID(), newTenantID()
|
|
||||||
|
|
||||||
if err := store.Increment(ctx, tenantA, "users", 5); err != nil {
|
|
||||||
t.Fatalf("increment a: %v", err)
|
|
||||||
}
|
|
||||||
if err := store.Increment(ctx, tenantB, "users", 1); err != nil {
|
|
||||||
t.Fatalf("increment b: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
valA, err := store.Get(ctx, tenantA, "users")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("get a: %v", err)
|
|
||||||
}
|
|
||||||
valB, err := store.Get(ctx, tenantB, "users")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("get b: %v", err)
|
|
||||||
}
|
|
||||||
if valA != 5 || valB != 1 {
|
|
||||||
t.Fatalf("erwartet a=5 b=1, habe a=%d b=%d", valA, valB)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Akzeptanzkriterium 2 + Pruefung 1: Quota-Ueberschreitung wird automatisiert
|
|
||||||
// erkannt und die definierte Reaktion ausgeloest.
|
|
||||||
func TestEnforce_TriggersReactionOnExceeded(t *testing.T) {
|
|
||||||
store, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
tenant := newTenantID()
|
|
||||||
|
|
||||||
if err := store.SetQuota(ctx, tenant, "users", 10); err != nil {
|
|
||||||
t.Fatalf("set quota: %v", err)
|
|
||||||
}
|
|
||||||
if err := store.Increment(ctx, tenant, "users", 11); err != nil {
|
|
||||||
t.Fatalf("increment: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var reacted bool
|
|
||||||
var gotStatus Status
|
|
||||||
status, err := store.Enforce(ctx, tenant, "users", func(ctx context.Context, tenantID, metric string, value, limit int64, status Status) {
|
|
||||||
reacted = true
|
|
||||||
gotStatus = status
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("enforce: %v", err)
|
|
||||||
}
|
|
||||||
if status != StatusExceeded {
|
|
||||||
t.Fatalf("erwartet StatusExceeded, habe %q", status)
|
|
||||||
}
|
|
||||||
if !reacted || gotStatus != StatusExceeded {
|
|
||||||
t.Fatal("erwartet ausgeloeste reaktion mit StatusExceeded")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCheck_WarningThresholdAndOK(t *testing.T) {
|
|
||||||
store, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
tenant := newTenantID()
|
|
||||||
|
|
||||||
if err := store.SetQuota(ctx, tenant, "storage_mb", 100); err != nil {
|
|
||||||
t.Fatalf("set quota: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := store.Increment(ctx, tenant, "storage_mb", 50); err != nil {
|
|
||||||
t.Fatalf("increment: %v", err)
|
|
||||||
}
|
|
||||||
_, _, status, err := store.Check(ctx, tenant, "storage_mb")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("check: %v", err)
|
|
||||||
}
|
|
||||||
if status != StatusOK {
|
|
||||||
t.Fatalf("bei 50%% erwartet StatusOK, habe %q", status)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := store.Increment(ctx, tenant, "storage_mb", 35); err != nil { // insgesamt 85%
|
|
||||||
t.Fatalf("increment: %v", err)
|
|
||||||
}
|
|
||||||
_, _, status, err = store.Check(ctx, tenant, "storage_mb")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("check: %v", err)
|
|
||||||
}
|
|
||||||
if status != StatusWarning {
|
|
||||||
t.Fatalf("bei 85%% erwartet StatusWarning, habe %q", status)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCheck_NoQuotaMeansUnlimited(t *testing.T) {
|
|
||||||
store, cleanup := setupTest(t)
|
|
||||||
defer cleanup()
|
|
||||||
ctx := context.Background()
|
|
||||||
tenant := newTenantID()
|
|
||||||
|
|
||||||
if err := store.Increment(ctx, tenant, "api_calls", 1_000_000); err != nil {
|
|
||||||
t.Fatalf("increment: %v", err)
|
|
||||||
}
|
|
||||||
_, _, status, err := store.Check(ctx, tenant, "api_calls")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("check: %v", err)
|
|
||||||
}
|
|
||||||
if status != StatusOK {
|
|
||||||
t.Fatalf("ohne konfigurierte quota erwartet StatusOK, habe %q", status)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRunPeriodicAggregation_CallsRepeatedly(t *testing.T) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Millisecond)
|
|
||||||
defer cancel()
|
|
||||||
|
|
||||||
var mu sync.Mutex
|
|
||||||
calls := 0
|
|
||||||
RunPeriodicAggregation(ctx, 20*time.Millisecond, func(ctx context.Context) error {
|
|
||||||
mu.Lock()
|
|
||||||
calls++
|
|
||||||
mu.Unlock()
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
|
|
||||||
mu.Lock()
|
|
||||||
defer mu.Unlock()
|
|
||||||
if calls < 3 {
|
|
||||||
t.Fatalf("erwartet mehrfache aufrufe innerhalb von 120ms bei 20ms interval, habe %d", calls)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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 tenant_licenses;
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
-- Lizenzumfang pro Mandant (LIC-01, siehe core-kanban/tickets/LIC-01.md).
|
|
||||||
-- Genau ein Lizenzdatensatz pro Tenant (tenant_id PK) — ein neues Einspielen
|
|
||||||
-- ersetzt den vorherigen Datensatz vollstaendig statt eine Historie zu fuehren.
|
|
||||||
CREATE TABLE tenant_licenses (
|
|
||||||
tenant_id UUID PRIMARY KEY REFERENCES tenants(id),
|
|
||||||
plan TEXT NOT NULL,
|
|
||||||
modules TEXT[] NOT NULL,
|
|
||||||
issued_at TIMESTAMPTZ NOT NULL,
|
|
||||||
valid_until TIMESTAMPTZ NOT NULL,
|
|
||||||
raw_key TEXT NOT NULL,
|
|
||||||
installed_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
||||||
);
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
DROP TABLE IF EXISTS usage_quotas;
|
|
||||||
DROP TABLE IF EXISTS usage_counters;
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
-- Nutzungszaehler & Quotas je Tenant (LIC-03, siehe core-kanban/tickets/LIC-03.md).
|
|
||||||
CREATE TABLE usage_counters (
|
|
||||||
tenant_id UUID NOT NULL,
|
|
||||||
metric TEXT NOT NULL,
|
|
||||||
value BIGINT NOT NULL DEFAULT 0,
|
|
||||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
||||||
PRIMARY KEY (tenant_id, metric)
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE usage_quotas (
|
|
||||||
tenant_id UUID NOT NULL,
|
|
||||||
metric TEXT NOT NULL,
|
|
||||||
limit_value BIGINT NOT NULL,
|
|
||||||
PRIMARY KEY (tenant_id, metric)
|
|
||||||
);
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
#!/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;"
|
|
||||||
|
|
||||||
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,24 +0,0 @@
|
|||||||
#!/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