A workspace whose company profile is submitted and whose Geschäftsleitung is named (Verantwortliche) now sees its AVV filled in: name with legal form, address, "Vertreten durch" and, as the owner decided, "Geschäftsleitung" on the Weisung line. The new package internal/legal/avvfill writes the details onto the released master as one incremental PDF update: the two content streams holding the blank lines are replaced, the underscores dropped and the value set in their place in Geist Regular at body size, inside the line's marked content. The master's bytes stay an untouched prefix, so its pin still holds; the result is deterministic and cached by master and details digest. Layouts are pinned per master SHA-256; a test makes every released AVV master have one.
Until then the master is listed with "missing" (profile, company_name, address, management) for the portal's hint; details that do not fit the form or the Windows-1252 character set give "manual" and a log line without the values. A staff upload still wins (filled_from: staff). The admin avv-values answer uses the same derivation; its Weisung is now "Geschäftsleitung" only. The legal form is no longer appended twice when the name writes it without spaces ("UG(haftungsbeschränkt)").
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
747 lines
32 KiB
Go
747 lines
32 KiB
Go
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"`
|
|
TOMs contractStatus `json:"toms"`
|
|
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 an AVV master and one Leistungsbeschreibung, so
|
|
// the AVV paths are tested apart from the committed table.
|
|
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" || v.TOMs.Status != "pending" {
|
|
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)
|
|
// AGB, AVV master and TOM come first for every workspace.
|
|
if got := docIDs(v.Documents); got != "agb,avv,tom,lb-plattform,lb-pruefwerk,lb-firmwerk" {
|
|
t.Fatalf("documents: %s", got)
|
|
}
|
|
if a := v.Documents[1]; a.TenantSpecific || a.Version != "1.0.0" || a.Date != "17.11.2026" || a.SHA256 != contractdocs.Default().Get("avv").SHA256 {
|
|
t.Errorf("avv master: %+v", a)
|
|
}
|
|
// With the TOM listed, the TOMs are available rather than pending.
|
|
if v.TOMs.Status != "available" {
|
|
t.Errorf("toms status %q", v.TOMs.Status)
|
|
}
|
|
pw := v.Documents[4]
|
|
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 != "agb,avv,tom,lb-plattform,lb-pruefwerk,lb-werkpilot,lb-firmwerk,lb-managed-git,lb-build-runner" {
|
|
t.Fatalf("documents: %s", got)
|
|
}
|
|
if v.Documents[7].ManagedService != "git" || v.Documents[7].Product != "" {
|
|
t.Errorf("managed git: %+v", v.Documents[7])
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
// The AVV master is served byte for byte like the others.
|
|
if code, _, body := f.contractPDF(t, "avv.pdf"); code != 200 || !bytes.Equal(body, contractdocs.Default().Get("avv").PDF) {
|
|
t.Errorf("avv master pdf: %d", code)
|
|
}
|
|
// Only what the overview lists, only as .pdf.
|
|
for _, file := range []string{"lb-werkmeister.pdf", "lb-pruefwerk", "avv", "..%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)
|
|
var noMaster []contractdocs.Doc
|
|
for _, d := range contractdocs.Default().All() {
|
|
if d.Kind != contractdocs.KindAVV {
|
|
noMaster = append(noMaster, *d)
|
|
}
|
|
}
|
|
f.s.Contracts = contractdocs.NewCatalogue(noMaster...)
|
|
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 != "agb,avv,tom,lb-plattform,lb-pruefwerk,lb-firmwerk" || !v.Documents[1].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("<html>"), 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",
|
|
// The function only (owner 19.11.2026): an e-mail would not fit the line.
|
|
Weisung: "Geschäftsleitung",
|
|
}
|
|
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(haftungsbeschränkt)", "ug", "Muster UG(haftungsbeschränkt)"}, // spaces do not count
|
|
{"Muster GmbH & Co.KG", "gmbh_co_kg", "Muster GmbH & Co.KG"},
|
|
{"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))
|
|
}
|
|
}
|
|
|
|
func submitProfile(t *testing.T, f *storeFixture) {
|
|
t.Helper()
|
|
cur, err := f.s.Store.GetCompanyProfile(context.Background(), f.tenant.ID)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := f.s.Store.SubmitCompanyProfile(context.Background(), f.tenant.ID, cur.Revision, "it@muster.test", time.Now()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func avvEntry(t *testing.T, f *storeFixture) contractDocument {
|
|
t.Helper()
|
|
v, _ := f.contracts(t)
|
|
for _, d := range v.Documents {
|
|
if d.Kind == contractdocs.KindAVV {
|
|
return d
|
|
}
|
|
}
|
|
t.Fatal("no AVV listed")
|
|
return contractDocument{}
|
|
}
|
|
|
|
// The AVV fills itself from the submitted profile and the named
|
|
// Geschäftsleitung; until then the master is listed with what is missing.
|
|
func TestContractDocuments_avvFilledFromProfile(t *testing.T) {
|
|
f := newContractFixture(t, true)
|
|
var logs bytes.Buffer
|
|
f.s.Log = slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
|
|
master := contractdocs.Default().Get("avv")
|
|
|
|
// Nothing yet: the master, and everything is missing.
|
|
a := avvEntry(t, f)
|
|
if a.TenantSpecific || a.FilledFrom != "" || a.SHA256 != master.SHA256 || strings.Join(a.Missing, ",") != "profile,company_name,address,management" {
|
|
t.Fatalf("empty: %+v", a)
|
|
}
|
|
if code, _, body := f.contractPDF(t, "avv.pdf"); code != 200 || !bytes.Equal(body, master.PDF) {
|
|
t.Fatalf("blank pdf: %d", code)
|
|
}
|
|
|
|
// A draft profile with all details and a Geschäftsleitung: only the submit is missing.
|
|
saveProfile(t, f, `{"companyName":"Muster Maschinenbau","legalForm":"gmbh","headquartersStreet":"Musterstraße 1",
|
|
"headquartersZip":"12345","headquartersCity":"Musterstadt","headquartersCountry":"DE"}`)
|
|
f.kc.Members["acme"] = append(f.kc.Members["acme"],
|
|
keycloak.OrgMember{UserID: "u-ceo", Email: "ceo@muster.test", FirstName: "Erika", LastName: "Mustermann", Enabled: true})
|
|
saveRoles(t, f, `{"assignments":[{"id":"a-1","function":"r1.geschaeftsleitung","holder":{"kind":"member","sub":"u-ceo"},"scope":null}]}`)
|
|
if a := avvEntry(t, f); a.TenantSpecific || strings.Join(a.Missing, ",") != "profile" {
|
|
t.Fatalf("draft: %+v", a)
|
|
}
|
|
|
|
// Submitted: the filled AVV, the master plus its update.
|
|
submitProfile(t, f)
|
|
a = avvEntry(t, f)
|
|
if !a.TenantSpecific || a.FilledFrom != "profile" || len(a.Missing) != 0 || a.Version != master.Version || a.Date != master.Date || a.SHA256 == master.SHA256 {
|
|
t.Fatalf("filled: %+v", a)
|
|
}
|
|
code, hdr, body := f.contractPDF(t, "avv.pdf")
|
|
if code != 200 || !bytes.HasPrefix(body, master.PDF) || len(body) <= len(master.PDF) || contractdocs.Sum(body) != a.SHA256 ||
|
|
hdr.Get("ETag") != `"`+a.SHA256+`"` || !strings.Contains(hdr.Get("Content-Disposition"), "Breakpilot_Auftragsverarbeitungsvertrag_1.0.0.pdf") {
|
|
t.Fatalf("filled pdf: %d %v", code, hdr)
|
|
}
|
|
// The same details give the same document.
|
|
if _, _, again := f.contractPDF(t, "avv.pdf"); !bytes.Equal(again, body) {
|
|
t.Error("not stable")
|
|
}
|
|
|
|
// Details that do not fit the form: the master, staff fill it in.
|
|
saveProfile(t, f, `{"companyName":"`+strings.Repeat("Muster Maschinenbau ", 4)+`","legalForm":"gmbh","headquartersStreet":"Musterstraße 1",
|
|
"headquartersZip":"12345","headquartersCity":"Musterstadt"}`)
|
|
submitProfile(t, f)
|
|
if a := avvEntry(t, f); a.TenantSpecific || strings.Join(a.Missing, ",") != "manual" {
|
|
t.Fatalf("too long: %+v", a)
|
|
}
|
|
|
|
// An uploaded AVV wins over the automatic one.
|
|
if rr := f.raw(t, "PUT", "/v1/admin/tenants/"+f.tenant.ID+"/contract-documents/avv", "application/pdf", []byte("%PDF-1.7 synthetic"), avvHeaders("1.0.0", strings.Repeat("d", 64))); rr.Code != 201 {
|
|
t.Fatalf("upload: %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
if a := avvEntry(t, f); !a.TenantSpecific || a.FilledFrom != "staff" || len(a.Missing) != 0 {
|
|
t.Fatalf("staff: %+v", a)
|
|
}
|
|
|
|
// The customer's details never reach the log.
|
|
for _, v := range []string{"Muster Maschinenbau", "Musterstraße", "Erika"} {
|
|
if strings.Contains(logs.String(), v) {
|
|
t.Errorf("log carries %q", v)
|
|
}
|
|
}
|
|
}
|