From 1b1e52b851c41f034d3c90c6918478b277afe8ec Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:55:06 +0100 Subject: [PATCH] feat(contracts): list and serve contract documents per tenant GET /v1/tenants/{id}/contracts gains "documents": AGB, AVV, TOM and the Leistungsbeschreibungen that apply to the tenant (platform always; products booked, on trial or under an active preview grant; Managed Git and Build-Runner when the tenant has that managed service). A filled AVV of the tenant replaces the master (tenant_specific). GET /v1/tenants/{id}/contracts/documents/{doc}.pdf serves the bytes after the digest check. Both are empty / 404 while CONTRACT_DOCUMENTS is off. Staff only: GET /v1/admin/tenants/{id}/avv-values derives the AVV details from the company profile and the role dataset (never logged), PUT /v1/admin/tenants/{id}/contract-documents/avv stores the filled PDF. Purging a tenant removes its filled documents from the bucket. Co-Authored-By: Claude Opus 5.5 --- internal/server/admin_lifecycle.go | 17 +- internal/server/contract_documents.go | 439 +++++++++++++ .../server/contract_documents_store_test.go | 80 +++ internal/server/contract_documents_test.go | 602 ++++++++++++++++++ internal/server/openapi_test.go | 4 + internal/server/server.go | 9 + internal/server/trialoffers.go | 7 + openapi.yaml | 117 ++++ 8 files changed, 1273 insertions(+), 2 deletions(-) create mode 100644 internal/server/contract_documents.go create mode 100644 internal/server/contract_documents_store_test.go create mode 100644 internal/server/contract_documents_test.go 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..5a5a982 --- /dev/null +++ b/internal/server/contract_documents.go @@ -0,0 +1,439 @@ +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 may use now (booked, on trial, or an unexpired preview grant) +// 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.Enabled || (tp.ExpiresAt != nil && !tp.ExpiresAt.After(now)) || (tp.Preview && !tp.PreviewActive(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 = profile["companyName"] + 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 +} + +// 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..f848898 --- /dev/null +++ b/internal/server/contract_documents_test.go @@ -0,0 +1,602 @@ +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", 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": true, "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 GmbH","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 +} + +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/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]