diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml index 241c33d..d42e266 100644 --- a/.gitea/workflows/ci.yaml +++ b/.gitea/workflows/ci.yaml @@ -83,7 +83,7 @@ jobs: # own test binary — and including it triggers a covdata-tool error # on packages with no _test.go files. -coverpkg makes the server's # exercise of store/* count toward coverage. - run: go test -race -coverpkg=./internal/... -coverprofile=cover.out ./internal/server/... ./internal/config/... ./internal/keycloak/... ./internal/llmkeys/... ./internal/erpsetup/... ./internal/scopes/... ./internal/secretbox/... ./internal/roles/... ./internal/telemetry/... + run: go test -race -coverpkg=./internal/... -coverprofile=cover.out ./internal/server/... ./internal/config/... ./internal/keycloak/... ./internal/llmkeys/... ./internal/erpsetup/... ./internal/scopes/... ./internal/secretbox/... ./internal/roles/... ./internal/telemetry/... ./internal/legal/... - name: coverage gate run: | diff --git a/cmd/server/main.go b/cmd/server/main.go index cb6305a..c6c0165 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -17,6 +17,7 @@ import ( "git.breakpilot.com/platform/tenant-registry/internal/config" "git.breakpilot.com/platform/tenant-registry/internal/erp" "git.breakpilot.com/platform/tenant-registry/internal/keycloak" + "git.breakpilot.com/platform/tenant-registry/internal/legal/contractdocs" "git.breakpilot.com/platform/tenant-registry/internal/licence" "git.breakpilot.com/platform/tenant-registry/internal/llmkeys" "git.breakpilot.com/platform/tenant-registry/internal/product" @@ -36,6 +37,13 @@ func main() { slog.Error("config load failed", "err", err) os.Exit(1) } + // The committed contract documents are served byte for byte: a PDF that + // does not match its pinned SHA-256 stops the start. + if err := contractdocs.Check(); err != nil { + slog.Error("contract documents do not match their pins", "err", err) + os.Exit(1) + } + slog.Info("contract documents", "released", len(contractdocs.Default().All()), "gate_on", cfg.ContractDocuments) // Traces to SigNoz when OTEL_EXPORTER_OTLP_ENDPOINT is set; every outbound // client without its own transport (Keycloak, ERP, LiteLLM, OIDC) goes diff --git a/internal/config/config.go b/internal/config/config.go index c767d43..e220c56 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -81,6 +81,12 @@ type Config struct { // StoreImportMaxBytes caps one document-store bundle import (default 2 GiB). StoreImportMaxBytes int64 + // ContractDocuments (CONTRACT_DOCUMENTS "on"/"off", default off) releases + // the contract documents (AGB, AVV, TOM, Leistungsbeschreibungen) in the + // Vertragsunterlagen. Off: the overview lists none and their PDF routes + // answer 404. + ContractDocuments bool + // Platform mail (F3). SMTPHost empty ⇒ notifications queue up unsent. SMTPHost string SMTPPort int @@ -154,6 +160,7 @@ func Load() (*Config, error) { DocumentsS3AccessKey: os.Getenv("DOCUMENTS_S3_ACCESS_KEY"), DocumentsS3SecretKey: os.Getenv("DOCUMENTS_S3_SECRET_KEY"), DocumentsMaxBytes: int64(getint("DOCUMENTS_MAX_MB", 200)) << 20, + ContractDocuments: getenv("CONTRACT_DOCUMENTS", "off") == "on", StoreImportMaxBytes: int64(getint("STORE_IMPORT_MAX_MB", 2048)) << 20, SMTPHost: os.Getenv("SMTP_HOST"), diff --git a/internal/config/config_test.go b/internal/config/config_test.go index acfc72f..b5e93fa 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -86,3 +86,18 @@ func TestLoad_litellmDefaultsAndOverrides(t *testing.T) { t.Errorf("blank list should fall back: %v", cfg.LiteLLMModels) } } + +// Contract documents stay off unless the env says exactly "on". +func TestLoad_contractDocumentsGate(t *testing.T) { + t.Setenv("APP_ENV", "") + for value, want := range map[string]bool{"": false, "off": false, "true": false, "ON": false, "on": true} { + t.Setenv("CONTRACT_DOCUMENTS", value) + cfg, err := Load() + if err != nil { + t.Fatal(err) + } + if cfg.ContractDocuments != want { + t.Errorf("CONTRACT_DOCUMENTS=%q: %v, want %v", value, cfg.ContractDocuments, want) + } + } +} diff --git a/internal/legal/contractdocs/contractdocs.go b/internal/legal/contractdocs/contractdocs.go new file mode 100644 index 0000000..ba9ab19 --- /dev/null +++ b/internal/legal/contractdocs/contractdocs.go @@ -0,0 +1,210 @@ +// Package contractdocs holds the released contract documents a workspace sees +// in its Vertragsunterlagen: AGB, AVV (the master, with blank lines for the +// customer's details), TOM and the Leistungsbeschreibungen. Each is a fixed +// PDF committed under files/ with its SHA-256 pinned in the table below; the +// pins are checked at startup and by a test, and a PDF is only ever served +// byte for byte. Never replace the PDF of a released version: a new text is a +// new version, i.e. a new PDF and its line in the table. +// +// Releasing a document is one line in released plus its PDF in files/. A +// document not released yet is simply not in the table, and the overview +// does not list it. +package contractdocs + +import ( + "crypto/sha256" + "embed" + "encoding/hex" + "fmt" + "regexp" +) + +//go:embed files/*.pdf +var files embed.FS + +// Kinds of contract documents. +const ( + KindAGB = "agb" // Allgemeine Geschäftsbedingungen + KindAVV = "avv" // Auftragsverarbeitungsvertrag + KindTOM = "tom" // Technische und organisatorische Maßnahmen + KindLB = "lb" // Leistungsbeschreibung (one per module) +) + +// Doc is one released contract document. +type Doc struct { + // ID names the document across versions ("agb", "lb-pruefwerk"); it is + // the path segment of the PDF route. AGB, AVV and TOM have their kind as + // ID, so a workspace's own filled AVV takes the master's place. + ID string + Kind string + Title string + Version string // "1.0.3" + Date string // the "Stand" printed in the document, DD.MM.YYYY + SHA256 string // pinned digest of the PDF + // Which workspaces a Leistungsbeschreibung applies to: Product (a product + // key) when the workspace holds that product, ManagedService (a managed + // service kind) when it has that service, neither: every workspace. + Product string + ManagedService string + File string // file name under files/ + PDF []byte +} + +// released is the table of released documents, in the order the overview +// lists them. Title is the title shown in the portal (the Plattform LB's PDF +// is headed "Leistungsbeschreibung Breakpilot"). Not released yet (add them here with their PDF once they are): +// +// {ID: "agb", Kind: KindAGB, Title: "Allgemeine Geschäftsbedingungen", Version: "1.0.0", Date: "TT.MM.JJJJ", File: "Breakpilot_AGB_1.0.0.pdf", SHA256: "…"}, +// {ID: "avv", Kind: KindAVV, Title: "Auftragsverarbeitungsvertrag", Version: "1.0.0", Date: "TT.MM.JJJJ", File: "Breakpilot_AVV_1.0.0.pdf", SHA256: "…"}, +// {ID: "tom", Kind: KindTOM, Title: "Technische und organisatorische Maßnahmen", Version: "1.0.0", Date: "TT.MM.JJJJ", File: "Breakpilot_TOM_1.0.0.pdf", SHA256: "…"}, +var released = []Doc{ + {ID: "lb-plattform", Kind: KindLB, Title: "Leistungsbeschreibung Breakpilot Plattform", Version: "1.0.0", Date: "06.11.2026", + File: "Breakpilot_Leistungsbeschreibung_Plattform_1.0.0.pdf", SHA256: "29205b6b8db23f6e0c213e0f2f6b28b13aaf36656c991789b43dd0610079c65b"}, + {ID: "lb-pruefwerk", Kind: KindLB, Title: "Leistungsbeschreibung Prüfwerk", Version: "1.0.3", Date: "09.11.2026", Product: "pruefwerk", + File: "Breakpilot_Leistungsbeschreibung_Pruefwerk_1.0.3.pdf", SHA256: "59672ea23c17621fac767cef27250d0b14b18a2d881da19408d03287628e6731"}, + {ID: "lb-werkpilot", Kind: KindLB, Title: "Leistungsbeschreibung Werkpilot", Version: "1.0.0", Date: "06.11.2026", Product: "werkpilot", + File: "Breakpilot_Leistungsbeschreibung_Werkpilot_1.0.0.pdf", SHA256: "b57197b60c7fdb15d2ea234cbd522941ae8ed6c4f581be2ae34055380f97aee3"}, + {ID: "lb-firmwerk", Kind: KindLB, Title: "Leistungsbeschreibung Firmwerk", Version: "1.0.0", Date: "06.11.2026", Product: "firmwerk", + File: "Breakpilot_Leistungsbeschreibung_Firmwerk_1.0.0.pdf", SHA256: "7b7e70a426283c75a277ca7983ade0463267c17f99088100ef0cad642df56e0c"}, + {ID: "lb-werkmeister", Kind: KindLB, Title: "Leistungsbeschreibung Werkmeister", Version: "1.0.0", Date: "06.11.2026", Product: "werkmeister", + File: "Breakpilot_Leistungsbeschreibung_Werkmeister_1.0.0.pdf", SHA256: "284b9b00f9649d39a1960e056b9dcbccf48ed2fcfb1f84fba052d8cba3ade1a0"}, + {ID: "lb-managed-git", Kind: KindLB, Title: "Leistungsbeschreibung Managed Git", Version: "1.0.0", Date: "06.11.2026", ManagedService: "git", + File: "Breakpilot_Leistungsbeschreibung_ManagedGit_1.0.0.pdf", SHA256: "d529c510577371d0223a8466434dd89aafbc07335803a6a91cac43223b569c92"}, + {ID: "lb-build-runner", Kind: KindLB, Title: "Leistungsbeschreibung Build-Runner", Version: "1.0.0", Date: "06.11.2026", ManagedService: "ci-runner", + File: "Breakpilot_Leistungsbeschreibung_BuildRunner_1.0.0.pdf", SHA256: "b71909f2177fc2aeb2542f9fad7b3f1ec59d4df8c621a6e4bf66667f9a735638"}, +} + +// titles are the document titles per kind; a workspace's own filled AVV +// carries the AVV title whether or not the master is released. +var titles = map[string]string{ + KindAGB: "Allgemeine Geschäftsbedingungen", + KindAVV: "Auftragsverarbeitungsvertrag", + KindTOM: "Technische und organisatorische Maßnahmen", + KindLB: "Leistungsbeschreibung", +} + +// Title is the title of a kind of document ("" for an unknown kind). +func Title(kind string) string { return titles[kind] } + +// Catalogue is a set of released documents. +type Catalogue struct { + docs []*Doc + byID map[string]*Doc +} + +var def = mustDefault() + +func mustDefault() *Catalogue { + docs := make([]Doc, len(released)) + for i, d := range released { + b, err := files.ReadFile("files/" + d.File) + if err != nil { + panic(fmt.Sprintf("contractdocs: %s: %v", d.ID, err)) + } + d.PDF = b + docs[i] = d + } + return NewCatalogue(docs...) +} + +// Default is the catalogue of committed documents. +func Default() *Catalogue { return def } + +// NewCatalogue builds a catalogue of docs (with their PDFs), in that order. +// It does not check them; Check does. +func NewCatalogue(docs ...Doc) *Catalogue { + c := &Catalogue{byID: map[string]*Doc{}} + for i := range docs { + d := docs[i] + c.docs = append(c.docs, &d) + c.byID[d.ID] = &d + } + return c +} + +// All returns every document in table order. +func (c *Catalogue) All() []*Doc { return c.docs } + +// Get returns the document with that ID, or nil. +func (c *Catalogue) Get(id string) *Doc { return c.byID[id] } + +// Holdings is what a workspace has that decides which Leistungsbeschreibungen +// apply: product keys and managed service kinds. +type Holdings struct { + Products map[string]bool + ManagedServices map[string]bool +} + +// Applies reports whether d applies to a workspace with holdings h. AGB, AVV +// and TOM apply to every workspace, and so does a Leistungsbeschreibung bound +// to neither a product nor a managed service (the platform's). +func (d *Doc) Applies(h Holdings) bool { + switch { + case d.Product != "": + return h.Products[d.Product] + case d.ManagedService != "": + return h.ManagedServices[d.ManagedService] + } + return true +} + +// For returns the documents that apply to a workspace with holdings h. +func (c *Catalogue) For(h Holdings) []*Doc { + out := make([]*Doc, 0, len(c.docs)) + for _, d := range c.docs { + if d.Applies(h) { + out = append(out, d) + } + } + return out +} + +var ( + versionRe = regexp.MustCompile(`^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$`) + dateRe = regexp.MustCompile(`^(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[0-2])\.20[0-9]{2}$`) + idRe = regexp.MustCompile(`^[a-z][a-z0-9-]{1,39}$`) +) + +// ValidVersion reports whether v is a document version ("1.0.0"). +func ValidVersion(v string) bool { return versionRe.MatchString(v) } + +// Check verifies every document: its PDF matches the pinned SHA-256 and is a +// PDF, and its table entry is well-formed (unique ID, known kind, version, +// Stand, at most one condition). +func (c *Catalogue) Check() error { + seen := map[string]bool{} + for _, d := range c.docs { + switch { + case !idRe.MatchString(d.ID) || seen[d.ID]: + return fmt.Errorf("contractdocs: id %q is malformed or used twice", d.ID) + case titles[d.Kind] == "": + return fmt.Errorf("contractdocs %s: unknown kind %q", d.ID, d.Kind) + case d.Kind != KindLB && d.ID != d.Kind: + return fmt.Errorf("contractdocs %s: the %s is listed under the id %q", d.ID, d.Kind, d.Kind) + case d.Kind != KindLB && (d.Product != "" || d.ManagedService != ""): + return fmt.Errorf("contractdocs %s: only a Leistungsbeschreibung is bound to a product or service", d.ID) + case d.Product != "" && d.ManagedService != "": + return fmt.Errorf("contractdocs %s: bound to both a product and a managed service", d.ID) + case !ValidVersion(d.Version): + return fmt.Errorf("contractdocs %s: version %q", d.ID, d.Version) + case !dateRe.MatchString(d.Date): + return fmt.Errorf("contractdocs %s: date %q is not DD.MM.YYYY", d.ID, d.Date) + case len(d.PDF) < 5 || string(d.PDF[:5]) != "%PDF-": + return fmt.Errorf("contractdocs %s: not a PDF", d.ID) + } + if got := Sum(d.PDF); got != d.SHA256 { + return fmt.Errorf("contractdocs %s %s: pdf sha256 %s, pinned %s", d.ID, d.Version, got, d.SHA256) + } + seen[d.ID] = true + } + return nil +} + +// Check verifies the committed documents (see Catalogue.Check). +func Check() error { return def.Check() } + +// Sum is the hex SHA-256 of b. +func Sum(b []byte) string { + h := sha256.Sum256(b) + return hex.EncodeToString(h[:]) +} diff --git a/internal/legal/contractdocs/contractdocs_test.go b/internal/legal/contractdocs/contractdocs_test.go new file mode 100644 index 0000000..0392feb --- /dev/null +++ b/internal/legal/contractdocs/contractdocs_test.go @@ -0,0 +1,126 @@ +package contractdocs + +import ( + "strings" + "testing" +) + +func TestCommittedDocumentsMatchTheirPins(t *testing.T) { + if err := Check(); err != nil { + t.Fatal(err) + } + // Every file under files/ is in the table: nothing is committed unpinned. + entries, err := files.ReadDir("files") + if err != nil { + t.Fatal(err) + } + inTable := map[string]bool{} + for _, d := range released { + inTable[d.File] = true + } + for _, e := range entries { + if !inTable[e.Name()] { + t.Errorf("files/%s is not in the table", e.Name()) + } + } + if len(entries) != len(released) { + t.Errorf("%d files, %d table entries", len(entries), len(released)) + } +} + +// The released set as of 09.11.2026: the seven Leistungsbeschreibungen, no +// AGB, AVV or TOM yet. +func TestReleasedSet(t *testing.T) { + want := map[string]string{ + "lb-plattform": "1.0.0", "lb-pruefwerk": "1.0.3", "lb-werkpilot": "1.0.0", "lb-firmwerk": "1.0.0", + "lb-werkmeister": "1.0.0", "lb-managed-git": "1.0.0", "lb-build-runner": "1.0.0", + } + all := Default().All() + if len(all) != len(want) { + t.Fatalf("%d documents", len(all)) + } + for _, d := range all { + if want[d.ID] != d.Version || d.Kind != KindLB || !strings.HasPrefix(d.Title, "Leistungsbeschreibung ") { + t.Errorf("%+v", d) + } + if Default().Get(d.ID) != d { + t.Errorf("get %s", d.ID) + } + } + if all[0].Title != "Leistungsbeschreibung Breakpilot Plattform" { + t.Errorf("platform title %q", all[0].Title) + } + if all[0].ID != "lb-plattform" || Default().Get("avv") != nil || Default().Get("lb-pruefwerk").Date != "09.11.2026" { + t.Error("order, absent AVV or Stand") + } +} + +// The one place that says which Leistungsbeschreibung applies to whom. +func TestApplicability(t *testing.T) { + ids := func(h Holdings) string { + var out []string + for _, d := range Default().For(h) { + out = append(out, d.ID) + } + return strings.Join(out, ",") + } + for name, c := range map[string]struct { + h Holdings + want string + }{ + "nothing booked": {Holdings{}, "lb-plattform"}, + "pruefwerk": {Holdings{Products: map[string]bool{"pruefwerk": true}}, "lb-plattform,lb-pruefwerk"}, + "all products": {Holdings{Products: map[string]bool{"pruefwerk": true, "werkpilot": true, "firmwerk": true, "werkmeister": true, "compliance": true}}, + "lb-plattform,lb-pruefwerk,lb-werkpilot,lb-firmwerk,lb-werkmeister"}, + "managed git": {Holdings{ManagedServices: map[string]bool{"git": true}}, "lb-plattform,lb-managed-git"}, + "git and runner": {Holdings{ManagedServices: map[string]bool{"git": true, "ci-runner": true}}, "lb-plattform,lb-managed-git,lb-build-runner"}, + "service named as product": {Holdings{Products: map[string]bool{"git": true}}, "lb-plattform"}, + } { + if got := ids(c.h); got != c.want { + t.Errorf("%s: %s, want %s", name, got, c.want) + } + } + // AGB, AVV and TOM apply to everyone once released. + for _, k := range []string{KindAGB, KindAVV, KindTOM} { + if !(&Doc{Kind: k}).Applies(Holdings{}) { + t.Errorf("%s does not apply", k) + } + } +} + +func TestTitles(t *testing.T) { + if Title(KindAVV) != "Auftragsverarbeitungsvertrag" || Title(KindAGB) == "" || Title(KindTOM) == "" || Title("x") != "" { + t.Error("titles") + } + if !ValidVersion("1.0.0") || ValidVersion("1.0") || ValidVersion("v1.0.0") || ValidVersion("1.0.0 ") { + t.Error("versions") + } +} + +func TestCheckRefusesBadEntries(t *testing.T) { + pdf := []byte("%PDF-1.7 synthetic") + good := Doc{ID: "avv", Kind: KindAVV, Version: "1.0.0", Date: "01.12.2026", PDF: pdf, SHA256: Sum(pdf)} + if err := NewCatalogue(good).Check(); err != nil { + t.Fatalf("good: %v", err) + } + for name, mod := range map[string]func(d *Doc){ + "changed pdf": func(d *Doc) { d.PDF = []byte("%PDF-1.7 changed") }, + "not a pdf": func(d *Doc) { d.PDF = []byte(""); d.SHA256 = Sum(d.PDF) }, + "bad id": func(d *Doc) { d.ID = "../avv" }, + "avv under other id": func(d *Doc) { d.ID = "avv-master" }, + "unknown kind": func(d *Doc) { d.Kind = "nda" }, + "avv for product": func(d *Doc) { d.Product = "pruefwerk" }, + "both conditions": func(d *Doc) { d.Kind = KindLB; d.Product = "pruefwerk"; d.ManagedService = "git" }, + "bad version": func(d *Doc) { d.Version = "1.0" }, + "iso date": func(d *Doc) { d.Date = "2026-12-01" }, + } { + d := good + mod(&d) + if NewCatalogue(d).Check() == nil { + t.Errorf("%s: not refused", name) + } + } + if NewCatalogue(good, good).Check() == nil { + t.Error("duplicate id not refused") + } +} diff --git a/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_BuildRunner_1.0.0.pdf b/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_BuildRunner_1.0.0.pdf new file mode 100644 index 0000000..70e71ee Binary files /dev/null and b/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_BuildRunner_1.0.0.pdf differ diff --git a/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_Firmwerk_1.0.0.pdf b/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_Firmwerk_1.0.0.pdf new file mode 100644 index 0000000..0ebba94 Binary files /dev/null and b/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_Firmwerk_1.0.0.pdf differ diff --git a/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_ManagedGit_1.0.0.pdf b/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_ManagedGit_1.0.0.pdf new file mode 100644 index 0000000..8e4e5fc Binary files /dev/null and b/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_ManagedGit_1.0.0.pdf differ diff --git a/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_Plattform_1.0.0.pdf b/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_Plattform_1.0.0.pdf new file mode 100644 index 0000000..5b71db7 Binary files /dev/null and b/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_Plattform_1.0.0.pdf differ diff --git a/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_Pruefwerk_1.0.3.pdf b/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_Pruefwerk_1.0.3.pdf new file mode 100644 index 0000000..c96df9d Binary files /dev/null and b/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_Pruefwerk_1.0.3.pdf differ diff --git a/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_Werkmeister_1.0.0.pdf b/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_Werkmeister_1.0.0.pdf new file mode 100644 index 0000000..3a91b0d Binary files /dev/null and b/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_Werkmeister_1.0.0.pdf differ diff --git a/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_Werkpilot_1.0.0.pdf b/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_Werkpilot_1.0.0.pdf new file mode 100644 index 0000000..e12c9a7 Binary files /dev/null and b/internal/legal/contractdocs/files/Breakpilot_Leistungsbeschreibung_Werkpilot_1.0.0.pdf differ diff --git a/internal/server/admin_lifecycle.go b/internal/server/admin_lifecycle.go index 16d634d..0ca9290 100644 --- a/internal/server/admin_lifecycle.go +++ b/internal/server/admin_lifecycle.go @@ -125,7 +125,12 @@ func (s *Server) adminPurgeTenant(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } - if len(docs) > 0 && s.Objects == nil { + contractDocs, err := s.Store.ListContractDocuments(ctx, t.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if len(docs)+len(contractDocs) > 0 && s.Objects == nil { writeError(w, http.StatusServiceUnavailable, "storage_unavailable", "document storage is not configured") return } @@ -136,6 +141,14 @@ func (s *Server) adminPurgeTenant(w http.ResponseWriter, r *http.Request) { return } } + // The tenant's filled contract documents (0027) go with it. + for _, d := range contractDocs { + if err := s.Objects.Delete(ctx, d.ObjectKey); err != nil { + s.Log.Error("purge: delete contract document object failed", "tenant_id", t.ID, "contract_document", d.ID, "err", err) + writeError(w, http.StatusBadGateway, "storage_error", "a document file could not be deleted; nothing else was removed") + return + } + } var emails []string if t.AdminEmail != "" { @@ -154,7 +167,7 @@ func (s *Server) adminPurgeTenant(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } - meta := map[string]interface{}{"slug": t.Slug, "name": t.Name, "accounts_removed": accounts, "documents_removed": len(docs)} + meta := map[string]interface{}{"slug": t.Slug, "name": t.Name, "accounts_removed": accounts, "documents_removed": len(docs), "contract_documents_removed": len(contractDocs)} if t.ErpCustomerID != "" { meta["erp_customer_id_kept"] = t.ErpCustomerID } diff --git a/internal/server/contract_documents.go b/internal/server/contract_documents.go new file mode 100644 index 0000000..cfcbaaa --- /dev/null +++ b/internal/server/contract_documents.go @@ -0,0 +1,468 @@ +package server + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "net/http" + "regexp" + "slices" + "strconv" + "strings" + "time" + + "github.com/google/uuid" + + "git.breakpilot.com/platform/tenant-registry/internal/keycloak" + "git.breakpilot.com/platform/tenant-registry/internal/legal/contractdocs" + "git.breakpilot.com/platform/tenant-registry/internal/roles" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// Contract documents of the Vertragsunterlagen: the released AGB, AVV, TOM +// and Leistungsbeschreibungen (internal/legal/contractdocs, embedded and +// pinned) and a workspace's own filled AVV (0027, in the document bucket). +// Behind the release gate CONTRACT_DOCUMENTS: off, the overview lists none +// and the PDF route answers 404. +// +// GET /v1/tenants/{id}/contracts overview, "documents" (tenants.read) +// GET /v1/tenants/{id}/contracts/documents/{doc}.pdf the PDF (tenants.read) +// GET /v1/admin/tenants/{id}/avv-values the details for the AVV (admin, staff only) +// PUT /v1/admin/tenants/{id}/contract-documents/avv the filled AVV (admin, staff only) + +// maxContractPDFBytes caps a filled AVV upload. +const maxContractPDFBytes = 5 << 20 + +type contractDocument struct { + ID string `json:"id"` + Kind string `json:"kind"` + Title string `json:"title"` + Version string `json:"version"` + Date string `json:"date"` // Stand, DD.MM.YYYY + SHA256 string `json:"sha256"` + Product string `json:"product,omitempty"` + ManagedService string `json:"managed_service,omitempty"` + TenantSpecific bool `json:"tenant_specific"` + + master *contractdocs.Doc + own *store.ContractDocument +} + +var contractKindOrder = map[string]int{contractdocs.KindAGB: 0, contractdocs.KindAVV: 1, contractdocs.KindTOM: 2, contractdocs.KindLB: 3} + +func (s *Server) contractCatalogue() *contractdocs.Catalogue { + if s.Contracts != nil { + return s.Contracts + } + return contractdocs.Default() +} + +// contractHoldings is what decides a tenant's Leistungsbeschreibungen: the +// products it has booked or on trial now (enabled, not expired; a staff +// preview grant is no booking and brings in no Leistungsbeschreibung) and the +// managed services it has (in any status: the contract stands while the +// service is provisioned, restricted or halted). +func contractHoldings(tps []store.TenantProduct, services []store.ManagedService, now time.Time) contractdocs.Holdings { + h := contractdocs.Holdings{Products: map[string]bool{}, ManagedServices: map[string]bool{}} + for _, tp := range tps { + if tp.Preview || !tp.Enabled || (tp.ExpiresAt != nil && !tp.ExpiresAt.After(now)) { + continue + } + h.Products[tp.Product] = true + } + for _, ms := range services { + h.ManagedServices[ms.Kind] = true + } + return h +} + +// tenantContractDocuments lists the contract documents of t: AGB, AVV, TOM, +// then the Leistungsbeschreibungen that apply. The tenant's own filled AVV +// takes the place of the master. Empty while the gate is off. +func (s *Server) tenantContractDocuments(ctx context.Context, t *store.Tenant) ([]contractDocument, error) { + out := []contractDocument{} + if !s.cfg().ContractDocuments { + return out, nil + } + tps, err := s.Store.ListTenantProducts(ctx, t.ID) + if err != nil { + return nil, err + } + services, err := s.Store.ListManagedServices(ctx, t.ID) + if err != nil { + return nil, err + } + own, err := s.Store.CurrentContractDocument(ctx, t.ID, store.ContractDocumentAVV) + if errors.Is(err, store.ErrNotFound) { + own, err = nil, nil + } + if err != nil { + return nil, err + } + cat := s.contractCatalogue() + for _, d := range cat.For(contractHoldings(tps, services, s.now())) { + if d.Kind == contractdocs.KindAVV && own != nil { + continue + } + out = append(out, contractDocument{ + ID: d.ID, Kind: d.Kind, Title: d.Title, Version: d.Version, Date: d.Date, SHA256: d.SHA256, + Product: d.Product, ManagedService: d.ManagedService, master: d, + }) + } + if own != nil { + // The Stand of the master it was filled from; without that master in + // the table, the day it was made. + date := own.CreatedAt.In(berlin).Format("02.01.2006") + if m := cat.Get(contractdocs.KindAVV); m != nil && m.Version == own.Version { + date = m.Date + } + out = append(out, contractDocument{ + ID: contractdocs.KindAVV, Kind: contractdocs.KindAVV, Title: contractdocs.Title(contractdocs.KindAVV), + Version: own.Version, Date: date, SHA256: own.SHA256, TenantSpecific: true, own: own, + }) + } + slices.SortStableFunc(out, func(a, b contractDocument) int { return contractKindOrder[a.Kind] - contractKindOrder[b.Kind] }) + return out, nil +} + +var berlin = func() *time.Location { + if loc, err := time.LoadLocation("Europe/Berlin"); err == nil { + return loc + } + return time.FixedZone("CET", 3600) +}() + +// tenantContractDocumentPDF is GET /v1/tenants/{id}/contracts/documents/{file} +// with file ".pdf": the document as the overview lists it for this +// tenant, byte for byte after its digest matched. +func (s *Server) tenantContractDocumentPDF(w http.ResponseWriter, r *http.Request) { + id, isPDF := strings.CutSuffix(r.PathValue("file"), ".pdf") + if !isPDF || !s.cfg().ContractDocuments { + writeError(w, http.StatusNotFound, "not_found", "no such contract document") + return + } + ctx, cancel := context.WithTimeout(r.Context(), time.Minute) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + docs, err := s.tenantContractDocuments(ctx, t) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + i := slices.IndexFunc(docs, func(d contractDocument) bool { return d.ID == id }) + if i < 0 { + writeError(w, http.StatusNotFound, "not_found", "no such contract document") + return + } + d := docs[i] + if d.own != nil { + if !s.documentsReady(w) { + return + } + s.serveVerified(ctx, w, d.own.ObjectKey, d.own.SHA256, "application/pdf", "Breakpilot_Auftragsverarbeitungsvertrag_"+d.own.Version+".pdf") + return + } + if contractdocs.Sum(d.master.PDF) != d.master.SHA256 { + s.Log.Error("contract document does not match its pin", "document", d.ID, "version", d.Version) + writeError(w, http.StatusInternalServerError, "digest_mismatch", "the document does not match its digest; it is not served") + return + } + h := w.Header() + h.Set("Content-Type", "application/pdf") + h.Set("Content-Disposition", inlineDisposition(d.master.File)) + h.Set("Content-Length", strconv.Itoa(len(d.master.PDF))) + h.Set("ETag", `"`+d.SHA256+`"`) + h.Set("X-Content-SHA256", d.SHA256) + h.Set("X-Content-Type-Options", "nosniff") + h.Set("Cache-Control", "private, max-age=3600") + _, _ = w.Write(d.master.PDF) +} + +// ─── the filled AVV (staff) ──────────────────────────────────────────────── + +// avvValues are the customer's details the AVV master leaves blank: the +// Auftraggeber's name, address, who represents it, and who gives +// instructions. ValuesSHA256 is the SHA-256 of the JSON object of the four +// fields in this order, for X-Values-SHA256 of the upload. +type avvValues struct { + Name string `json:"ag_name"` + Anschrift string `json:"ag_anschrift"` + Vertreten string `json:"ag_vertreten"` + Weisung string `json:"ag_weisung"` + ValuesSHA256 string `json:"values_sha256"` +} + +// countryNames are the company profile's country codes (portal schema +// companyProfile.ts, HQ_COUNTRY) as they appear in a contract. +var countryNames = map[string]string{ + "AT": "Österreich", "CH": "Schweiz", "LI": "Liechtenstein", "LU": "Luxemburg", + "NL": "Niederlande", "FR": "Frankreich", "IT": "Italien", +} + +// adminAVVValues is GET /v1/admin/tenants/{id}/avv-values. The values are +// the customer's data: they are answered, never logged or audited. +func (s *Server) adminAVVValues(w http.ResponseWriter, r *http.Request) { + if _, _, ok := s.staffActor(r); !ok { + writeError(w, http.StatusForbidden, "staff_only", "only a staff member (X-Staff-Subject) may read the AVV details") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + var v avvValues + profile, err := s.companyProfileAnswers(ctx, t.ID) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", "the company profile could not be read") + return + } + v.Name = companyWithLegalForm(profile["companyName"], profile["legalForm"]) + v.Anschrift = joinNonEmpty(", ", + profile["headquartersStreet"], + joinNonEmpty(" ", profile["headquartersZip"], profile["headquartersCity"]), + profileCountry(profile["headquartersCountry"], profile["headquartersCountryOther"])) + v.Weisung = "Geschäftsleitung" + if mail := profile["legalContactEmail"]; mail != "" { + v.Weisung += " (" + mail + ")" + } + names, err := s.managementNames(ctx, t) + if errors.Is(err, errRoleDatasetUnreadable) { + writeError(w, http.StatusInternalServerError, "internal", "the role dataset could not be read") + return + } + if err != nil { + s.writeKeycloakError(w, t.ID, "list members for the AVV", err) + return + } + v.Vertreten = germanList(names) + v.ValuesSHA256 = avvValuesDigest(v) + writeJSON(w, http.StatusOK, v) +} + +func avvValuesDigest(v avvValues) string { + b, _ := json.Marshal(struct { + Name string `json:"ag_name"` + Anschrift string `json:"ag_anschrift"` + Vertreten string `json:"ag_vertreten"` + Weisung string `json:"ag_weisung"` + }{v.Name, v.Anschrift, v.Vertreten, v.Weisung}) + h := sha256.Sum256(b) + return hex.EncodeToString(h[:]) +} + +// companyProfileAnswers returns the text answers of the profile's +// company_profile section, trimmed; empty when there is no profile. +func (s *Server) companyProfileAnswers(ctx context.Context, tenantID string) (map[string]string, error) { + out := map[string]string{} + p, err := s.Store.GetCompanyProfile(ctx, tenantID) + if errors.Is(err, store.ErrNotFound) { + return out, nil + } + if err != nil { + return nil, err + } + var doc struct { + Sections struct { + CompanyProfile map[string]json.RawMessage `json:"company_profile"` + } `json:"sections"` + } + if json.Unmarshal(p.Data, &doc) != nil { + return out, nil + } + for k, raw := range doc.Sections.CompanyProfile { + var str string + if json.Unmarshal(raw, &str) == nil { + out[k] = strings.TrimSpace(str) + } + } + return out, nil +} + +// legalFormNames are the company profile's legal forms (portal schema +// companyProfile.ts, LEGAL_FORM) as written after the company name; the +// first is the form's label, the others are spellings that count as already +// written. "Einzelunternehmen" and "Sonstige" are not appended; the e.V. is +// written without the form's "(Verein)". +var legalFormNames = map[string][]string{ + "gbr": {"GbR"}, "ohg": {"OHG"}, "kg": {"KG"}, "gmbh": {"GmbH"}, + "ug": {"UG (haftungsbeschränkt)", "UG"}, "ag": {"AG"}, "gmbh_co_kg": {"GmbH & Co. KG"}, + "ev": {"e.V."}, "stiftung": {"Stiftung"}, +} + +// companyWithLegalForm is the company name with its legal form ("Muster +// GmbH"), unless the name already ends with it (case-insensitive), the form +// is not appended, or there is no name. +func companyWithLegalForm(name, form string) string { + names := legalFormNames[form] + if name == "" || len(names) == 0 { + return name + } + lower := strings.ToLower(name) + for _, n := range names { + if strings.HasSuffix(lower, strings.ToLower(n)) { + return name + } + } + return name + " " + names[0] +} + +// profileCountry is the country as written in the address: none for +// Germany, the name for a listed code, the free text for "other". +func profileCountry(code, other string) string { + switch { + case code == "other": + code = other + case countryNames[code] != "": + return countryNames[code] + } + if c := strings.ToLower(code); c == "de" || c == "deutschland" { + return "" + } + return code +} + +var errRoleDatasetUnreadable = errors.New("role dataset unreadable") + +// managementNames are the holders of the management function +// (r1.geschaeftsleitung) in the role dataset, by name: members as the portal +// shows them (first and last name, else e-mail), external persons by name. +func (s *Server) managementNames(ctx context.Context, t *store.Tenant) ([]string, error) { + _, ds, err := s.currentRoleDataset(ctx, t.ID) + if err != nil { + return nil, errRoleDatasetUnreadable + } + var holders []roles.Holder + needMembers := false + for _, a := range ds.Assignments { + if a.Function == roles.Management { + holders = append(holders, a.Holder) + needMembers = needMembers || a.Holder.Kind == roles.HolderMember + } + } + byID := map[string]keycloak.OrgMember{} + if needMembers { + members, err := s.Keycloak.ListOrgMembers(ctx, t.Slug) + if err != nil && !errors.Is(err, keycloak.ErrOrgNotFound) { + return nil, err + } + for _, m := range members { + byID[m.UserID] = m + } + } + var names []string + for _, h := range holders { + name := "" + switch h.Kind { + case roles.HolderMember: + if m, ok := byID[h.Sub]; ok { + name = firstNonEmpty(joinNonEmpty(" ", strings.TrimSpace(m.FirstName), strings.TrimSpace(m.LastName)), m.Email) + } + case roles.HolderExternal: + name = firstNonEmpty(strings.TrimSpace(h.Name), strings.TrimSpace(h.Organisation)) + } + if name != "" && !slices.Contains(names, name) { + names = append(names, name) + } + } + return names, nil +} + +// germanList joins names as a German sentence does: "A", "A und B", +// "A, B und C". +func germanList(names []string) string { + if len(names) < 2 { + return strings.Join(names, "") + } + return strings.Join(names[:len(names)-1], ", ") + " und " + names[len(names)-1] +} + +func joinNonEmpty(sep string, parts ...string) string { + var out []string + for _, p := range parts { + if p != "" { + out = append(out, p) + } + } + return strings.Join(out, sep) +} + +var hexSHA256 = regexp.MustCompile(`^[0-9a-f]{64}$`) + +// adminPutAVV is PUT /v1/admin/tenants/{id}/contract-documents/avv: staff +// upload the AVV filled in for this tenant (body: the PDF, at most 5 MB; +// X-Document-Version: the master's version; X-Values-SHA256: the digest of +// the details filled in, as avv-values answers it). It becomes the tenant's +// current AVV; earlier ones stay in the bucket and the table. +func (s *Server) adminPutAVV(w http.ResponseWriter, r *http.Request) { + staff, _, ok := s.staffActor(r) + if !ok { + writeError(w, http.StatusForbidden, "staff_only", "only a staff member (X-Staff-Subject) may upload a contract document") + return + } + if !s.documentsReady(w) { + return + } + version := strings.TrimSpace(r.Header.Get("X-Document-Version")) + if !contractdocs.ValidVersion(version) { + writeError(w, http.StatusBadRequest, "invalid_version", "X-Document-Version must be the master's version, e.g. 1.0.0") + return + } + valuesSHA := strings.ToLower(strings.TrimSpace(r.Header.Get("X-Values-SHA256"))) + if !hexSHA256.MatchString(valuesSHA) { + writeError(w, http.StatusBadRequest, "invalid_values_sha256", "X-Values-SHA256 must be a hex SHA-256") + return + } + ctx, cancel := context.WithTimeout(r.Context(), time.Minute) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxContractPDFBytes)) + if err != nil { + if isTooLarge(err) { + writeError(w, http.StatusRequestEntityTooLarge, "too_large", "the PDF exceeds 5 MB") + return + } + writeError(w, http.StatusBadRequest, "invalid_body", "the PDF could not be read") + return + } + if !bytes.HasPrefix(body, []byte("%PDF")) { + writeError(w, http.StatusUnsupportedMediaType, "not_a_pdf", "the body must be a PDF") + return + } + key := "tenants/" + t.ID + "/contracts/avv/" + uuid.NewString() + ".pdf" + if err := s.Objects.Put(ctx, key, bytes.NewReader(body), int64(len(body)), "application/pdf"); err != nil { + s.Log.Error("contract document: store failed", "tenant_id", t.ID, "err", err) + writeError(w, http.StatusBadGateway, "storage_failed", "the PDF could not be stored") + return + } + sum := sha256.Sum256(body) + row, err := s.Store.CreateContractDocument(ctx, store.ContractDocument{ + TenantID: t.ID, Kind: store.ContractDocumentAVV, Version: version, SHA256: hex.EncodeToString(sum[:]), + ObjectKey: key, ValuesSHA256: valuesSHA, CreatedBy: staff, CreatedAt: s.now(), + }) + if err != nil { + _ = s.Objects.Delete(context.WithoutCancel(ctx), key) + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: t.ID, Action: "contract_document.uploaded", TargetID: strconv.FormatInt(row.ID, 10), + TargetType: "contract_document", TargetName: contractdocs.Title(contractdocs.KindAVV), ActorType: "staff", + Metadata: map[string]interface{}{"kind": row.Kind, "version": row.Version, "sha256": row.SHA256, "values_sha256": row.ValuesSHA256}, + }) + writeJSON(w, http.StatusCreated, row) +} diff --git a/internal/server/contract_documents_store_test.go b/internal/server/contract_documents_store_test.go new file mode 100644 index 0000000..74f30d0 --- /dev/null +++ b/internal/server/contract_documents_store_test.go @@ -0,0 +1,80 @@ +package server_test + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// The store contract on both stores: insert-only rows, the newest per tenant +// and kind is current, refusals of malformed rows and unknown tenants. +func TestContractDocumentStore(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + ctx := context.Background() + row := func(version, sha string) store.ContractDocument { + return store.ContractDocument{ + TenantID: h.tenant.ID, Kind: store.ContractDocumentAVV, Version: version, SHA256: strings.Repeat(sha, 64), + ObjectKey: "tenants/" + h.tenant.ID + "/contracts/avv/" + sha + ".pdf", ValuesSHA256: strings.Repeat("0", 64), + CreatedBy: "staff-sub-1", + } + } + if _, err := h.store.CurrentContractDocument(ctx, h.tenant.ID, store.ContractDocumentAVV); !errors.Is(err, store.ErrNotFound) { + t.Fatalf("none yet: %v", err) + } + first, err := h.store.CreateContractDocument(ctx, row("1.0.0", "a")) + if err != nil || first.ID == 0 || first.CreatedAt.IsZero() || first.CreatedBy != "staff-sub-1" || first.Version != "1.0.0" { + t.Fatalf("first: %+v %v", first, err) + } + withTime := row("1.0.1", "b") + withTime.CreatedAt = time.Now().Add(-time.Hour) // an older timestamp does not make it older + second, err := h.store.CreateContractDocument(ctx, withTime) + if err != nil || second.ID <= first.ID { + t.Fatalf("second: %+v %v", second, err) + } + cur, err := h.store.CurrentContractDocument(ctx, h.tenant.ID, store.ContractDocumentAVV) + if err != nil || cur.ID != second.ID || cur.SHA256 != strings.Repeat("b", 64) || cur.ObjectKey != withTime.ObjectKey { + t.Fatalf("current: %+v %v", cur, err) + } + all, err := h.store.ListContractDocuments(ctx, h.tenant.ID) + if err != nil || len(all) != 2 || all[0].ID != first.ID || all[1].ID != second.ID { + t.Fatalf("list: %+v %v", all, err) + } + + for name, mod := range map[string]func(d *store.ContractDocument){ + "kind": func(d *store.ContractDocument) { d.Kind = "tom" }, + "version": func(d *store.ContractDocument) { d.Version = "1.0" }, + "sha": func(d *store.ContractDocument) { d.SHA256 = "abc" }, + "values sha": func(d *store.ContractDocument) { d.ValuesSHA256 = strings.Repeat("A", 64) }, + "no key": func(d *store.ContractDocument) { d.ObjectKey = "" }, + "no staff": func(d *store.ContractDocument) { d.CreatedBy = "" }, + } { + d := row("1.0.0", "c") + mod(&d) + if _, err := h.store.CreateContractDocument(ctx, d); !errors.Is(err, store.ErrInvalidInput) { + t.Errorf("%s: %v", name, err) + } + } + unknown := row("1.0.0", "d") + unknown.TenantID = "00000000-0000-0000-0000-00000000beef" + if _, err := h.store.CreateContractDocument(ctx, unknown); !errors.Is(err, store.ErrNotFound) { + t.Errorf("unknown tenant: %v", err) + } + unknown.TenantID = "not-a-uuid" + if _, err := h.store.CreateContractDocument(ctx, unknown); !errors.Is(err, store.ErrNotFound) { + t.Errorf("bad tenant id: %v", err) + } + if _, err := h.store.CurrentContractDocument(ctx, "not-a-uuid", store.ContractDocumentAVV); !errors.Is(err, store.ErrNotFound) { + t.Errorf("current, bad id: %v", err) + } + if l, err := h.store.ListContractDocuments(ctx, "not-a-uuid"); err != nil || len(l) != 0 { + t.Errorf("list, bad id: %v %v", l, err) + } + if l, err := h.store.ListContractDocuments(ctx, "00000000-0000-0000-0000-00000000beef"); err != nil || len(l) != 0 { + t.Errorf("list, other tenant: %v %v", l, err) + } + }) +} diff --git a/internal/server/contract_documents_test.go b/internal/server/contract_documents_test.go new file mode 100644 index 0000000..209b52e --- /dev/null +++ b/internal/server/contract_documents_test.go @@ -0,0 +1,633 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "log/slog" + "net/http" + "strings" + "testing" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/config" + "git.breakpilot.com/platform/tenant-registry/internal/keycloak" + "git.breakpilot.com/platform/tenant-registry/internal/legal/contractdocs" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// All data here is synthetic: "Muster Maschinenbau GmbH" in Musterstadt. + +type contractsView struct { + Trial json.RawMessage `json:"trial"` + AVV contractStatus `json:"avv"` + Documents []contractDocument `json:"documents"` +} + +func newContractFixture(t *testing.T, gate bool) *storeFixture { + t.Helper() + f := newStoreFixture(t, portal) + f.s.Cfg = &config.Config{ContractDocuments: gate} + return f +} + +func (f *storeFixture) contracts(t *testing.T) (contractsView, string) { + t.Helper() + code, _, raw := f.call(t, "GET", "/v1/tenants/"+f.tenant.ID+"/contracts", "", nil) + if code != 200 { + t.Fatalf("contracts: %d %s", code, raw) + } + var v contractsView + if err := json.Unmarshal([]byte(raw), &v); err != nil { + t.Fatal(err) + } + return v, raw +} + +func (f *storeFixture) contractPDF(t *testing.T, file string) (int, http.Header, []byte) { + t.Helper() + rr := f.raw(t, "GET", "/v1/tenants/"+f.tenant.ID+"/contracts/documents/"+file, "", nil, nil) + return rr.Code, rr.Header(), rr.Body.Bytes() +} + +func docIDs(docs []contractDocument) string { + var ids []string + for _, d := range docs { + ids = append(ids, d.ID) + } + return strings.Join(ids, ",") +} + +// A synthetic catalogue with a released AVV master, for what the committed +// table does not hold yet. +func catalogueWithAVV() (*contractdocs.Catalogue, []byte) { + avv := []byte("%PDF-1.7 synthetic AVV master") + lb := []byte("%PDF-1.7 synthetic platform LB") + return contractdocs.NewCatalogue( + contractdocs.Doc{ID: "lb-plattform", Kind: contractdocs.KindLB, Title: "Leistungsbeschreibung Breakpilot Plattform", Version: "1.0.0", Date: "06.11.2026", PDF: lb, SHA256: contractdocs.Sum(lb), File: "LB.pdf"}, + contractdocs.Doc{ID: "avv", Kind: contractdocs.KindAVV, Title: "Auftragsverarbeitungsvertrag", Version: "1.0.0", Date: "01.12.2026", PDF: avv, SHA256: contractdocs.Sum(avv), File: "AVV.pdf"}, + ), avv +} + +var asStaff = map[string]string{headerStaffSubject: "staff-sub-1", headerStaffEmail: "staff@breakpilot.test"} + +func avvHeaders(version, values string) map[string]string { + return map[string]string{headerStaffSubject: "staff-sub-1", headerStaffEmail: "staff@breakpilot.test", + "X-Document-Version": version, "X-Values-SHA256": values} +} + +// The one place that decides which products and services count. +func TestContractHoldings(t *testing.T) { + now := time.Date(2026, 11, 9, 12, 0, 0, 0, time.UTC) + past, future := now.Add(-time.Hour), now.Add(24*time.Hour) + tps := []store.TenantProduct{ + {Product: "pruefwerk", Enabled: true}, // booked + {Product: "werkpilot", Enabled: true, ExpiresAt: &future}, // on trial + {Product: "firmwerk", Enabled: true, ExpiresAt: &past}, // trial over + {Product: "werkmeister", Enabled: true, Preview: true, PreviewExpiresAt: &future}, // preview grant + {Product: "compliance", Enabled: true, Preview: true, PreviewExpiresAt: &past}, // preview over + {Product: "other", Enabled: false}, // disabled + {Product: "edge", Enabled: true, ExpiresAt: &now}, // ends now + } + services := []store.ManagedService{{Kind: store.ManagedServiceKindGit, Status: store.ManagedServiceHalted}} + h := contractHoldings(tps, services, now) + for p, want := range map[string]bool{"pruefwerk": true, "werkpilot": true, "firmwerk": false, "werkmeister": false, "compliance": false, "other": false, "edge": false} { + if h.Products[p] != want { + t.Errorf("%s: %v", p, h.Products[p]) + } + } + if !h.ManagedServices["git"] || h.ManagedServices["ci-runner"] { + t.Errorf("services: %v", h.ManagedServices) + } +} + +// The table's conditions name products and service kinds that exist. +func TestContractCatalogueNamesKnownProductsAndServices(t *testing.T) { + known := map[string]bool{} + for _, p := range store.DefaultProducts() { + known[p.Key] = true + } + for _, d := range contractdocs.Default().All() { + if d.Product != "" && !known[d.Product] { + t.Errorf("%s: unknown product %q", d.ID, d.Product) + } + if d.ManagedService != "" && !store.ValidManagedServiceKind(d.ManagedService) { + t.Errorf("%s: unknown managed service %q", d.ID, d.ManagedService) + } + } +} + +func TestContractDocuments_gateOff(t *testing.T) { + f := newContractFixture(t, false) + v, raw := f.contracts(t) + if !strings.Contains(raw, `"documents":[]`) || len(v.Documents) != 0 || v.AVV.Status != "not_concluded" { + t.Fatalf("gate off: %s", raw) + } + if code, _, _ := f.contractPDF(t, "lb-plattform.pdf"); code != 404 { + t.Errorf("pdf with the gate off: %d", code) + } + // A server without config is off too. + f.s.Cfg = nil + if v, _ := f.contracts(t); len(v.Documents) != 0 { + t.Error("nil config lists documents") + } +} + +func TestContractDocuments_leistungsbeschreibungen(t *testing.T) { + f := newContractFixture(t, true) + ctx := context.Background() + // The seed tenant has Prüfwerk and Firmwerk booked. + v, _ := f.contracts(t) + if got := docIDs(v.Documents); got != "lb-plattform,lb-pruefwerk,lb-firmwerk" { + t.Fatalf("documents: %s", got) + } + pw := v.Documents[1] + if pw.Kind != "lb" || pw.Version != "1.0.3" || pw.Date != "09.11.2026" || pw.Product != "pruefwerk" || pw.TenantSpecific || + pw.SHA256 != contractdocs.Default().Get("lb-pruefwerk").SHA256 || pw.Title != "Leistungsbeschreibung Prüfwerk" { + t.Errorf("pruefwerk: %+v", pw) + } + + // A Werkpilot trial and Managed Git with a runner add theirs. + future := time.Now().Add(14 * 24 * time.Hour) + if _, err := f.s.Store.UpsertTenantProduct(ctx, store.TenantProduct{TenantID: f.tenant.ID, Product: "werkpilot", Enabled: true, ExpiresAt: &future, Config: map[string]interface{}{"source": "trial"}}); err != nil { + t.Fatal(err) + } + for _, kind := range []string{store.ManagedServiceKindGit, store.ManagedServiceKindCIRunner} { + if _, err := f.s.Store.CreateManagedService(ctx, store.ManagedService{TenantID: f.tenant.ID, Kind: kind, Name: kind, URL: "https://git.muster.example", SKU: "INF-X", Status: store.ManagedServiceProvisioning}); err != nil { + t.Fatal(err) + } + } + v, _ = f.contracts(t) + if got := docIDs(v.Documents); got != "lb-plattform,lb-pruefwerk,lb-werkpilot,lb-firmwerk,lb-managed-git,lb-build-runner" { + t.Fatalf("documents: %s", got) + } + if v.Documents[4].ManagedService != "git" || v.Documents[4].Product != "" { + t.Errorf("managed git: %+v", v.Documents[4]) + } + + // The PDF: the committed bytes, digest in the headers. + code, hdr, body := f.contractPDF(t, "lb-pruefwerk.pdf") + want := contractdocs.Default().Get("lb-pruefwerk") + if code != 200 || !bytes.Equal(body, want.PDF) || hdr.Get("Content-Type") != "application/pdf" || + hdr.Get("ETag") != `"`+want.SHA256+`"` || !strings.HasPrefix(hdr.Get("Content-Disposition"), "inline") || + !strings.Contains(hdr.Get("Content-Disposition"), want.File) { + t.Fatalf("pdf: %d %v", code, hdr) + } + // Only what the overview lists, only as .pdf. + for _, file := range []string{"lb-werkmeister.pdf", "lb-pruefwerk", "avv.pdf", "..%2Fx.pdf", "nope.pdf"} { + if code, _, _ := f.contractPDF(t, file); code != 404 { + t.Errorf("%s: %d", file, code) + } + } + // A changed embedded file is not served. + cat := contractdocs.NewCatalogue(contractdocs.Doc{ID: "lb-plattform", Kind: "lb", Version: "1.0.0", Date: "06.11.2026", PDF: []byte("%PDF-changed"), SHA256: want.SHA256}) + f.s.Contracts = cat + if code, _, body := f.contractPDF(t, "lb-plattform.pdf"); code != 500 || !strings.Contains(string(body), "digest_mismatch") { + t.Errorf("changed pdf: %d %s", code, body) + } +} + +func TestContractDocuments_userTokenOfAnotherTenant(t *testing.T) { + other := &authn.Principal{Subject: "u-x", ClientID: "portal", TenantID: "00000000-0000-0000-0000-0000000000aa"} + f := newStoreFixture(t, other) + f.s.Cfg = &config.Config{ContractDocuments: true} + if code, _, _ := f.contractPDF(t, "lb-plattform.pdf"); code != 404 { + t.Errorf("other tenant: %d", code) + } +} + +func TestContractDocuments_avvMasterThenOwn(t *testing.T) { + f := newContractFixture(t, true) + cat, master := catalogueWithAVV() + f.s.Contracts = cat + v, _ := f.contracts(t) + if got := docIDs(v.Documents); got != "avv,lb-plattform" || v.Documents[0].TenantSpecific || v.Documents[0].Date != "01.12.2026" { + t.Fatalf("master: %s %+v", got, v.Documents) + } + if code, _, body := f.contractPDF(t, "avv.pdf"); code != 200 || !bytes.Equal(body, master) { + t.Fatalf("master pdf: %d", code) + } + + filled := []byte("%PDF-1.7 synthetic AVV for Muster Maschinenbau GmbH") + values := strings.Repeat("c", 64) + rr := f.raw(t, "PUT", "/v1/admin/tenants/"+f.tenant.ID+"/contract-documents/avv", "application/pdf", filled, avvHeaders("1.0.0", values)) + if rr.Code != 201 { + t.Fatalf("upload: %d %s", rr.Code, rr.Body.String()) + } + var row store.ContractDocument + _ = json.Unmarshal(rr.Body.Bytes(), &row) + if row.Kind != "avv" || row.Version != "1.0.0" || row.SHA256 != hexsum(filled) || row.ValuesSHA256 != values || row.CreatedBy != "staff-sub-1" || + strings.Contains(rr.Body.String(), "tenants/") { + t.Fatalf("row: %s", rr.Body.String()) + } + v, _ = f.contracts(t) + if got := docIDs(v.Documents); got != "avv,lb-plattform" { + t.Fatalf("documents: %s", got) + } + own := v.Documents[0] + if !own.TenantSpecific || own.SHA256 != hexsum(filled) || own.Date != "01.12.2026" || own.Title != "Auftragsverarbeitungsvertrag" { + t.Fatalf("own: %+v", own) + } + code, hdr, body := f.contractPDF(t, "avv.pdf") + if code != 200 || !bytes.Equal(body, filled) || hdr.Get("X-Content-SHA256") != hexsum(filled) || + !strings.Contains(hdr.Get("Content-Disposition"), "Breakpilot_Auftragsverarbeitungsvertrag_1.0.0.pdf") { + t.Fatalf("own pdf: %d %v", code, hdr) + } + ev := f.audit(t, "contract_document.uploaded") + if len(ev) != 1 || ev[0].ActorType != "staff" || ev[0].ActorID != "staff-sub-1" || ev[0].Metadata["values_sha256"] != values { + t.Fatalf("audit: %+v", ev) + } + + // A corrected upload is a new row and the current one; the first stays. + second := []byte("%PDF-1.7 synthetic AVV, corrected") + if rr := f.raw(t, "PUT", "/v1/admin/tenants/"+f.tenant.ID+"/contract-documents/avv", "application/pdf", second, avvHeaders("1.0.1", values)); rr.Code != 201 { + t.Fatalf("second upload: %d", rr.Code) + } + v, _ = f.contracts(t) + if v.Documents[0].SHA256 != hexsum(second) || v.Documents[0].Version != "1.0.1" { + t.Fatalf("second: %+v", v.Documents[0]) + } + // No master of that version: the Stand is the day it was made. + if want := time.Now().In(berlin).Format("02.01.2006"); v.Documents[0].Date != want { + t.Errorf("date %s, want %s", v.Documents[0].Date, want) + } + rows, _ := f.s.Store.ListContractDocuments(context.Background(), f.tenant.ID) + if len(rows) != 2 || len(f.objects.Objects) != 2 { + t.Fatalf("rows %d, objects %d", len(rows), len(f.objects.Objects)) + } + + // A changed file in the bucket is refused; a missing one is a 404. + f.objects.Objects[rows[1].ObjectKey] = []byte("%PDF-tampered") + if code, _, body := f.contractPDF(t, "avv.pdf"); code != 502 || !strings.Contains(string(body), "digest_mismatch") { + t.Errorf("tampered: %d %s", code, body) + } + delete(f.objects.Objects, rows[1].ObjectKey) + if code, _, _ := f.contractPDF(t, "avv.pdf"); code != 404 { + t.Errorf("missing object: %d", code) + } + f.s.Objects = nil + if code, _, _ := f.contractPDF(t, "avv.pdf"); code != 503 { + t.Errorf("no storage: %d", code) + } +} + +// Without a released master, a filled AVV is listed on its own. +func TestContractDocuments_ownAVVWithoutMaster(t *testing.T) { + f := newContractFixture(t, true) + filled := []byte("%PDF-1.7 synthetic") + if rr := f.raw(t, "PUT", "/v1/admin/tenants/"+f.tenant.ID+"/contract-documents/avv", "application/pdf", filled, avvHeaders("1.0.0", strings.Repeat("d", 64))); rr.Code != 201 { + t.Fatalf("upload: %d %s", rr.Code, rr.Body.String()) + } + v, _ := f.contracts(t) + if got := docIDs(v.Documents); got != "avv,lb-plattform,lb-pruefwerk,lb-firmwerk" || !v.Documents[0].TenantSpecific { + t.Fatalf("documents: %s", got) + } + // Behind the gate like the rest. + f.s.Cfg = &config.Config{} + if code, _, _ := f.contractPDF(t, "avv.pdf"); code != 404 { + t.Errorf("gate off: %d", code) + } +} + +func TestAdminPutAVV_refusals(t *testing.T) { + f := newContractFixture(t, true) + path := "/v1/admin/tenants/" + f.tenant.ID + "/contract-documents/avv" + pdf := []byte("%PDF-1.7 synthetic") + good := strings.Repeat("e", 64) + noStaff := map[string]string{"X-Document-Version": "1.0.0", "X-Values-SHA256": good} + for name, c := range map[string]struct { + path string + hdr map[string]string + body []byte + code int + err string + }{ + "not staff": {path, noStaff, pdf, 403, "staff_only"}, + "no version": {path, avvHeaders("", good), pdf, 400, "invalid_version"}, + "bad version": {path, avvHeaders("v1", good), pdf, 400, "invalid_version"}, + "bad values sha": {path, avvHeaders("1.0.0", "xyz"), pdf, 400, "invalid_values_sha256"}, + "not a pdf": {path, avvHeaders("1.0.0", good), []byte(""), 415, "not_a_pdf"}, + "empty": {path, avvHeaders("1.0.0", good), nil, 415, "not_a_pdf"}, + "too large": {path, avvHeaders("1.0.0", good), append([]byte("%PDF"), make([]byte, maxContractPDFBytes)...), 413, "too_large"}, + "unknown tenant": {"/v1/admin/tenants/00000000-0000-0000-0000-0000000000ff/contract-documents/avv", avvHeaders("1.0.0", good), pdf, 404, "not_found"}, + } { + rr := f.raw(t, "PUT", c.path, "application/pdf", c.body, c.hdr) + if rr.Code != c.code || !strings.Contains(rr.Body.String(), c.err) { + t.Errorf("%s: %d %s", name, rr.Code, rr.Body.String()) + } + } + // Upper-case digests are taken as lower case. + if rr := f.raw(t, "PUT", path, "application/pdf", pdf, avvHeaders("1.0.0", strings.ToUpper(strings.Repeat("ab", 32)))); rr.Code != 201 { + t.Errorf("upper-case digest: %d", rr.Code) + } + n := len(f.objects.Objects) + + f.objects.FailPut = errors.New("bucket down") + if rr := f.raw(t, "PUT", path, "application/pdf", pdf, avvHeaders("1.0.0", good)); rr.Code != 502 { + t.Errorf("put failed: %d", rr.Code) + } + f.objects.FailPut = nil + if len(f.objects.Objects) != n { + t.Error("failed upload left an object") + } + f.s.Objects = nil + if rr := f.raw(t, "PUT", path, "application/pdf", pdf, avvHeaders("1.0.0", good)); rr.Code != 503 { + t.Errorf("no storage: %d", rr.Code) + } +} + +// failingContractStore fails the contract-document calls. +type failingContractStore struct { + store.Store + failCreate, failCurrent, failList, failProducts, failServices bool +} + +var errContractStore = errors.New("synthetic store failure") + +func (s failingContractStore) CreateContractDocument(ctx context.Context, d store.ContractDocument) (*store.ContractDocument, error) { + if s.failCreate { + return nil, errContractStore + } + return s.Store.CreateContractDocument(ctx, d) +} + +func (s failingContractStore) CurrentContractDocument(ctx context.Context, tenantID, kind string) (*store.ContractDocument, error) { + if s.failCurrent { + return nil, errContractStore + } + return s.Store.CurrentContractDocument(ctx, tenantID, kind) +} + +func (s failingContractStore) ListContractDocuments(ctx context.Context, tenantID string) ([]store.ContractDocument, error) { + if s.failList { + return nil, errContractStore + } + return s.Store.ListContractDocuments(ctx, tenantID) +} + +func (s failingContractStore) ListTenantProducts(ctx context.Context, tenantID string) ([]store.TenantProduct, error) { + if s.failProducts { + return nil, errContractStore + } + return s.Store.ListTenantProducts(ctx, tenantID) +} + +func (s failingContractStore) ListManagedServices(ctx context.Context, tenantID string) ([]store.ManagedService, error) { + if s.failServices { + return nil, errContractStore + } + return s.Store.ListManagedServices(ctx, tenantID) +} + +func TestContractDocuments_storeFailures(t *testing.T) { + for name, fs := range map[string]failingContractStore{ + "products": {failProducts: true}, "services": {failServices: true}, "current": {failCurrent: true}, + } { + f := newContractFixture(t, true) + fs.Store = f.s.Store + f.s.Store = fs + if code, _, _ := f.call(t, "GET", "/v1/tenants/"+f.tenant.ID+"/contracts", "", nil); code != 500 { + t.Errorf("%s: overview %d", name, code) + } + if code, _, _ := f.contractPDF(t, "lb-plattform.pdf"); code != 500 { + t.Errorf("%s: pdf %d", name, code) + } + } + f := newContractFixture(t, true) + f.s.Store = failingContractStore{Store: f.s.Store, failCreate: true} + rr := f.raw(t, "PUT", "/v1/admin/tenants/"+f.tenant.ID+"/contract-documents/avv", "application/pdf", []byte("%PDF-1.7"), avvHeaders("1.0.0", strings.Repeat("f", 64))) + if rr.Code != 500 || len(f.objects.Objects) != 0 { + t.Errorf("create failed: %d, %d objects left", rr.Code, len(f.objects.Objects)) + } +} + +// ─── avv-values ─────────────────────────────────────────────────────────── + +func saveProfile(t *testing.T, f *storeFixture, answers string) { + t.Helper() + cur, err := f.s.Store.GetCompanyProfile(context.Background(), f.tenant.ID) + rev := 0 + if err == nil { + rev = cur.Revision + } + if _, _, err := f.s.Store.SaveCompanyProfile(context.Background(), store.CompanyProfileWrite{ + TenantID: f.tenant.ID, Data: json.RawMessage(`{"sections":{"company_profile":` + answers + `}}`), SchemaVersion: "1", + ExpectedRevision: rev, Source: store.ProfileSourcePortal, By: "it@muster.test", At: time.Now(), + }); err != nil { + t.Fatal(err) + } +} + +func saveRoles(t *testing.T, f *storeFixture, data string) { + t.Helper() + cur, err := f.s.Store.GetRoleDataset(context.Background(), f.tenant.ID) + rev := 0 + if err == nil { + rev = cur.Revision + } + if _, _, err := f.s.Store.SaveRoleDataset(context.Background(), store.RoleDatasetWrite{ + TenantID: f.tenant.ID, Data: json.RawMessage(data), CatalogueVersion: "r1-test", ExpectedRevision: rev, By: "u-admin", At: time.Now(), + }); err != nil { + t.Fatal(err) + } +} + +func (f *storeFixture) avvValues(t *testing.T) (int, avvValues, string) { + t.Helper() + rr := f.raw(t, "GET", "/v1/admin/tenants/"+f.tenant.ID+"/avv-values", "", nil, asStaff) + var v avvValues + _ = json.Unmarshal(rr.Body.Bytes(), &v) + return rr.Code, v, rr.Body.String() +} + +func TestAdminAVVValues(t *testing.T) { + f := newContractFixture(t, false) // not behind the gate + var logs bytes.Buffer + f.s.Log = slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})) + + // Nothing entered yet: empty fields, the instructing body is the management. + code, v, raw := f.avvValues(t) + if code != 200 || v.Name != "" || v.Anschrift != "" || v.Vertreten != "" || v.Weisung != "Geschäftsleitung" || v.ValuesSHA256 != avvValuesDigest(v) { + t.Fatalf("empty: %d %s", code, raw) + } + + saveProfile(t, f, `{"companyName":"Muster Maschinenbau","legalForm":"gmbh","headquartersStreet":"Musterstraße 1", + "headquartersZip":"12345","headquartersCity":" Musterstadt ","headquartersCountry":"DE","legalContactEmail":"recht@muster.test","employees":12}`) + f.kc.Members["acme"] = append(f.kc.Members["acme"], + keycloak.OrgMember{UserID: "u-ceo", Email: "ceo@muster.test", FirstName: "Erika", LastName: "Mustermann", Enabled: true}, + keycloak.OrgMember{UserID: "u-cfo", Email: "cfo@muster.test", FirstName: "Max", LastName: "Muster", Enabled: true}, + ) + saveRoles(t, f, `{"assignments":[`+ + `{"id":"a-1","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-ceo"},"scope":null},`+ + `{"id":"a-2","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-cfo"},"scope":null},`+ + `{"id":"a-3","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-admin"},"scope":null},`+ + `{"id":"a-4","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-gone"},"scope":null},`+ + `{"id":"a-5","function":"r1.produkt_cybersecurity","holder":{"kind":"member","sub":"u-fin"},"scope":null}]}`) + code, v, raw = f.avvValues(t) + want := avvValues{ + Name: "Muster Maschinenbau GmbH", Anschrift: "Musterstraße 1, 12345 Musterstadt", + // u-admin has no name: the e-mail, as the portal shows it; u-gone is no member any more. + Vertreten: "Erika Mustermann, Max Muster und admin@acme.test", + Weisung: "Geschäftsleitung (recht@muster.test)", + } + want.ValuesSHA256 = avvValuesDigest(want) + if code != 200 || v != want { + t.Fatalf("filled: %d %s", code, raw) + } + if len(want.ValuesSHA256) != 64 || avvValuesDigest(avvValues{Name: "x"}) == want.ValuesSHA256 { + t.Error("digest") + } + + // Countries other than Germany are named; "other" takes the free text. + for country, wantAddr := range map[string]string{ + `"AT"`: "Musterstraße 1, 12345 Musterstadt, Österreich", + `"other","headquartersCountryOther":"Polen"`: "Musterstraße 1, 12345 Musterstadt, Polen", + `"other","headquartersCountryOther":"Deutschland"`: "Musterstraße 1, 12345 Musterstadt", + `"SE"`: "Musterstraße 1, 12345 Musterstadt, SE", + } { + saveProfile(t, f, `{"companyName":"Muster Maschinenbau GmbH","headquartersStreet":"Musterstraße 1","headquartersZip":"12345","headquartersCity":"Musterstadt","headquartersCountry":`+country+`}`) + if _, v, raw := f.avvValues(t); v.Anschrift != wantAddr || v.Weisung != "Geschäftsleitung" { + t.Errorf("%s: %s", country, raw) + } + } + // One holder: no "und". + saveRoles(t, f, `{"assignments":[{"id":"a-1","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-ceo"},"scope":null}]}`) + if _, v, _ := f.avvValues(t); v.Vertreten != "Erika Mustermann" { + t.Errorf("one holder: %q", v.Vertreten) + } + // External holders (a dataset written before the catalogue forbade them + // for the management) by name, else organisation; no Keycloak call. + saveRoles(t, f, `{"assignments":[`+ + `{"id":"a-1","function":"r1.geschaeftsleitung","holder":{"kind":"external","name":" Dr. Anna Beispiel "},"scope":null},`+ + `{"id":"a-2","function":"r1.geschaeftsleitung","holder":{"kind":"external","organisation":"Muster Holding AG"},"scope":null},`+ + `{"id":"a-3","function":"r1.geschaeftsleitung","holder":{"kind":"external","name":"Dr. Anna Beispiel"},"scope":null}]}`) + f.kc.FailNext = keycloak.ErrUnavailable + if _, v, raw := f.avvValues(t); v.Vertreten != "Dr. Anna Beispiel und Muster Holding AG" { + t.Errorf("externals: %s", raw) + } + f.kc.FailNext = nil + saveRoles(t, f, `{"assignments":[{"id":"a-1","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-ceo"},"scope":null}]}`) + if strings.Contains(logs.String(), "Muster") || strings.Contains(logs.String(), "recht@") { + t.Errorf("values were logged: %s", logs.String()) + } + + // Without Keycloak's member list the names are unknown: an error, not a blank. + f.kc.FailNext = keycloak.ErrUnavailable + if code, _, _ := f.avvValues(t); code != 503 { + t.Errorf("keycloak down: %d", code) + } + // No organisation in Keycloak yet: no member names. + delete(f.kc.Members, "acme") + if code, v, _ := f.avvValues(t); code != 200 || v.Vertreten != "" { + t.Errorf("no org: %d %q", code, v.Vertreten) + } + // Staff only, and only for a tenant that exists. + if rr := f.raw(t, "GET", "/v1/admin/tenants/"+f.tenant.ID+"/avv-values", "", nil, nil); rr.Code != 403 { + t.Errorf("not staff: %d", rr.Code) + } + if rr := f.raw(t, "GET", "/v1/admin/tenants/00000000-0000-0000-0000-0000000000ff/avv-values", "", nil, asStaff); rr.Code != 404 { + t.Errorf("unknown tenant: %d", rr.Code) + } +} + +func TestAdminAVVValues_unreadableData(t *testing.T) { + f := newContractFixture(t, false) + // A profile that is not the form's document leaves the fields empty. + if _, _, err := f.s.Store.SaveCompanyProfile(context.Background(), store.CompanyProfileWrite{ + TenantID: f.tenant.ID, Data: json.RawMessage(`{"sections":[]}`), SchemaVersion: "1", Source: store.ProfileSourcePortal, By: "x", At: time.Now(), + }); err != nil { + t.Fatal(err) + } + if code, v, raw := f.avvValues(t); code != 200 || v.Name != "" { + t.Errorf("odd profile: %d %s", code, raw) + } + // A stored role dataset that no longer decodes is an error. + saveRoles(t, f, `{"nope":1}`) + if code, _, raw := f.avvValues(t); code != 500 { + t.Errorf("bad dataset: %d %s", code, raw) + } + f.s.Store = failingProfileStore{Store: f.s.Store} + if code, _, _ := f.avvValues(t); code != 500 { + t.Errorf("profile read failed: %d", code) + } +} + +type failingProfileStore struct{ store.Store } + +func (failingProfileStore) GetCompanyProfile(context.Context, string) (*store.CompanyProfile, error) { + return nil, errContractStore +} + +// The legal form follows the name as the form labels it, once. +func TestCompanyWithLegalForm(t *testing.T) { + for _, c := range []struct{ name, form, want string }{ + {"Muster Maschinenbau", "gmbh", "Muster Maschinenbau GmbH"}, + {"Muster Maschinenbau GmbH", "gmbh", "Muster Maschinenbau GmbH"}, + {"Muster Maschinenbau gmbh", "gmbh", "Muster Maschinenbau gmbh"}, + {"Muster", "ug", "Muster UG (haftungsbeschränkt)"}, + {"Muster UG (haftungsbeschränkt)", "ug", "Muster UG (haftungsbeschränkt)"}, + {"Muster UG", "ug", "Muster UG"}, + {"Muster", "ag", "Muster AG"}, + {"Muster", "gmbh_co_kg", "Muster GmbH & Co. KG"}, + {"Muster GmbH & Co. KG", "gmbh_co_kg", "Muster GmbH & Co. KG"}, + {"Muster", "ohg", "Muster OHG"}, + {"Muster", "kg", "Muster KG"}, + {"Muster", "gbr", "Muster GbR"}, + {"Musterverein", "ev", "Musterverein e.V."}, + {"Musterverein e.V.", "ev", "Musterverein e.V."}, + {"Muster", "stiftung", "Muster Stiftung"}, + {"Muster-Stiftung", "stiftung", "Muster-Stiftung"}, + {"Erika Mustermann", "einzelunternehmen", "Erika Mustermann"}, + {"Muster", "other", "Muster"}, + {"Muster", "", "Muster"}, + {"Muster", "unknown", "Muster"}, + {"", "gmbh", ""}, + } { + if got := companyWithLegalForm(c.name, c.form); got != c.want { + t.Errorf("%q + %q: %q, want %q", c.name, c.form, got, c.want) + } + } +} + +func TestGermanList(t *testing.T) { + for want, in := range map[string][]string{"": nil, "A": {"A"}, "A und B": {"A", "B"}, "A, B und C": {"A", "B", "C"}} { + if got := germanList(in); got != want { + t.Errorf("%v: %q", in, got) + } + } +} + +// Purging a tenant removes its filled contract documents from the bucket. +func TestPurgeRemovesContractDocuments(t *testing.T) { + f := newContractFixture(t, true) + if rr := f.raw(t, "PUT", "/v1/admin/tenants/"+f.tenant.ID+"/contract-documents/avv", "application/pdf", []byte("%PDF-1.7"), avvHeaders("1.0.0", strings.Repeat("a", 64))); rr.Code != 201 { + t.Fatalf("upload: %d", rr.Code) + } + ctx := context.Background() + archived := store.StatusArchived + if _, err := f.s.Store.UpdateTenant(ctx, f.tenant.ID, store.TenantUpdate{Status: &archived}); err != nil { + t.Fatal(err) + } + f.s.Store = failingContractStore{Store: f.s.Store, failList: true} + if rr := f.raw(t, "DELETE", "/v1/admin/tenants/"+f.tenant.ID+"?confirm=acme", "", nil, asStaff); rr.Code != 500 { + t.Fatalf("list failed: %d %s", rr.Code, rr.Body.String()) + } + f.s.Store = f.s.Store.(failingContractStore).Store + objs := f.objects + f.s.Objects = nil + if rr := f.raw(t, "DELETE", "/v1/admin/tenants/"+f.tenant.ID+"?confirm=acme", "", nil, asStaff); rr.Code != 503 { + t.Fatalf("no storage: %d", rr.Code) + } + f.s.Objects = objs + if rr := f.raw(t, "DELETE", "/v1/admin/tenants/"+f.tenant.ID+"?confirm=acme", "", nil, asStaff); rr.Code != 200 { + t.Fatalf("purge: %d %s", rr.Code, rr.Body.String()) + } + if len(f.objects.Objects) != 0 { + t.Errorf("objects left: %d", len(f.objects.Objects)) + } + if rows, _ := f.s.Store.ListContractDocuments(ctx, f.tenant.ID); len(rows) != 0 { + t.Errorf("rows left: %d", len(rows)) + } +} diff --git a/internal/server/openapi_test.go b/internal/server/openapi_test.go index 66da889..e87b6d1 100644 --- a/internal/server/openapi_test.go +++ b/internal/server/openapi_test.go @@ -90,6 +90,10 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) { {"POST", "/v1/licences/00000000-0000-0000-0000-000000000001/revoke"}, {"GET", "/.well-known/licence-keys.json"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/managed-services"}, + {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/contracts"}, + {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/contracts/documents/lb-pruefwerk.pdf"}, + {"GET", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/avv-values"}, + {"PUT", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/contract-documents/avv"}, {"GET", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/managed-services"}, {"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/managed-services"}, {"PATCH", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/managed-services/00000000-0000-0000-0000-000000000002"}, diff --git a/internal/server/server.go b/internal/server/server.go index 3389cf2..f5fcf70 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -20,6 +20,7 @@ import ( "git.breakpilot.com/platform/tenant-registry/internal/config" "git.breakpilot.com/platform/tenant-registry/internal/erp" "git.breakpilot.com/platform/tenant-registry/internal/keycloak" + "git.breakpilot.com/platform/tenant-registry/internal/legal/contractdocs" "git.breakpilot.com/platform/tenant-registry/internal/licence" "git.breakpilot.com/platform/tenant-registry/internal/llmkeys" "git.breakpilot.com/platform/tenant-registry/internal/product" @@ -46,6 +47,9 @@ type Server struct { Objects storage.Objects // nil ⇒ document routes answer 503 (F2) Mail mail.Sender // nil ⇒ notifications queue up unsent (F3) Now func() time.Time // injectable clock (tests); nil ⇒ time.Now + // Contracts are the released contract documents; nil ⇒ the committed + // ones (contractdocs.Default). Tests pass their own. + Contracts *contractdocs.Catalogue blocks blockCache // MemberBlocked answers for user tokens (team.go) ciLimiter keyRateLimiter // CI licence issues per API key (licences_ci.go) @@ -137,6 +141,8 @@ func NewRouter(s *Server) http.Handler { mux.HandleFunc("POST /v1/trial-offers/verify", s.verifyTrialOffer) mux.HandleFunc("POST /v1/trial-offers/{id}/resend", s.resendTrialOffer) mux.HandleFunc("GET /v1/tenants/{id}/contracts/trial/terms.pdf", s.tenantTrialTermsPDF) + // Contract documents (AGB, AVV, TOM, Leistungsbeschreibungen): ".pdf". + mux.HandleFunc("GET /v1/tenants/{id}/contracts/documents/{file}", s.tenantContractDocumentPDF) // Projekte (0010): the list is a {sub} of tenantSubresource. mux.HandleFunc("POST /v1/tenants/{id}/projects", s.createTenantProject) mux.HandleFunc("PATCH /v1/tenants/{id}/projects/{pid}", s.updateTenantProject) @@ -216,6 +222,9 @@ func NewRouter(s *Server) http.Handler { mux.HandleFunc("POST /v1/admin/tenants/{id}/store/import", s.importStore) mux.HandleFunc("GET /v1/admin/tenants/{id}/company-profile", s.getCompanyProfile) mux.HandleFunc("PUT /v1/admin/tenants/{id}/company-profile", s.importCompanyProfile) + // The tenant's own filled AVV (0027): its details, then the PDF. + mux.HandleFunc("GET /v1/admin/tenants/{id}/avv-values", s.adminAVVValues) + mux.HandleFunc("PUT /v1/admin/tenants/{id}/contract-documents/avv", s.adminPutAVV) mux.HandleFunc("GET /v1/admin/tenants/{id}/documents", s.adminListDocuments) mux.HandleFunc("POST /v1/admin/tenants/{id}/documents", s.adminUploadDocument) mux.HandleFunc("POST /v1/admin/documents/{doc}/publish", s.adminPublishDocument) diff --git a/internal/server/trialoffers.go b/internal/server/trialoffers.go index 376e650..6a185c8 100644 --- a/internal/server/trialoffers.go +++ b/internal/server/trialoffers.go @@ -587,6 +587,9 @@ type contractsResp struct { AVV contractStatus `json:"avv"` TOMs contractStatus `json:"toms"` SaaS contractStatus `json:"saas"` + // Documents are the released contract documents for this tenant + // (contract_documents.go); empty while CONTRACT_DOCUMENTS is off. + Documents []contractDocument `json:"documents"` } // listTenantContracts is GET /v1/tenants/{id}/contracts: the tenant's contract @@ -624,6 +627,10 @@ func (s *Server) listTenantContracts(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } + if resp.Documents, err = s.tenantContractDocuments(ctx, t); err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } writeJSON(w, http.StatusOK, resp) } diff --git a/internal/store/contract_documents.go b/internal/store/contract_documents.go new file mode 100644 index 0000000..8c9664b --- /dev/null +++ b/internal/store/contract_documents.go @@ -0,0 +1,39 @@ +package store + +import ( + "regexp" + "time" +) + +// ContractDocument is a workspace's own filled contract document (0027): a +// PDF in the document bucket, made by staff from the released master and +// the workspace's details. Rows are never changed; a corrected document is a +// new row, and the newest per tenant and kind is the current one. +type ContractDocument struct { + ID int64 `json:"id"` + TenantID string `json:"tenant_id"` + Kind string `json:"doc_kind"` // avv + Version string `json:"version"` // version of the master it was filled from + SHA256 string `json:"sha256"` + ObjectKey string `json:"-"` + // ValuesSHA256 is the digest of the details filled in; the values + // themselves are not kept here. + ValuesSHA256 string `json:"values_sha256"` + CreatedBy string `json:"created_by"` // Keycloak sub of the staff member + CreatedAt time.Time `json:"created_at"` +} + +// ContractDocumentAVV is the only kind a workspace has its own copy of. +const ContractDocumentAVV = "avv" + +var ( + contractVersionRe = regexp.MustCompile(`^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$`) + hexDigestRe = regexp.MustCompile(`^[0-9a-f]{64}$`) +) + +// validContractDocument mirrors the CHECK constraints of 0027. +func validContractDocument(d ContractDocument) bool { + return d.Kind == ContractDocumentAVV && contractVersionRe.MatchString(d.Version) && + hexDigestRe.MatchString(d.SHA256) && hexDigestRe.MatchString(d.ValuesSHA256) && + d.ObjectKey != "" && len(d.ObjectKey) <= 512 && d.CreatedBy != "" && len(d.CreatedBy) <= 200 +} diff --git a/internal/store/memory.go b/internal/store/memory.go index ae8962a..82e7f54 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -47,6 +47,9 @@ type Memory struct { mailID int64 prodSets map[string]*TenantProductSettings // tenant_id + "/" + product (0025) + + contractDocs []ContractDocument // every row, oldest first (0027) + contractDocID int64 } type apiKeyWithHash struct { @@ -597,6 +600,13 @@ func (m *Memory) DeleteTenant(_ context.Context, id string) error { delete(m.prodSets, k) } } + kept := m.contractDocs[:0] + for _, d := range m.contractDocs { + if d.TenantID != id { + kept = append(kept, d) + } + } + m.contractDocs = kept for kid, k := range m.apiKeys { if k.TenantID == id { delete(m.apiKeys, kid) diff --git a/internal/store/memory_contract_documents.go b/internal/store/memory_contract_documents.go new file mode 100644 index 0000000..f9f5beb --- /dev/null +++ b/internal/store/memory_contract_documents.go @@ -0,0 +1,49 @@ +package store + +import ( + "context" + "time" +) + +func (m *Memory) CreateContractDocument(_ context.Context, d ContractDocument) (*ContractDocument, error) { + if !validContractDocument(d) { + return nil, ErrInvalidInput + } + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.tenants[d.TenantID]; !ok { + return nil, ErrNotFound + } + m.contractDocID++ + d.ID = m.contractDocID + if d.CreatedAt.IsZero() { + d.CreatedAt = time.Now() + } + d.CreatedAt = d.CreatedAt.UTC() + m.contractDocs = append(m.contractDocs, d) + cp := d + return &cp, nil +} + +func (m *Memory) CurrentContractDocument(_ context.Context, tenantID, kind string) (*ContractDocument, error) { + m.mu.RLock() + defer m.mu.RUnlock() + for i := len(m.contractDocs) - 1; i >= 0; i-- { + if d := m.contractDocs[i]; d.TenantID == tenantID && d.Kind == kind { + return &d, nil + } + } + return nil, ErrNotFound +} + +func (m *Memory) ListContractDocuments(_ context.Context, tenantID string) ([]ContractDocument, error) { + m.mu.RLock() + defer m.mu.RUnlock() + out := []ContractDocument{} + for _, d := range m.contractDocs { + if d.TenantID == tenantID { + out = append(out, d) + } + } + return out, nil +} diff --git a/internal/store/postgres_contract_documents.go b/internal/store/postgres_contract_documents.go new file mode 100644 index 0000000..be50bed --- /dev/null +++ b/internal/store/postgres_contract_documents.go @@ -0,0 +1,77 @@ +package store + +import ( + "context" + "errors" + + "github.com/jackc/pgx/v5" +) + +const contractDocumentCols = `id, tenant_id::text, doc_kind, version, sha256, object_key, values_sha256, created_by, created_at` + +func scanContractDocument(row pgx.Row) (*ContractDocument, error) { + var d ContractDocument + if err := row.Scan(&d.ID, &d.TenantID, &d.Kind, &d.Version, &d.SHA256, &d.ObjectKey, &d.ValuesSHA256, &d.CreatedBy, &d.CreatedAt); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + return nil, err + } + return &d, nil +} + +func (p *Postgres) CreateContractDocument(ctx context.Context, d ContractDocument) (*ContractDocument, error) { + if !validContractDocument(d) { + return nil, ErrInvalidInput + } + saved, err := scanContractDocument(p.pool.QueryRow(ctx, ` + INSERT INTO tenant_contract_documents (tenant_id, doc_kind, version, sha256, object_key, values_sha256, created_by) + VALUES ($1::uuid, $2, $3, $4, $5, $6, $7) + RETURNING `+contractDocumentCols, + d.TenantID, d.Kind, d.Version, d.SHA256, d.ObjectKey, d.ValuesSHA256, d.CreatedBy)) + switch { + case err == nil: + return saved, nil + case isFKViolation(err), isInvalidUUID(err): + return nil, ErrNotFound + case isCheckViolation(err): + return nil, ErrInvalidInput + } + return nil, err +} + +func (p *Postgres) CurrentContractDocument(ctx context.Context, tenantID, kind string) (*ContractDocument, error) { + d, err := scanContractDocument(p.pool.QueryRow(ctx, ` + SELECT `+contractDocumentCols+` FROM tenant_contract_documents + WHERE tenant_id = $1::uuid AND doc_kind = $2 + ORDER BY id DESC LIMIT 1`, tenantID, kind)) + if isInvalidUUID(err) { + return nil, ErrNotFound + } + return d, err +} + +func (p *Postgres) ListContractDocuments(ctx context.Context, tenantID string) ([]ContractDocument, error) { + rows, err := p.pool.Query(ctx, ` + SELECT `+contractDocumentCols+` FROM tenant_contract_documents + WHERE tenant_id = $1::uuid ORDER BY id`, tenantID) + if isInvalidUUID(err) { + return []ContractDocument{}, nil + } + if err != nil { + return nil, err + } + defer rows.Close() + out := []ContractDocument{} + for rows.Next() { + d, err := scanContractDocument(rows) + if err != nil { + return nil, err + } + out = append(out, *d) + } + if isInvalidUUID(rows.Err()) { + return []ContractDocument{}, nil + } + return out, rows.Err() +} diff --git a/internal/store/store.go b/internal/store/store.go index 54e428b..6e840ab 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -257,6 +257,16 @@ type Store interface { GetTenantProductSettings(ctx context.Context, tenantID, product string) (*TenantProductSettings, error) PutTenantProductSettings(ctx context.Context, ps TenantProductSettings) (*TenantProductSettings, error) + // Contract documents of a tenant (0027): its own filled copies, for now + // the AVV. Rows are never changed; the newest per tenant and kind is the + // current one. CreateContractDocument returns ErrNotFound for an unknown + // tenant and ErrInvalidInput for a malformed row; CurrentContractDocument + // is ErrNotFound when the tenant has none of that kind; + // ListContractDocuments returns every row, oldest first. + CreateContractDocument(ctx context.Context, d ContractDocument) (*ContractDocument, error) + CurrentContractDocument(ctx context.Context, tenantID, kind string) (*ContractDocument, error) + ListContractDocuments(ctx context.Context, tenantID string) ([]ContractDocument, error) + // Managed services (0012, portal#77), listed by created_at. One row per // (tenant, kind, url): ErrConflict otherwise. ListManagedServices(ctx context.Context, tenantID string) ([]ManagedService, error) diff --git a/migrations/0027_tenant_contract_documents.down.sql b/migrations/0027_tenant_contract_documents.down.sql new file mode 100644 index 0000000..56547f9 --- /dev/null +++ b/migrations/0027_tenant_contract_documents.down.sql @@ -0,0 +1,3 @@ +DROP TRIGGER IF EXISTS tenant_contract_documents_immutable ON tenant_contract_documents; +DROP FUNCTION IF EXISTS tenant_contract_documents_immutable(); +DROP TABLE IF EXISTS tenant_contract_documents; diff --git a/migrations/0027_tenant_contract_documents.up.sql b/migrations/0027_tenant_contract_documents.up.sql new file mode 100644 index 0000000..491d273 --- /dev/null +++ b/migrations/0027_tenant_contract_documents.up.sql @@ -0,0 +1,29 @@ +-- A workspace's own filled contract documents: for now the AVV, which staff +-- fill in from the released master with the company's details (name, +-- address, management, who gives instructions) and upload as a PDF to the +-- document bucket. The row records which master version it was made from, +-- the PDF's SHA-256 (checked before every download), the digest of the +-- details filled in (the details themselves are not stored here) and the +-- staff member who made it. Rows are never changed: a corrected document is a +-- new row, and the newest per tenant and kind is the current one. +CREATE TABLE tenant_contract_documents ( + id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, + doc_kind TEXT NOT NULL CHECK (doc_kind IN ('avv')), + version TEXT NOT NULL CHECK (version ~ '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'), + sha256 TEXT NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'), + object_key TEXT NOT NULL CHECK (char_length(object_key) BETWEEN 1 AND 512), + values_sha256 TEXT NOT NULL CHECK (values_sha256 ~ '^[0-9a-f]{64}$'), + created_by TEXT NOT NULL CHECK (char_length(created_by) BETWEEN 1 AND 200), + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); +CREATE INDEX tenant_contract_documents_current ON tenant_contract_documents (tenant_id, doc_kind, id DESC); + +CREATE FUNCTION tenant_contract_documents_immutable() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'tenant_contract_documents: rows are never changed; insert a new one'; +END $$ LANGUAGE plpgsql; + +CREATE TRIGGER tenant_contract_documents_immutable + BEFORE UPDATE ON tenant_contract_documents + FOR EACH ROW EXECUTE FUNCTION tenant_contract_documents_immutable(); diff --git a/migrations/migrations_test.go b/migrations/migrations_test.go index ef51d93..1a94854 100644 --- a/migrations/migrations_test.go +++ b/migrations/migrations_test.go @@ -107,6 +107,7 @@ func TestMigrate_upDownRoundTrip(t *testing.T) { "role_datasets", "role_dataset_revisions", "tenant_product_settings", + "tenant_contract_documents", } for _, table := range wantTables { var exists bool @@ -122,8 +123,8 @@ func TestMigrate_upDownRoundTrip(t *testing.T) { } } - // Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects; 0011: trial_offers; 0012: managed_services; 0024: role_datasets; 0025: tenant_product_settings). - for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}, {"projects", "kind"}, {"document_projects", "project_id"}, {"documents", "own_document"}, {"trial_offers", "terms_sha256"}, {"trial_offers", "trial_expires_at"}, {"managed_services", "instance_id"}, {"managed_services", "notes"}, {"role_datasets", "catalogue_version"}, {"role_dataset_revisions", "changed_by"}, {"tenant_product_settings", "settings"}} { + // Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents; 0009: mail_outbox; 0010: projects; 0011: trial_offers; 0012: managed_services; 0024: role_datasets; 0025: tenant_product_settings; 0027: tenant_contract_documents). + for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}, {"mail_outbox", "idempotency_key"}, {"projects", "kind"}, {"document_projects", "project_id"}, {"documents", "own_document"}, {"trial_offers", "terms_sha256"}, {"trial_offers", "trial_expires_at"}, {"managed_services", "instance_id"}, {"managed_services", "notes"}, {"role_datasets", "catalogue_version"}, {"role_dataset_revisions", "changed_by"}, {"tenant_product_settings", "settings"}, {"tenant_contract_documents", "values_sha256"}} { var exists bool err := db.QueryRow( "SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 AND column_name=$2)", @@ -315,15 +316,36 @@ func TestSeed_canInsertAndQuery(t *testing.T) { t.Error("settings that are not an object were stored") } + // 0027: filled contract documents, insert-only. + insDoc := `INSERT INTO tenant_contract_documents (tenant_id, doc_kind, version, sha256, object_key, values_sha256, created_by) + VALUES ($1, $2, $3, $4, 'tenants/x/contracts/avv/a.pdf', $4, 'staff-sub')` + digest := strings.Repeat("ab", 32) + if _, err := db.ExecContext(ctx, insDoc, tid, "avv", "1.0.0", digest); err != nil { + t.Fatalf("insert contract document: %v", err) + } + for name, args := range map[string][]any{ + "unknown kind": {tid, "nda", "1.0.0", digest}, + "bad version": {tid, "avv", "1.0", digest}, + "upper-case sha": {tid, "avv", "1.0.0", strings.ToUpper(digest)}, + } { + if _, err := db.ExecContext(ctx, insDoc, args...); err == nil { + t.Errorf("contract document with %s was stored", name) + } + } + if _, err := db.ExecContext(ctx, `UPDATE tenant_contract_documents SET version = '1.0.1' WHERE tenant_id = $1`, tid); err == nil { + t.Error("a contract document row was changed") + } + // FK cascade — delete tenant, projects/products/keys/audit_log handling. if _, err := db.ExecContext(ctx, `DELETE FROM tenants WHERE id = $1`, tid); err != nil { t.Fatalf("delete tenant: %v", err) } - var nServices, nSettings int + var nServices, nSettings, nContractDocs int _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM managed_services WHERE tenant_id = $1`, tid).Scan(&nServices) _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_product_settings WHERE tenant_id = $1`, tid).Scan(&nSettings) - if nServices != 0 || nSettings != 0 { - t.Errorf("FK cascade incomplete: managed_services=%d tenant_product_settings=%d", nServices, nSettings) + _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_contract_documents WHERE tenant_id = $1`, tid).Scan(&nContractDocs) + if nServices != 0 || nSettings != 0 || nContractDocs != 0 { + t.Errorf("FK cascade incomplete: managed_services=%d tenant_product_settings=%d tenant_contract_documents=%d", nServices, nSettings, nContractDocs) } var nProjects, nProducts, nKeys int _ = db.QueryRowContext(ctx, `SELECT COUNT(*) FROM tenant_projects WHERE tenant_id = $1`, tid).Scan(&nProjects) diff --git a/openapi.yaml b/openapi.yaml index cfd907b..c194d33 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -622,6 +622,55 @@ paths: "403": { $ref: "#/components/responses/Forbidden" } "404": { $ref: "#/components/responses/NotFound" } + /v1/tenants/{id}/contracts: + get: + summary: The tenant's Vertragsunterlagen (trial, AVV, TOM, SaaS, contract documents). + description: | + Served by the `{id}/{sub}` route (tenants.read). `documents` lists the + released contract documents for this tenant: AGB, AVV, TOM, then the + Leistungsbeschreibungen that apply (the platform's always; a product's + while the tenant holds it booked, on trial or as a preview grant; a + managed service's while the tenant has one). A filled AVV of the + tenant replaces the master (tenant_specific). Empty while the release + gate CONTRACT_DOCUMENTS is off. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The overview. + content: + application/json: + schema: + type: object + required: [trial, avv, toms, saas, documents] + properties: + trial: { type: object, nullable: true } + avv: { type: object, properties: { status: { type: string } } } + toms: { type: object, properties: { status: { type: string } } } + saas: { type: object, properties: { status: { type: string } } } + documents: { type: array, items: { $ref: "#/components/schemas/ContractDocument" } } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/tenants/{id}/contracts/documents/{file}: + get: + summary: One contract document of the tenant as PDF (".pdf"). + description: | + Only a document the overview lists for this tenant; the bytes are + checked against their SHA-256 (pinned for released documents, stored + for a filled AVV) before anything is sent. 404 while the release gate + CONTRACT_DOCUMENTS is off. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: file, required: true, schema: { type: string, example: lb-pruefwerk.pdf } } + responses: + "200": + description: The PDF, inline. + content: + application/pdf: { schema: { type: string, format: binary } } + "404": { $ref: "#/components/responses/NotFound" } + "502": { description: The stored file does not match its digest (digest_mismatch) or could not be read. } + "503": { description: Document storage is not configured. } + /v1/tenants/{id}/managed-services: get: summary: A tenant's managed services (Verwaltete Infrastruktur), oldest first. @@ -1204,6 +1253,60 @@ paths: "404": { $ref: "#/components/responses/NotFound" } "409": { $ref: "#/components/responses/ProfileRevisionConflict" } + /v1/admin/tenants/{id}/avv-values: + get: + summary: The customer's details for the AVV (staff only). + description: | + From the company profile (company name as entered; street, ZIP and + city, the country unless Germany; the legal contact e-mail) and the + role dataset (the holders of r1.geschaeftsleitung by name). Missing + data is an empty string. values_sha256 is the SHA-256 of the JSON + object of the four ag_* fields in this order, for X-Values-SHA256. + The values are never logged or audited. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The values. + content: + application/json: + schema: + type: object + properties: + ag_name: { type: string } + ag_anschrift: { type: string } + ag_vertreten: { type: string } + ag_weisung: { type: string } + values_sha256: { type: string } + "403": { description: No named staff member (staff_only). } + "404": { $ref: "#/components/responses/NotFound" } + "503": { description: Keycloak's member list is not available. } + + /v1/admin/tenants/{id}/contract-documents/avv: + put: + summary: Upload the AVV filled in for this tenant (staff only, audited). + description: | + The body is the PDF (at most 5 MB, starting with %PDF). It is stored + in the document bucket and becomes the tenant's current AVV; earlier + uploads stay. Audited as contract_document.uploaded (version and + digests only). + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: header, name: X-Document-Version, required: true, schema: { type: string, example: 1.0.0 } } + - { in: header, name: X-Values-SHA256, required: true, schema: { type: string } } + requestBody: + required: true + content: + application/pdf: { schema: { type: string, format: binary } } + responses: + "201": { description: Stored. } + "400": { description: "invalid_version or invalid_values_sha256." } + "403": { description: No named staff member (staff_only). } + "404": { $ref: "#/components/responses/NotFound" } + "413": { description: Larger than 5 MB. } + "415": { description: Not a PDF (not_a_pdf). } + "503": { description: Document storage is not configured. } + /v1/admin/tenants/{id}/preview-grants: post: summary: Grant a preview of a product not for sale yet (staff only, audited). @@ -2161,6 +2264,20 @@ components: plan: { type: string } tenant_status: { $ref: "#/components/schemas/TenantStatus" } + ContractDocument: + type: object + required: [id, kind, title, version, date, sha256, tenant_specific] + properties: + id: { type: string, example: lb-pruefwerk } + kind: { type: string, enum: [agb, avv, tom, lb] } + title: { type: string } + version: { type: string, example: 1.0.3 } + date: { type: string, description: "Stand, DD.MM.YYYY", example: 09.11.2026 } + sha256: { type: string } + product: { type: string, description: The product a Leistungsbeschreibung belongs to. } + managed_service: { type: string, description: The managed service kind a Leistungsbeschreibung belongs to. } + tenant_specific: { type: boolean, description: The tenant's own filled copy (AVV). } + Error: type: object required: [error]