From 251cddf3d331f9eed97f7d8f2f1c28757745684e Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Tue, 20 Oct 2026 15:07:57 +0200 Subject: [PATCH] =?UTF-8?q?feat(store):=20Dokumentenablage=20=E2=80=94=20t?= =?UTF-8?q?hree=20areas,=20digest-checked=20serving,=20staff=20bundle=20im?= =?UTF-8?q?port?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Workspace ticket #171 (decided 2026-10-20): the tenant's own documents live next to BreakPilot's deliveries ("Unterlagen") in the same table and bucket, in three areas, with the original and the prepared version the Factory delivers. - migration 0022: documents get area (legal_web / product_public / internal; NULL = Unterlagen), legal_kind (the 8 folders as the workspace and Factory name them), processing_status (none/pending/ready/failed), external_id (the Factory's tenant_document_id, unique per tenant); document_preparations (chunk file and/or cookie-banner capture with digest, format, revision, pin, image digests); store_assets (images per tenant, content-addressed) - GET /v1/tenants/{id}/store; POST …/store/documents (customer upload: legal folder, product of an internal document; legal and product documents wait for the Factory, an internal one only on request); GET …/original, …/prepared, …/consent-banner and …/store/assets/{sha}: every byte is hashed and compared before anything is sent (fail-closed, 502 digest_mismatch), HTML originals sandboxed - POST /v1/admin/tenants/{id}/store/import (named staff only): a .tar.gz in the Factory's run layout; unsafe paths and links refused, every file checked against its digest, keyed on tenant_document_id so it can run again; per-document outcome, never content - Unterlagen lists stay as they were (area NULL only); deleting a store document removes its prepared files; storage gains Get - OpenAPI for the seven routes; tests on memory and Postgres with synthetic data only Co-Authored-By: Claude Opus 5.5 --- internal/config/config.go | 3 + internal/server/document_import.go | 535 ++++++++++++++++++++++ internal/server/document_store.go | 426 +++++++++++++++++ internal/server/document_store_db_test.go | 134 ++++++ internal/server/document_store_test.go | 408 +++++++++++++++++ internal/server/documents.go | 9 + internal/server/members.go | 2 + internal/server/server.go | 7 + internal/storage/storage.go | 28 ++ internal/store/document_store.go | 88 ++++ internal/store/memory.go | 48 +- internal/store/memory_document_store.go | 185 ++++++++ internal/store/memory_documents.go | 12 +- internal/store/postgres_document_store.go | 191 ++++++++ internal/store/postgres_documents.go | 21 +- internal/store/store.go | 20 + internal/store/types.go | 8 + migrations/0022_document_store.down.sql | 11 + migrations/0022_document_store.up.sql | 53 +++ openapi.yaml | 181 ++++++++ 20 files changed, 2340 insertions(+), 30 deletions(-) create mode 100644 internal/server/document_import.go create mode 100644 internal/server/document_store.go create mode 100644 internal/server/document_store_db_test.go create mode 100644 internal/server/document_store_test.go create mode 100644 internal/store/document_store.go create mode 100644 internal/store/memory_document_store.go create mode 100644 internal/store/postgres_document_store.go create mode 100644 migrations/0022_document_store.down.sql create mode 100644 migrations/0022_document_store.up.sql diff --git a/internal/config/config.go b/internal/config/config.go index 3a6c972..c767d43 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -78,6 +78,8 @@ type Config struct { DocumentsS3SecretKey string // DocumentsMaxBytes caps one upload (default 200 MiB). DocumentsMaxBytes int64 + // StoreImportMaxBytes caps one document-store bundle import (default 2 GiB). + StoreImportMaxBytes int64 // Platform mail (F3). SMTPHost empty ⇒ notifications queue up unsent. SMTPHost string @@ -152,6 +154,7 @@ func Load() (*Config, error) { DocumentsS3AccessKey: os.Getenv("DOCUMENTS_S3_ACCESS_KEY"), DocumentsS3SecretKey: os.Getenv("DOCUMENTS_S3_SECRET_KEY"), DocumentsMaxBytes: int64(getint("DOCUMENTS_MAX_MB", 200)) << 20, + StoreImportMaxBytes: int64(getint("STORE_IMPORT_MAX_MB", 2048)) << 20, SMTPHost: os.Getenv("SMTP_HOST"), SMTPPort: getint("SMTP_PORT", 587), diff --git a/internal/server/document_import.go b/internal/server/document_import.go new file mode 100644 index 0000000..1cce34b --- /dev/null +++ b/internal/server/document_import.go @@ -0,0 +1,535 @@ +package server + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "path" + "path/filepath" + "regexp" + "sort" + "strings" + "time" + + "github.com/google/uuid" + + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// Staff import of a document store bundle (POST /v1/admin/tenants/{id}/store/import): +// a .tar.gz in the layout of the Factory's serving and chunk runs — +// +// LANE_B_INDEX_V1.json the documents (id, digest, title, folder) +// objects/.(pdf|html|txt) the originals +// presentation/CONSENT_BANNER_CAPTURES_V1.json which document has which capture +// presentation/consent_banner/.json the captures +// chunks/.json the prepared versions (LANE_B_UNIFIED_V5) +// figure_assets/sources/sha256/. their images +// LANE_B_UNIFIED_V5_RETURN_MANIFEST_V1.json optional: pin (its digest) and revision +// +// Every file is checked against the digest it is named by; a document whose +// original does not match is rejected, a prepared version with a missing or +// wrong image is not taken (the original still is). The import is keyed on +// the Factory's tenant_document_id, so it can run again: what is there and +// unchanged is skipped. The answer lists each document's outcome, never its +// content. + +const ( + importDefaultMaxBytes = 2 << 30 + importMaxFiles = 20000 +) + +var ( + importObjectRe = regexp.MustCompile(`^objects/([0-9a-f]{64})\.(pdf|html|txt)$`) + importConsentRe = regexp.MustCompile(`^presentation/consent_banner/([0-9a-f]{64})\.json$`) + importIDRe = regexp.MustCompile(`^[A-Za-z0-9._-]{1,120}$`) + importExtTypes = map[string]string{".pdf": "application/pdf", ".html": "text/html; charset=utf-8", ".txt": "text/plain; charset=utf-8"} + assetExtTypes = map[string]string{".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp"} +) + +type importIndex struct { + Documents []struct { + TenantDocumentID string `json:"tenant_document_id"` + ContentDigest string `json:"content_digest"` + Title string `json:"title"` + ObjectKey string `json:"object_key"` + DocumentClass string `json:"document_class"` + LegalKind string `json:"legal_kind"` + } `json:"documents"` +} + +type importCaptures struct { + Artifact string `json:"artifact"` + Captures []struct { + TenantDocumentID string `json:"tenant_document_id"` + ObjectKey string `json:"object_key"` + Digest string `json:"digest"` + } `json:"captures"` +} + +// ImportOutcome is what happened to one document of the bundle. +type ImportOutcome struct { + ExternalID string `json:"external_id"` + Title string `json:"title"` + Area string `json:"area,omitempty"` + LegalKind string `json:"legal_kind,omitempty"` + DocumentID string `json:"document_id,omitempty"` + Original string `json:"original"` // imported | exists | rejected + Prepared string `json:"prepared"` // imported | unchanged | absent | rejected + Consent string `json:"consent"` // imported | unchanged | absent | rejected + Assets int `json:"assets"` + Reason string `json:"reason,omitempty"` +} + +type importResp struct { + Documents []ImportOutcome `json:"documents"` + Counts map[string]int `json:"counts"` + Pin string `json:"pin,omitempty"` + Revision int `json:"revision,omitempty"` +} + +// importStore is POST /v1/admin/tenants/{id}/store/import; the body is the +// .tar.gz itself. Staff only (a named staff member). +func (s *Server) importStore(w http.ResponseWriter, r *http.Request) { + if !s.documentsReady(w) { + return + } + _, staffEmail, ok := s.staffActor(r) + if !ok { + writeError(w, http.StatusForbidden, "staff_only", "an import needs a staff member (X-Staff-Subject)") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Minute) + defer cancel() + t, err := s.Store.GetTenant(ctx, r.PathValue("id")) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + dir, err := os.MkdirTemp("", "store-import-*") + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", "no temporary space") + return + } + defer func() { _ = os.RemoveAll(dir) }() + max := s.cfg().StoreImportMaxBytes + if max <= 0 { + max = importDefaultMaxBytes + } + root, err := extractBundle(http.MaxBytesReader(w, r.Body, max), dir, max) + if err != nil { + code := http.StatusBadRequest + if isTooLarge(err) || errors.Is(err, errBundleTooLarge) { + code = http.StatusRequestEntityTooLarge + } + writeError(w, code, "invalid_bundle", err.Error()) + return + } + var idx importIndex + if err := readJSONFile(filepath.Join(root, "LANE_B_INDEX_V1.json"), &idx); err != nil || len(idx.Documents) == 0 { + writeError(w, http.StatusBadRequest, "invalid_bundle", "LANE_B_INDEX_V1.json is missing, unreadable or lists no documents") + return + } + var caps importCaptures + if err := readJSONFile(filepath.Join(root, "presentation", "CONSENT_BANNER_CAPTURES_V1.json"), &caps); err != nil && !errors.Is(err, os.ErrNotExist) { + writeError(w, http.StatusBadRequest, "invalid_bundle", "CONSENT_BANNER_CAPTURES_V1.json is unreadable") + return + } + pin, revision := bundleManifest(filepath.Join(root, "LANE_B_UNIFIED_V5_RETURN_MANIFEST_V1.json")) + + imp := &importer{s: s, root: root, tenantID: t.ID, by: firstNonEmpty(staffEmail, "staff"), pin: pin, revision: revision, caps: caps} + out := importResp{Documents: []ImportOutcome{}, Counts: map[string]int{}, Pin: pin, Revision: revision} + for _, d := range idx.Documents { + o := imp.document(ctx, d.TenantDocumentID, d.ContentDigest, d.Title, d.ObjectKey, d.DocumentClass, d.LegalKind) + out.Documents = append(out.Documents, o) + out.Counts["original_"+o.Original]++ + out.Counts["prepared_"+o.Prepared]++ + out.Counts["consent_"+o.Consent]++ + } + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: t.ID, Action: "store.imported", TargetID: t.ID, TargetType: "tenant", TargetName: t.Slug, + ActorType: "staff", ActorName: imp.by, + Metadata: map[string]interface{}{"documents": len(out.Documents), "counts": out.Counts, "pin": pin, "revision": revision}, + }) + writeJSON(w, http.StatusOK, out) +} + +var errBundleTooLarge = errors.New("the bundle is larger than the import limit") + +// extractBundle unpacks the .tar.gz into dir: regular files and directories +// only, no absolute paths, no "..", no links, at most importMaxFiles files and +// max bytes. It returns the bundle root: dir, or its only directory when the +// archive wraps everything in one. +func extractBundle(r io.Reader, dir string, max int64) (string, error) { + gz, err := gzip.NewReader(r) + if err != nil { + return "", errors.New("not a .tar.gz") + } + tr := tar.NewReader(gz) + var files int + var total int64 + for { + h, err := tr.Next() + if err == io.EOF { + break + } + if err != nil { + if isTooLarge(err) { + return "", err + } + return "", fmt.Errorf("the archive is broken: %w", err) + } + name := path.Clean(strings.TrimPrefix(h.Name, "./")) + if name == "." { + continue + } + if path.IsAbs(name) || name == ".." || strings.HasPrefix(name, "../") { + return "", fmt.Errorf("refused path %q", h.Name) + } + target := filepath.Join(dir, filepath.FromSlash(name)) + switch h.Typeflag { + case tar.TypeDir: + if err := os.MkdirAll(target, 0o700); err != nil { + return "", err + } + case tar.TypeReg: + if files++; files > importMaxFiles { + return "", fmt.Errorf("more than %d files", importMaxFiles) + } + if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil { + return "", err + } + f, err := os.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) + if err != nil { + return "", fmt.Errorf("refused path %q", h.Name) + } + n, err := io.Copy(f, io.LimitReader(tr, max-total+1)) + _ = f.Close() + if err != nil { + if isTooLarge(err) { + return "", err + } + return "", fmt.Errorf("the archive is broken: %w", err) + } + if total += n; total > max { + return "", errBundleTooLarge + } + default: + // Links and devices could point outside the bundle. + return "", fmt.Errorf("refused entry %q (only files and directories)", h.Name) + } + } + if _, err := os.Stat(filepath.Join(dir, "LANE_B_INDEX_V1.json")); err == nil { + return dir, nil + } + entries, _ := os.ReadDir(dir) + if len(entries) == 1 && entries[0].IsDir() { + return filepath.Join(dir, entries[0].Name()), nil + } + return dir, nil +} + +func readJSONFile(p string, into any) error { + b, err := os.ReadFile(p) //nolint:gosec // inside the import's temp dir + if err != nil { + return err + } + return json.Unmarshal(b, into) +} + +// bundleManifest: the pin is the manifest file's digest; the revision its +// "revision" field when there is one. +func bundleManifest(p string) (string, int) { + b, err := os.ReadFile(p) //nolint:gosec // inside the import's temp dir + if err != nil { + return "", 0 + } + sum := sha256.Sum256(b) + var m struct { + Revision int `json:"revision"` + } + _ = json.Unmarshal(b, &m) + return hex.EncodeToString(sum[:]), m.Revision +} + +type importer struct { + s *Server + root string + tenantID string + by string + pin string + revision int + caps importCaptures +} + +// fileWithDigest reads rel inside the bundle and checks it hashes to want. +func (im *importer) fileWithDigest(rel, want string) ([]byte, error) { + b, err := os.ReadFile(filepath.Join(im.root, filepath.FromSlash(rel))) //nolint:gosec // inside the import's temp dir + if err != nil { + return nil, fmt.Errorf("%s is missing", rel) + } + sum := sha256.Sum256(b) + if hex.EncodeToString(sum[:]) != want { + return nil, fmt.Errorf("%s does not match its digest", rel) + } + return b, nil +} + +func (im *importer) document(ctx context.Context, id, digest, title, objectKey, class, legalKind string) ImportOutcome { + o := ImportOutcome{ExternalID: id, Title: title, Original: "rejected", Prepared: "absent", Consent: "absent"} + if !importIDRe.MatchString(id) { + o.Reason = "invalid tenant_document_id" + return o + } + m := importObjectRe.FindStringSubmatch(objectKey) + if m == nil || digest != "sha256:"+m[1] { + o.Reason = "object_key and content_digest do not agree" + return o + } + o.Area = store.AreaProductPublic + if class == "LEGAL" { + o.Area, o.LegalKind = store.AreaLegalWeb, legalKind + if !store.ValidLegalKind(legalKind) { + o.Reason = fmt.Sprintf("unknown legal_kind %q", legalKind) + return o + } + } + doc, err := im.s.Store.GetDocumentByExternalID(ctx, im.tenantID, id) + switch { + case err == nil && doc.SHA256 != m[1]: + o.DocumentID = doc.ID + o.Reason = "a different original is already stored under this id" + return o + case err == nil: + o.Original, o.DocumentID = "exists", doc.ID + case errors.Is(err, store.ErrNotFound): + body, ferr := im.fileWithDigest(objectKey, m[1]) + if ferr != nil { + o.Reason = ferr.Error() + return o + } + if doc, err = im.createDocument(ctx, id, title, o.Area, o.LegalKind, m[1], "."+m[2], body); err != nil { + o.Reason = "could not be stored: " + err.Error() + return o + } + o.Original, o.DocumentID = "imported", doc.ID + default: + o.Reason = err.Error() + return o + } + im.preparation(ctx, doc, &o) + return o +} + +func (im *importer) createDocument(ctx context.Context, id, title, area, legalKind, sum, ext string, body []byte) (*store.Document, error) { + name := safeFilename(strings.TrimSpace(title) + ext) + if name == "" || name == ext { + name = id + ext + } + t := strings.Join(strings.Fields(title), " ") + if t == "" { + t = id + } + if len([]rune(t)) > 200 { + t = string([]rune(t)[:200]) + } + d := store.Document{ + ID: uuid.NewString(), TenantID: im.tenantID, Title: t, Filename: name, ContentType: importExtTypes[ext], + SizeBytes: int64(len(body)), SHA256: sum, Status: store.DocumentPublished, OwnDocument: true, + UploadedBy: im.by, Area: area, LegalKind: legalKind, ProcessingStatus: store.ProcessingPending, ExternalID: id, + } + d.ObjectKey = storeKey(im.tenantID, d.ID, "original/"+name) + if err := im.s.Objects.Put(ctx, d.ObjectKey, bytes.NewReader(body), int64(len(body)), d.ContentType); err != nil { + return nil, err + } + created, err := im.s.Store.CreateDocument(ctx, d) + if err != nil { + _ = im.s.Objects.Delete(context.WithoutCancel(ctx), d.ObjectKey) + return nil, err + } + return created, nil +} + +// preparation takes the document's chunk file (with its images) and its +// cookie-banner capture, where the bundle has them. +func (im *importer) preparation(ctx context.Context, doc *store.Document, o *ImportOutcome) { + cur, err := im.s.Store.GetDocumentPreparation(ctx, doc.ID) + if err != nil && !errors.Is(err, store.ErrNotFound) { + o.Prepared, o.Reason = "rejected", err.Error() + return + } + next := store.Preparation{DocumentID: doc.ID, DeliveredBy: im.by} + + chunkPath := filepath.Join(im.root, "chunks", o.ExternalID+".json") + if b, rerr := os.ReadFile(chunkPath); rerr == nil { //nolint:gosec // inside the import's temp dir + sum := sha256.Sum256(b) + hexSum := hex.EncodeToString(sum[:]) + switch count, digests, verr := checkChunkFile(b); { + case verr != nil: + o.Prepared, o.Reason = "rejected", verr.Error() + case cur != nil && cur.ChunkSHA256 == hexSum: + o.Prepared, o.Assets = "unchanged", len(cur.AssetDigests) + default: + if aerr := im.assets(ctx, digests); aerr != nil { + o.Prepared, o.Reason = "rejected", aerr.Error() + break + } + key := storeKey(im.tenantID, doc.ID, "prepared/chunks-"+hexSum+".json") + if perr := im.s.Objects.Put(ctx, key, bytes.NewReader(b), int64(len(b)), "application/json"); perr != nil { + o.Prepared, o.Reason = "rejected", "could not be stored" + break + } + next.Format, next.Revision, next.Pin = "LANE_B_UNIFIED_V5", im.revision, im.pin + next.ChunkObjectKey, next.ChunkSHA256, next.ChunkBytes, next.ChunkCount = key, hexSum, int64(len(b)), count + next.AssetDigests = digests + o.Prepared, o.Assets = "imported", len(digests) + } + } + + for _, c := range im.caps.Captures { + if c.TenantDocumentID != o.ExternalID { + continue + } + m := importConsentRe.FindStringSubmatch(c.ObjectKey) + if m == nil || c.Digest != "sha256:"+m[1] { + o.Consent, o.Reason = "rejected", "capture object_key and digest do not agree" + break + } + if cur != nil && cur.ConsentSHA256 == m[1] { + o.Consent = "unchanged" + break + } + b, ferr := im.fileWithDigest(c.ObjectKey, m[1]) + var head struct { + Artifact string `json:"artifact"` + } + if ferr == nil && (json.Unmarshal(b, &head) != nil || head.Artifact != "CONSENT_BANNER_CAPTURE_V1") { + ferr = errors.New("the capture is not a CONSENT_BANNER_CAPTURE_V1") + } + if ferr != nil { + o.Consent, o.Reason = "rejected", ferr.Error() + break + } + key := storeKey(im.tenantID, doc.ID, "prepared/consent-"+m[1]+".json") + if perr := im.s.Objects.Put(ctx, key, bytes.NewReader(b), int64(len(b)), "application/json"); perr != nil { + o.Consent, o.Reason = "rejected", "could not be stored" + break + } + next.ConsentObjectKey, next.ConsentSHA256 = key, m[1] + o.Consent = "imported" + break + } + + if next.HasChunks() || next.HasConsent() { + if _, err := im.s.Store.SaveDocumentPreparation(ctx, next); err != nil { + o.Prepared, o.Consent, o.Reason = "rejected", "rejected", err.Error() + } + } +} + +// assets stores every image the chunk file refers to (taken from the bundle, +// digest-checked); one the tenant already holds is not stored again. +func (im *importer) assets(ctx context.Context, digests []string) error { + dir := filepath.Join(im.root, "figure_assets", "sources", "sha256") + for _, sum := range digests { + if _, err := im.s.Store.GetStoreAsset(ctx, im.tenantID, sum); err == nil { + continue + } + var rel, ext string + for e := range assetExtTypes { + if _, err := os.Stat(filepath.Join(dir, sum+e)); err == nil { + rel, ext = "figure_assets/sources/sha256/"+sum+e, e + break + } + } + if rel == "" { + return fmt.Errorf("image %s… is missing from the bundle", sum[:12]) + } + b, err := im.fileWithDigest(rel, sum) + if err != nil { + return err + } + key := assetKey(im.tenantID, sum, ext) + if err := im.s.Objects.Put(ctx, key, bytes.NewReader(b), int64(len(b)), assetExtTypes[ext]); err != nil { + return errors.New("an image could not be stored") + } + if _, err := im.s.Store.PutStoreAsset(ctx, store.StoreAsset{ + TenantID: im.tenantID, SHA256: sum, ObjectKey: key, ContentType: assetExtTypes[ext], SizeBytes: int64(len(b)), + }); err != nil { + return err + } + } + return nil +} + +// checkChunkFile checks the outline of a LANE_B_UNIFIED_V5 chunk file — an +// object with a "chunk_list" and a "pages" list — and returns its unit count +// and every image digest it refers to ("asset_digest", with or without the +// "sha256:" prefix), sorted and without repeats. +func checkChunkFile(b []byte) (int, []string, error) { + var v map[string]any + if err := json.Unmarshal(b, &v); err != nil || v == nil { + return 0, nil, errors.New("the chunk file is not a JSON object") + } + units, ok := v["chunk_list"].([]any) + if !ok { + return 0, nil, errors.New("the chunk file has no chunk_list") + } + if _, ok := v["pages"].([]any); !ok { + return 0, nil, errors.New("the chunk file has no pages") + } + seen := map[string]bool{} + var bad error + var walk func(x any) + walk = func(x any) { + switch t := x.(type) { + case map[string]any: + for k, val := range t { + if s, ok := val.(string); ok && k == "asset_digest" && s != "" { + d := strings.TrimPrefix(s, "sha256:") + if !hexDigest(d) { + bad = fmt.Errorf("asset_digest %q is not a SHA-256", s) + continue + } + seen[d] = true + continue + } + walk(val) + } + case []any: + for _, e := range t { + walk(e) + } + } + } + walk(v) + if bad != nil { + return 0, nil, bad + } + out := make([]string, 0, len(seen)) + for d := range seen { + out = append(out, d) + } + sort.Strings(out) + return len(units), out, nil +} + +func hexDigest(s string) bool { + if len(s) != 64 { + return false + } + _, err := hex.DecodeString(s) + return err == nil && strings.ToLower(s) == s +} diff --git a/internal/server/document_store.go b/internal/server/document_store.go new file mode 100644 index 0000000..c977de3 --- /dev/null +++ b/internal/server/document_store.go @@ -0,0 +1,426 @@ +package server + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "net/http" + "os" + "path" + "strings" + "time" + + "github.com/google/uuid" + + "git.breakpilot.com/platform/tenant-registry/internal/storage" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// Dokumentenablage (0022, workspace ticket #171): the tenant's own documents +// in three areas — legal website documents (one folder per kind), public +// product documents, internal documents (optionally of one product). The +// portal shows the original and the prepared version the Factory delivers. +// Every byte served is checked against its stored SHA-256 first: a mismatch +// is refused (fail-closed), never served. +// +// GET /v1/tenants/{id}/store list (a {sub} of tenantSubresource) +// POST /v1/tenants/{id}/store/documents upload (the portal checks the role) +// GET /v1/tenants/{id}/store/documents/{doc}/original the original, inline +// GET /v1/tenants/{id}/store/documents/{doc}/prepared the chunk file +// GET /v1/tenants/{id}/store/documents/{doc}/consent-banner the cookie-banner capture +// GET /v1/tenants/{id}/store/assets/{sha} an image of a prepared document + +// storeTypes are the originals the store takes and serves. +var storeTypes = map[string]string{ + ".pdf": "application/pdf", + ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + ".txt": "text/plain; charset=utf-8", + ".html": "text/html; charset=utf-8", +} + +// storeKey is where the store keeps a document's objects. +func storeKey(tenantID, docID, part string) string { + return "tenants/" + tenantID + "/store/" + docID + "/" + part +} + +func assetKey(tenantID, sha, ext string) string { + return "tenants/" + tenantID + "/store/assets/" + sha + ext +} + +type storeItem struct { + store.Document + Preparation *preparationSummary `json:"preparation"` +} + +type preparationSummary struct { + Format string `json:"format,omitempty"` + Revision int `json:"revision,omitempty"` + ChunkCount int `json:"chunk_count"` + HasChunks bool `json:"has_chunks"` + HasConsent bool `json:"has_consent"` + Assets int `json:"assets"` + At time.Time `json:"delivered_at"` +} + +type storeListResp struct { + Items []storeItem `json:"items"` + LegalKinds []string `json:"legal_kinds"` +} + +// listStore is GET /v1/tenants/{id}/store. +func (s *Server) listStore(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + s.writeStoreList(ctx, w, t.ID) +} + +func (s *Server) writeStoreList(ctx context.Context, w http.ResponseWriter, tenantID string) { + docs, err := s.Store.ListStoreDocuments(ctx, tenantID) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + preps, err := s.Store.ListDocumentPreparations(ctx, tenantID) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + out := storeListResp{Items: make([]storeItem, 0, len(docs)), LegalKinds: store.LegalKinds} + for _, d := range docs { + it := storeItem{Document: d} + if p, ok := preps[d.ID]; ok { + it.Preparation = &preparationSummary{ + Format: p.Format, Revision: p.Revision, ChunkCount: p.ChunkCount, + HasChunks: p.HasChunks(), HasConsent: p.HasConsent(), Assets: len(p.AssetDigests), At: p.DeliveredAt, + } + } + out.Items = append(out.Items, it) + } + writeJSON(w, http.StatusOK, out) +} + +// storeDocument loads {doc} and checks it is a store document of the tenant +// in scope. +func (s *Server) storeDocument(ctx context.Context, w http.ResponseWriter, r *http.Request) (*store.Document, bool) { + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return nil, false + } + d, err := s.Store.GetDocument(ctx, r.PathValue("doc")) + if err == nil && (d.TenantID != t.ID || d.Area == "") { + err = store.ErrNotFound + } + if err != nil { + if mapStoreError(w, err) { + return nil, false + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return nil, false + } + return d, true +} + +// uploadStoreDocument is POST /v1/tenants/{id}/store/documents: multipart +// fields "area", "legal_kind" (legal area), "product_id" (internal area, a +// product project of the tenant), "title", "process" ("on": an internal +// document goes to the Factory too), then the "file". The file is streamed to +// the bucket; the document is visible at once with its original, and legal +// and product documents wait for the Factory ("pending"). +func (s *Server) uploadStoreDocument(w http.ResponseWriter, r *http.Request) { + if !s.documentsReady(w) { + return + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + max := s.cfg().DocumentsMaxBytes + if max <= 0 { + max = 200 << 20 + } + r.Body = http.MaxBytesReader(w, r.Body, max+1<<20) + mr, err := r.MultipartReader() + if err != nil { + writeError(w, http.StatusBadRequest, "invalid_body", "expected multipart/form-data") + return + } + fields := map[string]string{} + var doc *store.Document + for { + part, perr := mr.NextPart() + if perr == io.EOF { + break + } + if perr != nil { + s.dropUpload(ctx, doc) + writeError(w, http.StatusBadRequest, "invalid_body", perr.Error()) + return + } + name := part.FormName() + if name != "file" { + b, _ := io.ReadAll(io.LimitReader(part, 1<<10)) + fields[name] = strings.TrimSpace(string(b)) + continue + } + if doc != nil { + s.dropUpload(ctx, doc) + writeError(w, http.StatusBadRequest, "invalid_body", "one file per upload") + return + } + // The fields come before the file, so the upload is refused before a + // byte is stored when they are wrong. + d, code, msg := storeUploadFields(fields) + if code != "" { + writeError(w, http.StatusBadRequest, code, msg) + return + } + filename := safeFilename(part.FileName()) + ctype, okType := storeTypes[strings.ToLower(path.Ext(filename))] + if filename == "" || !okType { + writeError(w, http.StatusUnsupportedMediaType, "unsupported_type", "allowed: pdf, docx, txt, html") + return + } + if d.ProjectIDs, code = s.storeProduct(ctx, t.ID, fields["product_id"], d.Area); code != "" { + writeError(w, http.StatusBadRequest, code, "product_id must be a product of this workspace, and only for internal documents") + return + } + d.ID, d.TenantID, d.Filename, d.ContentType = uuid.NewString(), t.ID, filename, ctype + d.ObjectKey = storeKey(t.ID, d.ID, "original/"+filename) + hash := sha256.New() + cr := &countingReader{r: part, hash: hash} + if err := s.Objects.Put(ctx, d.ObjectKey, cr, -1, ctype); err != nil { + if isTooLarge(err) { + writeError(w, http.StatusRequestEntityTooLarge, "too_large", "the file is larger than the upload limit") + return + } + writeError(w, http.StatusBadGateway, "storage_failed", "the file could not be stored") + return + } + if cr.n > max { + _ = s.Objects.Delete(context.WithoutCancel(ctx), d.ObjectKey) + writeError(w, http.StatusRequestEntityTooLarge, "too_large", "the file is larger than the upload limit") + return + } + d.SizeBytes, d.SHA256 = cr.n, hex.EncodeToString(hash.Sum(nil)) + if d.Title == "" { + d.Title = strings.TrimSuffix(filename, path.Ext(filename)) + } + doc = &d + } + if doc == nil { + writeError(w, http.StatusBadRequest, "missing_file", "a file part named \"file\" is required") + return + } + doc.UploadedBy = s.projectActor(r) + created, err := s.Store.CreateDocument(ctx, *doc) + if err != nil { + s.dropUpload(ctx, doc) + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: t.ID, Action: "store.uploaded", TargetID: created.ID, TargetType: "document", TargetName: created.Title, + ActorType: s.projectActorType(r), ActorName: created.UploadedBy, + Metadata: map[string]interface{}{"area": created.Area, "legal_kind": created.LegalKind, "filename": created.Filename, + "size_bytes": created.SizeBytes, "sha256": created.SHA256, "processing": created.ProcessingStatus}, + }) + writeJSON(w, http.StatusCreated, created) +} + +// storeUploadFields turns the form fields into a document; a non-empty code +// says what is wrong. +func storeUploadFields(f map[string]string) (store.Document, string, string) { + d := store.Document{ + Area: f["area"], LegalKind: f["legal_kind"], Title: strings.Join(strings.Fields(f["title"]), " "), + Status: store.DocumentPublished, OwnDocument: true, + } + if !store.ValidArea(d.Area) { + return d, "invalid_area", "area must be legal_web, product_public or internal" + } + if d.Area == store.AreaLegalWeb { + if !store.ValidLegalKind(d.LegalKind) { + return d, "invalid_legal_kind", "legal_kind must be one of " + strings.Join(store.LegalKinds, ", ") + } + } else if d.LegalKind != "" { + return d, "invalid_legal_kind", "legal_kind only for legal website documents" + } + if len([]rune(d.Title)) > 200 { + return d, "invalid_title", "title ≤ 200 characters" + } + // Legal and product documents are public and always prepared; an internal + // one only when the uploader asks for it (it leaves for the Factory). + d.ProcessingStatus = store.ProcessingPending + if d.Area == store.AreaInternal && !isOn(f["process"]) { + d.ProcessingStatus = store.ProcessingNone + } + return d, "", "" +} + +func isOn(v string) bool { + v = strings.ToLower(v) + return v == "on" || v == "true" || v == "1" +} + +// storeProduct checks the optional product of an internal document: one +// product project of the tenant. +func (s *Server) storeProduct(ctx context.Context, tenantID, productID, area string) ([]string, string) { + if productID == "" { + return nil, "" + } + if area != store.AreaInternal { + return nil, "invalid_product" + } + p, err := s.Store.GetProject(ctx, productID) + if err != nil || p.TenantID != tenantID || p.Kind != store.ProjectKindProduct { + return nil, "invalid_product" + } + return []string{p.ID}, "" +} + +func isTooLarge(err error) bool { + var mbe *http.MaxBytesError + return errors.As(err, &mbe) +} + +// storeOriginal is GET …/store/documents/{doc}/original: the file inline, +// after its digest matched. +func (s *Server) storeOriginal(w http.ResponseWriter, r *http.Request) { + if !s.documentsReady(w) { + return + } + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute) + defer cancel() + d, ok := s.storeDocument(ctx, w, r) + if !ok { + return + } + s.serveVerified(ctx, w, d.ObjectKey, d.SHA256, d.ContentType, d.Filename) +} + +// storePrepared is GET …/store/documents/{doc}/prepared: the chunk file. +func (s *Server) storePrepared(w http.ResponseWriter, r *http.Request) { + s.servePreparationPart(w, r, false) +} + +// storeConsentBanner is GET …/store/documents/{doc}/consent-banner. +func (s *Server) storeConsentBanner(w http.ResponseWriter, r *http.Request) { + s.servePreparationPart(w, r, true) +} + +func (s *Server) servePreparationPart(w http.ResponseWriter, r *http.Request, consent bool) { + if !s.documentsReady(w) { + return + } + ctx, cancel := context.WithTimeout(r.Context(), time.Minute) + defer cancel() + d, ok := s.storeDocument(ctx, w, r) + if !ok { + return + } + p, err := s.Store.GetDocumentPreparation(ctx, d.ID) + if err != nil && !errors.Is(err, store.ErrNotFound) { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + key, sum, name := "", "", "chunks.json" + if p != nil && !consent { + key, sum = p.ChunkObjectKey, p.ChunkSHA256 + } + if p != nil && consent { + key, sum, name = p.ConsentObjectKey, p.ConsentSHA256, "consent-banner.json" + } + if sum == "" { + writeError(w, http.StatusNotFound, "not_prepared", "nothing delivered for this document yet") + return + } + s.serveVerified(ctx, w, key, sum, "application/json", name) +} + +// storeAsset is GET /v1/tenants/{id}/store/assets/{sha}: an image the tenant +// holds. +func (s *Server) storeAsset(w http.ResponseWriter, r *http.Request) { + if !s.documentsReady(w) { + return + } + ctx, cancel := context.WithTimeout(r.Context(), time.Minute) + defer cancel() + t, ok := s.tenantInScope(ctx, w, r) + if !ok { + return + } + a, err := s.Store.GetStoreAsset(ctx, t.ID, strings.ToLower(r.PathValue("sha"))) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + w.Header().Set("Cache-Control", "private, max-age=86400, immutable") + s.serveVerified(ctx, w, a.ObjectKey, a.SHA256, a.ContentType, a.SHA256) +} + +// serveVerified reads the object into a temporary file while hashing it and +// serves it only when the digest matches (502 digest_mismatch otherwise). +// Nothing reaches the client before the check. +func (s *Server) serveVerified(ctx context.Context, w http.ResponseWriter, key, sum, ctype, filename string) { + rc, err := s.Objects.Get(ctx, key) + if err != nil { + if errors.Is(err, storage.ErrObjectNotFound) { + writeError(w, http.StatusNotFound, "object_missing", "the stored file is missing") + return + } + writeError(w, http.StatusBadGateway, "storage_failed", "the file could not be read") + return + } + defer func() { _ = rc.Close() }() + tmp, err := os.CreateTemp("", "store-*") + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", "no temporary space") + return + } + defer func() { _ = tmp.Close(); _ = os.Remove(tmp.Name()) }() + h := sha256.New() + n, err := io.Copy(io.MultiWriter(tmp, h), rc) + if err != nil { + writeError(w, http.StatusBadGateway, "storage_failed", "the file could not be read") + return + } + if hex.EncodeToString(h.Sum(nil)) != sum { + s.Log.Error("store: digest mismatch", "key", key) + writeError(w, http.StatusBadGateway, "digest_mismatch", "the stored file does not match its digest; it is not served") + return + } + if _, err := tmp.Seek(0, io.SeekStart); err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + h2 := w.Header() + h2.Set("Content-Type", ctype) + h2.Set("Content-Length", fmt.Sprint(n)) + h2.Set("X-Content-Type-Options", "nosniff") + h2.Set("Content-Disposition", inlineDisposition(filename)) + h2.Set("X-Content-SHA256", sum) + if strings.HasPrefix(ctype, "text/html") { + // An HTML original is shown, never run. + h2.Set("Content-Security-Policy", "sandbox; default-src 'none'; img-src data:; style-src 'unsafe-inline'") + } + w.WriteHeader(http.StatusOK) + _, _ = io.Copy(w, tmp) +} + +func inlineDisposition(filename string) string { + return "inline" + strings.TrimPrefix(storage.ContentDisposition(filename), "attachment") +} diff --git a/internal/server/document_store_db_test.go b/internal/server/document_store_db_test.go new file mode 100644 index 0000000..6af311b --- /dev/null +++ b/internal/server/document_store_db_test.go @@ -0,0 +1,134 @@ +package server_test + +import ( + "context" + "errors" + "strings" + "testing" + + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// The document store contract on both stores (synthetic data). +func TestDocumentStoreContract(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + ctx := context.Background() + tid := h.tenant.ID + mk := func(id, title, area, kind, ext string) (*store.Document, error) { + return h.store.CreateDocument(ctx, store.Document{ + ID: id, TenantID: tid, Title: title, ObjectKey: "k/" + id, Status: store.DocumentPublished, + Area: area, LegalKind: kind, ExternalID: ext, ProcessingStatus: store.ProcessingPending, + }) + } + ids := []string{ + "10000000-0000-0000-0000-000000000001", "10000000-0000-0000-0000-000000000002", + "10000000-0000-0000-0000-000000000003", "10000000-0000-0000-0000-000000000004", + "10000000-0000-0000-0000-000000000005", + } + if _, err := mk(ids[0], "Datenblatt", store.AreaProductPublic, "", "wsdoc-a"); err != nil { + t.Fatal(err) + } + if _, err := mk(ids[1], "Widerruf", store.AreaLegalWeb, "widerruf", "wsdoc-b"); err != nil { + t.Fatal(err) + } + if _, err := mk(ids[2], "Impressum", store.AreaLegalWeb, "impressum", ""); err != nil { + t.Fatal(err) + } + if _, err := mk(ids[3], "Richtlinie", store.AreaInternal, "", ""); err != nil { + t.Fatal(err) + } + // Unterlagen (no area) stay apart. + if _, err := h.store.CreateDocument(ctx, store.Document{ID: ids[4], TenantID: tid, Title: "Report", ObjectKey: "k/r", Status: store.DocumentPublished}); err != nil { + t.Fatal(err) + } + for name, bad := range map[string]store.Document{ + "legal without folder": {Area: store.AreaLegalWeb}, + "folder outside legal": {Area: store.AreaInternal, LegalKind: "agb"}, + "unknown folder": {Area: store.AreaLegalWeb, LegalKind: "faq"}, + "unknown area": {Area: "secret"}, + "external id twice": {Area: store.AreaInternal, ExternalID: "wsdoc-a"}, + } { + bad.ID, bad.TenantID, bad.Title, bad.ObjectKey = "20000000-0000-0000-0000-00000000000"+string(rune('1'+len(name)%9)), tid, "x", "k/bad-"+name + if _, err := h.store.CreateDocument(ctx, bad); err == nil { + t.Errorf("%s: accepted", name) + } + } + + docs, err := h.store.ListStoreDocuments(ctx, tid) + if err != nil { + t.Fatal(err) + } + var order []string + for _, d := range docs { + order = append(order, d.Title) + } + if strings.Join(order, ",") != "Impressum,Widerruf,Datenblatt,Richtlinie" { + t.Errorf("order: %v", order) + } + if u, _ := h.store.ListDocuments(ctx, tid, false); len(u) != 1 || u[0].Title != "Report" { + t.Errorf("Unterlagen: %+v", u) + } + if d, err := h.store.GetDocumentByExternalID(ctx, tid, "wsdoc-b"); err != nil || d.ID != ids[1] { + t.Errorf("by external id: %v %v", d, err) + } + if _, err := h.store.GetDocumentByExternalID(ctx, tid, ""); !errors.Is(err, store.ErrNotFound) { + t.Errorf("empty external id: %v", err) + } + + // A chunk part, then a consent part: the second keeps the first. + a, b := strings.Repeat("a", 64), strings.Repeat("b", 64) + p, err := h.store.SaveDocumentPreparation(ctx, store.Preparation{ + DocumentID: ids[0], Format: "LANE_B_UNIFIED_V5", Revision: 8, ChunkObjectKey: "k/c", ChunkSHA256: a, ChunkCount: 12, AssetDigests: []string{b}, + }) + if err != nil || !p.HasChunks() || p.ChunkCount != 12 { + t.Fatalf("chunks: %+v %v", p, err) + } + p, err = h.store.SaveDocumentPreparation(ctx, store.Preparation{DocumentID: ids[0], ConsentObjectKey: "k/x", ConsentSHA256: b}) + if err != nil || p.ChunkSHA256 != a || p.ConsentSHA256 != b || p.Revision != 8 || len(p.AssetDigests) != 1 { + t.Fatalf("merge: %+v %v", p, err) + } + if d, _ := h.store.GetDocument(ctx, ids[0]); d.ProcessingStatus != store.ProcessingReady { + t.Errorf("status after chunks: %q", d.ProcessingStatus) + } + if _, err := h.store.SaveDocumentPreparation(ctx, store.Preparation{DocumentID: ids[1]}); !errors.Is(err, store.ErrInvalidInput) { + t.Errorf("empty preparation: %v", err) + } + if m, _ := h.store.ListDocumentPreparations(ctx, tid); len(m) != 1 || m[ids[0]].ChunkCount != 12 { + t.Errorf("list preparations: %+v", m) + } + if _, err := h.store.GetDocumentPreparation(ctx, ids[1]); !errors.Is(err, store.ErrNotFound) { + t.Errorf("no preparation: %v", err) + } + if d, err := h.store.SetDocumentProcessing(ctx, ids[1], store.ProcessingFailed, "unreadable scan"); err != nil || d.ProcessingError != "unreadable scan" { + t.Errorf("failed: %+v %v", d, err) + } + if _, err := h.store.SetDocumentProcessing(ctx, ids[1], "done", ""); err == nil { + t.Error("unknown status accepted") + } + + // Images per tenant, once. + for i := 0; i < 2; i++ { + if _, err := h.store.PutStoreAsset(ctx, store.StoreAsset{TenantID: tid, SHA256: b, ObjectKey: "k/a", ContentType: "image/png", SizeBytes: 3}); err != nil { + t.Fatal(err) + } + } + if got, err := h.store.GetStoreAsset(ctx, tid, b); err != nil || got.ContentType != "image/png" { + t.Errorf("asset: %+v %v", got, err) + } + other, _ := h.store.CreateTenant(ctx, store.TenantCreate{Slug: "andere", Name: "Andere GmbH"}) + if _, err := h.store.GetStoreAsset(ctx, other.ID, b); !errors.Is(err, store.ErrNotFound) { + t.Errorf("another tenant's asset: %v", err) + } + if _, err := h.store.PutStoreAsset(ctx, store.StoreAsset{TenantID: tid, SHA256: "nope", ObjectKey: "k"}); !errors.Is(err, store.ErrInvalidInput) { + t.Errorf("bad digest: %v", err) + } + + // Deleting a document takes its preparation along. + if err := h.store.DeleteDocument(ctx, ids[0]); err != nil { + t.Fatal(err) + } + if _, err := h.store.GetDocumentPreparation(ctx, ids[0]); !errors.Is(err, store.ErrNotFound) { + t.Errorf("preparation after delete: %v", err) + } + }) +} diff --git a/internal/server/document_store_test.go b/internal/server/document_store_test.go new file mode 100644 index 0000000..dfabed6 --- /dev/null +++ b/internal/server/document_store_test.go @@ -0,0 +1,408 @@ +package server + +import ( + "archive/tar" + "bytes" + "compress/gzip" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "mime/multipart" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/config" + "git.breakpilot.com/platform/tenant-registry/internal/storage" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// All data here is synthetic: "Muster Modellbau GmbH", product "Lok 100". + +type storeFixture struct { + *teamFixture + objects *storage.Memory +} + +func newStoreFixture(t *testing.T, p *authn.Principal, rules ...string) *storeFixture { + t.Helper() + f := newTeamFixture(t, p, rules...) + objs := storage.NewMemory() + f.s.Objects = objs + return &storeFixture{teamFixture: f, objects: objs} +} + +// raw sends body with the given content type and headers. +func (f *storeFixture) raw(t *testing.T, method, path, ctype string, body []byte, hdr map[string]string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(method, path, bytes.NewReader(body)) + if ctype != "" { + req.Header.Set("Content-Type", ctype) + } + for k, v := range hdr { + req.Header.Set(k, v) + } + rr := httptest.NewRecorder() + f.h.ServeHTTP(rr, req) + return rr +} + +func (f *storeFixture) upload(t *testing.T, fields map[string]string, filename string, content []byte) *httptest.ResponseRecorder { + t.Helper() + var buf bytes.Buffer + mw := multipart.NewWriter(&buf) + for _, k := range []string{"area", "legal_kind", "product_id", "title", "process"} { + if v, ok := fields[k]; ok { + _ = mw.WriteField(k, v) + } + } + fw, _ := mw.CreateFormFile("file", filename) + _, _ = fw.Write(content) + _ = mw.Close() + return f.raw(t, "POST", "/v1/tenants/"+f.tenant.ID+"/store/documents", mw.FormDataContentType(), buf.Bytes(), + map[string]string{"X-Portal-User-Email": "cxo@muster.test"}) +} + +func hexsum(b []byte) string { s := sha256.Sum256(b); return hex.EncodeToString(s[:]) } + +func TestStoreUploadRules(t *testing.T) { + f := newStoreFixture(t, portal, "portal-svc:*") + pdf := []byte("%PDF-1.7 synthetic impressum") + ctx := context.Background() + product, _ := f.s.Store.CreateProject(ctx, store.Project{TenantID: f.tenant.ID, Name: "Lok 100", Kind: store.ProjectKindProduct, Level: store.ProjectLevelProduct}) + topic, _ := f.s.Store.CreateProject(ctx, store.Project{TenantID: f.tenant.ID, Name: "CRA", Kind: store.ProjectKindTopic}) + + for name, c := range map[string]struct { + fields map[string]string + file string + code int + err string + }{ + "unknown area": {map[string]string{"area": "secret"}, "a.pdf", 400, "invalid_area"}, + "legal without folder": {map[string]string{"area": "legal_web"}, "a.pdf", 400, "invalid_legal_kind"}, + "legal unknown folder": {map[string]string{"area": "legal_web", "legal_kind": "faq"}, "a.pdf", 400, "invalid_legal_kind"}, + "folder outside legal": {map[string]string{"area": "product_public", "legal_kind": "agb"}, "a.pdf", 400, "invalid_legal_kind"}, + "product on public doc": {map[string]string{"area": "product_public", "product_id": product.ID}, "a.pdf", 400, "invalid_product"}, + "topic as product": {map[string]string{"area": "internal", "product_id": topic.ID}, "a.pdf", 400, "invalid_product"}, + "unsupported type": {map[string]string{"area": "internal"}, "a.exe", 415, "unsupported_type"}, + "title too long": {map[string]string{"area": "internal", "title": strings.Repeat("t", 201)}, "a.pdf", 400, "invalid_title"}, + } { + rr := f.upload(t, c.fields, c.file, pdf) + if rr.Code != c.code || !strings.Contains(rr.Body.String(), c.err) { + t.Errorf("%s: %d %s", name, rr.Code, rr.Body.String()) + } + } + if len(f.objects.Objects) != 0 { + t.Fatalf("refused uploads stored %d objects", len(f.objects.Objects)) + } + + legal := f.upload(t, map[string]string{"area": "legal_web", "legal_kind": "impressum"}, "Impressum.pdf", pdf) + internalPlain := f.upload(t, map[string]string{"area": "internal", "title": " Risikobeurteilung Lok 100 ", "product_id": product.ID}, "rb.docx", []byte("PK synthetic")) + internalSent := f.upload(t, map[string]string{"area": "internal", "process": "on"}, "Richtlinie.pdf", pdf) + public := f.upload(t, map[string]string{"area": "product_public"}, "Datenblatt.pdf", pdf) + var d1, d2, d3, d4 store.Document + for i, rr := range []*httptest.ResponseRecorder{legal, internalPlain, internalSent, public} { + if rr.Code != 201 { + t.Fatalf("upload %d: %d %s", i, rr.Code, rr.Body.String()) + } + } + _ = json.Unmarshal(legal.Body.Bytes(), &d1) + _ = json.Unmarshal(internalPlain.Body.Bytes(), &d2) + _ = json.Unmarshal(internalSent.Body.Bytes(), &d3) + _ = json.Unmarshal(public.Body.Bytes(), &d4) + if d1.Area != "legal_web" || d1.LegalKind != "impressum" || d1.ProcessingStatus != "pending" || d1.Status != "published" || d1.SHA256 != hexsum(pdf) || d1.Title != "Impressum" { + t.Errorf("legal: %+v", d1) + } + if d2.ProcessingStatus != "none" || d2.Title != "Risikobeurteilung Lok 100" || len(d2.ProjectIDs) != 1 || d2.ProjectIDs[0] != product.ID { + t.Errorf("internal without processing: %+v", d2) + } + if d3.ProcessingStatus != "pending" || d4.ProcessingStatus != "pending" { + t.Errorf("processing: internal sent %q, public %q", d3.ProcessingStatus, d4.ProcessingStatus) + } + + // The store lists them by area and folder; "Unterlagen" does not. + code, _, raw := f.call(t, "GET", "/v1/tenants/"+f.tenant.ID+"/store", "", nil) + var list storeListResp + _ = json.Unmarshal([]byte(raw), &list) + if code != 200 || len(list.Items) != 4 || list.Items[0].Area != "legal_web" || list.Items[1].Area != "product_public" || len(list.LegalKinds) != 8 { + t.Fatalf("store list: %d %s", code, raw) + } + docs, _ := f.s.Store.ListDocuments(ctx, f.tenant.ID, false) + if len(docs) != 0 { + t.Errorf("store documents appear under Unterlagen: %d", len(docs)) + } + if ev := f.audit(t, "store.uploaded"); len(ev) != 4 || ev[0].Metadata["area"] == nil { + t.Errorf("audit: %+v", ev) + } +} + +func TestStoreServesOnlyVerifiedBytes(t *testing.T) { + f := newStoreFixture(t, portal, "portal-svc:*") + pdf := []byte("%PDF-1.7 synthetic datenblatt") + rr := f.upload(t, map[string]string{"area": "product_public"}, "Datenblatt Lok 100.pdf", pdf) + var d store.Document + _ = json.Unmarshal(rr.Body.Bytes(), &d) + path := "/v1/tenants/" + f.tenant.ID + "/store/documents/" + d.ID + + got := f.raw(t, "GET", path+"/original", "", nil, nil) + if got.Code != 200 || !bytes.Equal(got.Body.Bytes(), pdf) || got.Header().Get("Content-Type") != "application/pdf" || + !strings.HasPrefix(got.Header().Get("Content-Disposition"), "inline;") || got.Header().Get("X-Content-SHA256") != d.SHA256 { + t.Fatalf("original: %d %v", got.Code, got.Header()) + } + if rr := f.raw(t, "GET", path+"/prepared", "", nil, nil); rr.Code != 404 || !strings.Contains(rr.Body.String(), "not_prepared") { + t.Errorf("prepared before delivery: %d %s", rr.Code, rr.Body.String()) + } + + // A changed object is never served. + for k := range f.objects.Objects { + f.objects.Objects[k] = []byte("%PDF-1.7 tampered") + } + if rr := f.raw(t, "GET", path+"/original", "", nil, nil); rr.Code != 502 || !strings.Contains(rr.Body.String(), "digest_mismatch") || strings.Contains(rr.Body.String(), "tampered") { + t.Errorf("tampered: %d %s", rr.Code, rr.Body.String()) + } + for k := range f.objects.Objects { + delete(f.objects.Objects, k) + } + if rr := f.raw(t, "GET", path+"/original", "", nil, nil); rr.Code != 404 { + t.Errorf("missing object: %d", rr.Code) + } +} + +func TestStoreIsTenantScoped(t *testing.T) { + f := newStoreFixture(t, portal, "portal-svc:*") + rr := f.upload(t, map[string]string{"area": "internal"}, "Richtlinie.pdf", []byte("%PDF synthetic")) + var d store.Document + _ = json.Unmarshal(rr.Body.Bytes(), &d) + + // A signed-in user of another workspace sees nothing of it. + other := &authn.Principal{Subject: "u-x", ClientID: "portal", TenantID: "00000000-0000-0000-0000-00000000beef"} + g := newStoreFixture(t, other) + g.s.Store, g.s.Objects = f.s.Store, f.objects + base := "/v1/tenants/" + f.tenant.ID + for _, p := range []string{base + "/store", base + "/store/documents/" + d.ID + "/original", base + "/store/assets/" + strings.Repeat("a", 64)} { + if rr := g.raw(t, "GET", p, "", nil, nil); rr.Code != 404 { + t.Errorf("%s: %d", p, rr.Code) + } + } + // A BreakPilot delivery is not reachable through the store routes. + ctx := context.Background() + _, _ = f.s.Store.CreateDocument(ctx, store.Document{ID: "11111111-1111-1111-1111-111111111111", TenantID: f.tenant.ID, Title: "Report", ObjectKey: "k", Status: store.DocumentPublished}) + if rr := f.raw(t, "GET", base+"/store/documents/11111111-1111-1111-1111-111111111111/original", "", nil, nil); rr.Code != 404 { + t.Errorf("Unterlagen via store: %d", rr.Code) + } +} + +// bundle builds a synthetic store bundle (.tar.gz) in the Factory layout. +type bundle struct { + files map[string][]byte + index []map[string]any + caps []map[string]any +} + +func newBundle() *bundle { return &bundle{files: map[string][]byte{}} } + +func (b *bundle) doc(id, title, class, kind string, original []byte, ext string) string { + sum := hexsum(original) + b.files["objects/"+sum+ext] = original + d := map[string]any{"tenant_document_id": id, "content_digest": "sha256:" + sum, "title": title, "object_key": "objects/" + sum + ext} + if class != "" { + d["document_class"], d["legal_kind"] = class, kind + } + b.index = append(b.index, d) + return sum +} + +func (b *bundle) chunks(id string, assets ...[]byte) { + pages := []any{} + units := []any{map[string]any{"chunk_id": id + "#c00001", "unit_type": "TEXT_SECTION", "text": "Synthetischer Text"}} + for i, a := range assets { + sum := hexsum(a) + b.files["figure_assets/sources/sha256/"+sum+".png"] = a + if i == 0 { + pages = append(pages, map[string]any{"page": 1, "page_image": map[string]any{"asset_digest": sum, "asset_status": "PNG_PAGE_RENDER_BOUND"}}) + } else { + units = append(units, map[string]any{"chunk_id": id + "#f00001", "unit_type": "FIGURE", "figure": map[string]any{"asset_digest": "sha256:" + sum}}) + } + } + body, _ := json.Marshal(map[string]any{"status": "UNIFIED_V5", "text_source": "PDF_TEXT_LAYER", "chunk_list": units, "pages": pages}) + b.files["chunks/"+id+".json"] = body +} + +func (b *bundle) capture(id string) { + body := []byte(`{"artifact":"CONSENT_BANNER_CAPTURE_V1","cmp":"synthetic","first_layer":{"title":"Cookies"}}`) + sum := hexsum(body) + b.files["presentation/consent_banner/"+sum+".json"] = body + b.caps = append(b.caps, map[string]any{"tenant_document_id": id, "object_key": "presentation/consent_banner/" + sum + ".json", "digest": "sha256:" + sum}) +} + +func (b *bundle) tgz(t *testing.T, prefix string) []byte { + t.Helper() + idx, _ := json.Marshal(map[string]any{"artifact": "LANE_B_INDEX_V1", "documents": b.index}) + b.files["LANE_B_INDEX_V1.json"] = idx + if len(b.caps) > 0 { + c, _ := json.Marshal(map[string]any{"artifact": "CONSENT_BANNER_CAPTURES_V1", "captures": b.caps}) + b.files["presentation/CONSENT_BANNER_CAPTURES_V1.json"] = c + } + b.files["LANE_B_UNIFIED_V5_RETURN_MANIFEST_V1.json"] = []byte(`{"revision":8}`) + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + for name, body := range b.files { + _ = tw.WriteHeader(&tar.Header{Name: prefix + name, Mode: 0o600, Size: int64(len(body)), Typeflag: tar.TypeReg}) + _, _ = tw.Write(body) + } + _ = tw.Close() + _ = gz.Close() + return buf.Bytes() +} + +var staff = map[string]string{"X-Staff-Subject": "staff-1", "X-Staff-Email": "staff@breakpilot.test"} + +func (f *storeFixture) importBundle(t *testing.T, body []byte, hdr map[string]string) (int, importResp, string) { + t.Helper() + rr := f.raw(t, "POST", "/v1/admin/tenants/"+f.tenant.ID+"/store/import", "application/gzip", body, hdr) + var out importResp + _ = json.Unmarshal(rr.Body.Bytes(), &out) + return rr.Code, out, rr.Body.String() +} + +func TestStoreImport(t *testing.T) { + f := newStoreFixture(t, portal, "portal-svc:*") + b := newBundle() + b.doc("wsdoc-impressum", "Impressum", "LEGAL", "impressum", []byte("Muster Modellbau GmbH\nMusterstraße 1"), ".txt") + b.doc("wsdoc-cookie", "Cookie-Banner", "LEGAL", "cookie", []byte("Wir verwenden Cookies."), ".txt") + b.doc("wsdoc-lok100", "Lok 100 Datenblatt", "", "", []byte("%PDF-1.7 synthetic lok"), ".pdf") + b.doc("wsdoc-faq", "FAQ", "LEGAL", "faq", []byte("unknown folder"), ".txt") + b.doc("wsdoc-noasset", "Lok 200 Datenblatt", "", "", []byte("%PDF-1.7 synthetic lok 200"), ".pdf") + b.chunks("wsdoc-impressum") + b.chunks("wsdoc-lok100", []byte("PNG page 1"), []byte("PNG figure 1")) + b.chunks("wsdoc-noasset", []byte("PNG page of lok 200")) + b.capture("wsdoc-cookie") + // The image of Lok 200 goes missing; a bogus original is listed but absent. + for k, v := range b.files { + if string(v) == "PNG page of lok 200" { + delete(b.files, k) + } + } + b.index = append(b.index, map[string]any{"tenant_document_id": "wsdoc-ghost", "content_digest": "sha256:" + strings.Repeat("b", 64), "title": "Ghost", "object_key": "objects/" + strings.Repeat("b", 64) + ".pdf"}) + body := b.tgz(t, "bundle/") // wrapped in one directory, as `tar czf bundle.tgz bundle/` makes it + + if code, _, _ := f.importBundle(t, body, nil); code != http.StatusForbidden { + t.Fatalf("import without staff: %d", code) + } + code, out, raw := f.importBundle(t, body, staff) + if code != 200 || out.Revision != 8 || len(out.Pin) != 64 { + t.Fatalf("import: %d %s", code, raw) + } + byID := map[string]ImportOutcome{} + for _, o := range out.Documents { + byID[o.ExternalID] = o + } + check := func(id, original, prepared, consent string) { + t.Helper() + o := byID[id] + if o.Original != original || o.Prepared != prepared || o.Consent != consent { + t.Errorf("%s: %+v", id, o) + } + } + check("wsdoc-impressum", "imported", "imported", "absent") + check("wsdoc-cookie", "imported", "absent", "imported") + check("wsdoc-lok100", "imported", "imported", "absent") + check("wsdoc-faq", "rejected", "absent", "absent") + check("wsdoc-noasset", "imported", "rejected", "absent") + check("wsdoc-ghost", "rejected", "absent", "absent") + if byID["wsdoc-lok100"].Assets != 2 || byID["wsdoc-lok100"].Area != "product_public" || byID["wsdoc-cookie"].LegalKind != "cookie" { + t.Errorf("lok100 / cookie: %+v %+v", byID["wsdoc-lok100"], byID["wsdoc-cookie"]) + } + if strings.Contains(raw, "Musterstraße") || strings.Contains(raw, "Synthetischer Text") { + t.Error("the import answer carries document content") + } + + // What was imported is served, checked. + base := "/v1/tenants/" + f.tenant.ID + "/store" + lok := byID["wsdoc-lok100"].DocumentID + if rr := f.raw(t, "GET", base+"/documents/"+lok+"/prepared", "", nil, nil); rr.Code != 200 || !strings.Contains(rr.Body.String(), "UNIFIED_V5") { + t.Errorf("prepared: %d", rr.Code) + } + if rr := f.raw(t, "GET", base+"/assets/"+hexsum([]byte("PNG figure 1")), "", nil, nil); rr.Code != 200 || rr.Body.String() != "PNG figure 1" || rr.Header().Get("Content-Type") != "image/png" { + t.Errorf("asset: %d %v", rr.Code, rr.Header()) + } + cookie := byID["wsdoc-cookie"].DocumentID + if rr := f.raw(t, "GET", base+"/documents/"+cookie+"/consent-banner", "", nil, nil); rr.Code != 200 || !strings.Contains(rr.Body.String(), "CONSENT_BANNER_CAPTURE_V1") { + t.Errorf("consent: %d", rr.Code) + } + if rr := f.raw(t, "GET", base+"/documents/"+byID["wsdoc-impressum"].DocumentID+"/original", "", nil, nil); rr.Code != 200 || !strings.HasPrefix(rr.Header().Get("Content-Type"), "text/plain") { + t.Errorf("text original: %d", rr.Code) + } + ctx := context.Background() + d, _ := f.s.Store.GetDocument(ctx, lok) + noasset, _ := f.s.Store.GetDocument(ctx, byID["wsdoc-noasset"].DocumentID) + if d.ProcessingStatus != "ready" || noasset.ProcessingStatus != "pending" || d.ExternalID != "wsdoc-lok100" || d.UploadedBy != "staff@breakpilot.test" { + t.Errorf("status: lok100 %+v, noasset %q", d, noasset.ProcessingStatus) + } + + // Again: nothing new, nothing duplicated. + _, again, _ := f.importBundle(t, body, staff) + for _, o := range again.Documents { + if o.Original == "imported" || o.Prepared == "imported" || o.Consent == "imported" { + t.Errorf("rerun imported again: %+v", o) + } + } + if docs, _ := f.s.Store.ListStoreDocuments(ctx, f.tenant.ID); len(docs) != 4 { + t.Errorf("documents after rerun: %d", len(docs)) + } + if ev := f.audit(t, "store.imported"); len(ev) != 2 || ev[0].ActorType != "staff" { + t.Errorf("audit: %+v", ev) + } +} + +func TestStoreImportRefusesUnsafeBundles(t *testing.T) { + f := newStoreFixture(t, portal, "portal-svc:*") + mk := func(entries ...*tar.Header) []byte { + var buf bytes.Buffer + gz := gzip.NewWriter(&buf) + tw := tar.NewWriter(gz) + for _, h := range entries { + _ = tw.WriteHeader(h) + if h.Typeflag == tar.TypeReg { + _, _ = tw.Write(make([]byte, h.Size)) + } + } + _ = tw.Close() + _ = gz.Close() + return buf.Bytes() + } + for name, body := range map[string][]byte{ + "not gzip": []byte("plain text"), + "dotdot": mk(&tar.Header{Name: "../evil.json", Size: 1, Mode: 0o600, Typeflag: tar.TypeReg}), + "absolute": mk(&tar.Header{Name: "/etc/evil", Size: 1, Mode: 0o600, Typeflag: tar.TypeReg}), + "symlink": mk(&tar.Header{Name: "objects/link", Linkname: "/etc/passwd", Typeflag: tar.TypeSymlink}), + "no index": mk(&tar.Header{Name: "objects/x.pdf", Size: 3, Mode: 0o600, Typeflag: tar.TypeReg}), + } { + if code, _, raw := f.importBundle(t, body, staff); code != 400 || !strings.Contains(raw, "invalid_bundle") { + t.Errorf("%s: %d %s", name, code, raw) + } + } + f.s.Cfg = &config.Config{StoreImportMaxBytes: 64} + big := newBundle() + big.doc("wsdoc-big", "Big", "", "", bytes.Repeat([]byte("x"), 4096), ".txt") + if code, _, raw := f.importBundle(t, big.tgz(t, ""), staff); code != http.StatusRequestEntityTooLarge { + t.Errorf("too large: %d %s", code, raw) + } +} + +func TestCheckChunkFile(t *testing.T) { + a, b := strings.Repeat("a", 64), strings.Repeat("b", 64) + n, d, err := checkChunkFile([]byte(`{"chunk_list":[{"figure":{"asset_digest":"sha256:` + a + `"}},{}],"pages":[{"page_image":{"asset_digest":"` + b + `"}},{"page_image":{"asset_digest":"` + a + `"}}]}`)) + if err != nil || n != 2 || len(d) != 2 || d[0] != a || d[1] != b { + t.Fatalf("%d %v %v", n, d, err) + } + for _, bad := range []string{`[]`, `{"pages":[]}`, `{"chunk_list":[]}`, `{"chunk_list":[],"pages":[{"page_image":{"asset_digest":"xyz"}}]}`} { + if _, _, err := checkChunkFile([]byte(bad)); err == nil { + t.Errorf("accepted %s", bad) + } + } +} diff --git a/internal/server/documents.go b/internal/server/documents.go index 7af64da..addb1d0 100644 --- a/internal/server/documents.go +++ b/internal/server/documents.go @@ -372,6 +372,15 @@ func (s *Server) adminDeleteDocument(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadGateway, "storage_failed", "the file could not be deleted") return } + // A store document's prepared version goes with it; its images stay, they + // are content-addressed per tenant and may serve other documents. + if p, err := s.Store.GetDocumentPreparation(ctx, d.ID); err == nil { + for _, key := range []string{p.ChunkObjectKey, p.ConsentObjectKey} { + if key != "" { + _ = s.Objects.Delete(ctx, key) + } + } + } if err := s.Store.DeleteDocument(ctx, d.ID); err != nil && !errors.Is(err, store.ErrNotFound) { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return diff --git a/internal/server/members.go b/internal/server/members.go index 29e698c..82dd4e0 100644 --- a/internal/server/members.go +++ b/internal/server/members.go @@ -86,6 +86,8 @@ func (s *Server) tenantSubresource(w http.ResponseWriter, r *http.Request) { s.listTenantManagedServices(w, r) case "company-profile": s.getCompanyProfile(w, r) + case "store": + s.listStore(w, r) default: writeError(w, http.StatusNotFound, "not_found", "no such tenant sub-resource") } diff --git a/internal/server/server.go b/internal/server/server.go index 7822973..5deeee6 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -139,6 +139,12 @@ func NewRouter(s *Server) http.Handler { mux.HandleFunc("PATCH /v1/tenants/{id}/projects/{pid}", s.updateTenantProject) mux.HandleFunc("DELETE /v1/tenants/{id}/projects/{pid}", s.deleteTenantProject) mux.HandleFunc("GET /v1/tenants/{id}/projects/{pid}/targets", s.listProjectTargets) + // Dokumentenablage (0022): the list is a {sub} of tenantSubresource. + mux.HandleFunc("POST /v1/tenants/{id}/store/documents", s.uploadStoreDocument) + mux.HandleFunc("GET /v1/tenants/{id}/store/documents/{doc}/original", s.storeOriginal) + mux.HandleFunc("GET /v1/tenants/{id}/store/documents/{doc}/prepared", s.storePrepared) + mux.HandleFunc("GET /v1/tenants/{id}/store/documents/{doc}/consent-banner", s.storeConsentBanner) + mux.HandleFunc("GET /v1/tenants/{id}/store/assets/{sha}", s.storeAsset) // Unternehmensprofil (0021): the GET is a {sub} of tenantSubresource. mux.HandleFunc("PUT /v1/tenants/{id}/company-profile", s.saveCompanyProfile) mux.HandleFunc("POST /v1/tenants/{id}/company-profile/submit", s.submitCompanyProfile) @@ -197,6 +203,7 @@ func NewRouter(s *Server) http.Handler { mux.HandleFunc("POST /v1/admin/tenants/{id}/preview-grants", s.adminGrantPreview) mux.HandleFunc("DELETE /v1/admin/tenants/{id}/preview-grants/{product}", s.adminRevokePreview) mux.HandleFunc("GET /v1/admin/audit", s.listAudit) + 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) mux.HandleFunc("GET /v1/admin/tenants/{id}/documents", s.adminListDocuments) diff --git a/internal/storage/storage.go b/internal/storage/storage.go index d20e322..5b04979 100644 --- a/internal/storage/storage.go +++ b/internal/storage/storage.go @@ -5,6 +5,7 @@ package storage import ( + "bytes" "context" "errors" "fmt" @@ -28,8 +29,13 @@ type Objects interface { // PresignGet returns a GET URL valid for ttl that downloads as filename. PresignGet(ctx context.Context, key, filename string, ttl time.Duration) (string, error) Delete(ctx context.Context, key string) error + // Get opens key for reading (ErrObjectNotFound when it is not there). + Get(ctx context.Context, key string) (io.ReadCloser, error) } +// ErrObjectNotFound: Get of a key the bucket does not hold. +var ErrObjectNotFound = errors.New("storage: object not found") + // Config for an S3 bucket. type Config struct { Endpoint string // https://nbg1.your-objectstorage.com @@ -108,6 +114,18 @@ func (s *S3) Delete(ctx context.Context, key string) error { return s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}) } +// Get opens the object; a missing key is ErrObjectNotFound (minio reports it +// on the first read, so it is checked with Stat first). +func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, error) { + if _, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{}); err != nil { + if minio.ToErrorResponse(err).Code == "NoSuchKey" { + return nil, ErrObjectNotFound + } + return nil, err + } + return s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{}) +} + // ContentDisposition is an attachment header with an ASCII fallback name and // the UTF-8 name (RFC 6266 / 5987), so "Prüfbericht.pdf" survives. func ContentDisposition(filename string) string { @@ -155,6 +173,16 @@ func (m *Memory) PresignGet(_ context.Context, key, filename string, ttl time.Du return "memory://" + key + "?filename=" + url.QueryEscape(filename) + "&ttl=" + ttl.String(), nil } +func (m *Memory) Get(_ context.Context, key string) (io.ReadCloser, error) { + m.mu.Lock() + defer m.mu.Unlock() + b, ok := m.Objects[key] + if !ok { + return nil, ErrObjectNotFound + } + return io.NopCloser(bytes.NewReader(append([]byte(nil), b...))), nil +} + func (m *Memory) Delete(_ context.Context, key string) error { m.mu.Lock() defer m.mu.Unlock() diff --git a/internal/store/document_store.go b/internal/store/document_store.go new file mode 100644 index 0000000..45838e2 --- /dev/null +++ b/internal/store/document_store.go @@ -0,0 +1,88 @@ +package store + +import "time" + +// Dokumentenablage (0022, workspace ticket #171): a tenant's own documents in +// three areas, each with its original and, once the Factory has delivered it, +// a prepared version (LANE_B_UNIFIED_V5 chunk file, images, cookie-banner +// capture). Everything is addressed by SHA-256 and checked when it is served. +const ( + AreaLegalWeb = "legal_web" // Rechtliche Website-Dokumente + AreaProductPublic = "product_public" // Produktdokumente (öffentlich) + AreaInternal = "internal" // Interne Dokumente + + ProcessingNone = "none" + ProcessingPending = "pending" + ProcessingReady = "ready" + ProcessingFailed = "failed" +) + +// LegalKinds are the folders of the legal website documents, in display +// order, with the codes the workspace and the Factory use. +var LegalKinds = []string{"impressum", "dse", "cookie", "agb", "widerruf", "barrierefreiheit", "entsorgung", "vsbg"} + +// ValidArea reports whether area is one of the three store areas. +func ValidArea(area string) bool { + return area == AreaLegalWeb || area == AreaProductPublic || area == AreaInternal +} + +// ValidLegalKind reports whether kind is one of the legal folders. +func ValidLegalKind(kind string) bool { + for _, k := range LegalKinds { + if k == kind { + return true + } + } + return false +} + +// validStoreFields: a legal kind exactly for legal documents, a known area, +// a known status. +func validStoreFields(d Document) bool { + if d.Area == "" { + return d.LegalKind == "" && d.ExternalID == "" + } + if !ValidArea(d.Area) || (d.Area == AreaLegalWeb) != (d.LegalKind != "") { + return false + } + if d.LegalKind != "" && !ValidLegalKind(d.LegalKind) { + return false + } + switch d.ProcessingStatus { + case "", ProcessingNone, ProcessingPending, ProcessingReady, ProcessingFailed: + return len(d.ExternalID) <= 120 + } + return false +} + +// Preparation is the prepared version of a document as delivered. The chunk +// part and the consent part are delivered independently; either may be empty. +type Preparation struct { + DocumentID string `json:"document_id"` + Format string `json:"format,omitempty"` + Revision int `json:"revision,omitempty"` + Pin string `json:"pin,omitempty"` + ChunkObjectKey string `json:"-"` + ChunkSHA256 string `json:"chunk_sha256,omitempty"` + ChunkBytes int64 `json:"chunk_bytes,omitempty"` + ChunkCount int `json:"chunk_count"` + ConsentObjectKey string `json:"-"` + ConsentSHA256 string `json:"consent_sha256,omitempty"` + AssetDigests []string `json:"asset_digests"` + DeliveredBy string `json:"delivered_by,omitempty"` + DeliveredAt time.Time `json:"delivered_at"` +} + +// HasChunks and HasConsent say which parts are there. +func (p Preparation) HasChunks() bool { return p.ChunkSHA256 != "" } +func (p Preparation) HasConsent() bool { return p.ConsentSHA256 != "" } + +// StoreAsset is one image of a tenant's prepared documents. +type StoreAsset struct { + TenantID string `json:"tenant_id"` + SHA256 string `json:"sha256"` + ObjectKey string `json:"-"` + ContentType string `json:"content_type"` + SizeBytes int64 `json:"size_bytes"` + CreatedAt time.Time `json:"created_at"` +} diff --git a/internal/store/memory.go b/internal/store/memory.go index 75e22ca..3c5e77b 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -34,14 +34,16 @@ type Memory struct { receipts map[string]time.Time licences map[string]*Licence - documents map[string]*Document - projects map[string]*Project - offers map[string]*TrialOffer - services map[string]*ManagedService - profiles map[string]*CompanyProfile // tenant_id → current - profRevs map[string][]CompanyProfile // tenant_id → every revision - mail []*MailItem - mailID int64 + documents map[string]*Document + projects map[string]*Project + offers map[string]*TrialOffer + services map[string]*ManagedService + preparations map[string]*Preparation // document id → delivered prepared version (0022) + assets map[string]*StoreAsset // tenant_id + "/" + sha256 (0022) + profiles map[string]*CompanyProfile // tenant_id → current + profRevs map[string][]CompanyProfile // tenant_id → every revision + mail []*MailItem + mailID int64 } type apiKeyWithHash struct { @@ -53,20 +55,22 @@ type apiKeyWithHash struct { // NewMemory returns a fresh in-memory store with the seed acme tenant. func NewMemory() *Memory { m := &Memory{ - tenants: make(map[string]*Tenant), - bySlug: make(map[string]string), - products: make(map[string]map[string]*TenantProduct), - apiKeys: make(map[string]*apiKeyWithHash), - catalog: DefaultProducts(), - subs: make(map[string]*Subscription), - usageKey: make(map[string]int64), - receipts: make(map[string]time.Time), - licences: make(map[string]*Licence), - projects: make(map[string]*Project), - offers: make(map[string]*TrialOffer), - services: make(map[string]*ManagedService), - profiles: make(map[string]*CompanyProfile), - profRevs: make(map[string][]CompanyProfile), + tenants: make(map[string]*Tenant), + bySlug: make(map[string]string), + products: make(map[string]map[string]*TenantProduct), + apiKeys: make(map[string]*apiKeyWithHash), + catalog: DefaultProducts(), + subs: make(map[string]*Subscription), + usageKey: make(map[string]int64), + receipts: make(map[string]time.Time), + licences: make(map[string]*Licence), + projects: make(map[string]*Project), + offers: make(map[string]*TrialOffer), + services: make(map[string]*ManagedService), + profiles: make(map[string]*CompanyProfile), + preparations: make(map[string]*Preparation), + assets: make(map[string]*StoreAsset), + profRevs: make(map[string][]CompanyProfile), documents: make(map[string]*Document), } diff --git a/internal/store/memory_document_store.go b/internal/store/memory_document_store.go new file mode 100644 index 0000000..c454dec --- /dev/null +++ b/internal/store/memory_document_store.go @@ -0,0 +1,185 @@ +package store + +import ( + "context" + "sort" + "time" +) + +// storeOrder sorts the tenant's own documents: by area, legal folder (in the +// folders' order), title, then id. +func storeOrder(out []Document) { + area := map[string]int{AreaLegalWeb: 0, AreaProductPublic: 1, AreaInternal: 2} + kind := map[string]int{} + for i, k := range LegalKinds { + kind[k] = i + } + sort.Slice(out, func(i, j int) bool { + a, b := out[i], out[j] + if area[a.Area] != area[b.Area] { + return area[a.Area] < area[b.Area] + } + if kind[a.LegalKind] != kind[b.LegalKind] { + return kind[a.LegalKind] < kind[b.LegalKind] + } + if a.Title != b.Title { + return a.Title < b.Title + } + return a.ID < b.ID + }) +} + +func (m *Memory) ListStoreDocuments(_ context.Context, tenantID string) ([]Document, error) { + m.mu.RLock() + defer m.mu.RUnlock() + out := []Document{} + for _, d := range m.documents { + if d.TenantID == tenantID && d.Area != "" { + out = append(out, *d.copy()) + } + } + storeOrder(out) + return out, nil +} + +func (m *Memory) GetDocumentByExternalID(_ context.Context, tenantID, externalID string) (*Document, error) { + m.mu.RLock() + defer m.mu.RUnlock() + for _, d := range m.documents { + if externalID != "" && d.TenantID == tenantID && d.ExternalID == externalID { + return d.copy(), nil + } + } + return nil, ErrNotFound +} + +func (m *Memory) SetDocumentProcessing(_ context.Context, docID, status, errMsg string) (*Document, error) { + m.mu.Lock() + defer m.mu.Unlock() + d, ok := m.documents[docID] + if !ok { + return nil, ErrNotFound + } + switch status { + case ProcessingNone, ProcessingPending, ProcessingReady, ProcessingFailed: + default: + return nil, ErrInvalidInput + } + if len(errMsg) > 500 { + errMsg = errMsg[:500] + } + d.ProcessingStatus, d.ProcessingError, d.UpdatedAt = status, errMsg, time.Now().UTC() + return d.copy(), nil +} + +func (m *Memory) SaveDocumentPreparation(_ context.Context, p Preparation) (*Preparation, error) { + if !p.HasChunks() && !p.HasConsent() { + return nil, ErrInvalidInput + } + m.mu.Lock() + defer m.mu.Unlock() + d, ok := m.documents[p.DocumentID] + if !ok { + return nil, ErrNotFound + } + cur := m.preparations[p.DocumentID] + next := mergePreparation(cur, p) + next.DeliveredAt = time.Now().UTC() + m.preparations[p.DocumentID] = &next + if next.HasChunks() { + d.ProcessingStatus, d.ProcessingError = ProcessingReady, "" + } + out := next + out.AssetDigests = append([]string(nil), next.AssetDigests...) + return &out, nil +} + +// mergePreparation lays the delivered parts over what is stored: a part that +// was not delivered stays as it was. +func mergePreparation(cur *Preparation, p Preparation) Preparation { + next := p + if cur != nil { + if !p.HasChunks() { + next.Format, next.Revision, next.Pin = cur.Format, cur.Revision, cur.Pin + next.ChunkObjectKey, next.ChunkSHA256, next.ChunkBytes, next.ChunkCount = cur.ChunkObjectKey, cur.ChunkSHA256, cur.ChunkBytes, cur.ChunkCount + next.AssetDigests = cur.AssetDigests + } + if !p.HasConsent() { + next.ConsentObjectKey, next.ConsentSHA256 = cur.ConsentObjectKey, cur.ConsentSHA256 + } + } + if next.AssetDigests == nil { + next.AssetDigests = []string{} + } + return next +} + +func (m *Memory) GetDocumentPreparation(_ context.Context, docID string) (*Preparation, error) { + m.mu.RLock() + defer m.mu.RUnlock() + p, ok := m.preparations[docID] + if !ok { + return nil, ErrNotFound + } + out := *p + out.AssetDigests = append([]string(nil), p.AssetDigests...) + return &out, nil +} + +func (m *Memory) ListDocumentPreparations(_ context.Context, tenantID string) (map[string]Preparation, error) { + m.mu.RLock() + defer m.mu.RUnlock() + out := map[string]Preparation{} + for id, p := range m.preparations { + if d, ok := m.documents[id]; ok && d.TenantID == tenantID { + cp := *p + cp.AssetDigests = append([]string(nil), p.AssetDigests...) + out[id] = cp + } + } + return out, nil +} + +func (m *Memory) PutStoreAsset(_ context.Context, a StoreAsset) (*StoreAsset, error) { + if !hex64(a.SHA256) || a.ObjectKey == "" { + return nil, ErrInvalidInput + } + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.tenants[a.TenantID]; !ok { + return nil, ErrNotFound + } + key := a.TenantID + "/" + a.SHA256 + if cur, ok := m.assets[key]; ok { + out := *cur + return &out, nil + } + a.CreatedAt = time.Now().UTC() + m.assets[key] = &a + out := a + return &out, nil +} + +func (m *Memory) GetStoreAsset(_ context.Context, tenantID, sha string) (*StoreAsset, error) { + m.mu.RLock() + defer m.mu.RUnlock() + a, ok := m.assets[tenantID+"/"+sha] + if !ok { + return nil, ErrNotFound + } + out := *a + return &out, nil +} + +// hex64 reports whether s is a lowercase hex SHA-256. +func hex64(s string) bool { + if len(s) != 64 { + return false + } + for _, c := range s { + if (c < '0' || c > '9') && (c < 'a' || c > 'f') { + return false + } + } + return true +} diff --git a/internal/store/memory_documents.go b/internal/store/memory_documents.go index 84e2188..1776f1d 100644 --- a/internal/store/memory_documents.go +++ b/internal/store/memory_documents.go @@ -15,8 +15,12 @@ func (m *Memory) CreateDocument(_ context.Context, d Document) (*Document, error if _, ok := m.tenants[d.TenantID]; !ok { return nil, ErrNotFound } + if !validStoreFields(d) { + return nil, ErrInvalidInput + } for _, x := range m.documents { - if x.ID == d.ID || x.ObjectKey == d.ObjectKey { + if x.ID == d.ID || x.ObjectKey == d.ObjectKey || + (d.ExternalID != "" && x.TenantID == d.TenantID && x.ExternalID == d.ExternalID) { return nil, ErrConflict } } @@ -24,6 +28,9 @@ func (m *Memory) CreateDocument(_ context.Context, d Document) (*Document, error if d.Status == "" { d.Status = DocumentDraft } + if d.ProcessingStatus == "" { + d.ProcessingStatus = ProcessingNone + } ids, ok := m.tenantProjectIDs(d.TenantID, d.ProjectIDs) if !ok { return nil, ErrInvalidInput @@ -97,7 +104,7 @@ func (m *Memory) ListDocuments(_ context.Context, tenantID string, publishedOnly defer m.mu.RUnlock() out := []Document{} for _, d := range m.documents { - if d.TenantID != tenantID || (publishedOnly && d.Status != DocumentPublished) { + if d.TenantID != tenantID || d.Area != "" || (publishedOnly && d.Status != DocumentPublished) { continue } out = append(out, *d.copy()) @@ -132,5 +139,6 @@ func (m *Memory) DeleteDocument(_ context.Context, id string) error { return ErrNotFound } delete(m.documents, id) + delete(m.preparations, id) return nil } diff --git a/internal/store/postgres_document_store.go b/internal/store/postgres_document_store.go new file mode 100644 index 0000000..c4af86f --- /dev/null +++ b/internal/store/postgres_document_store.go @@ -0,0 +1,191 @@ +package store + +import ( + "context" + "errors" + + "github.com/jackc/pgx/v5" +) + +func (p *Postgres) ListStoreDocuments(ctx context.Context, tenantID string) ([]Document, error) { + rows, err := p.pool.Query(ctx, documentSelect+` + WHERE tenant_id = $1::uuid AND area IS NOT NULL + ORDER BY array_position(ARRAY['legal_web','product_public','internal'], area), + array_position($2::text[], legal_kind) NULLS FIRST, title, id`, tenantID, LegalKinds) + if isInvalidUUID(err) { + return []Document{}, nil + } + if err != nil { + return nil, err + } + defer rows.Close() + out := []Document{} + for rows.Next() { + d, err := scanDocument(rows) + if err != nil { + return nil, err + } + out = append(out, *d) + } + return out, rows.Err() +} + +func (p *Postgres) GetDocumentByExternalID(ctx context.Context, tenantID, externalID string) (*Document, error) { + if externalID == "" { + return nil, ErrNotFound + } + d, err := scanDocument(p.pool.QueryRow(ctx, documentSelect+`WHERE tenant_id = $1::uuid AND external_id = $2`, tenantID, externalID)) + if isInvalidUUID(err) { + return nil, ErrNotFound + } + return d, err +} + +func (p *Postgres) SetDocumentProcessing(ctx context.Context, docID, status, errMsg string) (*Document, error) { + if len(errMsg) > 500 { + errMsg = errMsg[:500] + } + tag, err := p.pool.Exec(ctx, ` + UPDATE documents SET processing_status = $2, processing_error = $3, updated_at = now() WHERE id = $1::uuid`, + docID, status, errMsg) + switch { + case isInvalidUUID(err): + return nil, ErrNotFound + case isCheckViolation(err): + return nil, ErrInvalidInput + case err != nil: + return nil, err + case tag.RowsAffected() == 0: + return nil, ErrNotFound + } + return p.GetDocument(ctx, docID) +} + +const preparationSelect = ` +SELECT document_id::text, format, revision, pin, chunk_object_key, chunk_sha256, chunk_bytes, chunk_count, + consent_object_key, consent_sha256, asset_digests, delivered_by, delivered_at +FROM document_preparations ` + +func scanPreparation(row pgx.Row) (*Preparation, error) { + var x Preparation + if err := row.Scan(&x.DocumentID, &x.Format, &x.Revision, &x.Pin, &x.ChunkObjectKey, &x.ChunkSHA256, &x.ChunkBytes, &x.ChunkCount, + &x.ConsentObjectKey, &x.ConsentSHA256, &x.AssetDigests, &x.DeliveredBy, &x.DeliveredAt); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + return nil, err + } + if x.AssetDigests == nil { + x.AssetDigests = []string{} + } + return &x, nil +} + +func (p *Postgres) SaveDocumentPreparation(ctx context.Context, in Preparation) (*Preparation, error) { + if !in.HasChunks() && !in.HasConsent() { + return nil, ErrInvalidInput + } + tx, err := p.pool.Begin(ctx) + if err != nil { + return nil, err + } + defer func() { _ = tx.Rollback(ctx) }() + cur, err := scanPreparation(tx.QueryRow(ctx, preparationSelect+`WHERE document_id = $1::uuid FOR UPDATE`, in.DocumentID)) + switch { + case isInvalidUUID(err): + return nil, ErrNotFound + case errors.Is(err, ErrNotFound): + cur = nil + case err != nil: + return nil, err + } + next := mergePreparation(cur, in) + _, err = tx.Exec(ctx, ` + INSERT INTO document_preparations (document_id, format, revision, pin, chunk_object_key, chunk_sha256, chunk_bytes, chunk_count, + consent_object_key, consent_sha256, asset_digests, delivered_by, delivered_at) + VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, now()) + ON CONFLICT (document_id) DO UPDATE SET format = $2, revision = $3, pin = $4, chunk_object_key = $5, chunk_sha256 = $6, + chunk_bytes = $7, chunk_count = $8, consent_object_key = $9, consent_sha256 = $10, asset_digests = $11, + delivered_by = $12, delivered_at = now()`, + next.DocumentID, next.Format, next.Revision, next.Pin, next.ChunkObjectKey, next.ChunkSHA256, next.ChunkBytes, next.ChunkCount, + next.ConsentObjectKey, next.ConsentSHA256, next.AssetDigests, next.DeliveredBy) + switch { + case isFKViolation(err): + return nil, ErrNotFound + case isCheckViolation(err): + return nil, ErrInvalidInput + case err != nil: + return nil, err + } + if next.HasChunks() { + if _, err := tx.Exec(ctx, `UPDATE documents SET processing_status = 'ready', processing_error = '', updated_at = now() WHERE id = $1::uuid`, + next.DocumentID); err != nil { + return nil, err + } + } + if err := tx.Commit(ctx); err != nil { + return nil, err + } + return p.GetDocumentPreparation(ctx, next.DocumentID) +} + +func (p *Postgres) GetDocumentPreparation(ctx context.Context, docID string) (*Preparation, error) { + x, err := scanPreparation(p.pool.QueryRow(ctx, preparationSelect+`WHERE document_id = $1::uuid`, docID)) + if isInvalidUUID(err) { + return nil, ErrNotFound + } + return x, err +} + +func (p *Postgres) ListDocumentPreparations(ctx context.Context, tenantID string) (map[string]Preparation, error) { + rows, err := p.pool.Query(ctx, preparationSelect+` + WHERE document_id IN (SELECT id FROM documents WHERE tenant_id = $1::uuid)`, tenantID) + if isInvalidUUID(err) { + return map[string]Preparation{}, nil + } + if err != nil { + return nil, err + } + defer rows.Close() + out := map[string]Preparation{} + for rows.Next() { + x, err := scanPreparation(rows) + if err != nil { + return nil, err + } + out[x.DocumentID] = *x + } + return out, rows.Err() +} + +func (p *Postgres) PutStoreAsset(ctx context.Context, a StoreAsset) (*StoreAsset, error) { + if !hex64(a.SHA256) || a.ObjectKey == "" { + return nil, ErrInvalidInput + } + _, err := p.pool.Exec(ctx, ` + INSERT INTO store_assets (tenant_id, sha256, object_key, content_type, size_bytes) + VALUES ($1::uuid, $2, $3, $4, $5) ON CONFLICT (tenant_id, sha256) DO NOTHING`, + a.TenantID, a.SHA256, a.ObjectKey, a.ContentType, a.SizeBytes) + switch { + case isFKViolation(err), isInvalidUUID(err): + return nil, ErrNotFound + case err != nil: + return nil, err + } + return p.GetStoreAsset(ctx, a.TenantID, a.SHA256) +} + +func (p *Postgres) GetStoreAsset(ctx context.Context, tenantID, sha string) (*StoreAsset, error) { + var a StoreAsset + err := p.pool.QueryRow(ctx, ` + SELECT tenant_id::text, sha256, object_key, content_type, size_bytes, created_at + FROM store_assets WHERE tenant_id = $1::uuid AND sha256 = $2`, tenantID, sha). + Scan(&a.TenantID, &a.SHA256, &a.ObjectKey, &a.ContentType, &a.SizeBytes, &a.CreatedAt) + switch { + case errors.Is(err, pgx.ErrNoRows), isInvalidUUID(err): + return nil, ErrNotFound + case err != nil: + return nil, err + } + return &a, nil +} diff --git a/internal/store/postgres_documents.go b/internal/store/postgres_documents.go index 8baaf1d..5e2fae1 100644 --- a/internal/store/postgres_documents.go +++ b/internal/store/postgres_documents.go @@ -11,7 +11,7 @@ import ( const documentSelect = ` SELECT id::text, tenant_id::text, title, description, filename, content_type, size_bytes, sha256, object_key, status, uploaded_by, COALESCE(published_by, ''), published_at, created_at, updated_at, - own_document, + own_document, COALESCE(area, ''), COALESCE(legal_kind, ''), processing_status, processing_error, external_id, COALESCE((SELECT array_agg(dp.project_id::text ORDER BY dp.project_id) FROM document_projects dp WHERE dp.document_id = documents.id), '{}') FROM documents ` @@ -20,7 +20,7 @@ func scanDocument(row pgx.Row) (*Document, error) { var d Document if err := row.Scan(&d.ID, &d.TenantID, &d.Title, &d.Description, &d.Filename, &d.ContentType, &d.SizeBytes, &d.SHA256, &d.ObjectKey, &d.Status, &d.UploadedBy, &d.PublishedBy, &d.PublishedAt, &d.CreatedAt, &d.UpdatedAt, - &d.OwnDocument, &d.ProjectIDs); err != nil { + &d.OwnDocument, &d.Area, &d.LegalKind, &d.ProcessingStatus, &d.ProcessingError, &d.ExternalID, &d.ProjectIDs); err != nil { if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound } @@ -36,10 +36,18 @@ func (p *Postgres) CreateDocument(ctx context.Context, d Document) (*Document, e if d.Status == "" { d.Status = DocumentDraft } + if d.ProcessingStatus == "" { + d.ProcessingStatus = ProcessingNone + } + if !validStoreFields(d) { + return nil, ErrInvalidInput + } _, err := p.pool.Exec(ctx, ` - INSERT INTO documents (id, tenant_id, title, description, filename, content_type, size_bytes, sha256, object_key, status, uploaded_by, own_document) - VALUES ($1::uuid, $2::uuid, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`, - d.ID, d.TenantID, d.Title, d.Description, d.Filename, d.ContentType, d.SizeBytes, d.SHA256, d.ObjectKey, d.Status, d.UploadedBy, d.OwnDocument) + INSERT INTO documents (id, tenant_id, title, description, filename, content_type, size_bytes, sha256, object_key, status, uploaded_by, own_document, + area, legal_kind, processing_status, external_id) + VALUES ($1::uuid, $2::uuid, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, NULLIF($13, ''), NULLIF($14, ''), $15, $16)`, + d.ID, d.TenantID, d.Title, d.Description, d.Filename, d.ContentType, d.SizeBytes, d.SHA256, d.ObjectKey, d.Status, d.UploadedBy, d.OwnDocument, + d.Area, d.LegalKind, d.ProcessingStatus, d.ExternalID) switch { case err == nil: if len(d.ProjectIDs) > 0 { @@ -72,7 +80,8 @@ func (p *Postgres) GetDocument(ctx context.Context, id string) (*Document, error } func (p *Postgres) ListDocuments(ctx context.Context, tenantID string, publishedOnly bool) ([]Document, error) { - q := documentSelect + `WHERE tenant_id = $1::uuid` + // BreakPilot's deliveries only; the tenant's own documents are the store's. + q := documentSelect + `WHERE tenant_id = $1::uuid AND area IS NULL` if publishedOnly { q += ` AND status = 'published'` } diff --git a/internal/store/store.go b/internal/store/store.go index 1b9ea63..c9303b2 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -176,6 +176,26 @@ type Store interface { SetDocumentProjects(ctx context.Context, docID string, projectIDs []string) (*Document, error) SetDocumentOwn(ctx context.Context, docID string, own bool) (*Document, error) + // Dokumentenablage (0022). ListDocuments returns only BreakPilot's + // deliveries (no area); ListStoreDocuments the tenant's own documents + // (with an area), by area, legal folder and title. GetDocumentByExternalID + // finds a document by the Factory's id (ErrNotFound when none). + ListStoreDocuments(ctx context.Context, tenantID string) ([]Document, error) + GetDocumentByExternalID(ctx context.Context, tenantID, externalID string) (*Document, error) + SetDocumentProcessing(ctx context.Context, docID, status, errMsg string) (*Document, error) + // SaveDocumentPreparation stores the delivered parts (a chunk part and/or a + // consent part; a part left empty keeps what is stored) and marks the + // document ready when it has a chunk part. + SaveDocumentPreparation(ctx context.Context, p Preparation) (*Preparation, error) + // GetDocumentPreparation is ErrNotFound when nothing was delivered. + GetDocumentPreparation(ctx context.Context, docID string) (*Preparation, error) + // ListDocumentPreparations maps document id → preparation for a tenant. + ListDocumentPreparations(ctx context.Context, tenantID string) (map[string]Preparation, error) + // PutStoreAsset is idempotent on (tenant, sha256); GetStoreAsset is + // ErrNotFound for an asset the tenant does not hold. + PutStoreAsset(ctx context.Context, a StoreAsset) (*StoreAsset, error) + GetStoreAsset(ctx context.Context, tenantID, sha256 string) (*StoreAsset, error) + // Trial offers (0011, portal#64). Only the state moves; the snapshot is // written by CreateTrialOffer and never changed. CreateTrialOffer(ctx context.Context, o TrialOffer) (*TrialOffer, error) diff --git a/internal/store/types.go b/internal/store/types.go index 7043e19..62d1617 100644 --- a/internal/store/types.go +++ b/internal/store/types.go @@ -291,6 +291,14 @@ type Document struct { OwnDocument bool `json:"own_document"` // ProjectIDs are the tenant projects the document belongs to (0010). ProjectIDs []string `json:"project_ids"` + // Dokumentenablage (0022): the tenant's own documents carry an area + // (empty = a BreakPilot delivery, "Unterlagen"), legal documents their + // folder; ProcessingStatus says whether the prepared version is there. + Area string `json:"area,omitempty"` + LegalKind string `json:"legal_kind,omitempty"` + ProcessingStatus string `json:"processing_status"` + ProcessingError string `json:"processing_error,omitempty"` + ExternalID string `json:"external_id,omitempty"` } const ( diff --git a/migrations/0022_document_store.down.sql b/migrations/0022_document_store.down.sql new file mode 100644 index 0000000..ae7d33f --- /dev/null +++ b/migrations/0022_document_store.down.sql @@ -0,0 +1,11 @@ +DROP TABLE IF EXISTS store_assets; +DROP TABLE IF EXISTS document_preparations; +DROP INDEX IF EXISTS documents_processing_pending; +DROP INDEX IF EXISTS documents_tenant_external_id; +ALTER TABLE documents + DROP CONSTRAINT IF EXISTS documents_legal_kind_in_legal_area, + DROP COLUMN IF EXISTS external_id, + DROP COLUMN IF EXISTS processing_error, + DROP COLUMN IF EXISTS processing_status, + DROP COLUMN IF EXISTS legal_kind, + DROP COLUMN IF EXISTS area; diff --git a/migrations/0022_document_store.up.sql b/migrations/0022_document_store.up.sql new file mode 100644 index 0000000..0efb6a2 --- /dev/null +++ b/migrations/0022_document_store.up.sql @@ -0,0 +1,53 @@ +-- Dokumentenablage (workspace ticket #171, decided 2026-10-20): the tenant's +-- own documents in three areas, next to what BreakPilot delivers to them +-- ("Unterlagen", area NULL). Read-only view: the original, and the prepared +-- version the Factory delivers (chunk file in LANE_B_UNIFIED_V5, images, +-- cookie-banner capture), every piece addressed and checked by its SHA-256. +ALTER TABLE documents + ADD COLUMN area TEXT CHECK (area IN ('legal_web', 'product_public', 'internal')), + -- the folder of a legal website document, as the workspace and the + -- Factory name it + ADD COLUMN legal_kind TEXT CHECK (legal_kind IN + ('impressum', 'dse', 'cookie', 'agb', 'widerruf', 'barrierefreiheit', 'entsorgung', 'vsbg')), + -- none: not sent for preparation; pending: waiting for the Factory; + -- ready: prepared version stored; failed: the Factory gave up (reason kept) + ADD COLUMN processing_status TEXT NOT NULL DEFAULT 'none' + CHECK (processing_status IN ('none', 'pending', 'ready', 'failed')), + ADD COLUMN processing_error TEXT NOT NULL DEFAULT '' CHECK (char_length(processing_error) <= 500), + -- the Factory's id of the document (tenant_document_id), for imports + ADD COLUMN external_id TEXT NOT NULL DEFAULT '' CHECK (char_length(external_id) <= 120), + ADD CONSTRAINT documents_legal_kind_in_legal_area CHECK ((area = 'legal_web') = (legal_kind IS NOT NULL)); + +CREATE UNIQUE INDEX documents_tenant_external_id ON documents (tenant_id, external_id) WHERE external_id <> ''; +CREATE INDEX documents_processing_pending ON documents (created_at) WHERE processing_status = 'pending'; + +-- The prepared version of a document, as delivered: the chunk file and/or the +-- cookie-banner capture, each stored as an object and kept by its digest. +CREATE TABLE document_preparations ( + document_id UUID PRIMARY KEY REFERENCES documents(id) ON DELETE CASCADE, + format TEXT NOT NULL DEFAULT '' CHECK (char_length(format) <= 60), + revision INTEGER NOT NULL DEFAULT 0 CHECK (revision >= 0), + pin TEXT NOT NULL DEFAULT '' CHECK (char_length(pin) <= 80), + chunk_object_key TEXT NOT NULL DEFAULT '', + chunk_sha256 TEXT NOT NULL DEFAULT '' CHECK (chunk_sha256 = '' OR chunk_sha256 ~ '^[0-9a-f]{64}$'), + chunk_bytes BIGINT NOT NULL DEFAULT 0, + chunk_count INTEGER NOT NULL DEFAULT 0, + consent_object_key TEXT NOT NULL DEFAULT '', + consent_sha256 TEXT NOT NULL DEFAULT '' CHECK (consent_sha256 = '' OR consent_sha256 ~ '^[0-9a-f]{64}$'), + asset_digests TEXT[] NOT NULL DEFAULT '{}', + delivered_by TEXT NOT NULL DEFAULT '', + delivered_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK (chunk_sha256 <> '' OR consent_sha256 <> '') +); + +-- Images of prepared documents (figures, page images), content-addressed per +-- tenant: a tenant only ever reads its own. +CREATE TABLE store_assets ( + tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, + sha256 TEXT NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'), + object_key TEXT NOT NULL, + content_type TEXT NOT NULL, + size_bytes BIGINT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (tenant_id, sha256) +); diff --git a/openapi.yaml b/openapi.yaml index 3c81a0d..15d1af8 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -333,6 +333,108 @@ paths: url: { type: string, description: The object in the Prüfwerk dashboard. } "404": { $ref: "#/components/responses/NotFound" } + /v1/tenants/{id}/store: + get: + summary: The tenant's document store (Dokumentenablage), by area and legal folder. + description: | + Served by the `{id}/{sub}` route; user tokens reach their own tenant + only. Each item carries its processing status and, once delivered, + a summary of its prepared version. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: The store. + content: + application/json: + schema: + type: object + properties: + items: { type: array, items: { $ref: "#/components/schemas/StoreDocument" } } + legal_kinds: { type: array, items: { type: string }, description: The legal folders in display order. } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/tenants/{id}/store/documents: + post: + summary: Upload a document into an area of the store. + description: | + multipart/form-data: `area` (legal_web, product_public, internal), + `legal_kind` (legal_web only), `product_id` (internal only, a product + project of the tenant), `title`, `process` ("on": an internal document + goes to the Factory too), then `file` (pdf, docx, txt, html). Legal + and product documents wait for the Factory (`pending`). The portal + checks the user's org role and names them in X-Portal-User-Email. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: + multipart/form-data: + schema: + type: object + required: [area, file] + properties: + area: { type: string, enum: [legal_web, product_public, internal] } + legal_kind: { type: string } + product_id: { type: string } + title: { type: string, maxLength: 200 } + process: { type: string } + file: { type: string, format: binary } + responses: + "201": + description: Stored. + content: + application/json: { schema: { $ref: "#/components/schemas/StoreDocument" } } + "400": { description: "invalid_area, invalid_legal_kind, invalid_product, invalid_title, missing_file or invalid_body." } + "404": { $ref: "#/components/responses/NotFound" } + "413": { description: Larger than the upload limit (too_large). } + "415": { description: "Not pdf, docx, txt or html (unsupported_type)." } + + /v1/tenants/{id}/store/documents/{doc}/original: + get: + summary: The original, inline, after its SHA-256 matched. + description: A mismatch is refused with 502 digest_mismatch and nothing is served. HTML is sent with a sandboxing CSP. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: doc, required: true, schema: { type: string, format: uuid } } + responses: + "200": { description: The file; X-Content-SHA256 carries its digest. } + "404": { $ref: "#/components/responses/NotFound" } + "502": { description: digest_mismatch or storage_failed. } + + /v1/tenants/{id}/store/documents/{doc}/prepared: + get: + summary: The prepared version (LANE_B_UNIFIED_V5 chunk file), digest-checked. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: doc, required: true, schema: { type: string, format: uuid } } + responses: + "200": { description: The chunk file as delivered. } + "404": { description: "Unknown document, or nothing delivered yet (not_prepared)." } + "502": { description: digest_mismatch or storage_failed. } + + /v1/tenants/{id}/store/documents/{doc}/consent-banner: + get: + summary: The cookie-banner capture (CONSENT_BANNER_CAPTURE_V1), digest-checked. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: doc, required: true, schema: { type: string, format: uuid } } + responses: + "200": { description: The capture as delivered. } + "404": { description: "Unknown document, or no capture (not_prepared)." } + "502": { description: digest_mismatch or storage_failed. } + + /v1/tenants/{id}/store/assets/{sha}: + get: + summary: An image of a prepared document the tenant holds, digest-checked. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: sha, required: true, schema: { type: string, pattern: "^[0-9a-f]{64}$" } } + responses: + "200": { description: The image. } + "404": { $ref: "#/components/responses/NotFound" } + "502": { description: digest_mismatch or storage_failed. } + /v1/tenants/{id}/company-profile: get: summary: The tenant's company profile (Unternehmensprofil), current revision. @@ -889,6 +991,55 @@ paths: "204": { description: Deleted. } "404": { $ref: "#/components/responses/NotFound" } + /v1/admin/tenants/{id}/store/import: + post: + summary: Import a document-store bundle (staff only). + description: | + The body is a .tar.gz in the Factory's layout: LANE_B_INDEX_V1.json, + objects/.(pdf|html|txt), presentation/CONSENT_BANNER_CAPTURES_V1.json + with presentation/consent_banner/.json, chunks/.json, + figure_assets/sources/sha256/., optionally the + LANE_B_UNIFIED_V5_RETURN_MANIFEST_V1.json (pin = its digest). Every file is + checked against its digest; keyed on tenant_document_id, so it can run + again. The answer lists each document's outcome, never its content. + Needs a named staff member (X-Staff-Subject). + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + requestBody: + required: true + content: + application/gzip: { schema: { type: string, format: binary } } + responses: + "200": + description: The outcome per document. + content: + application/json: + schema: + type: object + properties: + documents: + type: array + items: + type: object + properties: + external_id: { type: string } + title: { type: string } + area: { type: string } + legal_kind: { type: string } + document_id: { type: string } + original: { type: string, enum: [imported, exists, rejected] } + prepared: { type: string, enum: [imported, unchanged, absent, rejected] } + consent: { type: string, enum: [imported, unchanged, absent, rejected] } + assets: { type: integer } + reason: { type: string } + counts: { type: object, additionalProperties: { type: integer } } + pin: { type: string } + revision: { type: integer } + "400": { description: "invalid_bundle: not a .tar.gz, an unsafe path or link, or no index." } + "403": { description: No named staff member (staff_only). } + "404": { $ref: "#/components/responses/NotFound" } + "413": { description: Larger than STORE_IMPORT_MAX_MB. } + /v1/admin/tenants/{id}/company-profile: get: summary: A tenant's company profile (staff). @@ -1917,6 +2068,36 @@ components: description: { type: string, maxLength: 1000 } level: { type: string, enum: [family, product, component], description: "Products only; defaults to product. A family has no parent, a product sits below a family or nothing, a component below a product or component; at most 4 levels." } parent_id: { type: string, description: "uuid of the project above, \"\" to detach. Must be a product project of the same tenant that fits the level." } + StoreDocument: + type: object + required: [id, tenant_id, title, filename, sha256, area, processing_status] + properties: + id: { type: string, format: uuid } + tenant_id: { type: string, format: uuid } + title: { type: string } + filename: { type: string } + content_type: { type: string } + size_bytes: { type: integer } + sha256: { type: string } + area: { type: string, enum: [legal_web, product_public, internal] } + legal_kind: { type: string, enum: [impressum, dse, cookie, agb, widerruf, barrierefreiheit, entsorgung, vsbg] } + processing_status: { type: string, enum: [none, pending, ready, failed] } + processing_error: { type: string } + external_id: { type: string, description: "The Factory's tenant_document_id, for imported documents." } + project_ids: { type: array, items: { type: string } } + uploaded_by: { type: string } + created_at: { type: string, format: date-time } + preparation: + type: object + nullable: true + properties: + format: { type: string } + revision: { type: integer } + chunk_count: { type: integer } + has_chunks: { type: boolean } + has_consent: { type: boolean } + assets: { type: integer } + delivered_at: { type: string, format: date-time } CompanyProfile: type: object required: [tenant_id, data, schema_version, revision, status, updated_by, updated_at]