feat(documents): tenant documents in object storage #34
No files matched your search
+19
-1
@@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/storage"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -134,7 +135,24 @@ func main() {
|
||||
slog.Warn("LITELLM_MASTER_KEY not set — Werkpilot licences are issued without a LiteLLM key")
|
||||
}
|
||||
|
||||
app := &server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv, ERP: erpClient, Licences: signer, LLMKeys: llmKeys}
|
||||
var objects storage.Objects
|
||||
docCfg := storage.Config{Endpoint: cfg.DocumentsS3Endpoint, Region: cfg.DocumentsS3Region, Bucket: cfg.DocumentsS3Bucket,
|
||||
AccessKey: cfg.DocumentsS3AccessKey, SecretKey: cfg.DocumentsS3SecretKey}
|
||||
if docCfg.Configured() {
|
||||
sctx, scancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
s3, serr := storage.NewS3(sctx, docCfg)
|
||||
scancel()
|
||||
if serr != nil {
|
||||
// Documents are one feature; the registry keeps serving everything else.
|
||||
logger.Error("document storage unavailable; document routes answer 503", "err", serr)
|
||||
} else {
|
||||
objects = s3
|
||||
logger.Info("document storage ready", "bucket", docCfg.Bucket)
|
||||
}
|
||||
} else {
|
||||
logger.Warn("DOCUMENTS_S3_* not set; document routes answer 503")
|
||||
}
|
||||
app := &server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv, ERP: erpClient, Licences: signer, LLMKeys: llmKeys, Objects: objects}
|
||||
handler := server.NewRouter(app)
|
||||
srv := &http.Server{
|
||||
Addr: cfg.Addr,
|
||||
|
||||
@@ -10,6 +10,7 @@ require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgerrcode v0.0.0-20250907135507-afb5586c32a6
|
||||
github.com/jackc/pgx/v5 v5.9.2
|
||||
github.com/minio/minio-go/v7 v7.0.95
|
||||
github.com/testcontainers/testcontainers-go/modules/postgres v0.42.0
|
||||
golang.org/x/crypto v0.55.0
|
||||
)
|
||||
@@ -29,21 +30,27 @@ require (
|
||||
github.com/distribution/reference v0.6.0 // indirect
|
||||
github.com/docker/go-connections v0.6.0 // indirect
|
||||
github.com/docker/go-units v0.5.0 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/ebitengine/purego v0.10.0 // indirect
|
||||
github.com/felixge/httpsnoop v1.0.4 // indirect
|
||||
github.com/go-ini/ini v1.67.0 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-ole/go-ole v1.2.6 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.22.5 // indirect
|
||||
github.com/go-openapi/swag/jsonname v0.25.5 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/gorilla/mux v1.8.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/klauspost/compress v1.18.7 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.11 // indirect
|
||||
github.com/lib/pq v1.10.9 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
|
||||
github.com/magiconair/properties v1.8.10 // indirect
|
||||
github.com/minio/crc64nvme v1.0.2 // indirect
|
||||
github.com/minio/md5-simd v1.1.2 // indirect
|
||||
github.com/moby/docker-image-spec v1.3.1 // indirect
|
||||
github.com/moby/go-archive v0.3.0 // indirect
|
||||
github.com/moby/moby/api v1.54.1 // indirect
|
||||
@@ -57,13 +64,16 @@ require (
|
||||
github.com/oasdiff/yaml3 v0.0.14 // indirect
|
||||
github.com/opencontainers/go-digest v1.0.0 // indirect
|
||||
github.com/opencontainers/image-spec v1.1.1 // indirect
|
||||
github.com/philhofer/fwd v1.2.0 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
|
||||
github.com/rs/xid v1.6.0 // indirect
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect
|
||||
github.com/shirou/gopsutil/v4 v4.26.3 // indirect
|
||||
github.com/sirupsen/logrus v1.9.4 // indirect
|
||||
github.com/stretchr/testify v1.11.1 // indirect
|
||||
github.com/testcontainers/testcontainers-go v0.42.0 // indirect
|
||||
github.com/tinylib/msgp v1.3.0 // indirect
|
||||
github.com/tklauser/go-sysconf v0.3.16 // indirect
|
||||
github.com/tklauser/numcpus v0.11.0 // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
@@ -72,6 +82,7 @@ require (
|
||||
go.opentelemetry.io/otel v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.41.0 // indirect
|
||||
golang.org/x/net v0.57.0 // indirect
|
||||
golang.org/x/oauth2 v0.36.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
|
||||
@@ -39,12 +39,16 @@ github.com/docker/go-connections v0.6.0 h1:LlMG9azAe1TqfR7sO+NJttz1gy6KO7VJBh+pM
|
||||
github.com/docker/go-connections v0.6.0/go.mod h1:AahvXYshr6JgfUJGdDCs2b5EZG/vmaMAntpSFH5BFKE=
|
||||
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=
|
||||
github.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/getkin/kin-openapi v0.144.0 h1:hIRcTH+KjLfkLpYU6bSSfdFpi0fZi1fp+hSPi4aQu9Y=
|
||||
github.com/getkin/kin-openapi v0.144.0/go.mod h1:3BH9M9XDe/y9M5DSvEocVYAYq1w0qrhJHjC/vZi0AaY=
|
||||
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
|
||||
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
@@ -60,6 +64,8 @@ github.com/go-openapi/swag/jsonname v0.25.5 h1:8p150i44rv/Drip4vWI3kGi9+4W9TdI3U
|
||||
github.com/go-openapi/swag/jsonname v0.25.5/go.mod h1:jNqqikyiAK56uS7n8sLkdaNY/uq6+D2m2LANat09pKU=
|
||||
github.com/go-openapi/testify/v2 v2.4.0 h1:8nsPrHVCWkQ4p8h1EsRVymA2XABB4OT40gcvAu+voFM=
|
||||
github.com/go-openapi/testify/v2 v2.4.0/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/golang-migrate/migrate/v4 v4.19.1 h1:OCyb44lFuQfYXYLx1SCxPZQGU7mcaZ7gH9yH4jSFbBA=
|
||||
@@ -83,6 +89,9 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw=
|
||||
github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.11 h1:0OwqZRYI2rFrjS4kvkDnqJkKHdHaRnCm68/DY4OxRzU=
|
||||
github.com/klauspost/cpuid/v2 v2.2.11/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
@@ -95,6 +104,12 @@ github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8S
|
||||
github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/mdelapenya/tlscert v0.2.0 h1:7H81W6Z/4weDvZBNOfQte5GpIMo0lGYEeWbkGp5LJHI=
|
||||
github.com/mdelapenya/tlscert v0.2.0/go.mod h1:O4njj3ELLnJjGdkN7M/vIVCpZ+Cf0L6muqOG4tLSl8o=
|
||||
github.com/minio/crc64nvme v1.0.2 h1:6uO1UxGAD+kwqWWp7mBFsi5gAse66C4NXO8cmcVculg=
|
||||
github.com/minio/crc64nvme v1.0.2/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg=
|
||||
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
|
||||
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
|
||||
github.com/minio/minio-go/v7 v7.0.95 h1:ywOUPg+PebTMTzn9VDsoFJy32ZuARN9zhB+K3IYEvYU=
|
||||
github.com/minio/minio-go/v7 v7.0.95/go.mod h1:wOOX3uxS334vImCNRVyIDdXX9OsXDm89ToynKgqUKlo=
|
||||
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
||||
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
||||
github.com/moby/go-archive v0.3.0 h1:nos4BtzzUIqB406BgQnWGMI4qib9BZ8XUHU+ucv/n1c=
|
||||
@@ -123,6 +138,8 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
|
||||
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
|
||||
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
|
||||
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
@@ -132,6 +149,8 @@ github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ=
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
|
||||
github.com/shirou/gopsutil/v4 v4.26.3 h1:2ESdQt90yU3oXF/CdOlRCJxrP+Am1aBYubTMTfxJ1qc=
|
||||
@@ -149,6 +168,8 @@ github.com/testcontainers/testcontainers-go v0.42.0 h1:He3IhTzTZOygSXLJPMX7n44Xt
|
||||
github.com/testcontainers/testcontainers-go v0.42.0/go.mod h1:vZjdY1YmUA1qEForxOIOazfsrdyORJAbhi0bp8plN30=
|
||||
github.com/testcontainers/testcontainers-go/modules/postgres v0.42.0 h1:GCbb1ndrF7OTDiIvxXyItaDab4qkzTFJ48LKFdM7EIo=
|
||||
github.com/testcontainers/testcontainers-go/modules/postgres v0.42.0/go.mod h1:IRPBaI8jXdrNfD0e4Zm7Fbcgaz5shKxOQv4axiL09xs=
|
||||
github.com/tinylib/msgp v1.3.0 h1:ULuf7GPooDaIlbyvgAxBV/FI7ynli6LZ1/nVUNu+0ww=
|
||||
github.com/tinylib/msgp v1.3.0/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0=
|
||||
github.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA=
|
||||
github.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI=
|
||||
github.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw=
|
||||
@@ -171,6 +192,8 @@ go.opentelemetry.io/otel/trace v1.41.0 h1:Vbk2co6bhj8L59ZJ6/xFTskY+tGAbOnCtQGVVa
|
||||
go.opentelemetry.io/otel/trace v1.41.0/go.mod h1:U1NU4ULCoxeDKc09yCWdWe+3QoyweJcISEVa1RBzOis=
|
||||
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
|
||||
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
|
||||
@@ -67,6 +67,15 @@ type Config struct {
|
||||
|
||||
// LiteLLM virtual keys for Werkpilot licences (D6). Empty master key ⇒
|
||||
// feature off, grants carry no LLM key. Budgets are USD per 30 days.
|
||||
// Tenant documents (F2): S3-compatible bucket. Unset ⇒ document routes 503.
|
||||
DocumentsS3Endpoint string
|
||||
DocumentsS3Region string
|
||||
DocumentsS3Bucket string
|
||||
DocumentsS3AccessKey string
|
||||
DocumentsS3SecretKey string
|
||||
// DocumentsMaxBytes caps one upload (default 200 MiB).
|
||||
DocumentsMaxBytes int64
|
||||
|
||||
LiteLLMBaseURL string
|
||||
LiteLLMMasterKey string
|
||||
LiteLLMModels []string
|
||||
@@ -118,6 +127,13 @@ func Load() (*Config, error) {
|
||||
LicenceIssuer: getenv("LICENCE_ISSUER", "tenant-registry"),
|
||||
LicenceTTLDays: getint("LICENCE_TTL_DAYS", 30),
|
||||
|
||||
DocumentsS3Endpoint: os.Getenv("DOCUMENTS_S3_ENDPOINT"),
|
||||
DocumentsS3Region: getenv("DOCUMENTS_S3_REGION", "nbg1"),
|
||||
DocumentsS3Bucket: os.Getenv("DOCUMENTS_S3_BUCKET"),
|
||||
DocumentsS3AccessKey: os.Getenv("DOCUMENTS_S3_ACCESS_KEY"),
|
||||
DocumentsS3SecretKey: os.Getenv("DOCUMENTS_S3_SECRET_KEY"),
|
||||
DocumentsMaxBytes: int64(getint("DOCUMENTS_MAX_MB", 200)) << 20,
|
||||
|
||||
LiteLLMBaseURL: getenv("LITELLM_BASE_URL", "https://llm.breakpilot.com"),
|
||||
LiteLLMMasterKey: os.Getenv("LITELLM_MASTER_KEY"),
|
||||
LiteLLMModels: getlist("LITELLM_MODELS", []string{"Qwen3-Coder-30B-A3B-Instruct", "gpt-oss-120b", "Qwen3.8-27B"}),
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
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 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 "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
|
||||
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",
|
||||
})
|
||||
s.documentPublished(ctx, d)
|
||||
writeJSON(w, http.StatusOK, d)
|
||||
}
|
||||
|
||||
// documentPublished is where F3 hangs the tenant notification.
|
||||
func (s *Server) documentPublished(_ context.Context, _ *store.Document) {}
|
||||
|
||||
// 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
|
||||
}
|
||||
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),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package server_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/storage"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
||||
)
|
||||
|
||||
func upload(t *testing.T, h *testHarness, tenantID string, fields map[string]string, filename, content string) (*http.Response, []byte) {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
for _, k := range []string{"title", "description"} {
|
||||
if v, ok := fields[k]; ok {
|
||||
_ = mw.WriteField(k, v)
|
||||
}
|
||||
}
|
||||
if filename != "" {
|
||||
fw, _ := mw.CreateFormFile("file", filename)
|
||||
_, _ = io.WriteString(fw, content)
|
||||
}
|
||||
_ = mw.Close()
|
||||
req, _ := http.NewRequest("POST", h.srv.URL+"/v1/admin/tenants/"+tenantID+"/documents", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
return resp, raw
|
||||
}
|
||||
|
||||
func TestDocuments_uploadPublishDownloadDelete(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
objs := storage.NewMemory()
|
||||
h.app.Objects = objs
|
||||
content := "%PDF-1.7 conformity"
|
||||
|
||||
resp, raw := upload(t, h, h.tenant.ID, map[string]string{"title": "CRA-Dossier", "description": "Q3"}, "../../Prüfbericht.pdf", content)
|
||||
if resp.StatusCode != 201 {
|
||||
t.Fatalf("upload: %d %s", resp.StatusCode, raw)
|
||||
}
|
||||
var d store.Document
|
||||
_ = json.Unmarshal(raw, &d)
|
||||
sum := sha256.Sum256([]byte(content))
|
||||
if d.Status != "draft" || d.Filename != "Prüfbericht.pdf" || d.SizeBytes != int64(len(content)) || d.SHA256 != hex.EncodeToString(sum[:]) || d.ContentType != "application/pdf" {
|
||||
t.Fatalf("stored: %+v", d)
|
||||
}
|
||||
if len(objs.Objects) != 1 || strings.Contains(string(raw), "object_key") {
|
||||
t.Fatalf("object not stored or key leaked: %d %s", len(objs.Objects), raw)
|
||||
}
|
||||
|
||||
// drafts are invisible to the tenant
|
||||
_, raw = h.do("GET", "/v1/tenants/"+h.tenant.ID+"/documents", nil)
|
||||
if !strings.Contains(string(raw), `"items":[]`) {
|
||||
t.Fatalf("draft visible: %s", raw)
|
||||
}
|
||||
if resp, _ := h.do("GET", "/v1/tenants/"+h.tenant.ID+"/documents/"+d.ID+"/download", nil); resp.StatusCode != 404 {
|
||||
t.Fatalf("draft downloadable: %d", resp.StatusCode)
|
||||
}
|
||||
// staff see it
|
||||
_, raw = h.do("GET", "/v1/admin/tenants/"+h.tenant.ID+"/documents", nil)
|
||||
if !strings.Contains(string(raw), d.ID) {
|
||||
t.Fatalf("admin list: %s", raw)
|
||||
}
|
||||
|
||||
resp, raw = h.do("POST", "/v1/admin/documents/"+d.ID+"/publish", nil)
|
||||
if resp.StatusCode != 200 || !strings.Contains(string(raw), `"status":"published"`) {
|
||||
t.Fatalf("publish: %d %s", resp.StatusCode, raw)
|
||||
}
|
||||
if resp, _ := h.do("POST", "/v1/admin/documents/"+d.ID+"/publish", nil); resp.StatusCode != 200 {
|
||||
t.Fatalf("publish twice: %d", resp.StatusCode)
|
||||
}
|
||||
_, raw = h.do("GET", "/v1/tenants/"+h.tenant.ID+"/documents", nil)
|
||||
if !strings.Contains(string(raw), d.ID) {
|
||||
t.Fatalf("published not listed: %s", raw)
|
||||
}
|
||||
resp, raw = h.do("GET", "/v1/tenants/"+h.tenant.ID+"/documents/"+d.ID+"/download", nil)
|
||||
if resp.StatusCode != 200 || !strings.Contains(string(raw), `"url":"memory://`) || !strings.Contains(string(raw), "Pr%C3%BCfbericht.pdf") {
|
||||
t.Fatalf("download: %d %s", resp.StatusCode, raw)
|
||||
}
|
||||
// another tenant cannot reach it
|
||||
other := newTenant(t, h, "other-docs")
|
||||
if resp, _ := h.do("GET", "/v1/tenants/"+other.ID+"/documents/"+d.ID+"/download", nil); resp.StatusCode != 404 {
|
||||
t.Fatalf("cross-tenant download: %d", resp.StatusCode)
|
||||
}
|
||||
items, _, _ := h.store.ListAudit(context.Background(), store.AuditFilter{TenantID: h.tenant.ID})
|
||||
seen := map[string]bool{}
|
||||
for _, a := range items {
|
||||
seen[a.Action] = true
|
||||
}
|
||||
for _, a := range []string{"document.uploaded", "document.published", "document.downloaded"} {
|
||||
if !seen[a] {
|
||||
t.Fatalf("audit %s missing: %v", a, seen)
|
||||
}
|
||||
}
|
||||
|
||||
if resp, _ := h.do("DELETE", "/v1/admin/documents/"+d.ID, nil); resp.StatusCode != 204 {
|
||||
t.Fatalf("delete: %d", resp.StatusCode)
|
||||
}
|
||||
if len(objs.Objects) != 0 {
|
||||
t.Fatal("object not deleted")
|
||||
}
|
||||
if resp, _ := h.do("DELETE", "/v1/admin/documents/"+d.ID, nil); resp.StatusCode != 404 {
|
||||
t.Fatalf("delete twice: %d", resp.StatusCode)
|
||||
}
|
||||
if resp, _ := h.do("POST", "/v1/admin/documents/not-a-uuid/publish", nil); resp.StatusCode != 404 {
|
||||
t.Fatalf("publish unknown: %d", resp.StatusCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestDocuments_uploadRules(t *testing.T) {
|
||||
eachStore(t, func(t *testing.T, h *testHarness) {
|
||||
objs := storage.NewMemory()
|
||||
h.app.Objects = objs
|
||||
|
||||
if resp, _ := upload(t, h, h.tenant.ID, nil, "tool.exe", "MZ"); resp.StatusCode != 415 {
|
||||
t.Fatalf("exe: %d", resp.StatusCode)
|
||||
}
|
||||
if resp, _ := upload(t, h, h.tenant.ID, map[string]string{"title": "x"}, "", ""); resp.StatusCode != 400 {
|
||||
t.Fatalf("no file: %d", resp.StatusCode)
|
||||
}
|
||||
// the title defaults to the file name without extension
|
||||
resp, raw := upload(t, h, h.tenant.ID, nil, "Risikobewertung.docx", "PK")
|
||||
if resp.StatusCode != 201 || !strings.Contains(string(raw), `"title":"Risikobewertung"`) {
|
||||
t.Fatalf("default title: %d %s", resp.StatusCode, raw)
|
||||
}
|
||||
if resp, _ := upload(t, h, h.tenant.ID, map[string]string{"title": strings.Repeat("x", 201)}, "a.pdf", "x"); resp.StatusCode != 400 {
|
||||
t.Fatalf("long title: %d", resp.StatusCode)
|
||||
}
|
||||
if len(objs.Objects) != 1 {
|
||||
t.Fatalf("rejected upload left an object: %d", len(objs.Objects))
|
||||
}
|
||||
// over the size limit
|
||||
h.app.Cfg.DocumentsMaxBytes = 4
|
||||
if resp, _ := upload(t, h, h.tenant.ID, nil, "big.pdf", "123456789"); resp.StatusCode != 413 {
|
||||
t.Fatalf("too large: %d", resp.StatusCode)
|
||||
}
|
||||
h.app.Cfg.DocumentsMaxBytes = 0
|
||||
// storage failure
|
||||
objs.FailPut = errors.New("down")
|
||||
if resp, _ := upload(t, h, h.tenant.ID, nil, "a.pdf", "x"); resp.StatusCode != 502 {
|
||||
t.Fatalf("storage down: %d", resp.StatusCode)
|
||||
}
|
||||
objs.FailPut = nil
|
||||
if resp, _ := upload(t, h, "00000000-0000-0000-0000-00000000dead", nil, "a.pdf", "x"); resp.StatusCode != 404 {
|
||||
t.Fatalf("unknown tenant: %d", resp.StatusCode)
|
||||
}
|
||||
req, _ := http.NewRequest("POST", h.srv.URL+"/v1/admin/tenants/"+h.tenant.ID+"/documents", strings.NewReader("{}"))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if resp, err := http.DefaultClient.Do(req); err != nil || resp.StatusCode != 400 {
|
||||
t.Fatalf("not multipart: %v %v", resp, err)
|
||||
}
|
||||
|
||||
// not configured
|
||||
h.app.Objects = nil
|
||||
if resp, _ := upload(t, h, h.tenant.ID, nil, "a.pdf", "x"); resp.StatusCode != 503 {
|
||||
t.Fatalf("unconfigured: %d", resp.StatusCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -73,11 +73,14 @@ func (s *Server) tenantInScope(ctx context.Context, w http.ResponseWriter, r *ht
|
||||
// collection exists; anything else is a 404 rather than a route that silently
|
||||
// swallowed a typo.
|
||||
func (s *Server) tenantSubresource(w http.ResponseWriter, r *http.Request) {
|
||||
if r.PathValue("sub") != "members" {
|
||||
switch r.PathValue("sub") {
|
||||
case "members":
|
||||
s.listTenantMembers(w, r)
|
||||
case "documents":
|
||||
s.listTenantDocuments(w, r)
|
||||
default:
|
||||
writeError(w, http.StatusNotFound, "not_found", "no such tenant sub-resource")
|
||||
return
|
||||
}
|
||||
s.listTenantMembers(w, r)
|
||||
}
|
||||
|
||||
func (s *Server) listTenantMembers(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -53,6 +53,10 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) {
|
||||
{"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/trial"},
|
||||
{"POST", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/invites/resend"},
|
||||
{"GET", "/v1/admin/audit?limit=10"},
|
||||
{"GET", "/v1/admin/tenants/00000000-0000-0000-0000-000000000001/documents"},
|
||||
{"POST", "/v1/admin/documents/00000000-0000-0000-0000-000000000002/publish"},
|
||||
{"DELETE", "/v1/admin/documents/00000000-0000-0000-0000-000000000002"},
|
||||
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/documents/00000000-0000-0000-0000-000000000002/download"},
|
||||
{"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/status"},
|
||||
{"POST", "/v1/internal/entitlements/check"},
|
||||
{"POST", "/v1/internal/erp/webhook"},
|
||||
|
||||
@@ -6,6 +6,7 @@ package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"git.breakpilot.com/platform/tenant-registry/internal/storage"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
@@ -34,6 +35,7 @@ type Server struct {
|
||||
ERP *erp.Client // nil / disabled ⇒ outbox accumulates, reconcile idle
|
||||
Licences *licence.Signer // nil ⇒ licence endpoints return 503
|
||||
LLMKeys *llmkeys.Client // nil / disabled ⇒ Werkpilot grants carry no LiteLLM key (D6)
|
||||
Objects storage.Objects // nil ⇒ document routes answer 503 (F2)
|
||||
Now func() time.Time // injectable clock (tests); nil ⇒ time.Now
|
||||
}
|
||||
|
||||
@@ -150,6 +152,13 @@ func NewRouter(s *Server) http.Handler {
|
||||
mux.HandleFunc("POST /v1/admin/tenants/{id}/trial", s.adminExtendTrial)
|
||||
mux.HandleFunc("POST /v1/admin/tenants/{id}/invites/resend", s.adminResendInvite)
|
||||
mux.HandleFunc("GET /v1/admin/audit", s.listAudit)
|
||||
mux.HandleFunc("GET /v1/admin/tenants/{id}/documents", s.adminListDocuments)
|
||||
mux.HandleFunc("POST /v1/admin/tenants/{id}/documents", s.adminUploadDocument)
|
||||
mux.HandleFunc("POST /v1/admin/documents/{doc}/publish", s.adminPublishDocument)
|
||||
mux.HandleFunc("DELETE /v1/admin/documents/{doc}", s.adminDeleteDocument)
|
||||
|
||||
// Tenant documents (F2): the list is a {sub} of tenantSubresource.
|
||||
mux.HandleFunc("GET /v1/tenants/{id}/documents/{doc}/download", s.downloadTenantDocument)
|
||||
|
||||
root.Handle("/", s.requireAuth(s.requireAuthz(mux)))
|
||||
return logRequest(s.Log)(root)
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
// 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 (
|
||||
"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
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
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, minio.PutObjectOptions{ContentType: 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{})
|
||||
}
|
||||
|
||||
// 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) Delete(_ context.Context, key string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.Objects, key)
|
||||
delete(m.Types, key)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestContentDisposition(t *testing.T) {
|
||||
got := ContentDisposition(`Prüfbericht "Q3".pdf`)
|
||||
want := `attachment; filename="Pr_fbericht _Q3_.pdf"; filename*=UTF-8''Pr%C3%BCfbericht%20%22Q3%22.pdf`
|
||||
if got != want {
|
||||
t.Fatalf("got %s\nwant %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigured(t *testing.T) {
|
||||
if (Config{}).Configured() {
|
||||
t.Fatal("empty config is configured")
|
||||
}
|
||||
if !(Config{Endpoint: "https://x", Bucket: "b", AccessKey: "a", SecretKey: "s"}).Configured() {
|
||||
t.Fatal("full config not configured")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewS3_rejectsBadEndpoint(t *testing.T) {
|
||||
if _, err := NewS3(context.Background(), Config{Endpoint: "::nope", Bucket: "b", AccessKey: "a", SecretKey: "s"}); err == nil {
|
||||
t.Fatal("bad endpoint accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemory(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
m := NewMemory()
|
||||
if err := m.Put(ctx, "k", strings.NewReader("hello"), -1, "text/plain"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(m.Objects["k"]) != "hello" || m.Types["k"] != "text/plain" {
|
||||
t.Fatalf("stored %q %q", m.Objects["k"], m.Types["k"])
|
||||
}
|
||||
u, err := m.PresignGet(ctx, "k", "a b.pdf", time.Minute)
|
||||
if err != nil || !strings.Contains(u, "filename=a+b.pdf") {
|
||||
t.Fatalf("presign %q %v", u, err)
|
||||
}
|
||||
if _, err := m.PresignGet(ctx, "missing", "x", time.Minute); err == nil {
|
||||
t.Fatal("presign of a missing object")
|
||||
}
|
||||
if err := m.Delete(ctx, "k"); err != nil || len(m.Objects) != 0 {
|
||||
t.Fatalf("delete %v", err)
|
||||
}
|
||||
m.FailPut = errors.New("boom")
|
||||
if err := m.Put(ctx, "k", strings.NewReader("x"), 1, ""); err == nil {
|
||||
t.Fatal("FailPut ignored")
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,8 @@ type Memory struct {
|
||||
outboxID int64
|
||||
receipts map[string]time.Time
|
||||
licences map[string]*Licence
|
||||
|
||||
documents map[string]*Document
|
||||
}
|
||||
|
||||
type apiKeyWithHash struct {
|
||||
@@ -53,6 +55,8 @@ func NewMemory() *Memory {
|
||||
usageKey: make(map[string]int64),
|
||||
receipts: make(map[string]time.Time),
|
||||
licences: make(map[string]*Licence),
|
||||
|
||||
documents: make(map[string]*Document),
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
seed := &Tenant{
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (m *Memory) CreateDocument(_ context.Context, d Document) (*Document, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if d.ID == "" || d.ObjectKey == "" || d.Title == "" {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if _, ok := m.tenants[d.TenantID]; !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
for _, x := range m.documents {
|
||||
if x.ID == d.ID || x.ObjectKey == d.ObjectKey {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
if d.Status == "" {
|
||||
d.Status = DocumentDraft
|
||||
}
|
||||
d.CreatedAt, d.UpdatedAt = now, now
|
||||
row := d
|
||||
m.documents[d.ID] = &row
|
||||
out := row
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func (m *Memory) GetDocument(_ context.Context, id string) (*Document, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
d, ok := m.documents[id]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
out := *d
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func (m *Memory) ListDocuments(_ context.Context, tenantID string, publishedOnly bool) ([]Document, error) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
out := []Document{}
|
||||
for _, d := range m.documents {
|
||||
if d.TenantID != tenantID || (publishedOnly && d.Status != DocumentPublished) {
|
||||
continue
|
||||
}
|
||||
out = append(out, *d)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].CreatedAt.Equal(out[j].CreatedAt) {
|
||||
return out[i].ID > out[j].ID
|
||||
}
|
||||
return out[i].CreatedAt.After(out[j].CreatedAt)
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m *Memory) PublishDocument(_ context.Context, id, by string, at time.Time) (*Document, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
d, ok := m.documents[id]
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if d.Status != DocumentPublished {
|
||||
at = at.UTC()
|
||||
d.Status, d.PublishedBy, d.PublishedAt, d.UpdatedAt = DocumentPublished, by, &at, at
|
||||
}
|
||||
out := *d
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func (m *Memory) DeleteDocument(_ context.Context, id string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if _, ok := m.documents[id]; !ok {
|
||||
return ErrNotFound
|
||||
}
|
||||
delete(m.documents, id)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
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
|
||||
FROM documents `
|
||||
|
||||
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); err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &d, nil
|
||||
}
|
||||
|
||||
func (p *Postgres) CreateDocument(ctx context.Context, d Document) (*Document, error) {
|
||||
if d.ID == "" || d.ObjectKey == "" || d.Title == "" {
|
||||
return nil, ErrInvalidInput
|
||||
}
|
||||
if d.Status == "" {
|
||||
d.Status = DocumentDraft
|
||||
}
|
||||
_, err := p.pool.Exec(ctx, `
|
||||
INSERT INTO documents (id, tenant_id, title, description, filename, content_type, size_bytes, sha256, object_key, status, uploaded_by)
|
||||
VALUES ($1::uuid, $2::uuid, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
|
||||
d.ID, d.TenantID, d.Title, d.Description, d.Filename, d.ContentType, d.SizeBytes, d.SHA256, d.ObjectKey, d.Status, d.UploadedBy)
|
||||
switch {
|
||||
case err == nil:
|
||||
return p.GetDocument(ctx, d.ID)
|
||||
case isFKViolation(err), isInvalidUUID(err):
|
||||
return nil, ErrNotFound
|
||||
case isUniqueViolation(err):
|
||||
return nil, ErrConflict
|
||||
case isCheckViolation(err):
|
||||
return nil, ErrInvalidInput
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Postgres) GetDocument(ctx context.Context, id string) (*Document, error) {
|
||||
d, err := scanDocument(p.pool.QueryRow(ctx, documentSelect+`WHERE id = $1::uuid`, id))
|
||||
if isInvalidUUID(err) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return d, err
|
||||
}
|
||||
|
||||
func (p *Postgres) ListDocuments(ctx context.Context, tenantID string, publishedOnly bool) ([]Document, error) {
|
||||
q := documentSelect + `WHERE tenant_id = $1::uuid`
|
||||
if publishedOnly {
|
||||
q += ` AND status = 'published'`
|
||||
}
|
||||
rows, err := p.pool.Query(ctx, q+` ORDER BY created_at DESC, id DESC`, tenantID)
|
||||
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) PublishDocument(ctx context.Context, id, by string, at time.Time) (*Document, error) {
|
||||
// An already published document is returned unchanged.
|
||||
_, err := p.pool.Exec(ctx, `
|
||||
UPDATE documents SET status = 'published', published_by = $2, published_at = $3, updated_at = $3
|
||||
WHERE id = $1::uuid AND status <> 'published'`, id, by, at.UTC())
|
||||
if isInvalidUUID(err) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return p.GetDocument(ctx, id)
|
||||
}
|
||||
|
||||
func (p *Postgres) DeleteDocument(ctx context.Context, id string) error {
|
||||
tag, err := p.pool.Exec(ctx, `DELETE FROM documents WHERE id = $1::uuid`, id)
|
||||
if isInvalidUUID(err) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -127,6 +127,14 @@ type Store interface {
|
||||
// SetLicenceLLMKey records (or clears, with "") the LiteLLM key id.
|
||||
SetLicenceLLMKey(ctx context.Context, id string, keyID string) error
|
||||
|
||||
// Documents (0008). ID and ObjectKey are chosen by the caller (the object
|
||||
// is stored before the row). ListDocuments with publishedOnly hides drafts.
|
||||
CreateDocument(ctx context.Context, d Document) (*Document, error)
|
||||
GetDocument(ctx context.Context, id string) (*Document, error)
|
||||
ListDocuments(ctx context.Context, tenantID string, publishedOnly bool) ([]Document, error)
|
||||
PublishDocument(ctx context.Context, id, by string, at time.Time) (*Document, error)
|
||||
DeleteDocument(ctx context.Context, id string) error
|
||||
|
||||
// Lifecycle
|
||||
Close()
|
||||
Ping(ctx context.Context) error
|
||||
|
||||
@@ -245,3 +245,28 @@ type Licence struct {
|
||||
// Werkpilot licence (D6); the handle for /key/delete. Never the secret.
|
||||
LLMKeyID string `json:"llm_key_id,omitempty"`
|
||||
}
|
||||
|
||||
// Document — a file BreakPilot hands to a tenant (migration 0008). Staff
|
||||
// upload it as a draft; tenants see it once it is published.
|
||||
type Document struct {
|
||||
ID string `json:"id"`
|
||||
TenantID string `json:"tenant_id"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
ObjectKey string `json:"-"`
|
||||
Status string `json:"status"` // draft | published
|
||||
UploadedBy string `json:"uploaded_by,omitempty"`
|
||||
PublishedBy string `json:"published_by,omitempty"`
|
||||
PublishedAt *time.Time `json:"published_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
const (
|
||||
DocumentDraft = "draft"
|
||||
DocumentPublished = "published"
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS documents;
|
||||
@@ -0,0 +1,23 @@
|
||||
-- F2 (go-live 2026-09): documents BreakPilot hands to a tenant (conformity
|
||||
-- documents, reports) until breakpilot-compliance delivers them itself. Staff
|
||||
-- upload a draft, publish it, and only then does the tenant see it. The file
|
||||
-- lives in object storage under object_key; this row is its index.
|
||||
CREATE TABLE documents (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
|
||||
title TEXT NOT NULL CHECK (char_length(title) BETWEEN 1 AND 200),
|
||||
description TEXT NOT NULL DEFAULT '' CHECK (char_length(description) <= 2000),
|
||||
filename TEXT NOT NULL,
|
||||
content_type TEXT NOT NULL,
|
||||
size_bytes BIGINT NOT NULL CHECK (size_bytes >= 0),
|
||||
sha256 TEXT NOT NULL,
|
||||
object_key TEXT NOT NULL UNIQUE,
|
||||
status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'published')),
|
||||
uploaded_by TEXT NOT NULL DEFAULT '',
|
||||
published_by TEXT,
|
||||
published_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX documents_tenant_created ON documents (tenant_id, created_at DESC);
|
||||
@@ -114,8 +114,8 @@ func TestMigrate_upDownRoundTrip(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Column assertions for later migrations (0007: licences.llm_key_id).
|
||||
for _, c := range [][2]string{{"licences", "llm_key_id"}} {
|
||||
// Column assertions for later migrations (0007: licences.llm_key_id; 0008: documents).
|
||||
for _, c := range [][2]string{{"licences", "llm_key_id"}, {"documents", "object_key"}, {"documents", "published_at"}} {
|
||||
var exists bool
|
||||
err := db.QueryRow(
|
||||
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema='public' AND table_name=$1 AND column_name=$2)",
|
||||
|
||||
+117
@@ -206,6 +206,20 @@ paths:
|
||||
application/json: { schema: { $ref: "#/components/schemas/Tenant" } }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/tenants/{id}/documents:
|
||||
get:
|
||||
summary: A tenant's published documents.
|
||||
description: Served by the same `{id}/{sub}` route as members; user tokens reach their own tenant only.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
responses:
|
||||
"200":
|
||||
description: Published documents, newest first.
|
||||
content:
|
||||
application/json:
|
||||
schema: { type: object, properties: { items: { type: array, items: { $ref: "#/components/schemas/Document" } } } }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/tenants/{id}/members:
|
||||
get:
|
||||
summary: List the tenant's Keycloak organization members.
|
||||
@@ -400,6 +414,93 @@ paths:
|
||||
"200": { description: One page of audit entries. }
|
||||
"400": { $ref: "#/components/responses/BadRequest" }
|
||||
|
||||
/v1/admin/tenants/{id}/documents:
|
||||
get:
|
||||
summary: A tenant's documents, drafts included (staff).
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
responses:
|
||||
"200":
|
||||
description: The documents, newest first.
|
||||
content:
|
||||
application/json:
|
||||
schema: { type: object, properties: { items: { type: array, items: { $ref: "#/components/schemas/Document" } } } }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
post:
|
||||
summary: Upload a document as a draft (staff).
|
||||
description: |
|
||||
multipart/form-data with optional `title` and `description` fields
|
||||
before the `file` part. The file is streamed to object storage (limit
|
||||
DOCUMENTS_MAX_MB, default 200). Allowed: pdf, zip, docx, xlsx, pptx,
|
||||
png, jpg, txt, csv, json, xml. The title defaults to the file name.
|
||||
parameters:
|
||||
- { in: path, name: id, required: true, schema: { type: string, format: uuid } }
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
multipart/form-data:
|
||||
schema:
|
||||
type: object
|
||||
required: [file]
|
||||
properties:
|
||||
title: { type: string, maxLength: 200 }
|
||||
description: { type: string, maxLength: 2000 }
|
||||
file: { type: string, format: binary }
|
||||
responses:
|
||||
"201":
|
||||
description: Stored as a draft.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/Document" } }
|
||||
"400": { $ref: "#/components/responses/BadRequest" }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
"413": { description: Larger than the upload limit. }
|
||||
"415": { description: File type not allowed. }
|
||||
"503": { description: Document storage not configured. }
|
||||
|
||||
/v1/admin/documents/{doc}/publish:
|
||||
post:
|
||||
summary: Publish a draft so the tenant sees it (staff). Idempotent.
|
||||
parameters:
|
||||
- { in: path, name: doc, required: true, schema: { type: string, format: uuid } }
|
||||
responses:
|
||||
"200":
|
||||
description: The published document.
|
||||
content:
|
||||
application/json: { schema: { $ref: "#/components/schemas/Document" } }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/admin/documents/{doc}:
|
||||
delete:
|
||||
summary: Delete a document and its file (staff).
|
||||
parameters:
|
||||
- { in: path, name: doc, required: true, schema: { type: string, format: uuid } }
|
||||
responses:
|
||||
"204": { description: Deleted. }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/tenants/{id}/documents/{doc}/download:
|
||||
get:
|
||||
summary: A five-minute download link for a published document.
|
||||
description: |
|
||||
User tokens only reach their own tenant. A service client may name the
|
||||
downloading person in `X-Portal-User-Email` for the audit log.
|
||||
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 link.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
url: { type: string }
|
||||
filename: { type: string }
|
||||
content_type: { type: string }
|
||||
expires_at: { type: string, format: date-time }
|
||||
"404": { $ref: "#/components/responses/NotFound" }
|
||||
|
||||
/v1/entitlements:
|
||||
get:
|
||||
summary: List product entitlements for a tenant.
|
||||
@@ -1105,6 +1206,22 @@ components:
|
||||
error: { type: string, example: invalid_input }
|
||||
message: { type: string }
|
||||
|
||||
Document:
|
||||
type: object
|
||||
properties:
|
||||
id: { type: string, format: uuid }
|
||||
tenant_id: { type: string, format: uuid }
|
||||
title: { type: string }
|
||||
description: { type: string }
|
||||
filename: { type: string }
|
||||
content_type: { type: string }
|
||||
size_bytes: { type: integer }
|
||||
sha256: { type: string }
|
||||
status: { type: string, enum: [draft, published] }
|
||||
uploaded_by: { type: string }
|
||||
published_by: { type: string }
|
||||
published_at: { type: string, format: date-time }
|
||||
created_at: { type: string, format: date-time }
|
||||
TenantActivity:
|
||||
type: object
|
||||
properties:
|
||||
|
||||
Reference in new issue
Block a user