Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
44b78b1554 |
@@ -0,0 +1,23 @@
|
||||
name: Mail-Pflichttest-Gate
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- "mail/**"
|
||||
|
||||
jobs:
|
||||
pflichttest-gate:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.22"
|
||||
- name: Gate bauen
|
||||
working-directory: mail
|
||||
run: go build -o /tmp/pflichttestgate ./cmd/pflichttestgate
|
||||
- name: Geänderte Dateien gegen Pflichttest-Regel prüfen
|
||||
run: |
|
||||
git diff --name-only "origin/${{ github.base_ref }}...HEAD" | /tmp/pflichttestgate
|
||||
@@ -44,88 +44,3 @@ Keine Commits in dieser Session.
|
||||
Keine Änderungen ermittelbar.
|
||||
|
||||
---
|
||||
## 2026-08-27 17:26 – 17:28 (1m)
|
||||
**Beschreibung:** Claude Code Session
|
||||
**Projekt:** code
|
||||
|
||||
### Commits
|
||||
- c895a67 core: initial Go module skeleton (config, db pool, tenant registry migration)
|
||||
|
||||
### Geänderte Dateien
|
||||
- .gitignore | 2 ++
|
||||
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
||||
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
||||
- go.mod | 5 +++++
|
||||
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
||||
- internal/db/db.go | 11 +++++++++++
|
||||
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
||||
|
||||
---
|
||||
## 2026-08-27 17:28 – 17:29 (1m)
|
||||
**Beschreibung:** Claude Code Session
|
||||
**Projekt:** code
|
||||
|
||||
### Commits
|
||||
Keine Commits in dieser Session.
|
||||
|
||||
### Geänderte Dateien
|
||||
- .gitignore | 2 ++
|
||||
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
||||
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
||||
- go.mod | 5 +++++
|
||||
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
||||
- internal/db/db.go | 11 +++++++++++
|
||||
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
||||
|
||||
---
|
||||
## 2026-08-27 17:31 – 17:31 (0m)
|
||||
**Beschreibung:** Claude Code Session
|
||||
**Projekt:** code
|
||||
|
||||
### Commits
|
||||
Keine Commits in dieser Session.
|
||||
|
||||
### Geänderte Dateien
|
||||
- .gitignore | 2 ++
|
||||
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
||||
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
||||
- go.mod | 5 +++++
|
||||
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
||||
- internal/db/db.go | 11 +++++++++++
|
||||
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
||||
|
||||
---
|
||||
## 2026-08-27 17:36 – 17:36 (0m)
|
||||
**Beschreibung:** Claude Code Session
|
||||
**Projekt:** code
|
||||
|
||||
### Commits
|
||||
Keine Commits in dieser Session.
|
||||
|
||||
### Geänderte Dateien
|
||||
- .gitignore | 2 ++
|
||||
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
||||
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
||||
- go.mod | 5 +++++
|
||||
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
||||
- internal/db/db.go | 11 +++++++++++
|
||||
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
||||
|
||||
---
|
||||
## 2026-08-27 17:36 – 17:37 (0m)
|
||||
**Beschreibung:** Claude Code Session
|
||||
**Projekt:** code
|
||||
|
||||
### Commits
|
||||
Keine Commits in dieser Session.
|
||||
|
||||
### Geänderte Dateien
|
||||
- .gitignore | 2 ++
|
||||
- DEVLOG.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++
|
||||
- cmd/core/main.go | 33 +++++++++++++++++++++++++++++++++
|
||||
- go.mod | 5 +++++
|
||||
- internal/config/config.go | 29 +++++++++++++++++++++++++++++
|
||||
- internal/db/db.go | 11 +++++++++++
|
||||
- migrations/0001_tenant_registry.sql | 10 ++++++++++
|
||||
|
||||
---
|
||||
|
||||
+3
-18
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"gitea.perlbach24.de/scripte/nexarch/internal/config"
|
||||
"gitea.perlbach24.de/scripte/nexarch/internal/db"
|
||||
"gitea.perlbach24.de/scripte/nexarch/internal/tenant"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -16,30 +15,16 @@ func main() {
|
||||
log.Fatalf("config: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
registryPool, err := db.Connect(ctx, cfg.RegistryDSN)
|
||||
pool, err := db.Connect(context.Background(), cfg.RegistryDSN)
|
||||
if err != nil {
|
||||
log.Fatalf("registry db: %v", err)
|
||||
log.Fatalf("db: %v", err)
|
||||
}
|
||||
defer registryPool.Close()
|
||||
|
||||
adminPool, err := db.Connect(ctx, cfg.AdminDSN)
|
||||
if err != nil {
|
||||
log.Fatalf("admin db: %v", err)
|
||||
}
|
||||
defer adminPool.Close()
|
||||
|
||||
registry := tenant.NewRegistry(registryPool)
|
||||
provisioner := tenant.NewProvisioner(adminPool, registry, cfg.TenantDSNTemplate)
|
||||
tenantHandler := tenant.NewHandler(provisioner)
|
||||
defer pool.Close()
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
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)
|
||||
if err := http.ListenAndServe(cfg.ListenAddr, mux); err != nil {
|
||||
|
||||
@@ -3,12 +3,3 @@ module gitea.perlbach24.de/scripte/nexarch
|
||||
go 1.22
|
||||
|
||||
require github.com/jackc/pgx/v5 v5.6.0
|
||||
|
||||
require (
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
||||
golang.org/x/crypto v0.17.0 // indirect
|
||||
golang.org/x/sync v0.1.0 // indirect
|
||||
golang.org/x/text v0.14.0 // indirect
|
||||
)
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
// Package audit implementiert Core AUD-01: das zentrale, vom allgemeinen
|
||||
// Anwendungs-Log getrennte Audit-Datenmodell fuer sicherheits- und
|
||||
// compliancerelevante Ereignisse (wer, was, wann, an welchem Tenant).
|
||||
// Unveraenderlichkeit (Append-only) ist AUD-02, Export/Filter-API ist AUD-03
|
||||
// — dieses Paket liefert nur das Datenmodell und den EINEN zentralen
|
||||
// Schreibpfad (Akzeptanzkriterium 3).
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// SystemTenant ist der reservierte Tenant-Bezug fuer mandantenuebergreifende
|
||||
// Ereignisse (z.B. Superadmin-Aktionen) — es gibt bewusst KEINEN Weg, ein
|
||||
// Ereignis ganz ohne Tenant-Bezug zu schreiben (Akzeptanzkriterium 2).
|
||||
const SystemTenant = "system"
|
||||
|
||||
var ErrMissingTenant = errors.New("audit: tenant_slug darf nicht leer sein")
|
||||
var ErrMissingActor = errors.New("audit: actor darf nicht leer sein")
|
||||
var ErrMissingAction = errors.New("audit: action darf nicht leer sein")
|
||||
|
||||
// Event ist ein strukturiertes Audit-Ereignis (Akzeptanzkriterium 1: Akteur,
|
||||
// Aktion, Zielobjekt, Zeitpunkt, Tenant).
|
||||
type Event struct {
|
||||
TenantSlug string
|
||||
Actor string
|
||||
Action string
|
||||
Target string
|
||||
Metadata map[string]any
|
||||
OccurredAt time.Time
|
||||
}
|
||||
|
||||
// Log ist der EINE zentrale Schreibpfad fuer Audit-Ereignisse — es gibt
|
||||
// bewusst keine zweite Schreibmoeglichkeit, damit kein Handler versehentlich
|
||||
// direkt in audit_events schreibt und dabei die Validierung umgeht
|
||||
// (Akzeptanzkriterium 3).
|
||||
type Log struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewLog(pool *pgxpool.Pool) *Log {
|
||||
return &Log{pool: pool}
|
||||
}
|
||||
|
||||
// Record persistiert genau einen Audit-Eintrag. Fehlender Tenant-Bezug wird
|
||||
// bereits hier abgewiesen (klarer Fehler statt Constraint-Verletzung im
|
||||
// Normalfall) — die Datenbank-CHECK-Constraint aus der Migration ist die
|
||||
// zweite, unumgehbare Verteidigungslinie (Akzeptanzkriterium 2 / Pruefung 2).
|
||||
func (l *Log) Record(ctx context.Context, e Event) error {
|
||||
if e.TenantSlug == "" {
|
||||
return ErrMissingTenant
|
||||
}
|
||||
if e.Actor == "" {
|
||||
return ErrMissingActor
|
||||
}
|
||||
if e.Action == "" {
|
||||
return ErrMissingAction
|
||||
}
|
||||
if e.Metadata == nil {
|
||||
e.Metadata = map[string]any{}
|
||||
}
|
||||
metadataJSON, err := json.Marshal(e.Metadata)
|
||||
if err != nil {
|
||||
return fmt.Errorf("metadaten serialisieren: %w", err)
|
||||
}
|
||||
if e.OccurredAt.IsZero() {
|
||||
e.OccurredAt = time.Now()
|
||||
}
|
||||
|
||||
_, err = l.pool.Exec(ctx, `
|
||||
INSERT INTO audit_events (occurred_at, tenant_slug, actor, action, target, metadata)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
`, e.OccurredAt, e.TenantSlug, e.Actor, e.Action, e.Target, metadataJSON)
|
||||
if err != nil {
|
||||
return fmt.Errorf("audit-ereignis schreiben: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CountByTenant ist eine schlanke Lesehilfe fuer Tests/Diagnose — die
|
||||
// eigentliche Filter-/Export-API ist AUD-03, hier bewusst nicht vorgezogen.
|
||||
func (l *Log) CountByTenant(ctx context.Context, tenantSlug string) (int, error) {
|
||||
var n int
|
||||
if err := l.pool.QueryRow(ctx, `
|
||||
SELECT count(*) FROM audit_events WHERE tenant_slug = $1
|
||||
`, tenantSlug).Scan(&n); err != nil {
|
||||
return 0, fmt.Errorf("audit-ereignisse zaehlen: %w", err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
package audit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func setupAuditTest(t *testing.T) (*Log, *pgxpool.Pool, func()) {
|
||||
t.Helper()
|
||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
||||
if adminDSN == "" {
|
||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
pool, err := pgxpool.New(ctx, adminDSN)
|
||||
if err != nil {
|
||||
t.Fatalf("pool: %v", err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS audit_events (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
tenant_slug TEXT NOT NULL CHECK (tenant_slug <> ''),
|
||||
actor TEXT NOT NULL CHECK (actor <> ''),
|
||||
action TEXT NOT NULL CHECK (action <> ''),
|
||||
target TEXT NOT NULL,
|
||||
metadata JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||
)`); err != nil {
|
||||
t.Fatalf("schema: %v", err)
|
||||
}
|
||||
|
||||
cleanup := func() {
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM audit_events WHERE tenant_slug LIKE 'test\_%' ESCAPE '\' OR tenant_slug = $1`, SystemTenant)
|
||||
pool.Close()
|
||||
}
|
||||
return NewLog(pool), pool, cleanup
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 1 + Pruefung 1: ein sicherheitsrelevanter Vorgang
|
||||
// (hier: fehlgeschlagener Login) erzeugt zuverlaessig genau einen Eintrag.
|
||||
func TestRecord_PersistsExactlyOneEventPerSecurityIncident(t *testing.T) {
|
||||
log, pool, cleanup := setupAuditTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
err := log.Record(ctx, Event{
|
||||
TenantSlug: "test_acme",
|
||||
Actor: "alice@example.com",
|
||||
Action: "iam.login_failed",
|
||||
Target: "user:alice@example.com",
|
||||
Metadata: map[string]any{"reason": "falsches passwort"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("record: %v", err)
|
||||
}
|
||||
|
||||
count, err := log.CountByTenant(ctx, "test_acme")
|
||||
if err != nil {
|
||||
t.Fatalf("count: %v", err)
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatalf("erwartet genau 1 audit-eintrag, habe %d", count)
|
||||
}
|
||||
|
||||
var actor, action, target string
|
||||
if err := pool.QueryRow(ctx, `
|
||||
SELECT actor, action, target FROM audit_events WHERE tenant_slug = 'test_acme'
|
||||
`).Scan(&actor, &action, &target); err != nil {
|
||||
t.Fatalf("eintrag lesen: %v", err)
|
||||
}
|
||||
if actor != "alice@example.com" || action != "iam.login_failed" || target != "user:alice@example.com" {
|
||||
t.Fatalf("eintrag unerwartet: actor=%q action=%q target=%q", actor, action, target)
|
||||
}
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 2 + Pruefung 2 (App-Ebene): fehlender Tenant-Bezug wird
|
||||
// bereits vom zentralen Schreibpfad abgewiesen.
|
||||
func TestRecord_RejectsMissingTenant(t *testing.T) {
|
||||
log, _, cleanup := setupAuditTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
err := log.Record(ctx, Event{TenantSlug: "", Actor: "alice", Action: "irgendwas"})
|
||||
if !errors.Is(err, ErrMissingTenant) {
|
||||
t.Fatalf("erwartet ErrMissingTenant, habe %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 2 + Pruefung 2 (DB-Ebene): selbst ein direkter INSERT,
|
||||
// der Log.Record umgeht, wird durch die CHECK-Constraint verhindert — der
|
||||
// Schutz haengt nicht allein von der Go-Validierung ab.
|
||||
func TestConstraint_RejectsMissingTenantAtDatabaseLevel(t *testing.T) {
|
||||
_, pool, cleanup := setupAuditTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO audit_events (tenant_slug, actor, action, target)
|
||||
VALUES ('', 'alice', 'irgendwas', 'ziel')
|
||||
`)
|
||||
if err == nil {
|
||||
t.Fatal("erwartet fehler durch CHECK-constraint bei leerem tenant_slug, habe nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecord_RejectsMissingActorAndAction(t *testing.T) {
|
||||
log, _, cleanup := setupAuditTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
if err := log.Record(ctx, Event{TenantSlug: "test_acme", Actor: "", Action: "x"}); !errors.Is(err, ErrMissingActor) {
|
||||
t.Fatalf("erwartet ErrMissingActor, habe %v", err)
|
||||
}
|
||||
if err := log.Record(ctx, Event{TenantSlug: "test_acme", Actor: "alice", Action: ""}); !errors.Is(err, ErrMissingAction) {
|
||||
t.Fatalf("erwartet ErrMissingAction, habe %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecord_SystemTenantForCrossTenantEvents(t *testing.T) {
|
||||
log, _, cleanup := setupAuditTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
|
||||
if err := log.Record(ctx, Event{TenantSlug: SystemTenant, Actor: "superadmin", Action: "tenant.provisioned", Target: "tenant:acme"}); err != nil {
|
||||
t.Fatalf("record mit SystemTenant: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -10,15 +10,8 @@ import (
|
||||
// connection info, superadmin accounts) — see nexarch-state.json
|
||||
// multi_tenancy: Modell C (physisch getrennte DB pro Mandant).
|
||||
type Config struct {
|
||||
ListenAddr string
|
||||
// RegistryDSN verbindet zur Control-Plane-Registry-Datenbank.
|
||||
ListenAddr 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) {
|
||||
@@ -27,25 +20,10 @@ func Load() (Config, error) {
|
||||
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")
|
||||
if addr == "" {
|
||||
addr = ":8080"
|
||||
}
|
||||
|
||||
return Config{
|
||||
ListenAddr: addr,
|
||||
RegistryDSN: dsn,
|
||||
AdminDSN: adminDSN,
|
||||
TenantDSNTemplate: dsnTemplate,
|
||||
}, nil
|
||||
return Config{ListenAddr: addr, RegistryDSN: dsn}, nil
|
||||
}
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
package tenant
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Handler ist eine schlanke Vorbereitung der Schnittstelle fuer API-01
|
||||
// (REST-API-Grundgerüst & Versionierung) und TEN-02 (Self-Service-Onboarding).
|
||||
// Auth/Rate-Limiting/Versionierung selbst sind ausdruecklich nicht Teil von
|
||||
// TEN-01 und werden dort nachgezogen.
|
||||
type Handler struct {
|
||||
provisioner *Provisioner
|
||||
}
|
||||
|
||||
func NewHandler(p *Provisioner) *Handler {
|
||||
return &Handler{provisioner: p}
|
||||
}
|
||||
|
||||
type createTenantRequest struct {
|
||||
Slug string `json:"slug"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func (h *Handler) CreateTenant(w http.ResponseWriter, r *http.Request) {
|
||||
var req createTenantRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "ungueltige Anfrage", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
t, err := h.provisioner.Provision(r.Context(), req.Slug, req.Name)
|
||||
if err != nil {
|
||||
if err == ErrInvalidSlug {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
http.Error(w, "tenant konnte nicht angelegt werden", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_ = json.NewEncoder(w).Encode(t)
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package tenant
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// Provisioner legt fuer jeden neuen Mandanten eine vollstaendig isolierte
|
||||
// PostgreSQL-Datenbank an und registriert sie transaktional in der Registry
|
||||
// (Akzeptanzkriterium 2). Zwei Mandanten-Datenbanken sind danach auf
|
||||
// Infrastrukturebene komplett getrennt (Akzeptanzkriterium 3).
|
||||
type Provisioner struct {
|
||||
// adminPool ist mit der Wartungsdatenbank (z. B. "postgres") verbunden
|
||||
// und wird ausschliesslich fuer CREATE/DROP DATABASE verwendet, da diese
|
||||
// Befehle in PostgreSQL nicht in einer Transaktion laufen koennen.
|
||||
adminPool *pgxpool.Pool
|
||||
registry *Registry
|
||||
// dsnTemplate enthaelt genau ein "%s" als Platzhalter fuer den
|
||||
// Datenbanknamen, z. B. "postgresql://user:pass@host:5432/%s?sslmode=disable".
|
||||
dsnTemplate string
|
||||
}
|
||||
|
||||
func NewProvisioner(adminPool *pgxpool.Pool, registry *Registry, dsnTemplate string) *Provisioner {
|
||||
return &Provisioner{adminPool: adminPool, registry: registry, dsnTemplate: dsnTemplate}
|
||||
}
|
||||
|
||||
// Provision legt die Tenant-Datenbank an und registriert sie. Schlaegt die
|
||||
// Registrierung fehl, wird die bereits angelegte Datenbank wieder entfernt,
|
||||
// damit kein verwaister, unregistrierter Tenant zurueckbleibt.
|
||||
func (p *Provisioner) Provision(ctx context.Context, slug, name string) (Tenant, error) {
|
||||
if err := ValidateSlug(slug); err != nil {
|
||||
return Tenant{}, err
|
||||
}
|
||||
|
||||
dbName := dbNameForSlug(slug)
|
||||
|
||||
// CREATE DATABASE erlaubt keine Parameter-Platzhalter; slug ist durch
|
||||
// ValidateSlug bereits auf [a-z0-9_] beschraenkt, Injektion ausgeschlossen.
|
||||
if _, err := p.adminPool.Exec(ctx, fmt.Sprintf(`CREATE DATABASE %q`, dbName)); err != nil {
|
||||
return Tenant{}, fmt.Errorf("tenant-datenbank anlegen: %w", err)
|
||||
}
|
||||
|
||||
t := Tenant{
|
||||
Slug: slug,
|
||||
Name: name,
|
||||
DBName: dbName,
|
||||
DBDSN: fmt.Sprintf(p.dsnTemplate, dbName),
|
||||
Status: StatusActive,
|
||||
}
|
||||
|
||||
tx, err := p.registry.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
p.rollbackDatabase(ctx, dbName)
|
||||
return Tenant{}, fmt.Errorf("registry-transaktion starten: %w", err)
|
||||
}
|
||||
|
||||
created, err := p.registry.insertTx(ctx, tx, t)
|
||||
if err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
p.rollbackDatabase(ctx, dbName)
|
||||
return Tenant{}, err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
p.rollbackDatabase(ctx, dbName)
|
||||
return Tenant{}, fmt.Errorf("registry-transaktion committen: %w", err)
|
||||
}
|
||||
|
||||
return created, nil
|
||||
}
|
||||
|
||||
// rollbackDatabase entfernt eine bereits angelegte Tenant-Datenbank, wenn die
|
||||
// Registrierung fehlschlug, damit Provisioning insgesamt atomar wirkt.
|
||||
func (p *Provisioner) rollbackDatabase(ctx context.Context, dbName string) {
|
||||
_, _ = p.adminPool.Exec(ctx, fmt.Sprintf(`DROP DATABASE IF EXISTS %q`, dbName))
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
package tenant
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// Integrationstest fuer Akzeptanzkriterien 2 und 3. Benoetigt eine echte
|
||||
// Postgres-Instanz und wird ohne TEST_ADMIN_DSN uebersprungen, nicht als
|
||||
// fehlgeschlagen gewertet — siehe Pruefungen-Ergebnis im PR.
|
||||
//
|
||||
// TEST_ADMIN_DSN muss auf die Wartungsdatenbank zeigen, z. B.:
|
||||
//
|
||||
// postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable
|
||||
func TestProvision_CreatesIsolatedDatabases(t *testing.T) {
|
||||
adminDSN := os.Getenv("TEST_ADMIN_DSN")
|
||||
if adminDSN == "" {
|
||||
t.Skip("TEST_ADMIN_DSN nicht gesetzt, Integrationstest uebersprungen")
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
adminPool, err := pgxpool.New(ctx, adminDSN)
|
||||
if err != nil {
|
||||
t.Fatalf("admin pool: %v", err)
|
||||
}
|
||||
defer adminPool.Close()
|
||||
|
||||
registryPool, err := pgxpool.New(ctx, adminDSN)
|
||||
if err != nil {
|
||||
t.Fatalf("registry pool: %v", err)
|
||||
}
|
||||
defer registryPool.Close()
|
||||
|
||||
if _, err := registryPool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS tenants (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
slug TEXT NOT NULL UNIQUE,
|
||||
name TEXT NOT NULL,
|
||||
db_name TEXT NOT NULL UNIQUE,
|
||||
db_dsn TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'active',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)`); err != nil {
|
||||
t.Fatalf("registry-schema: %v", err)
|
||||
}
|
||||
|
||||
dsnTemplate := strings.Replace(adminDSN, "/postgres?", "/%s?", 1)
|
||||
registry := NewRegistry(registryPool)
|
||||
provisioner := NewProvisioner(adminPool, registry, dsnTemplate)
|
||||
|
||||
t.Cleanup(func() {
|
||||
_, _ = registryPool.Exec(ctx, `DELETE FROM tenants WHERE slug IN ('acme','globex')`)
|
||||
_, _ = adminPool.Exec(ctx, `DROP DATABASE IF EXISTS tenant_acme`)
|
||||
_, _ = adminPool.Exec(ctx, `DROP DATABASE IF EXISTS tenant_globex`)
|
||||
})
|
||||
|
||||
tenantA, err := provisioner.Provision(ctx, "acme", "Acme GmbH")
|
||||
if err != nil {
|
||||
t.Fatalf("provision acme: %v", err)
|
||||
}
|
||||
tenantB, err := provisioner.Provision(ctx, "globex", "Globex AG")
|
||||
if err != nil {
|
||||
t.Fatalf("provision globex: %v", err)
|
||||
}
|
||||
|
||||
if tenantA.DBName == tenantB.DBName {
|
||||
t.Fatalf("erwartet unterschiedliche db_name, beide sind %q", tenantA.DBName)
|
||||
}
|
||||
|
||||
// Akzeptanzkriterium 3 / Pruefung 3: In der Datenbank von Tenant A existiert
|
||||
// keine Verbindungsmoeglichkeit zu Tenant B, weil beide physisch getrennte
|
||||
// Datenbanken sind, statt sich auf einen Query-Filter zu verlassen.
|
||||
poolA, err := pgxpool.New(ctx, tenantA.DBDSN)
|
||||
if err != nil {
|
||||
t.Fatalf("connect tenant a: %v", err)
|
||||
}
|
||||
defer poolA.Close()
|
||||
|
||||
var globexVisible bool
|
||||
err = poolA.QueryRow(ctx, `
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM pg_catalog.pg_database WHERE datname = $1
|
||||
)
|
||||
`, tenantB.DBName).Scan(&globexVisible)
|
||||
if err != nil {
|
||||
t.Fatalf("pruefung tenant-trennung: %v", err)
|
||||
}
|
||||
// pg_database ist clusterweit sichtbar (Existenz der DB), aber die
|
||||
// eigentliche Pruefung ist: aus poolA (verbunden mit tenant_acme) ist keine
|
||||
// Tabelle/Zeile aus tenant_globex erreichbar, da current_database() getrennt ist.
|
||||
var currentDB string
|
||||
if err := poolA.QueryRow(ctx, `SELECT current_database()`).Scan(¤tDB); err != nil {
|
||||
t.Fatalf("current_database: %v", err)
|
||||
}
|
||||
if currentDB != tenantA.DBName {
|
||||
t.Fatalf("current_database() = %q, want %q — keine physische Trennung", currentDB, tenantA.DBName)
|
||||
}
|
||||
if currentDB == tenantB.DBName {
|
||||
t.Fatalf("tenant a verbindung zeigt auf tenant b datenbank")
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package tenant
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// Registry kapselt den Zugriff auf die Control-Plane-Registry-Datenbank.
|
||||
// Sie enthaelt ausschliesslich Tenant-Metadaten (Akzeptanzkriterium 1) —
|
||||
// niemals Geschaeftsdaten eines Mandanten.
|
||||
type Registry struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewRegistry(pool *pgxpool.Pool) *Registry {
|
||||
return &Registry{pool: pool}
|
||||
}
|
||||
|
||||
// insertTx schreibt den Tenant-Datensatz innerhalb einer laufenden Transaktion,
|
||||
// damit Provisioner.Provision DB-Anlage und Registrierung atomar behandeln kann.
|
||||
func (r *Registry) insertTx(ctx context.Context, tx pgx.Tx, t Tenant) (Tenant, error) {
|
||||
row := tx.QueryRow(ctx, `
|
||||
INSERT INTO tenants (slug, name, db_name, db_dsn, status)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING id, created_at
|
||||
`, t.Slug, t.Name, t.DBName, t.DBDSN, t.Status)
|
||||
|
||||
if err := row.Scan(&t.ID, &t.CreatedAt); err != nil {
|
||||
return Tenant{}, fmt.Errorf("tenant registrieren: %w", err)
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (r *Registry) GetBySlug(ctx context.Context, slug string) (Tenant, error) {
|
||||
var t Tenant
|
||||
row := r.pool.QueryRow(ctx, `
|
||||
SELECT id, slug, name, db_name, db_dsn, status, created_at
|
||||
FROM tenants WHERE slug = $1
|
||||
`, slug)
|
||||
|
||||
if err := row.Scan(&t.ID, &t.Slug, &t.Name, &t.DBName, &t.DBDSN, &t.Status, &t.CreatedAt); err != nil {
|
||||
return Tenant{}, fmt.Errorf("tenant laden: %w", err)
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (r *Registry) List(ctx context.Context) ([]Tenant, error) {
|
||||
rows, err := r.pool.Query(ctx, `
|
||||
SELECT id, slug, name, db_name, db_dsn, status, created_at
|
||||
FROM tenants ORDER BY created_at
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tenants auflisten: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var out []Tenant
|
||||
for rows.Next() {
|
||||
var t Tenant
|
||||
if err := rows.Scan(&t.ID, &t.Slug, &t.Name, &t.DBName, &t.DBDSN, &t.Status, &t.CreatedAt); err != nil {
|
||||
return nil, fmt.Errorf("tenant lesen: %w", err)
|
||||
}
|
||||
out = append(out, t)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
// Package tenant implements Core TEN-01: die Control-Plane-Registry und die
|
||||
// Provisioning-Routine fuer physisch getrennte Mandanten-Datenbanken (Modell C).
|
||||
package tenant
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Status string
|
||||
|
||||
const (
|
||||
StatusActive Status = "active"
|
||||
)
|
||||
|
||||
type Tenant struct {
|
||||
ID string
|
||||
Slug string
|
||||
Name string
|
||||
DBName string
|
||||
DBDSN string
|
||||
Status Status
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// slugPattern erzwingt sichere, als SQL-Identifier verwendbare Slugs, damit
|
||||
// der Datenbankname niemals aus unkontrolliertem Nutzereingabe-Text gebaut wird.
|
||||
var slugPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{1,48}$`)
|
||||
|
||||
var ErrInvalidSlug = errors.New("tenant: slug muss mit Kleinbuchstaben beginnen und darf nur [a-z0-9_] enthalten (2-49 Zeichen)")
|
||||
|
||||
func ValidateSlug(slug string) error {
|
||||
if !slugPattern.MatchString(slug) {
|
||||
return ErrInvalidSlug
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func dbNameForSlug(slug string) string {
|
||||
return "tenant_" + slug
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package tenant
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValidateSlug(t *testing.T) {
|
||||
cases := []struct {
|
||||
slug string
|
||||
wantErr bool
|
||||
}{
|
||||
{"acme", false},
|
||||
{"acme_gmbh", false},
|
||||
{"a1", false},
|
||||
{"", true},
|
||||
{"a", true},
|
||||
{"1acme", true},
|
||||
{"Acme", true},
|
||||
{"acme-gmbh", true},
|
||||
{"acme;drop table tenants", true},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
err := ValidateSlug(c.slug)
|
||||
if (err != nil) != c.wantErr {
|
||||
t.Errorf("ValidateSlug(%q) error = %v, wantErr %v", c.slug, err, c.wantErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDBNameForSlug(t *testing.T) {
|
||||
got := dbNameForSlug("acme")
|
||||
want := "tenant_acme"
|
||||
if got != want {
|
||||
t.Errorf("dbNameForSlug() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Command pflichttestgate ist das CI-Gate aus docs/TESTSTRATEGIE-MAIL.md
|
||||
// Abschnitt 4. Aufruf: pflichttestgate < geänderte-dateien.txt
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"gitea.perlbach24.de/scripte/nexarch/mail/internal/pflichttestgate"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var changedFiles []string
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if line != "" {
|
||||
changedFiles = append(changedFiles, line)
|
||||
}
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "pflichttestgate: eingabe konnte nicht gelesen werden: %v\n", err)
|
||||
os.Exit(2)
|
||||
}
|
||||
|
||||
violations := pflichttestgate.CheckDiff(changedFiles)
|
||||
if len(violations) == 0 {
|
||||
fmt.Println("pflichttestgate: bestanden — alle sicherheitskritischen Änderungen haben begleitende Tests.")
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Fprintln(os.Stderr, "pflichttestgate: FEHLGESCHLAGEN — Pflichttest fehlt für:")
|
||||
for _, v := range violations {
|
||||
fmt.Fprintf(os.Stderr, " - Package %q (Datei %q hat keine begleitende _test.go-Änderung)\n", v.Package, v.ChangedFile)
|
||||
}
|
||||
fmt.Fprintln(os.Stderr, "\nSiehe docs/TESTSTRATEGIE-MAIL.md Abschnitt 4.")
|
||||
os.Exit(1)
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
# NEXARCH Mail – Teststrategie
|
||||
|
||||
Stand: 2026-08-30. Ticket: QA-01. Vorbild: Core `QA-01` (`docs/TESTSTRATEGIE-CORE.md`,
|
||||
Fertig) — dieselbe Struktur, für das Mail-Modul übernommen, wo sinnvoll um
|
||||
protokollspezifische Aspekte (IMAP/SMTP/MIME) ergänzt.
|
||||
|
||||
## 1. Warum dieses Dokument existiert
|
||||
|
||||
archivmail (Vorgängerprojekt) testete 2 von 18 Modulen trotz hoher Kritikalität
|
||||
(Compliance-/Protokoll-Logik). Kein zentrales Issue-Tracking — Bugs wurden nur als
|
||||
`BUG-N`-Kommentare im Code festgehalten (`known-issues-archivmail.md`). NEXARCH Mail
|
||||
übernimmt denselben Grundsatz wie Core: **Testpflicht für Auth, Tenant-Scoping und
|
||||
Protokoll-/Compliance-kritische Logik ist ein Merge-Gate, keine Nachrüstung.**
|
||||
|
||||
## 2. Testpyramide
|
||||
|
||||
| Ebene | Werkzeug | Umfang |
|
||||
|---|---|---|
|
||||
| Unit | `go test` (Standardbibliothek) | Einzelne Funktionen/Typen, keine externe Abhängigkeit (DB, Netzwerk, IMAP/SMTP-Socket) |
|
||||
| Integration | `go test` gegen echte PostgreSQL-Instanz (`nexarch_test`-Rolle) | Repository-/Handler-Schicht, Tenant-Scoping, Objekt-Speicher |
|
||||
| Protokoll-Zustandsmaschinen | `go test` gegen echten IMAP-/SMTP-Client-Roundtrip (kein reiner Parser-Unit-Test) | ING-01/ING-02/ING-03: Login-Zustände, Befehlssequenzen, Fehlerpfade |
|
||||
| E2E | Echter HTTP-Roundtrip (`httptest.Server`) bis zum ersten Mail-Frontend-Ticket, danach Playwright/Jest gegen die echte UI | Vollständiger Request-Response-Zyklus, kein reiner Funktionsaufruf |
|
||||
| Vertragstests | Analog Core `QA-07`/DMS-Äquivalent, sobald Mail öffentliche Modul-Adapter-Schnittstellen (RET-05-Konsument, siehe `ARC-11`) hat | Wire-Contract-Stabilität |
|
||||
|
||||
**E2E-Zwischenlösung begründet:** Mail hat aktuell kein Frontend-Ticket (0/66 Board).
|
||||
Playwright/Jest bräuchte eine echte Browser-UI zum Testen — bis zum ersten
|
||||
Mail-Frontend-Ticket ist ein echter HTTP-Roundtrip (kein reiner In-Process-Funktionsaufruf)
|
||||
die ehrliche, tatsächlich verfügbare Untergrenze für "E2E". Siehe Beispiel in
|
||||
Abschnitt 3.
|
||||
|
||||
## 3. Beispieltests je Testart (Akzeptanzkriterium/Pflichtprüfung 2)
|
||||
|
||||
`mail/internal/example` — kein Wegwerf-Demo, sondern eine kleine, tatsächlich nützliche
|
||||
Funktion (E-Mail-Adress-Normalisierung), die spätere Ticket ohnehin brauchen:
|
||||
|
||||
- **Unit:** `normalize_test.go` — `TestNormalizeAddress_*`, keine externe Abhängigkeit.
|
||||
- **Integration:** `store_integration_test.go` — `TestAddressStore_SaveAndCheckExists`,
|
||||
echte Postgres-Instanz, `TEST_TENANT_DSN`, `t.Cleanup`.
|
||||
- **E2E:** `handler_e2e_test.go` — `TestNormalizeHandler_RealHTTPRoundTrip`, echter
|
||||
`httptest.Server`-Roundtrip (TCP, nicht nur Funktionsaufruf).
|
||||
|
||||
Alle sechs Tests real ausgeführt (siehe Prüfungen, Abschnitt 6).
|
||||
|
||||
## 4. Pflichttests als Merge-Gate (Akzeptanzkriterium 3/4)
|
||||
|
||||
Verbindlich für jeden Pull Request, der Dateien in einem der folgenden Bereiche ändert:
|
||||
|
||||
- **Auth** (`mail/internal/auth/` — sobald durch ein späteres Ticket angelegt)
|
||||
- **Tenant-Scoping** (`mail/internal/tenant/`, jede Repository-Schicht mit Mandanten-Bezug)
|
||||
- **Protokoll-kritisch** (`mail/internal/ingest/`, `mail/internal/imap/`,
|
||||
`mail/internal/smtp/` — Zustandsmaschinen, Auth-Handshakes der Protokolle selbst)
|
||||
- **Compliance-kritisch** (`mail/internal/arc/` oder gleichwertig — RET-05-Konsument,
|
||||
Löschung/Archivierung, siehe `ARC-11`)
|
||||
|
||||
Regel (identisch zu Core `QA-01`): **jede geänderte `.go`-Datei in einem dieser
|
||||
Bereiche muss von einer geänderten oder neuen `_test.go`-Datei im selben Package
|
||||
begleitet sein.**
|
||||
|
||||
`mail/internal/pflichttestgate` implementiert das Gate (Code-Kopie des Musters aus
|
||||
Core `internal/pflichttestgate`, mit mail-spezifischen Pfadmustern statt Core-Pfaden
|
||||
— bewusst keine Cross-Modul-Abhängigkeit, da Mail als eigenständiges Go-Modul Core
|
||||
nicht importieren kann). `.gitea/workflows/mail-pflichttest-gate.yml` führt es gegen
|
||||
jeden PR-Diff aus.
|
||||
|
||||
Negativtest des Gates selbst (Prüfung 1 dieses Tickets):
|
||||
`mail/internal/pflichttestgate/gate_test.go` simuliert einen Diff mit geänderter
|
||||
`mail/internal/auth/login.go` ohne begleitende Testdatei und erwartet, dass das Gate
|
||||
das als Verstoß erkennt.
|
||||
|
||||
## 5. Bug-Tracking (Akzeptanzkriterium 3)
|
||||
|
||||
**Konvention: Gitea-Issues** auf `gitea.perlbach24.de/scripte/nexarch`, Label `mail`
|
||||
plus Schweregrad-Label (`bug-kritisch`/`bug-normal`/`bug-kosmetisch`). Durchsuchbar
|
||||
über Gitea-Suche/Label-Filter — explizit KEIN Code-Kommentar-Tracking (`BUG-N` wie in
|
||||
archivmail), das laut `known-issues-archivmail.md` genau diese Sichtbarkeitslücke
|
||||
verursacht hat.
|
||||
|
||||
**Realer Durchspiel-Nachweis (Prüfung 3):** Diese Session (nicht Mail-spezifisch, aber
|
||||
derselbe reale Vorgang) fand mehrere echte Bugs, dokumentiert nach exakt diesem
|
||||
Muster in den jeweiligen `*-PRUEFPROTOKOLL.md`-Dateien statt als Code-Kommentar, z. B.
|
||||
`archive/docs/RET-10-PRUEFPROTOKOLL.md`: fehlende CORS-Header bei RET-06-API,
|
||||
gefunden bei einer Sichtprüfung, Symptom (Browser hätte Fetch blockiert), Ursache
|
||||
(kein `Access-Control-Allow-Origin`), Fix (RET-10-Ticket), Nachweis (curl-Test vorher/
|
||||
nachher) — alles durchsuchbar in der Protokolldatei, nicht im Quelltext verstreut.
|
||||
|
||||
**Ehrlich vermerkt:** Ein ECHTER Gitea-Issue konnte in dieser Session nicht angelegt
|
||||
werden (kein Gitea-API-Token verfügbar, nur Git-SSH/HTTPS-Push-Zugriff). Das oben
|
||||
verlinkte Beispiel demonstriert das Vorgehen strukturell (Symptom → Ursache → Fix →
|
||||
Nachweis, durchsuchbar abgelegt), aber NICHT über die Gitea-Issue-Oberfläche selbst.
|
||||
Sobald ein Gitea-Zugriffstoken verfügbar ist, sollte mindestens ein Test-Issue real
|
||||
angelegt werden, um die Konvention vollständig nachzuweisen — offener Punkt, siehe
|
||||
Abschnitt 7.
|
||||
|
||||
## 6. Prüfungen (real durchgeführt)
|
||||
|
||||
| # | Prüfung | Ergebnis |
|
||||
|---|---|---|
|
||||
| 1 | Dokument liegt vor und wurde von zweiter Person gegengelesen | **bestanden** — Dokument von der Nutzerin/dem Nutzer (zweite Person) gegengelesen und freigegeben (2026-08-30) |
|
||||
| 2 | Stichprobe: mindestens ein Beispieltest je benannter Testart ist umgesetzt | **bestanden** — 6 Tests real ausgeführt auf 131: `go test ./mail/internal/example/... -v -p 1`, alle grün (3 Unit, 1 Integration, 2 E2E) |
|
||||
| 3 | Bug-Tracking-Vorgehen wurde einmal exemplarisch für einen realen Befund durchgespielt | **teilweise bestanden** — Vorgehen strukturell durchgespielt anhand eines realen, bereits dokumentierten Befunds (RET-10), aber NICHT über die echte Gitea-Issue-Oberfläche (kein API-Token verfügbar). Siehe Abschnitt 5, offener Punkt in Abschnitt 7 |
|
||||
|
||||
## 7. Offene Punkte
|
||||
|
||||
- Echter Gitea-Issue als Nachweis der Bug-Tracking-Konvention noch nicht angelegt
|
||||
(fehlendes API-Token in dieser Session). Sollte nachgeholt werden, sobald Zugriff
|
||||
besteht.
|
||||
- `mail/internal/auth/`, `mail/internal/tenant/`, `mail/internal/ingest/` etc. existieren
|
||||
noch nicht — die Pflichttest-Gate-Pfadmuster sind auf Basis der geplanten
|
||||
Modulstruktur vordefiniert, nicht an echtem Code verifiziert. Erste Nagelprobe: das
|
||||
erste Ticket, das einen dieser Pfade tatsächlich anlegt (voraussichtlich `ING-01`).
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
module gitea.perlbach24.de/scripte/nexarch/mail
|
||||
|
||||
go 1.22
|
||||
|
||||
require github.com/jackc/pgx/v5 v5.6.0
|
||||
|
||||
require (
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
||||
golang.org/x/crypto v0.17.0 // indirect
|
||||
golang.org/x/sync v0.1.0 // indirect
|
||||
golang.org/x/text v0.14.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,36 @@
|
||||
package example
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// NormalizeHandler ist das E2E-Test-Beispiel (QA-01): ein echter
|
||||
// HTTP-Endpunkt, gegen den ein Test einen vollständigen Request-Response-
|
||||
// Zyklus fährt (httptest.Server, echter TCP-Roundtrip, kein reiner
|
||||
// Funktionsaufruf). Sobald das erste Mail-Frontend-Ticket eine echte
|
||||
// Browser-UI mitbringt, wird die E2E-Ebene um Playwright/Jest ergänzt
|
||||
// (siehe QA-01-Teststrategiedokument, Abschnitt 2) — bis dahin ist ein
|
||||
// echter HTTP-Roundtrip die ehrliche, verfügbare Untergrenze für "E2E".
|
||||
type normalizeRequest struct {
|
||||
Address string `json:"address"`
|
||||
}
|
||||
|
||||
type normalizeResponse struct {
|
||||
Normalized string `json:"normalized"`
|
||||
}
|
||||
|
||||
func NormalizeHandler(w http.ResponseWriter, r *http.Request) {
|
||||
var req normalizeRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "ungültiger request-body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
normalized, err := NormalizeAddress(req.Address)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(normalizeResponse{Normalized: normalized})
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// E2E-Test-Beispiel (QA-01 Akzeptanzkriterium 1/Prüfung 2): echter
|
||||
// HTTP-Request über einen laufenden httptest.Server (TCP-Roundtrip),
|
||||
// nicht nur ein Funktionsaufruf im selben Prozess.
|
||||
package example
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNormalizeHandler_RealHTTPRoundTrip(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(NormalizeHandler))
|
||||
defer server.Close()
|
||||
|
||||
body, _ := json.Marshal(normalizeRequest{Address: "Kunde@Beispiel.DE"})
|
||||
resp, err := http.Post(server.URL, "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatalf("post: %v", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", resp.StatusCode)
|
||||
}
|
||||
var out normalizeResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||
t.Fatalf("antwort dekodieren: %v", err)
|
||||
}
|
||||
if out.Normalized != "Kunde@beispiel.de" {
|
||||
t.Fatalf("got %q", out.Normalized)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeHandler_InvalidAddressReturns400(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(NormalizeHandler))
|
||||
defer server.Close()
|
||||
|
||||
body, _ := json.Marshal(normalizeRequest{Address: "keine-gueltige-adresse"})
|
||||
resp, err := http.Post(server.URL, "application/json", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatalf("post: %v", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Package example dient QA-01 (Mail): liefert je Testart (Unit,
|
||||
// Integration, E2E) genau EIN reales, lauffähiges Beispiel, an dem sich
|
||||
// spätere Mail-Tickets orientieren können — keine Wegwerf-Demo, sondern
|
||||
// eine tatsächlich nützliche, kleine Funktion (Adress-Normalisierung),
|
||||
// die spätere Ticket (z. B. ING-01/ING-04) ohnehin brauchen werden.
|
||||
package example
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ErrInvalidAddress = errors.New("example: keine gültige e-mail-adresse")
|
||||
|
||||
// NormalizeAddress normalisiert eine E-Mail-Adresse für den
|
||||
// tenant-scoped Vergleich: Kleinschreibung der Domain-Hälfte
|
||||
// (lokaler Teil bleibt case-sensitive, RFC 5321), Leerraum entfernt.
|
||||
func NormalizeAddress(addr string) (string, error) {
|
||||
addr = strings.TrimSpace(addr)
|
||||
at := strings.LastIndex(addr, "@")
|
||||
if at <= 0 || at == len(addr)-1 {
|
||||
return "", ErrInvalidAddress
|
||||
}
|
||||
local, domain := addr[:at], addr[at+1:]
|
||||
return local + "@" + strings.ToLower(domain), nil
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// Unit-Test-Beispiel (QA-01 Akzeptanzkriterium 1/Prüfung 2): keine
|
||||
// externe Abhängigkeit (DB, Netzwerk), reine Funktionsprüfung.
|
||||
package example
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNormalizeAddress_LowercasesDomainOnly(t *testing.T) {
|
||||
got, err := NormalizeAddress("User.Name@Example.COM")
|
||||
if err != nil {
|
||||
t.Fatalf("unerwarteter fehler: %v", err)
|
||||
}
|
||||
want := "User.Name@example.com"
|
||||
if got != want {
|
||||
t.Fatalf("got %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeAddress_TrimsWhitespace(t *testing.T) {
|
||||
got, err := NormalizeAddress(" user@example.com ")
|
||||
if err != nil {
|
||||
t.Fatalf("unerwarteter fehler: %v", err)
|
||||
}
|
||||
if got != "user@example.com" {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeAddress_RejectsInvalidInput(t *testing.T) {
|
||||
cases := []string{"", "no-at-sign", "@nolocalpart.com", "trailing@"}
|
||||
for _, c := range cases {
|
||||
if _, err := NormalizeAddress(c); !errors.Is(err, ErrInvalidAddress) {
|
||||
t.Fatalf("input %q: erwartet ErrInvalidAddress, habe: %v", c, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package example
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// AddressStore ist das Integrationstest-Beispiel (QA-01): eine
|
||||
// minimale, aber echte DB-gestützte Komponente — nutzt dieselbe
|
||||
// Tenant-DB-Isolationskonvention wie DMS/Archive (t.Cleanup, geteilte
|
||||
// physische Postgres-Instanz auf dem Testhost).
|
||||
type AddressStore struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewAddressStore(pool *pgxpool.Pool) *AddressStore {
|
||||
return &AddressStore{pool: pool}
|
||||
}
|
||||
|
||||
func (s *AddressStore) SaveNormalized(ctx context.Context, addr string) (string, error) {
|
||||
normalized, err := NormalizeAddress(addr)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO example_addresses (address) VALUES ($1)
|
||||
ON CONFLICT (address) DO NOTHING
|
||||
`, normalized); err != nil {
|
||||
return "", fmt.Errorf("example: adresse speichern: %w", err)
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func (s *AddressStore) Exists(ctx context.Context, addr string) (bool, error) {
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM example_addresses WHERE address = $1)`, addr).Scan(&exists); err != nil {
|
||||
return false, fmt.Errorf("example: existenz prüfen: %w", err)
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// Integrations-Test-Beispiel (QA-01 Akzeptanzkriterium 1/Prüfung 2):
|
||||
// echte Postgres-Instanz, folgt derselben Testhost-Konvention wie
|
||||
// DMS/Archive/Core (TEST_TENANT_DSN, t.Cleanup, geteilte physische
|
||||
// Instanz auf 192.168.1.131 — siehe project-nexarch-test-infra).
|
||||
package example
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func setupTest(t *testing.T) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("TEST_TENANT_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("TEST_TENANT_DSN nicht gesetzt, Integrationstest übersprungen")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatalf("pool: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { pool.Close() })
|
||||
|
||||
if _, err := pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS example_addresses (
|
||||
address TEXT PRIMARY KEY
|
||||
);
|
||||
`); err != nil {
|
||||
t.Fatalf("schema: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_, _ = pool.Exec(context.Background(), `TRUNCATE example_addresses`)
|
||||
})
|
||||
return pool
|
||||
}
|
||||
|
||||
func TestAddressStore_SaveAndCheckExists(t *testing.T) {
|
||||
pool := setupTest(t)
|
||||
store := NewAddressStore(pool)
|
||||
ctx := context.Background()
|
||||
|
||||
normalized, err := store.SaveNormalized(ctx, "Kunde@Beispiel.DE")
|
||||
if err != nil {
|
||||
t.Fatalf("savenormalized: %v", err)
|
||||
}
|
||||
if normalized != "Kunde@beispiel.de" {
|
||||
t.Fatalf("erwartet normalisierte adresse, habe %q", normalized)
|
||||
}
|
||||
|
||||
exists, err := store.Exists(ctx, normalized)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !exists {
|
||||
t.Fatal("erwartet real gespeicherte adresse")
|
||||
}
|
||||
|
||||
notExists, err := store.Exists(ctx, "unbekannt@beispiel.de")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if notExists {
|
||||
t.Fatal("nie gespeicherte adresse haette nicht existieren duerfen")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// Package pflichttestgate erzwingt die in docs/TESTSTRATEGIE-MAIL.md
|
||||
// Abschnitt 4 festgelegte Regel: jede geänderte Go-Datei in einem
|
||||
// sicherheitskritischen Bereich (Auth, Tenant-Scoping, Protokoll-/
|
||||
// Compliance-kritisch) muss von einer geänderten oder neuen _test.go-
|
||||
// Datei im selben Package begleitet sein. Bewusste Code-Kopie des
|
||||
// Musters aus Core internal/pflichttestgate — Mail ist ein eigenständiges
|
||||
// Go-Modul und kann Core nicht importieren.
|
||||
package pflichttestgate
|
||||
|
||||
import (
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// sensitivePathPatterns beschreibt die Bereiche aus
|
||||
// TESTSTRATEGIE-MAIL.md Abschnitt 4.
|
||||
var sensitivePathPatterns = []*regexp.Regexp{
|
||||
regexp.MustCompile(`(^|/)mail/internal/auth/`),
|
||||
regexp.MustCompile(`(^|/)mail/internal/tenant/`),
|
||||
regexp.MustCompile(`(^|/)mail/internal/ingest/`),
|
||||
regexp.MustCompile(`(^|/)mail/internal/imap/`),
|
||||
regexp.MustCompile(`(^|/)mail/internal/smtp/`),
|
||||
regexp.MustCompile(`(^|/)mail/internal/arc/`),
|
||||
}
|
||||
|
||||
// Violation beschreibt ein Package mit sicherheitskritischer Änderung
|
||||
// ohne begleitende Testdatei.
|
||||
type Violation struct {
|
||||
Package string
|
||||
ChangedFile string
|
||||
}
|
||||
|
||||
func isSensitive(file string) bool {
|
||||
if !strings.HasSuffix(file, ".go") || strings.HasSuffix(file, "_test.go") {
|
||||
return false
|
||||
}
|
||||
for _, re := range sensitivePathPatterns {
|
||||
if re.MatchString(file) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// CheckDiff prüft eine Liste geänderter Dateipfade gegen die
|
||||
// Pflichttest-Regel — ein leeres Ergebnis bedeutet: Gate besteht.
|
||||
func CheckDiff(changedFiles []string) []Violation {
|
||||
sensitiveByPkg := map[string]string{}
|
||||
testTouchedPkgs := map[string]bool{}
|
||||
|
||||
for _, f := range changedFiles {
|
||||
pkg := path.Dir(f)
|
||||
if strings.HasSuffix(f, "_test.go") {
|
||||
testTouchedPkgs[pkg] = true
|
||||
continue
|
||||
}
|
||||
if isSensitive(f) {
|
||||
if _, seen := sensitiveByPkg[pkg]; !seen {
|
||||
sensitiveByPkg[pkg] = f
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var violations []Violation
|
||||
for pkg, file := range sensitiveByPkg {
|
||||
if !testTouchedPkgs[pkg] {
|
||||
violations = append(violations, Violation{Package: pkg, ChangedFile: file})
|
||||
}
|
||||
}
|
||||
return violations
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// Negativtest des Gates selbst (QA-01 Prüfung 1): ein Diff mit
|
||||
// geänderter mail/internal/auth/login.go ohne begleitende Testdatei
|
||||
// muss als Verstoß erkannt werden.
|
||||
package pflichttestgate
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCheckDiff_FlagsSensitiveChangeWithoutTest(t *testing.T) {
|
||||
violations := CheckDiff([]string{"mail/internal/auth/login.go"})
|
||||
if len(violations) != 1 {
|
||||
t.Fatalf("erwartet genau 1 verstoß, habe %d: %+v", len(violations), violations)
|
||||
}
|
||||
if violations[0].Package != "mail/internal/auth" {
|
||||
t.Fatalf("falsches package gemeldet: %+v", violations[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckDiff_PassesWhenTestFileAccompanies(t *testing.T) {
|
||||
violations := CheckDiff([]string{
|
||||
"mail/internal/auth/login.go",
|
||||
"mail/internal/auth/login_test.go",
|
||||
})
|
||||
if len(violations) != 0 {
|
||||
t.Fatalf("erwartet keine verstöße, habe: %+v", violations)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckDiff_IgnoresNonSensitivePaths(t *testing.T) {
|
||||
violations := CheckDiff([]string{"mail/internal/example/normalize.go"})
|
||||
if len(violations) != 0 {
|
||||
t.Fatalf("erwartet keine verstöße für nicht-sensiblen pfad, habe: %+v", violations)
|
||||
}
|
||||
}
|
||||
@@ -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 audit_events;
|
||||
@@ -1,17 +0,0 @@
|
||||
-- Zentrales Audit-Log-Modell (AUD-01, siehe core-kanban/tickets/AUD-01.md).
|
||||
-- Getrennt vom allgemeinen Anwendungs-Log (Akzeptanzkriterium 2): eigene
|
||||
-- Tabelle, eigenes Paket (internal/audit), kein Log-Framework.
|
||||
-- tenant_slug ist NOT NULL + darf nicht leer sein (Akzeptanzkriterium 2 /
|
||||
-- Pruefung 2) — mandantenuebergreifende Ereignisse nutzen den reservierten
|
||||
-- Wert 'system', niemals NULL oder leeren String.
|
||||
CREATE TABLE audit_events (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
occurred_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
tenant_slug TEXT NOT NULL CHECK (tenant_slug <> ''),
|
||||
actor TEXT NOT NULL CHECK (actor <> ''),
|
||||
action TEXT NOT NULL CHECK (action <> ''),
|
||||
target TEXT NOT NULL,
|
||||
metadata JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||
);
|
||||
|
||||
CREATE INDEX audit_events_tenant_slug_idx ON audit_events (tenant_slug, occurred_at);
|
||||
@@ -1,24 +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;"
|
||||
psql -h localhost -U "$ROLE" -d postgres -v ON_ERROR_STOP=1 -c "DROP TABLE IF EXISTS audit_events CASCADE;"
|
||||
|
||||
dbs=$(psql -h localhost -U "$ROLE" -d postgres -tAc "SELECT datname FROM pg_database WHERE datname LIKE 'tenant\_%' ESCAPE '\'")
|
||||
for db in $dbs; do
|
||||
psql -h localhost -U "$ROLE" -d postgres -v ON_ERROR_STOP=1 -c "DROP DATABASE IF EXISTS \"${db}\";"
|
||||
done
|
||||
|
||||
echo "Testumgebung zurueckgesetzt: registry-tabelle + $(echo "$dbs" | grep -c . || true) tenant-datenbank(en) entfernt."
|
||||
@@ -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