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")) // Drafts (staff uploads before publishing) are not shown yet. if err == nil && (d.TenantID != t.ID || d.Status != store.DocumentPublished) { 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") }