Files
tenant-registry/internal/storage/storage.go
T
Sharang ParnerkarandClaude Opus 5.5 251cddf3d3
ci / shared (pull_request) Failing after 4s
ci / test (pull_request) Successful in 25m54s
ci / image (pull_request) Skipped
feat(store): Dokumentenablage — three areas, digest-checked serving, staff bundle import
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 <noreply@anthropic.com>
2026-10-20 15:07:57 +02:00

193 lines
6.2 KiB
Go

// Package storage keeps tenant documents in S3-compatible object storage
// (Hetzner Object Storage in production, MinIO locally). The registry never
// serves file bytes itself: uploads are streamed to the bucket, downloads are
// short-lived presigned URLs the browser follows.
package storage
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/url"
"strings"
"sync"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
// ErrNotConfigured is returned by a nil store: document routes answer 503.
var ErrNotConfigured = errors.New("storage: object storage not configured")
// Objects is what the document handlers need.
type Objects interface {
// Put streams r to key; size -1 means unknown (multipart upload).
Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
// 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
Region string // nbg1
Bucket string
AccessKey string
SecretKey string
}
// Configured reports whether every field needed for S3 is set.
func (c Config) Configured() bool {
return c.Endpoint != "" && c.Bucket != "" && c.AccessKey != "" && c.SecretKey != ""
}
// S3 is Objects on an S3-compatible bucket.
type S3 struct {
client *minio.Client
bucket string
}
// NewS3 connects and makes sure the bucket exists (created private, in the
// configured region: Hetzner refuses a CreateBucket without a matching
// location constraint).
func NewS3(ctx context.Context, cfg Config) (*S3, error) {
u, err := url.Parse(cfg.Endpoint)
if err != nil || u.Host == "" {
return nil, fmt.Errorf("storage: endpoint %q is not a URL", cfg.Endpoint)
}
client, err := minio.New(u.Host, &minio.Options{
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
Secure: u.Scheme != "http",
Region: cfg.Region,
})
if err != nil {
return nil, fmt.Errorf("storage: client: %w", err)
}
exists, err := client.BucketExists(ctx, cfg.Bucket)
if err != nil {
return nil, fmt.Errorf("storage: bucket %s: %w", cfg.Bucket, err)
}
if !exists {
if err := client.MakeBucket(ctx, cfg.Bucket, minio.MakeBucketOptions{Region: cfg.Region}); err != nil {
return nil, fmt.Errorf("storage: create bucket %s: %w", cfg.Bucket, err)
}
}
return &S3{client: client, bucket: cfg.Bucket}, nil
}
// uploadPartSize is the multipart chunk minio-go buffers in memory. Uploads
// are streamed with an unknown size, and minio-go then sizes a part for the
// largest possible object (5 TiB / 10000 parts, about 550 MiB) and allocates
// it up front: every upload killed the registry at its 384 MiB limit. 16 MiB
// parts cap the buffer and still allow objects far beyond the upload limit.
const uploadPartSize = 16 << 20
func putOptions(contentType string) minio.PutObjectOptions {
return minio.PutObjectOptions{ContentType: contentType, PartSize: uploadPartSize}
}
func (s *S3) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error {
_, err := s.client.PutObject(ctx, s.bucket, key, r, size, putOptions(contentType))
return err
}
func (s *S3) PresignGet(ctx context.Context, key, filename string, ttl time.Duration) (string, error) {
params := url.Values{}
params.Set("response-content-disposition", ContentDisposition(filename))
u, err := s.client.PresignedGetObject(ctx, s.bucket, key, ttl, params)
if err != nil {
return "", err
}
return u.String(), nil
}
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 {
ascii := strings.Map(func(r rune) rune {
if r < 0x20 || r > 0x7e || r == '"' || r == '\\' {
return '_'
}
return r
}, filename)
return fmt.Sprintf(`attachment; filename="%s"; filename*=UTF-8''%s`, ascii, url.PathEscape(filename))
}
// Memory is Objects in process memory, for tests and local development.
type Memory struct {
mu sync.Mutex
Objects map[string][]byte
Types map[string]string
FailPut error
}
func NewMemory() *Memory {
return &Memory{Objects: map[string][]byte{}, Types: map[string]string{}}
}
func (m *Memory) Put(_ context.Context, key string, r io.Reader, _ int64, contentType string) error {
if m.FailPut != nil {
return m.FailPut
}
b, err := io.ReadAll(r)
if err != nil {
return err
}
m.mu.Lock()
defer m.mu.Unlock()
m.Objects[key], m.Types[key] = b, contentType
return nil
}
func (m *Memory) PresignGet(_ context.Context, key, filename string, ttl time.Duration) (string, error) {
m.mu.Lock()
defer m.mu.Unlock()
if _, ok := m.Objects[key]; !ok {
return "", fmt.Errorf("storage: no object %s", key)
}
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()
delete(m.Objects, key)
delete(m.Types, key)
return nil
}