diff --git a/mail/docs/IMP-07-PRUEFPROTOKOLL.md b/mail/docs/IMP-07-PRUEFPROTOKOLL.md new file mode 100644 index 0000000..1c3d262 --- /dev/null +++ b/mail/docs/IMP-07-PRUEFPROTOKOLL.md @@ -0,0 +1,48 @@ +# IMP-07 – Prüfprotokoll: Mehrfach-Postfach-Verwaltung pro Tenant + +Voraussetzung IMP-01 (Fertig), Core TEN-01/TEN-02 (Fertig, +Tenant-Datenmodell & Onboarding). + +## Umsetzung + +- `mail/internal/mailboxconfig/store.go` — `Store` (Postgres, + `mail_mailboxes`): `Create` legt beliebig viele, voneinander + unabhängige Postfächer je Mandant an (Akzeptanzkriterium 1). Jedes + Postfach hat eigene Abrufparameter — Intervall, IMAP-Host/Port/ + Benutzername, Ordnerauswahl (Akzeptanzkriterium 2). +- Passwort wird NIE im Klartext gespeichert — Wiederverwendung von + `mail/internal/crypto` (ARC-02, unverändert): `Create` verschlüsselt + über `crypto.Service.Seal`, `GetDecryptedPassword` entschlüsselt bei + Bedarf über `crypto.Service.Open`, als separater, bewusster Aufruf + (nicht Bestandteil von `List`, damit Zugangsdaten nicht beiläufig + mitgeliefert werden). +- `List` filtert strikt nach `tenant_slug` (Akzeptanzkriterium 3). + `Update`/`Delete` sind streng auf `tenant_slug` + `id` beschränkt. +- Kein Umbau: `mail/internal/crypto` unverändert wiederverwendet, kein + anderes Paket angefasst. + +## Prüfungen + +| # | Prüfung | Ergebnis | +|---|---|---| +| 1 | Test: zwei Mandanten mit je mehreren Postfächern sehen ausschließlich eigene Postfächer | **bestanden** – `TestList_TwoTenantsWithMultipleMailboxesSeeOnlyOwn`: Mandant A mit 2, Mandant B mit 1 Postfach — jeweils real nur die eigenen sichtbar | +| 2 | Test: Löschen eines Postfachs beeinträchtigt andere Postfächer desselben Mandanten nicht | **bestanden** – `TestDelete_DoesNotAffectSiblingMailboxes`: Postfach „eins" real gelöscht, Postfach „zwei" bleibt real vollständig funktionsfähig (Zugangsdaten weiterhin real entschlüsselbar) | +| 3 | Konfigurationsänderung an einem Postfach wirkt nicht auf andere | **bestanden** – `TestUpdate_ConfigChangeDoesNotAffectOtherMailboxes`: Änderung an Postfach „eins" (Host/Intervall) real übernommen, Postfach „zwei" real unverändert | + +## Build/Test-Ergebnis (192.168.1.131) + +``` +go build ./... -> clean +go vet ./... -> clean +golangci-lint run ./... -> 0 issues +TEST_TENANT_DSN=... go test ./internal/mailboxconfig/... -v -timeout 60s -> 3/3 bestanden +TEST_TENANT_DSN=... TEST_MANTICORE_URL=... go test ./... -p 1 + -> alle 22 Pakete bestanden, keine Regression +``` + +## Gesamtergebnis + +**Bestanden.** Alle drei Akzeptanzkriterien und alle drei Pflichtprüfungen +real erfüllt. Entsperrt ARC-09, trägt zu QA-02 bei — QA-02 bleibt +weiterhin blockiert, bis dessen übrige Abhängigkeiten (ING-07, ING-08, +ING-10) fertig sind. diff --git a/mail/internal/mailboxconfig/migrations/0001_mail_mailboxes.sql b/mail/internal/mailboxconfig/migrations/0001_mail_mailboxes.sql new file mode 100644 index 0000000..e72df97 --- /dev/null +++ b/mail/internal/mailboxconfig/migrations/0001_mail_mailboxes.sql @@ -0,0 +1,15 @@ +CREATE TABLE IF NOT EXISTS mail_mailboxes ( + id BIGSERIAL PRIMARY KEY, + tenant_slug TEXT NOT NULL, + name TEXT NOT NULL, + imap_host TEXT NOT NULL, + imap_port INT NOT NULL DEFAULT 993, + imap_username TEXT NOT NULL, + wrapped_password_dek BYTEA NOT NULL, + encrypted_password BYTEA NOT NULL, + folder_selection TEXT NOT NULL DEFAULT 'INBOX', + interval_seconds INT NOT NULL DEFAULT 300, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (tenant_slug, name) +) diff --git a/mail/internal/mailboxconfig/store.go b/mail/internal/mailboxconfig/store.go new file mode 100644 index 0000000..f94854f --- /dev/null +++ b/mail/internal/mailboxconfig/store.go @@ -0,0 +1,211 @@ +// Package mailboxconfig implementiert IMP-07: Verwaltung mehrerer +// Postfächer je Mandant (Anlage, getrennte Abrufkonfiguration je +// Postfach). Setzt NEXARCH-Core TEN-01/TEN-02 (Tenant-Datenmodell, +// beide Fertig) voraus — dieses Paket kennt tenant_slug nur als +// opaken String, keine eigene Tenant-Verwaltung. +// +// Postfach-Zugangsdaten (Passwort) werden NIE im Klartext gespeichert — +// Wiederverwendung von mail/internal/crypto (ARC-02, bereits fertig, +// unverändert) für Envelope-Encryption, gleiches Muster wie +// mail/internal/encstorage. +package mailboxconfig + +import ( + "bytes" + "context" + _ "embed" + "errors" + "fmt" + "io" + "strings" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "gitea.perlbach24.de/scripte/nexarch/mail/internal/crypto" +) + +//go:embed migrations/0001_mail_mailboxes.sql +var schemaMigration string + +// ErrNotFound wird geliefert, wenn kein Postfach mit den angegebenen +// Bezugsdaten existiert. +var ErrNotFound = errors.New("mailboxconfig: postfach nicht gefunden") + +// MailboxConfig ist die Konfiguration EINES Postfachs +// (Akzeptanzkriterium 2: eigene Abrufparameter — Intervall, Ordnerauswahl; +// Zugangsdaten werden separat über GetDecryptedPassword bezogen, nie +// beim Auflisten mitgeliefert). +type MailboxConfig struct { + ID int64 + TenantSlug string + Name string + IMAPHost string + IMAPPort int + IMAPUsername string + FolderSelection []string + IntervalSeconds int +} + +const defaultIntervalSeconds = 300 + +// Store verwaltet Postfachkonfigurationen je Mandant in Postgres. +type Store struct { + pool *pgxpool.Pool + crypto *crypto.Service +} + +func NewStore(pool *pgxpool.Pool, cryptoSvc *crypto.Service) *Store { + return &Store{pool: pool, crypto: cryptoSvc} +} + +// EnsureSchema legt die Tabelle an, falls sie noch nicht existiert. +func (s *Store) EnsureSchema(ctx context.Context) error { + if _, err := s.pool.Exec(ctx, schemaMigration); err != nil { + return fmt.Errorf("mailboxconfig: schema anlegen: %w", err) + } + return nil +} + +// CreateInput sind die für die Anlage nötigen Angaben. +type CreateInput struct { + Name string + IMAPHost string + IMAPPort int + IMAPUsername string + Password string + FolderSelection []string + IntervalSeconds int +} + +// Create legt ein neues Postfach für tenantSlug an (Akzeptanzkriterium 1: +// ein Mandant kann mehrere Postfächer unabhängig konfigurieren — kein +// Limit, keine gegenseitige Abhängigkeit zwischen Postfächern desselben +// Mandanten). Das Passwort wird über mail/internal/crypto verschlüsselt, +// niemals im Klartext gespeichert. +func (s *Store) Create(ctx context.Context, tenantSlug string, in CreateInput) (int64, error) { + if in.IntervalSeconds <= 0 { + in.IntervalSeconds = defaultIntervalSeconds + } + if len(in.FolderSelection) == 0 { + in.FolderSelection = []string{"INBOX"} + } + + env, err := s.crypto.Seal(ctx, tenantSlug, strings.NewReader(in.Password)) + if err != nil { + return 0, fmt.Errorf("mailboxconfig: passwort verschlüsseln: %w", err) + } + ciphertext, err := io.ReadAll(env.Ciphertext) + if err != nil { + return 0, fmt.Errorf("mailboxconfig: chiffretext lesen: %w", err) + } + + var id int64 + err = s.pool.QueryRow(ctx, ` + INSERT INTO mail_mailboxes + (tenant_slug, name, imap_host, imap_port, imap_username, wrapped_password_dek, encrypted_password, folder_selection, interval_seconds) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) + RETURNING id + `, tenantSlug, in.Name, in.IMAPHost, in.IMAPPort, in.IMAPUsername, env.WrappedDEK, ciphertext, strings.Join(in.FolderSelection, ","), in.IntervalSeconds).Scan(&id) + if err != nil { + return 0, fmt.Errorf("mailboxconfig: postfach anlegen: %w", err) + } + return id, nil +} + +// List liefert alle Postfächer eines Mandanten (Akzeptanzkriterium 3: +// strikt nach tenant_slug gefiltert) — OHNE Zugangsdaten. +func (s *Store) List(ctx context.Context, tenantSlug string) ([]MailboxConfig, error) { + rows, err := s.pool.Query(ctx, ` + SELECT id, name, imap_host, imap_port, imap_username, folder_selection, interval_seconds + FROM mail_mailboxes WHERE tenant_slug = $1 ORDER BY name + `, tenantSlug) + if err != nil { + return nil, fmt.Errorf("mailboxconfig: postfächer lesen: %w", err) + } + defer rows.Close() + + var configs []MailboxConfig + for rows.Next() { + var c MailboxConfig + var folders string + c.TenantSlug = tenantSlug + if err := rows.Scan(&c.ID, &c.Name, &c.IMAPHost, &c.IMAPPort, &c.IMAPUsername, &folders, &c.IntervalSeconds); err != nil { + return nil, fmt.Errorf("mailboxconfig: postfachzeile lesen: %w", err) + } + c.FolderSelection = strings.Split(folders, ",") + configs = append(configs, c) + } + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("mailboxconfig: postfächer iterieren: %w", err) + } + return configs, nil +} + +// UpdateInput sind die änderbaren Felder eines Postfachs +// (Akzeptanzkriterium 2/3: Konfigurationsänderung betrifft ausschließlich +// dieses eine Postfach). +type UpdateInput struct { + IMAPHost string + IMAPPort int + FolderSelection []string + IntervalSeconds int +} + +// Update ändert die Abrufparameter EINES Postfachs, streng auf +// tenantSlug+id beschränkt. +func (s *Store) Update(ctx context.Context, tenantSlug string, id int64, in UpdateInput) error { + tag, err := s.pool.Exec(ctx, ` + UPDATE mail_mailboxes + SET imap_host = $3, imap_port = $4, folder_selection = $5, interval_seconds = $6, updated_at = now() + WHERE tenant_slug = $1 AND id = $2 + `, tenantSlug, id, in.IMAPHost, in.IMAPPort, strings.Join(in.FolderSelection, ","), in.IntervalSeconds) + if err != nil { + return fmt.Errorf("mailboxconfig: postfach aktualisieren: %w", err) + } + if tag.RowsAffected() == 0 { + return ErrNotFound + } + return nil +} + +// Delete entfernt GENAU EIN Postfach, streng auf tenantSlug+id beschränkt +// (Akzeptanzkriterium/Pflichtprüfung 2: andere Postfächer desselben +// Mandanten bleiben unberührt). +func (s *Store) Delete(ctx context.Context, tenantSlug string, id int64) error { + tag, err := s.pool.Exec(ctx, `DELETE FROM mail_mailboxes WHERE tenant_slug = $1 AND id = $2`, tenantSlug, id) + if err != nil { + return fmt.Errorf("mailboxconfig: postfach löschen: %w", err) + } + if tag.RowsAffected() == 0 { + return ErrNotFound + } + return nil +} + +// GetDecryptedPassword entschlüsselt das Postfach-Passwort — separater, +// bewusster Aufruf statt Bestandteil von List/Get, damit Zugangsdaten +// nicht beiläufig mitgeliefert werden. +func (s *Store) GetDecryptedPassword(ctx context.Context, tenantSlug string, id int64) (string, error) { + var wrappedDEK, ciphertext []byte + err := s.pool.QueryRow(ctx, ` + SELECT wrapped_password_dek, encrypted_password FROM mail_mailboxes + WHERE tenant_slug = $1 AND id = $2 + `, tenantSlug, id).Scan(&wrappedDEK, &ciphertext) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return "", ErrNotFound + } + return "", fmt.Errorf("mailboxconfig: postfach lesen: %w", err) + } + + plaintextReader, err := s.crypto.Open(ctx, tenantSlug, wrappedDEK, bytes.NewReader(ciphertext)) + if err != nil { + return "", fmt.Errorf("mailboxconfig: passwort entschlüsseln: %w", err) + } + plaintext, err := io.ReadAll(plaintextReader) + if err != nil { + return "", fmt.Errorf("mailboxconfig: passwort lesen: %w", err) + } + return string(plaintext), nil +} diff --git a/mail/internal/mailboxconfig/store_test.go b/mail/internal/mailboxconfig/store_test.go new file mode 100644 index 0000000..46a3f2c --- /dev/null +++ b/mail/internal/mailboxconfig/store_test.go @@ -0,0 +1,172 @@ +// Integrationstest (IMP-07): echte Postgres-Instanz, folgt derselben +// Testhost-Konvention wie mail/internal/dedup/folderstate — TEST_TENANT_DSN. +package mailboxconfig + +import ( + "bytes" + "context" + "os" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + + "gitea.perlbach24.de/scripte/nexarch/mail/internal/crypto" +) + +// fakeKEKProvider liefert einen festen, mandantenspezifischen KEK — +// gleiche Testkonvention wie encstorage_test.go (ARC-02). +type fakeKEKProvider struct{} + +func (fakeKEKProvider) TenantKEK(_ context.Context, _ string) ([]byte, error) { + return bytes.Repeat([]byte{0x42}, crypto.KEKSize), nil +} + +func setupStore(t *testing.T) *Store { + 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() }) + + store := NewStore(pool, crypto.NewService(fakeKEKProvider{})) + if err := store.EnsureSchema(ctx); err != nil { + t.Fatalf("schema: %v", err) + } + t.Cleanup(func() { + _, _ = pool.Exec(context.Background(), `DELETE FROM mail_mailboxes WHERE tenant_slug LIKE 'mandant-%'`) + }) + return store +} + +func createTestMailbox(t *testing.T, store *Store, tenant, name string) int64 { + t.Helper() + id, err := store.Create(context.Background(), tenant, CreateInput{ + Name: name, + IMAPHost: "imap." + name + ".example", + IMAPPort: 993, + IMAPUsername: "user@" + name + ".example", + Password: "geheim-" + name, + FolderSelection: []string{"INBOX"}, + IntervalSeconds: 300, + }) + if err != nil { + t.Fatalf("postfach %s anlegen: %v", name, err) + } + return id +} + +// TestList_TwoTenantsWithMultipleMailboxesSeeOnlyOwn ist die geforderte +// Pflichtprüfung 1: zwei Mandanten mit je mehreren Postfächern sehen +// ausschließlich eigene Postfächer. +func TestList_TwoTenantsWithMultipleMailboxesSeeOnlyOwn(t *testing.T) { + store := setupStore(t) + ctx := context.Background() + tenantA := "mandant-imp07-a" + tenantB := "mandant-imp07-b" + + createTestMailbox(t, store, tenantA, "vertrieb") + createTestMailbox(t, store, tenantA, "support") + createTestMailbox(t, store, tenantB, "buchhaltung") + + listA, err := store.List(ctx, tenantA) + if err != nil { + t.Fatalf("list mandant a: %v", err) + } + if len(listA) != 2 { + t.Fatalf("mandant a: erwartete 2 eigene postfächer, habe %d: %+v", len(listA), listA) + } + + listB, err := store.List(ctx, tenantB) + if err != nil { + t.Fatalf("list mandant b: %v", err) + } + if len(listB) != 1 || listB[0].Name != "buchhaltung" { + t.Fatalf("mandant b sieht falsche/fremde postfächer: %+v", listB) + } + for _, mb := range listB { + if mb.Name == "vertrieb" || mb.Name == "support" { + t.Fatalf("mandant b sieht postfach von mandant a: %+v", mb) + } + } +} + +// TestDelete_DoesNotAffectSiblingMailboxes ist die geforderte +// Pflichtprüfung 2: Löschen eines Postfachs beeinträchtigt andere +// Postfächer desselben Mandanten nicht. +func TestDelete_DoesNotAffectSiblingMailboxes(t *testing.T) { + store := setupStore(t) + ctx := context.Background() + tenant := "mandant-imp07-loeschen" + + idA := createTestMailbox(t, store, tenant, "eins") + idB := createTestMailbox(t, store, tenant, "zwei") + + if err := store.Delete(ctx, tenant, idA); err != nil { + t.Fatalf("löschen: %v", err) + } + + list, err := store.List(ctx, tenant) + if err != nil { + t.Fatalf("list: %v", err) + } + if len(list) != 1 || list[0].ID != idB { + t.Fatalf("erwartete nur postfach 'zwei' übrig, habe: %+v", list) + } + + // Das verbleibende Postfach ist real weiterhin voll funktionsfähig + // (Zugangsdaten weiterhin entschlüsselbar). + pw, err := store.GetDecryptedPassword(ctx, tenant, idB) + if err != nil { + t.Fatalf("verbleibendes postfach nicht mehr funktionsfähig: %v", err) + } + if pw != "geheim-zwei" { + t.Fatalf("erwartetes passwort für verbleibendes postfach, habe %q", pw) + } +} + +// TestUpdate_ConfigChangeDoesNotAffectOtherMailboxes ist die geforderte +// Pflichtprüfung 3: Konfigurationsänderung an einem Postfach wirkt nicht +// auf andere. +func TestUpdate_ConfigChangeDoesNotAffectOtherMailboxes(t *testing.T) { + store := setupStore(t) + ctx := context.Background() + tenant := "mandant-imp07-update" + + idA := createTestMailbox(t, store, tenant, "eins") + idB := createTestMailbox(t, store, tenant, "zwei") + + if err := store.Update(ctx, tenant, idA, UpdateInput{ + IMAPHost: "neuer-host.example", + IMAPPort: 143, + FolderSelection: []string{"INBOX", "Archiv"}, + IntervalSeconds: 900, + }); err != nil { + t.Fatalf("update: %v", err) + } + + list, err := store.List(ctx, tenant) + if err != nil { + t.Fatalf("list: %v", err) + } + var mbA, mbB MailboxConfig + for _, mb := range list { + switch mb.ID { + case idA: + mbA = mb + case idB: + mbB = mb + } + } + if mbA.IMAPHost != "neuer-host.example" || mbA.IntervalSeconds != 900 { + t.Fatalf("änderung an postfach 'eins' wurde nicht real übernommen: %+v", mbA) + } + if mbB.IMAPHost != "imap.zwei.example" || mbB.IntervalSeconds != 300 { + t.Fatalf("postfach 'zwei' wurde fälschlich mitverändert: %+v", mbB) + } +}