Files
tenant-registry/internal/server/contract_documents.go
sharang 5525759392
ci / shared (push) Successful in 12s
ci / test (push) Successful in 25m50s
ci / image (push) Successful in 35s
feat(contracts): serve contract documents in Vertragsunterlagen (#118)
2026-11-09 12:59:20 +00:00

469 lines
16 KiB
Go

package server
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
"regexp"
"slices"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
"git.breakpilot.com/platform/tenant-registry/internal/legal/contractdocs"
"git.breakpilot.com/platform/tenant-registry/internal/roles"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// Contract documents of the Vertragsunterlagen: the released AGB, AVV, TOM
// and Leistungsbeschreibungen (internal/legal/contractdocs, embedded and
// pinned) and a workspace's own filled AVV (0027, in the document bucket).
// Behind the release gate CONTRACT_DOCUMENTS: off, the overview lists none
// and the PDF route answers 404.
//
// GET /v1/tenants/{id}/contracts overview, "documents" (tenants.read)
// GET /v1/tenants/{id}/contracts/documents/{doc}.pdf the PDF (tenants.read)
// GET /v1/admin/tenants/{id}/avv-values the details for the AVV (admin, staff only)
// PUT /v1/admin/tenants/{id}/contract-documents/avv the filled AVV (admin, staff only)
// maxContractPDFBytes caps a filled AVV upload.
const maxContractPDFBytes = 5 << 20
type contractDocument struct {
ID string `json:"id"`
Kind string `json:"kind"`
Title string `json:"title"`
Version string `json:"version"`
Date string `json:"date"` // Stand, DD.MM.YYYY
SHA256 string `json:"sha256"`
Product string `json:"product,omitempty"`
ManagedService string `json:"managed_service,omitempty"`
TenantSpecific bool `json:"tenant_specific"`
master *contractdocs.Doc
own *store.ContractDocument
}
var contractKindOrder = map[string]int{contractdocs.KindAGB: 0, contractdocs.KindAVV: 1, contractdocs.KindTOM: 2, contractdocs.KindLB: 3}
func (s *Server) contractCatalogue() *contractdocs.Catalogue {
if s.Contracts != nil {
return s.Contracts
}
return contractdocs.Default()
}
// contractHoldings is what decides a tenant's Leistungsbeschreibungen: the
// products it has booked or on trial now (enabled, not expired; a staff
// preview grant is no booking and brings in no Leistungsbeschreibung) and the
// managed services it has (in any status: the contract stands while the
// service is provisioned, restricted or halted).
func contractHoldings(tps []store.TenantProduct, services []store.ManagedService, now time.Time) contractdocs.Holdings {
h := contractdocs.Holdings{Products: map[string]bool{}, ManagedServices: map[string]bool{}}
for _, tp := range tps {
if tp.Preview || !tp.Enabled || (tp.ExpiresAt != nil && !tp.ExpiresAt.After(now)) {
continue
}
h.Products[tp.Product] = true
}
for _, ms := range services {
h.ManagedServices[ms.Kind] = true
}
return h
}
// tenantContractDocuments lists the contract documents of t: AGB, AVV, TOM,
// then the Leistungsbeschreibungen that apply. The tenant's own filled AVV
// takes the place of the master. Empty while the gate is off.
func (s *Server) tenantContractDocuments(ctx context.Context, t *store.Tenant) ([]contractDocument, error) {
out := []contractDocument{}
if !s.cfg().ContractDocuments {
return out, nil
}
tps, err := s.Store.ListTenantProducts(ctx, t.ID)
if err != nil {
return nil, err
}
services, err := s.Store.ListManagedServices(ctx, t.ID)
if err != nil {
return nil, err
}
own, err := s.Store.CurrentContractDocument(ctx, t.ID, store.ContractDocumentAVV)
if errors.Is(err, store.ErrNotFound) {
own, err = nil, nil
}
if err != nil {
return nil, err
}
cat := s.contractCatalogue()
for _, d := range cat.For(contractHoldings(tps, services, s.now())) {
if d.Kind == contractdocs.KindAVV && own != nil {
continue
}
out = append(out, contractDocument{
ID: d.ID, Kind: d.Kind, Title: d.Title, Version: d.Version, Date: d.Date, SHA256: d.SHA256,
Product: d.Product, ManagedService: d.ManagedService, master: d,
})
}
if own != nil {
// The Stand of the master it was filled from; without that master in
// the table, the day it was made.
date := own.CreatedAt.In(berlin).Format("02.01.2006")
if m := cat.Get(contractdocs.KindAVV); m != nil && m.Version == own.Version {
date = m.Date
}
out = append(out, contractDocument{
ID: contractdocs.KindAVV, Kind: contractdocs.KindAVV, Title: contractdocs.Title(contractdocs.KindAVV),
Version: own.Version, Date: date, SHA256: own.SHA256, TenantSpecific: true, own: own,
})
}
slices.SortStableFunc(out, func(a, b contractDocument) int { return contractKindOrder[a.Kind] - contractKindOrder[b.Kind] })
return out, nil
}
var berlin = func() *time.Location {
if loc, err := time.LoadLocation("Europe/Berlin"); err == nil {
return loc
}
return time.FixedZone("CET", 3600)
}()
// tenantContractDocumentPDF is GET /v1/tenants/{id}/contracts/documents/{file}
// with file "<doc>.pdf": the document as the overview lists it for this
// tenant, byte for byte after its digest matched.
func (s *Server) tenantContractDocumentPDF(w http.ResponseWriter, r *http.Request) {
id, isPDF := strings.CutSuffix(r.PathValue("file"), ".pdf")
if !isPDF || !s.cfg().ContractDocuments {
writeError(w, http.StatusNotFound, "not_found", "no such contract document")
return
}
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
t, ok := s.tenantInScope(ctx, w, r)
if !ok {
return
}
docs, err := s.tenantContractDocuments(ctx, t)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
i := slices.IndexFunc(docs, func(d contractDocument) bool { return d.ID == id })
if i < 0 {
writeError(w, http.StatusNotFound, "not_found", "no such contract document")
return
}
d := docs[i]
if d.own != nil {
if !s.documentsReady(w) {
return
}
s.serveVerified(ctx, w, d.own.ObjectKey, d.own.SHA256, "application/pdf", "Breakpilot_Auftragsverarbeitungsvertrag_"+d.own.Version+".pdf")
return
}
if contractdocs.Sum(d.master.PDF) != d.master.SHA256 {
s.Log.Error("contract document does not match its pin", "document", d.ID, "version", d.Version)
writeError(w, http.StatusInternalServerError, "digest_mismatch", "the document does not match its digest; it is not served")
return
}
h := w.Header()
h.Set("Content-Type", "application/pdf")
h.Set("Content-Disposition", inlineDisposition(d.master.File))
h.Set("Content-Length", strconv.Itoa(len(d.master.PDF)))
h.Set("ETag", `"`+d.SHA256+`"`)
h.Set("X-Content-SHA256", d.SHA256)
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Cache-Control", "private, max-age=3600")
_, _ = w.Write(d.master.PDF)
}
// ─── the filled AVV (staff) ────────────────────────────────────────────────
// avvValues are the customer's details the AVV master leaves blank: the
// Auftraggeber's name, address, who represents it, and who gives
// instructions. ValuesSHA256 is the SHA-256 of the JSON object of the four
// fields in this order, for X-Values-SHA256 of the upload.
type avvValues struct {
Name string `json:"ag_name"`
Anschrift string `json:"ag_anschrift"`
Vertreten string `json:"ag_vertreten"`
Weisung string `json:"ag_weisung"`
ValuesSHA256 string `json:"values_sha256"`
}
// countryNames are the company profile's country codes (portal schema
// companyProfile.ts, HQ_COUNTRY) as they appear in a contract.
var countryNames = map[string]string{
"AT": "Österreich", "CH": "Schweiz", "LI": "Liechtenstein", "LU": "Luxemburg",
"NL": "Niederlande", "FR": "Frankreich", "IT": "Italien",
}
// adminAVVValues is GET /v1/admin/tenants/{id}/avv-values. The values are
// the customer's data: they are answered, never logged or audited.
func (s *Server) adminAVVValues(w http.ResponseWriter, r *http.Request) {
if _, _, ok := s.staffActor(r); !ok {
writeError(w, http.StatusForbidden, "staff_only", "only a staff member (X-Staff-Subject) may read the AVV details")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
t, ok := s.tenantInScope(ctx, w, r)
if !ok {
return
}
var v avvValues
profile, err := s.companyProfileAnswers(ctx, t.ID)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", "the company profile could not be read")
return
}
v.Name = companyWithLegalForm(profile["companyName"], profile["legalForm"])
v.Anschrift = joinNonEmpty(", ",
profile["headquartersStreet"],
joinNonEmpty(" ", profile["headquartersZip"], profile["headquartersCity"]),
profileCountry(profile["headquartersCountry"], profile["headquartersCountryOther"]))
v.Weisung = "Geschäftsleitung"
if mail := profile["legalContactEmail"]; mail != "" {
v.Weisung += " (" + mail + ")"
}
names, err := s.managementNames(ctx, t)
if errors.Is(err, errRoleDatasetUnreadable) {
writeError(w, http.StatusInternalServerError, "internal", "the role dataset could not be read")
return
}
if err != nil {
s.writeKeycloakError(w, t.ID, "list members for the AVV", err)
return
}
v.Vertreten = germanList(names)
v.ValuesSHA256 = avvValuesDigest(v)
writeJSON(w, http.StatusOK, v)
}
func avvValuesDigest(v avvValues) string {
b, _ := json.Marshal(struct {
Name string `json:"ag_name"`
Anschrift string `json:"ag_anschrift"`
Vertreten string `json:"ag_vertreten"`
Weisung string `json:"ag_weisung"`
}{v.Name, v.Anschrift, v.Vertreten, v.Weisung})
h := sha256.Sum256(b)
return hex.EncodeToString(h[:])
}
// companyProfileAnswers returns the text answers of the profile's
// company_profile section, trimmed; empty when there is no profile.
func (s *Server) companyProfileAnswers(ctx context.Context, tenantID string) (map[string]string, error) {
out := map[string]string{}
p, err := s.Store.GetCompanyProfile(ctx, tenantID)
if errors.Is(err, store.ErrNotFound) {
return out, nil
}
if err != nil {
return nil, err
}
var doc struct {
Sections struct {
CompanyProfile map[string]json.RawMessage `json:"company_profile"`
} `json:"sections"`
}
if json.Unmarshal(p.Data, &doc) != nil {
return out, nil
}
for k, raw := range doc.Sections.CompanyProfile {
var str string
if json.Unmarshal(raw, &str) == nil {
out[k] = strings.TrimSpace(str)
}
}
return out, nil
}
// legalFormNames are the company profile's legal forms (portal schema
// companyProfile.ts, LEGAL_FORM) as written after the company name; the
// first is the form's label, the others are spellings that count as already
// written. "Einzelunternehmen" and "Sonstige" are not appended; the e.V. is
// written without the form's "(Verein)".
var legalFormNames = map[string][]string{
"gbr": {"GbR"}, "ohg": {"OHG"}, "kg": {"KG"}, "gmbh": {"GmbH"},
"ug": {"UG (haftungsbeschränkt)", "UG"}, "ag": {"AG"}, "gmbh_co_kg": {"GmbH & Co. KG"},
"ev": {"e.V."}, "stiftung": {"Stiftung"},
}
// companyWithLegalForm is the company name with its legal form ("Muster
// GmbH"), unless the name already ends with it (case-insensitive), the form
// is not appended, or there is no name.
func companyWithLegalForm(name, form string) string {
names := legalFormNames[form]
if name == "" || len(names) == 0 {
return name
}
lower := strings.ToLower(name)
for _, n := range names {
if strings.HasSuffix(lower, strings.ToLower(n)) {
return name
}
}
return name + " " + names[0]
}
// profileCountry is the country as written in the address: none for
// Germany, the name for a listed code, the free text for "other".
func profileCountry(code, other string) string {
switch {
case code == "other":
code = other
case countryNames[code] != "":
return countryNames[code]
}
if c := strings.ToLower(code); c == "de" || c == "deutschland" {
return ""
}
return code
}
var errRoleDatasetUnreadable = errors.New("role dataset unreadable")
// managementNames are the holders of the management function
// (r1.geschaeftsleitung) in the role dataset, by name: members as the portal
// shows them (first and last name, else e-mail), external persons by name.
func (s *Server) managementNames(ctx context.Context, t *store.Tenant) ([]string, error) {
_, ds, err := s.currentRoleDataset(ctx, t.ID)
if err != nil {
return nil, errRoleDatasetUnreadable
}
var holders []roles.Holder
needMembers := false
for _, a := range ds.Assignments {
if a.Function == roles.Management {
holders = append(holders, a.Holder)
needMembers = needMembers || a.Holder.Kind == roles.HolderMember
}
}
byID := map[string]keycloak.OrgMember{}
if needMembers {
members, err := s.Keycloak.ListOrgMembers(ctx, t.Slug)
if err != nil && !errors.Is(err, keycloak.ErrOrgNotFound) {
return nil, err
}
for _, m := range members {
byID[m.UserID] = m
}
}
var names []string
for _, h := range holders {
name := ""
switch h.Kind {
case roles.HolderMember:
if m, ok := byID[h.Sub]; ok {
name = firstNonEmpty(joinNonEmpty(" ", strings.TrimSpace(m.FirstName), strings.TrimSpace(m.LastName)), m.Email)
}
case roles.HolderExternal:
name = firstNonEmpty(strings.TrimSpace(h.Name), strings.TrimSpace(h.Organisation))
}
if name != "" && !slices.Contains(names, name) {
names = append(names, name)
}
}
return names, nil
}
// germanList joins names as a German sentence does: "A", "A und B",
// "A, B und C".
func germanList(names []string) string {
if len(names) < 2 {
return strings.Join(names, "")
}
return strings.Join(names[:len(names)-1], ", ") + " und " + names[len(names)-1]
}
func joinNonEmpty(sep string, parts ...string) string {
var out []string
for _, p := range parts {
if p != "" {
out = append(out, p)
}
}
return strings.Join(out, sep)
}
var hexSHA256 = regexp.MustCompile(`^[0-9a-f]{64}$`)
// adminPutAVV is PUT /v1/admin/tenants/{id}/contract-documents/avv: staff
// upload the AVV filled in for this tenant (body: the PDF, at most 5 MB;
// X-Document-Version: the master's version; X-Values-SHA256: the digest of
// the details filled in, as avv-values answers it). It becomes the tenant's
// current AVV; earlier ones stay in the bucket and the table.
func (s *Server) adminPutAVV(w http.ResponseWriter, r *http.Request) {
staff, _, ok := s.staffActor(r)
if !ok {
writeError(w, http.StatusForbidden, "staff_only", "only a staff member (X-Staff-Subject) may upload a contract document")
return
}
if !s.documentsReady(w) {
return
}
version := strings.TrimSpace(r.Header.Get("X-Document-Version"))
if !contractdocs.ValidVersion(version) {
writeError(w, http.StatusBadRequest, "invalid_version", "X-Document-Version must be the master's version, e.g. 1.0.0")
return
}
valuesSHA := strings.ToLower(strings.TrimSpace(r.Header.Get("X-Values-SHA256")))
if !hexSHA256.MatchString(valuesSHA) {
writeError(w, http.StatusBadRequest, "invalid_values_sha256", "X-Values-SHA256 must be a hex SHA-256")
return
}
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
t, ok := s.tenantInScope(ctx, w, r)
if !ok {
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxContractPDFBytes))
if err != nil {
if isTooLarge(err) {
writeError(w, http.StatusRequestEntityTooLarge, "too_large", "the PDF exceeds 5 MB")
return
}
writeError(w, http.StatusBadRequest, "invalid_body", "the PDF could not be read")
return
}
if !bytes.HasPrefix(body, []byte("%PDF")) {
writeError(w, http.StatusUnsupportedMediaType, "not_a_pdf", "the body must be a PDF")
return
}
key := "tenants/" + t.ID + "/contracts/avv/" + uuid.NewString() + ".pdf"
if err := s.Objects.Put(ctx, key, bytes.NewReader(body), int64(len(body)), "application/pdf"); err != nil {
s.Log.Error("contract document: store failed", "tenant_id", t.ID, "err", err)
writeError(w, http.StatusBadGateway, "storage_failed", "the PDF could not be stored")
return
}
sum := sha256.Sum256(body)
row, err := s.Store.CreateContractDocument(ctx, store.ContractDocument{
TenantID: t.ID, Kind: store.ContractDocumentAVV, Version: version, SHA256: hex.EncodeToString(sum[:]),
ObjectKey: key, ValuesSHA256: valuesSHA, CreatedBy: staff, CreatedAt: s.now(),
})
if err != nil {
_ = s.Objects.Delete(context.WithoutCancel(ctx), key)
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: t.ID, Action: "contract_document.uploaded", TargetID: strconv.FormatInt(row.ID, 10),
TargetType: "contract_document", TargetName: contractdocs.Title(contractdocs.KindAVV), ActorType: "staff",
Metadata: map[string]interface{}{"kind": row.Kind, "version": row.Version, "sha256": row.SHA256, "values_sha256": row.ValuesSHA256},
})
writeJSON(w, http.StatusCreated, row)
}