Files
tenant-registry/internal/server/documents.go
T
sharangandClaude Opus 5.5 2a0a274108
ci / shared (push) Successful in 13s
ci / test (push) Successful in 25m46s
ci / image (push) Successful in 51s
feat(store): Dokumentenablage with areas, checked serving, import (#88)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:38:10 +00:00

451 lines
15 KiB
Go

package server
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"net/http"
"path"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"git.breakpilot.com/platform/tenant-registry/internal/authn"
"git.breakpilot.com/platform/tenant-registry/internal/store"
)
// Tenant documents (F2): files BreakPilot prepares for a tenant — conformity
// documents, reports — until breakpilot-compliance delivers them itself.
// Staff upload a draft and publish it (admin group); the tenant lists and
// downloads published ones (tenants.read, user tokens scoped to their tenant).
const downloadTTL = 5 * time.Minute
// allowedDocumentTypes maps an accepted extension to the stored content type.
var allowedDocumentTypes = map[string]string{
".pdf": "application/pdf",
".zip": "application/zip",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".txt": "text/plain; charset=utf-8",
".csv": "text/csv; charset=utf-8",
".json": "application/json",
".xml": "application/xml",
}
// safeFilename keeps the base name, drops control and path characters, and
// bounds the length; "" when nothing usable is left.
func safeFilename(name string) string {
name = path.Base(strings.ReplaceAll(name, `\`, "/"))
name = strings.Map(func(r rune) rune {
if r < 0x20 || r == 0x7f || r == '/' || r == '"' {
return -1
}
return r
}, strings.TrimSpace(name))
if utf8.RuneCountInString(name) > 150 {
ext := path.Ext(name)
if utf8.RuneCountInString(ext) > 10 {
ext = ""
}
stem := []rune(strings.TrimSuffix(name, ext))
name = string(stem[:150-utf8.RuneCountInString(ext)]) + ext
}
if name == "." || name == ".." {
return ""
}
return name
}
func (s *Server) documentsReady(w http.ResponseWriter) bool {
if s.Objects == nil {
writeError(w, http.StatusServiceUnavailable, "documents_unavailable", "document storage is not configured")
return false
}
return true
}
// countingReader counts bytes and hashes them on the way to the bucket.
type countingReader struct {
r io.Reader
n int64
hash io.Writer
}
func (c *countingReader) Read(p []byte) (int, error) {
n, err := c.r.Read(p)
c.n += int64(n)
_, _ = c.hash.Write(p[:n])
return n, err
}
// adminUploadDocument is POST /v1/admin/tenants/{id}/documents, a
// multipart/form-data body with optional fields "title" and "description"
// before the "file" part. The file is streamed to the bucket, never buffered
// whole; the result is a draft.
func (s *Server) adminUploadDocument(w http.ResponseWriter, r *http.Request) {
if !s.documentsReady(w) {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*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
}
max := s.cfg().DocumentsMaxBytes
if max <= 0 {
max = 200 << 20
}
r.Body = http.MaxBytesReader(w, r.Body, max+1<<20) // + the multipart envelope
mr, err := r.MultipartReader()
if err != nil {
writeError(w, http.StatusBadRequest, "invalid_body", "expected multipart/form-data")
return
}
var title, description string
var own bool
var projectIDs []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
}
switch part.FormName() {
case "own_document":
b, _ := io.ReadAll(io.LimitReader(part, 16))
v := strings.ToLower(strings.TrimSpace(string(b)))
own = v == "on" || v == "true" || v == "1"
case "project_ids":
// Repeated fields or one comma-separated value.
b, _ := io.ReadAll(io.LimitReader(part, 8<<10))
for _, id := range strings.Split(string(b), ",") {
if id = strings.TrimSpace(id); id != "" {
projectIDs = append(projectIDs, id)
}
}
case "title", "description":
b, _ := io.ReadAll(io.LimitReader(part, 4<<10))
if part.FormName() == "title" {
title = strings.TrimSpace(string(b))
} else {
description = strings.TrimSpace(string(b))
}
case "file":
if doc != nil {
s.dropUpload(ctx, doc)
writeError(w, http.StatusBadRequest, "invalid_body", "one file per upload")
return
}
name := safeFilename(part.FileName())
ctype, ok := allowedDocumentTypes[strings.ToLower(path.Ext(name))]
if name == "" || !ok {
writeError(w, http.StatusUnsupportedMediaType, "unsupported_type", "allowed: pdf, zip, docx, xlsx, pptx, png, jpg, txt, csv, json, xml")
return
}
id := uuid.NewString()
key := "tenants/" + t.ID + "/" + id + "/" + name
h := sha256.New()
cr := &countingReader{r: part, hash: h}
if perr := s.Objects.Put(ctx, key, cr, -1, ctype); perr != nil {
_ = s.Objects.Delete(context.WithoutCancel(ctx), key)
var tooBig *http.MaxBytesError
if errors.As(perr, &tooBig) || cr.n > max {
writeError(w, http.StatusRequestEntityTooLarge, "too_large", "the file is larger than the upload limit")
return
}
s.Log.Error("document upload failed", "tenant_id", t.ID, "err", perr)
writeError(w, http.StatusBadGateway, "storage_failed", "the file could not be stored")
return
}
if cr.n > max {
_ = s.Objects.Delete(context.WithoutCancel(ctx), key)
writeError(w, http.StatusRequestEntityTooLarge, "too_large", "the file is larger than the upload limit")
return
}
doc = &store.Document{ID: id, TenantID: t.ID, Filename: name, ContentType: ctype, SizeBytes: cr.n,
SHA256: hex.EncodeToString(h.Sum(nil)), ObjectKey: key, Status: store.DocumentDraft}
default:
_, _ = io.Copy(io.Discard, io.LimitReader(part, 1<<20))
}
}
if doc == nil {
writeError(w, http.StatusBadRequest, "missing_file", "a file part named \"file\" is required")
return
}
if title == "" {
title = strings.TrimSuffix(doc.Filename, path.Ext(doc.Filename))
}
if utf8.RuneCountInString(title) > 200 || utf8.RuneCountInString(description) > 2000 {
s.dropUpload(ctx, doc)
writeError(w, http.StatusBadRequest, "invalid_input", "title ≤ 200 and description ≤ 2000 characters")
return
}
doc.Title, doc.Description = title, description
doc.OwnDocument, doc.ProjectIDs = own, projectIDs
if sub, email, ok := s.staffActor(r); ok {
doc.UploadedBy = firstNonEmpty(email, sub)
}
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: "document.uploaded", TargetID: created.ID, TargetType: "document", TargetName: created.Title,
ActorType: "service", Metadata: map[string]interface{}{"filename": created.Filename, "size_bytes": created.SizeBytes, "sha256": created.SHA256},
})
writeJSON(w, http.StatusCreated, created)
}
// dropUpload removes an object stored for an upload that did not complete.
func (s *Server) dropUpload(ctx context.Context, d *store.Document) {
if d != nil {
_ = s.Objects.Delete(context.WithoutCancel(ctx), d.ObjectKey)
}
}
func firstNonEmpty(v ...string) string {
for _, s := range v {
if s != "" {
return s
}
}
return ""
}
// adminListDocuments is GET /v1/admin/tenants/{id}/documents: drafts included.
func (s *Server) adminListDocuments(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
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
}
docs, err := s.Store.ListDocuments(ctx, t.ID, false)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"items": docs})
}
// adminPublishDocument is POST /v1/admin/documents/{doc}/publish. Publishing
// makes the document visible to the tenant; publishing twice is harmless.
func (s *Server) adminPublishDocument(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
d, err := s.Store.GetDocument(ctx, r.PathValue("doc"))
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
if d.Status == store.DocumentPublished {
writeJSON(w, http.StatusOK, d)
return
}
by := ""
if sub, email, ok := s.staffActor(r); ok {
by = firstNonEmpty(email, sub)
}
d, err = s.Store.PublishDocument(ctx, d.ID, by, s.now())
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: d.TenantID, Action: "document.published", TargetID: d.ID, TargetType: "document", TargetName: d.Title,
ActorType: "service",
})
// The tenant's own documents are kept here for them: they appear in the
// portal, but nobody is told "BreakPilot published a document".
if !d.OwnDocument {
s.documentPublished(ctx, d)
}
writeJSON(w, http.StatusOK, d)
}
type documentUpdateReq struct {
ProjectIDs *[]string `json:"project_ids"`
OwnDocument *bool `json:"own_document"`
}
// adminUpdateDocument is PATCH /v1/admin/documents/{doc}: staff assign a
// document to projects (replacing the set) and mark it as the tenant's own.
// Both work on drafts and published documents.
func (s *Server) adminUpdateDocument(w http.ResponseWriter, r *http.Request) {
var in documentUpdateReq
if !decodeJSON(w, r, &in) {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
d, err := s.Store.GetDocument(ctx, r.PathValue("doc"))
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
meta := map[string]interface{}{}
if in.OwnDocument != nil && *in.OwnDocument != d.OwnDocument {
if d, err = s.Store.SetDocumentOwn(ctx, d.ID, *in.OwnDocument); err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
meta["own_document"] = d.OwnDocument
}
if in.ProjectIDs != nil {
if d, err = s.Store.SetDocumentProjects(ctx, d.ID, *in.ProjectIDs); err != nil {
if errors.Is(err, store.ErrInvalidInput) {
writeError(w, http.StatusBadRequest, "invalid_projects", "every project must exist and belong to the document's tenant")
return
}
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
meta["project_ids"] = d.ProjectIDs
}
if len(meta) > 0 {
if sub, email, ok := s.staffActor(r); ok {
meta["by"] = firstNonEmpty(email, sub)
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: d.TenantID, Action: "document.updated", TargetID: d.ID, TargetType: "document", TargetName: d.Title,
ActorType: "service", Metadata: meta,
})
}
writeJSON(w, http.StatusOK, d)
}
// adminDeleteDocument is DELETE /v1/admin/documents/{doc}.
func (s *Server) adminDeleteDocument(w http.ResponseWriter, r *http.Request) {
if !s.documentsReady(w) {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
d, err := s.Store.GetDocument(ctx, r.PathValue("doc"))
if err != nil {
if mapStoreError(w, err) {
return
}
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
if err := s.Objects.Delete(ctx, d.ObjectKey); err != nil {
s.Log.Error("document object delete failed", "document_id", d.ID, "err", err)
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
}
s.emitAudit(ctx, r, store.AuditEvent{
TenantID: d.TenantID, Action: "document.deleted", TargetID: d.ID, TargetType: "document", TargetName: d.Title,
ActorType: "service",
})
w.WriteHeader(http.StatusNoContent)
}
// listTenantDocuments is GET /v1/tenants/{id}/documents: published only.
func (s *Server) listTenantDocuments(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
t, ok := s.tenantInScope(ctx, w, r)
if !ok {
return
}
docs, err := s.Store.ListDocuments(ctx, t.ID, true)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"items": docs})
}
// downloadTenantDocument is GET /v1/tenants/{id}/documents/{doc}/download:
// a presigned URL valid for five minutes, and an audit entry naming who
// downloaded it (the user token's subject, or the person the portal names in
// X-Portal-User-Email).
func (s *Server) downloadTenantDocument(w http.ResponseWriter, r *http.Request) {
if !s.documentsReady(w) {
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
t, ok := s.tenantInScope(ctx, w, r)
if !ok {
return
}
d, err := s.Store.GetDocument(ctx, r.PathValue("doc"))
if err != nil || d.TenantID != t.ID || d.Status != store.DocumentPublished {
writeError(w, http.StatusNotFound, "not_found", "resource does not exist")
return
}
u, err := s.Objects.PresignGet(ctx, d.ObjectKey, d.Filename, downloadTTL)
if err != nil {
s.Log.Error("presign failed", "document_id", d.ID, "err", err)
writeError(w, http.StatusBadGateway, "storage_failed", "no download link could be made")
return
}
ev := store.AuditEvent{TenantID: t.ID, Action: "document.downloaded", TargetID: d.ID, TargetType: "document", TargetName: d.Title}
if p, has := authn.PrincipalFrom(r.Context()); has {
ev.ActorID, ev.ActorName, ev.ActorType = p.Subject, p.Email, "service"
if p.IsUser() {
ev.ActorType = "user"
} else if email := strings.TrimSpace(r.Header.Get("X-Portal-User-Email")); email != "" {
ev.ActorName, ev.ActorType = email, "user"
}
}
s.emitAudit(ctx, r, ev)
writeJSON(w, http.StatusOK, map[string]any{
"url": u, "filename": d.Filename, "content_type": d.ContentType,
"expires_at": s.now().Add(downloadTTL),
})
}