diff --git a/PLAN.md b/PLAN.md index 425cdf9..deebfad 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1947,6 +1947,27 @@ than planned: rather than helpers in every query, the SQL stays as it is the value last read is used. - On Postgres, the web tests run with this store. +**Part 5 built 2026-11-25** on `phase9`. +- `internal/storage`: one interface (put, get, stat, list, delete) with + two stores, a folder (`/files` by default) and an S3 bucket + (minio-go, path-style, so Garage needs no wildcard DNS). File names are + checked so none reaches outside the store. A folder store writes through + a temporary file and a rename, readable only by the app's user. +- An S3 store is checked when the app starts (write, read, delete a small + file), so a wrong key stops the start. `supermarket config` checks the + file storage, and Postgres, for real. +- The same tests run on a folder and on Garage (`SUPERMARKET_TEST_S3`), + checked on Garage v2.1 in Docker. +- What goes in it: nothing yet. Looking through the code, nothing the app + writes today needs it: + - SQLite's backups are the local edition's own. + - The sites' clones and previews are a cache. + - The files Hermes and CoreDesktop share with the app (`crm-state`, + `hermes-ai.json`, `mcp-token`, `ai-servers.json`) are for the local + edition only: on a server, Hermes reaches the app over MCP (Phase 10). + + The first users: exports (part 7), then uploads and images. + Nothing changes for the local user; this makes the rest possible. A commit after each part; the whole test suite runs against both SQLite and Postgres from part 2 on. diff --git a/README.md b/README.md index 9982c1b..cd35de0 100644 --- a/README.md +++ b/README.md @@ -241,6 +241,10 @@ collation. New SQL should run on both: use `db.Insert` (not `LastInsertId`), `ON CONFLICT … DO NOTHING` (not `INSERT OR IGNORE`), table-qualified columns in an upsert's `DO UPDATE`, and every selected column in `GROUP BY`. +File storage (`internal/storage`) is tested on a folder, and on an +S3-compatible bucket when `SUPERMARKET_TEST_S3` names one, such as a Garage in +Docker: `SUPERMARKET_TEST_S3='http://ACCESS_KEY:SECRET_KEY@127.0.0.1:3900/bucket'`. + **Changing the schema.** Add a `db.Migration` to `both` in `internal/db/migrations.go`, written in SQLite's SQL. Postgres gets the same statements translated (`INTEGER` → `BIGINT`, `INTEGER PRIMARY KEY` → an identity @@ -258,6 +262,7 @@ together), and each is recorded in `schema_migrations`. | `cmd/supermarket` | The server | | `internal/config` | The edition (local, server, multi-tenant) and its settings | | `internal/db` | The database: SQLite or Postgres, the schema and its migrations | +| `internal/storage` | Files that must last (exports, uploads): a folder, or an S3 bucket (Garage) | | `internal/web` | Pages (Go templates + [htmx](https://htmx.org), no JavaScript build) | | `internal/profile`, `internal/inventory` | The company profile and the inventory | | `internal/ai` | AI providers: Anthropic (official Go SDK) and OpenAI-compatible servers | diff --git a/TEST.md b/TEST.md index 4a3b38c..40a320e 100644 --- a/TEST.md +++ b/TEST.md @@ -800,3 +800,8 @@ Throughout, also notice: key, mail, an https:// address). With them all set, it says the server edition isn't built yet. `supermarket config` never shows a password or the key. +- [ ] `supermarket config` also checks the file storage ("writable"), and on + the other editions that Postgres can be reached. With a wrong S3 key or + Postgres password, it says which and why. +- [ ] After the update to schema 30, Settings → Backups shows the "before + schema 30" backup, and `~/.local/share/supermarket/files` exists, empty. diff --git a/cmd/supermarket/main.go b/cmd/supermarket/main.go index edc1ece..c8a6a19 100644 --- a/cmd/supermarket/main.go +++ b/cmd/supermarket/main.go @@ -45,6 +45,7 @@ import ( "supermarket/internal/legacy" "supermarket/internal/mcpserver" "supermarket/internal/secrets" + "supermarket/internal/storage" "supermarket/internal/web" ) @@ -96,6 +97,10 @@ func configCommand() int { for _, it := range cfg.Summary() { fmt.Printf("%-9s %s\n", it.Name+":", it.Value) } + if err == nil { + fmt.Println() + err = liveChecks(cfg) + } if err == nil { err = cfg.Ready() } @@ -111,6 +116,43 @@ func configCommand() int { return 0 } +// liveChecks reaches what the settings name: Postgres, and file storage +// (writing, reading and deleting a small file). +func liveChecks(cfg *config.Config) error { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + var problems []string + if cfg.DatabaseURL != "" { + fmt.Print("Checking the database… ") + d, err := sql.Open("pgx", cfg.DatabaseURL) + if err == nil { + err = d.PingContext(ctx) + d.Close() + } + if err != nil { + fmt.Println("no") + problems = append(problems, "Postgres can't be reached: "+err.Error()) + } else { + fmt.Println("reachable") + } + } + fmt.Print("Checking the file storage… ") + st, err := storage.Open(cfg.Storage) + if err == nil { + err = storage.Check(ctx, st) + } + if err != nil { + fmt.Println("no") + problems = append(problems, "The file storage doesn't work: "+err.Error()) + } else { + fmt.Println("writable") + } + if len(problems) > 0 { + return errors.New(strings.Join(problems, "\n")) + } + return nil +} + func run(log *slog.Logger) error { cfg, err := config.Load(os.Getenv) if err != nil { @@ -193,6 +235,21 @@ func run(log *slog.Logger) error { if err != nil { return err } + // Files that must outlast this copy of the app: a folder, or S3, + // checked now so a wrong key is found at the start. + files, err := storage.Open(cfg.Storage) + if err != nil { + return err + } + if cfg.Storage.S3() { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + err = storage.Check(ctx, files) + cancel() + if err != nil { + return err + } + } + token, err := mcpToken(filepath.Join(dataDir, "mcp-token")) if err != nil { return err @@ -221,6 +278,7 @@ func run(log *slog.Logger) error { Secrets: sec, Core: c, DataDir: dataDir, + Files: files, PublicURL: publicURL, Version: version, MCPToken: token, diff --git a/go.mod b/go.mod index df5fede..824fb1f 100644 --- a/go.mod +++ b/go.mod @@ -17,6 +17,7 @@ require ( require ( github.com/bahlo/generic-list-go v0.2.0 // indirect github.com/buger/jsonparser v1.1.2 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/dustin/go-humanize v1.1.0 // indirect github.com/emersion/go-sasl v0.0.0-20200509203442-7bfe0ed36a21 // indirect github.com/go-logr/logr v1.4.2 // indirect @@ -27,10 +28,18 @@ require ( 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.3 // indirect + github.com/klauspost/compress v1.19.2 // indirect + github.com/klauspost/cpuid/v2 v2.4.0 // indirect + github.com/klauspost/crc32 v1.3.0 // indirect github.com/mattn/go-isatty v0.0.24 // indirect + github.com/minio/crc64nvme v1.1.1 // indirect + github.com/minio/md5-simd v1.1.2 // indirect + github.com/minio/minio-go/v7 v7.4.1 // indirect github.com/ncruces/go-strftime v1.1.0 // indirect github.com/pb33f/ordered-map/v2 v2.3.1 // indirect + github.com/philhofer/fwd v1.2.0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/rs/xid v1.6.0 // indirect github.com/segmentio/asm v1.1.3 // indirect github.com/segmentio/encoding v0.5.4 // indirect github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 // indirect @@ -38,16 +47,21 @@ require ( github.com/tidwall/match v1.1.1 // indirect github.com/tidwall/pretty v1.2.1 // indirect github.com/tidwall/sjson v1.2.5 // indirect + github.com/tinylib/msgp v1.6.4 // indirect github.com/yosida95/uritemplate/v3 v3.0.2 // indirect + github.com/zeebo/xxh3 v1.1.0 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect go.opentelemetry.io/otel v1.33.0 // indirect go.opentelemetry.io/otel/metric v1.33.0 // indirect go.opentelemetry.io/otel/trace v1.33.0 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect go.yaml.in/yaml/v4 v4.0.0-rc.2 // indirect + golang.org/x/crypto v0.59.0 // indirect golang.org/x/oauth2 v0.35.0 // indirect golang.org/x/sync v0.25.0 // indirect golang.org/x/sys v0.50.0 // indirect golang.org/x/time v0.15.0 // indirect + gopkg.in/ini.v1 v1.67.3 // indirect modernc.org/libc v1.80.1 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.12.1 // indirect diff --git a/go.sum b/go.sum index dadfc94..f83b3ef 100644 --- a/go.sum +++ b/go.sum @@ -38,6 +38,8 @@ github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPn github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg= github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJk= github.com/buger/jsonparser v1.1.2/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -90,24 +92,42 @@ github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4= github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds= github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao= github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8= +github.com/klauspost/compress v1.19.2/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.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= +github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= +github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM= +github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw= 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= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/minio/crc64nvme v1.1.1 h1:8dwx/Pz49suywbO+auHCBpCtlW1OfpcLN7wYgVR6wAI= +github.com/minio/crc64nvme v1.1.1/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.4.1 h1:PtU/zIOfQRWZ+QydXAZysc+xZYHdG+BBR4Z6TUvy73w= +github.com/minio/minio-go/v7 v7.4.1/go.mod h1:nQnQi7zTfXR4lREtYXZQWqo5aw0Rqv+ZqCGrTORygRk= github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4= github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts= github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= github.com/pb33f/ordered-map/v2 v2.3.1 h1:5319HDO0aw4DA4gzi+zv4FXU9UlSs3xGZ40wcP1nBjY= github.com/pb33f/ordered-map/v2 v2.3.1/go.mod h1:qxFQgd0PkVUtOMCkTapqotNgzRhMPL7VvaHKbd1HnmQ= +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/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= +github.com/rogpeppe/go-internal v1.16.0 h1:O9DK+vNMDVGLr2BeZqmpLeMjiMNkuXfcqntWbZV6S5g= +github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= +github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc= github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg= github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0= @@ -115,10 +135,17 @@ github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJn github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 h1:uOfcYT+3QungH6tIGSVCR/Y3KJmgJiHcojJbMTPDZAI= github.com/standard-webhooks/standard-webhooks/libraries v0.0.1/go.mod h1:L1MQhA6x4dn9r007T033lsaZMv9EmBAdXyU/+EF40fo= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= @@ -129,9 +156,13 @@ github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= +github.com/tinylib/msgp v1.6.4 h1:mOwYbyYDLPj35mkA2BjjYejgJk9BuHxDdvRnb6v2ZcQ= +github.com/tinylib/msgp v1.6.4/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA= github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4= github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= +github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= @@ -148,6 +179,8 @@ go.opentelemetry.io/otel/sdk v1.33.0 h1:iax7M131HuAm9QkZotNHEfstof92xM+N8sr3uHXc go.opentelemetry.io/otel/sdk v1.33.0/go.mod h1:A1Q5oi7/9XaMlIWzPSxLRWOI8nG3FnzHJNbiENQuihM= go.opentelemetry.io/otel/trace v1.33.0 h1:cCJuF7LRjUFso9LPnEAHJDB2pqzp+hbO8eu1qqW2d/s= go.opentelemetry.io/otel/trace v1.33.0/go.mod h1:uIcdVUZMpTAmz0tI1z04GoVSezK37CbGV4fr1f2nBck= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= go.yaml.in/yaml/v4 v4.0.0-rc.2 h1:/FrI8D64VSr4HtGIlUtlFMGsm7H7pWTbj6vOLVZcA6s= go.yaml.in/yaml/v4 v4.0.0-rc.2/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= @@ -207,11 +240,15 @@ google.golang.org/grpc v1.64.1 h1:LKtvyfbX3UGVPFcGqJ9ItpVWW6oN/2XqTxfAnwRRXiA= google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0= google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/ini.v1 v1.67.3 h1:iM9Lhz5MRSGhHVGGwCuzG9KO8PoirCXj/m/qTmOJJQw= +gopkg.in/ini.v1 v1.67.3/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss= gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/config/config.go b/internal/config/config.go index e2a3fc9..c6893c6 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -217,7 +217,7 @@ func Load(getenv func(string) string) (*Config, error) { func loadStorage(get func(string, string) string, bad func(string, ...any), dataDir string) Storage { v := get(EnvStorage, "") if v == "" { - return Storage{Dir: dataDir} + return Storage{Dir: filepath.Join(dataDir, "files")} } if !strings.HasPrefix(v, "s3://") { if !filepath.IsAbs(v) { @@ -333,10 +333,10 @@ func (c *Config) Summary() []Item { default: items = append(items, Item{"Database", "Postgres: " + RedactURL(c.DatabaseURL), EnvDatabaseURL + "."}) } - files := Item{"Files", c.Storage.String(), "Backups, exports and uploads (" + EnvStorage + ")."} - if !c.Storage.S3() && c.Storage.Dir == c.DataDir { - files.Value = c.HostData - files.Help = "The data folder." + files := Item{"Files", c.Storage.String(), "Exports and uploaded files (" + EnvStorage + ")."} + if !c.Storage.S3() && c.Storage.Dir == filepath.Join(c.DataDir, "files") { + files.Value = filepath.Join(c.HostData, "files") + files.Help = "Exports and uploaded files, in the data folder." } items = append(items, files) switch { diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 9948b2e..e35a270 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -17,7 +17,7 @@ func TestLocalDefaults(t *testing.T) { t.Fatal(err) } if c.Edition != Local || c.DataDir != "/data" || c.Addr != ":8080" || c.PublicURL != "http://localhost:8470" || - c.Storage.Dir != "/data" || c.Storage.S3() || c.Mail != nil || c.SecretKey != nil || c.DatabaseURL != "" { + c.Storage.Dir != "/data/files" || c.Storage.S3() || c.Mail != nil || c.SecretKey != nil || c.DatabaseURL != "" { t.Fatalf("%+v", c) } if c.CoreConf != "/data/core.conf" || c.MCPSocket != "/data/mcp.sock" || c.HostData != "/data" { @@ -76,7 +76,7 @@ func TestServer(t *testing.T) { if err != nil { t.Fatal(err) } - if c.Edition != Server || len(c.SecretKey) != 32 || c.Storage.Dir != "/data" { + if c.Edition != Server || len(c.SecretKey) != 32 || c.Storage.Dir != "/data/files" { t.Fatalf("%+v", c) } m := c.Mail diff --git a/internal/storage/dir.go b/internal/storage/dir.go new file mode 100644 index 0000000..ba56f4f --- /dev/null +++ b/internal/storage/dir.go @@ -0,0 +1,151 @@ +package storage + +import ( + "context" + "errors" + "io" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" +) + +// Dir keeps files in a folder, readable only by the app's user. +type Dir struct { + root string +} + +// OpenDir opens (creating) the folder at root. +func OpenDir(root string) (*Dir, error) { + if err := os.MkdirAll(root, 0o700); err != nil { + return nil, err + } + return &Dir{root: root}, nil +} + +func (d *Dir) String() string { return d.root } + +func (d *Dir) path(key string) (string, error) { + if err := CheckKey(key); err != nil { + return "", err + } + return filepath.Join(d.root, filepath.FromSlash(key)), nil +} + +// Put writes to a temporary file beside the target and renames it, so a +// reader never sees half a file. +func (d *Dir) Put(ctx context.Context, key string, r io.Reader, size int64) error { + p, err := d.path(key) + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { + return err + } + tmp, err := os.CreateTemp(filepath.Dir(p), ".put-*") + if err != nil { + return err + } + defer os.Remove(tmp.Name()) // a no-op once renamed + if _, err := io.Copy(tmp, readerCtx{ctx, r}); err != nil { + tmp.Close() + return err + } + if err := tmp.Sync(); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmp.Name(), p) +} + +func (d *Dir) Get(ctx context.Context, key string) (io.ReadCloser, error) { + p, err := d.path(key) + if err != nil { + return nil, err + } + f, err := os.Open(p) + if errors.Is(err, fs.ErrNotExist) { + return nil, ErrNotExist + } + return f, err +} + +func (d *Dir) Stat(ctx context.Context, key string) (Info, error) { + p, err := d.path(key) + if err != nil { + return Info{}, err + } + fi, err := os.Stat(p) + if errors.Is(err, fs.ErrNotExist) || (err == nil && fi.IsDir()) { + return Info{}, ErrNotExist + } + if err != nil { + return Info{}, err + } + return Info{Key: key, Size: fi.Size(), Modified: fi.ModTime()}, nil +} + +func (d *Dir) List(ctx context.Context, prefix string) ([]Info, error) { + if err := checkPrefix(prefix); err != nil { + return nil, err + } + var out []Info + err := filepath.WalkDir(d.root, func(p string, e fs.DirEntry, err error) error { + if err != nil { + return err + } + if e.IsDir() || strings.HasPrefix(e.Name(), ".put-") { + return nil + } + rel, err := filepath.Rel(d.root, p) + if err != nil { + return err + } + key := filepath.ToSlash(rel) + if !strings.HasPrefix(key, prefix) || strings.HasPrefix(key, ".") { + return nil + } + fi, err := e.Info() + if err != nil { + return err + } + out = append(out, Info{Key: key, Size: fi.Size(), Modified: fi.ModTime()}) + return nil + }) + sort.Slice(out, func(i, j int) bool { return out[i].Key < out[j].Key }) + return out, err +} + +// Delete removes the file, and the folders it leaves empty. +func (d *Dir) Delete(ctx context.Context, key string) error { + p, err := d.path(key) + if err != nil { + return err + } + if err := os.Remove(p); err != nil && !errors.Is(err, fs.ErrNotExist) { + return err + } + for dir := filepath.Dir(p); dir != d.root && strings.HasPrefix(dir, d.root); dir = filepath.Dir(dir) { + if os.Remove(dir) != nil { // not empty + break + } + } + return nil +} + +// readerCtx stops a copy when the context ends. +type readerCtx struct { + ctx context.Context + r io.Reader +} + +func (r readerCtx) Read(p []byte) (int, error) { + if err := r.ctx.Err(); err != nil { + return 0, err + } + return r.r.Read(p) +} diff --git a/internal/storage/s3.go b/internal/storage/s3.go new file mode 100644 index 0000000..fa9e2b9 --- /dev/null +++ b/internal/storage/s3.go @@ -0,0 +1,128 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + + "github.com/minio/minio-go/v7" + "github.com/minio/minio-go/v7/pkg/credentials" + + "supermarket/internal/config" +) + +// S3 keeps files in an S3-compatible bucket (Garage), under a prefix. +type S3 struct { + c *minio.Client + bucket, prefix string // prefix: "" or ending in / + desc string +} + +// OpenS3 connects to the bucket. It doesn't call the server: Check does. +func OpenS3(s config.Storage) (*S3, error) { + u, err := url.Parse(s.Endpoint) + if err != nil || u.Host == "" { + return nil, fmt.Errorf("storage: the S3 address %q isn't usable", s.Endpoint) + } + c, err := minio.New(u.Host, &minio.Options{ + Creds: credentials.NewStaticV4(s.AccessKey, s.SecretKey, ""), + Secure: u.Scheme == "https", + Region: s.Region, + BucketLookup: minio.BucketLookupPath, // bucket in the path: Garage's default, and no wildcard DNS needed + }) + if err != nil { + return nil, err + } + prefix := strings.Trim(s.Prefix, "/") + if prefix != "" { + prefix += "/" + } + return &S3{c: c, bucket: s.Bucket, prefix: prefix, desc: s.String()}, nil +} + +func (s *S3) String() string { return s.desc } + +func (s *S3) object(key string) (string, error) { + if err := CheckKey(key); err != nil { + return "", err + } + return s.prefix + key, nil +} + +// notFound turns S3's "no such key" into ErrNotExist. +func notFound(err error) error { + var e minio.ErrorResponse + if errors.As(err, &e) && (e.Code == "NoSuchKey" || e.StatusCode == http.StatusNotFound) { + return ErrNotExist + } + return err +} + +func (s *S3) Put(ctx context.Context, key string, r io.Reader, size int64) error { + obj, err := s.object(key) + if err != nil { + return err + } + _, err = s.c.PutObject(ctx, s.bucket, obj, r, size, minio.PutObjectOptions{ContentType: "application/octet-stream"}) + return err +} + +func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, error) { + obj, err := s.object(key) + if err != nil { + return nil, err + } + o, err := s.c.GetObject(ctx, s.bucket, obj, minio.GetObjectOptions{}) + if err != nil { + return nil, notFound(err) + } + // GetObject doesn't ask the server until read: ask now, so a missing + // file is ErrNotExist here, as with a folder. + if _, err := o.Stat(); err != nil { + o.Close() + return nil, notFound(err) + } + return o, nil +} + +func (s *S3) Stat(ctx context.Context, key string) (Info, error) { + obj, err := s.object(key) + if err != nil { + return Info{}, err + } + oi, err := s.c.StatObject(ctx, s.bucket, obj, minio.StatObjectOptions{}) + if err != nil { + return Info{}, notFound(err) + } + return Info{Key: key, Size: oi.Size, Modified: oi.LastModified}, nil +} + +func (s *S3) List(ctx context.Context, prefix string) ([]Info, error) { + if err := checkPrefix(prefix); err != nil { + return nil, err + } + var out []Info + for oi := range s.c.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: s.prefix + prefix, Recursive: true}) { + if oi.Err != nil { + return nil, oi.Err + } + key := strings.TrimPrefix(oi.Key, s.prefix) + if strings.HasPrefix(key, ".") { + continue + } + out = append(out, Info{Key: key, Size: oi.Size, Modified: oi.LastModified}) + } + return out, nil +} + +func (s *S3) Delete(ctx context.Context, key string) error { + obj, err := s.object(key) + if err != nil { + return err + } + return s.c.RemoveObject(ctx, s.bucket, obj, minio.RemoveObjectOptions{}) +} diff --git a/internal/storage/storage.go b/internal/storage/storage.go new file mode 100644 index 0000000..392ff2c --- /dev/null +++ b/internal/storage/storage.go @@ -0,0 +1,104 @@ +// Package storage keeps the files that must outlast the app's own disk: +// exports, uploaded files, images. The local and server editions keep +// them in a folder; the multi-tenant edition in an S3-compatible bucket +// (Garage), so every copy of the app sees the same files. +// +// Not for scratch: the sites' git clones and page previews stay on local +// disk, as a cache that can be made again. +package storage + +import ( + "context" + "errors" + "fmt" + "io" + "path" + "strings" + "time" + + "supermarket/internal/config" +) + +// ErrNotExist is returned for a file that isn't there. +var ErrNotExist = errors.New("no such file") + +// Info describes a stored file. +type Info struct { + Key string // its name: slash-separated, such as exports/2026-11-25.tar.gz + Size int64 + Modified time.Time +} + +// Store keeps files by key. +type Store interface { + // Put stores r's contents as key, replacing any file there. size is + // the length, or -1 if unknown. + Put(ctx context.Context, key string, r io.Reader, size int64) error + // Get opens a file; ErrNotExist if there's none. + Get(ctx context.Context, key string) (io.ReadCloser, error) + // Stat describes a file; ErrNotExist if there's none. + Stat(ctx context.Context, key string) (Info, error) + // List lists the files whose keys start with prefix, by key. + List(ctx context.Context, prefix string) ([]Info, error) + // Delete removes a file; one that isn't there is not an error. + Delete(ctx context.Context, key string) error + // String says where the files are, without credentials. + String() string +} + +// CheckKey refuses a key that isn't a plain, relative, slash-separated +// name: no "..", no leading slash, no empty parts, no backslashes. +func CheckKey(key string) error { + if key == "" || strings.HasPrefix(key, "/") || strings.HasSuffix(key, "/") || strings.Contains(key, "\\") || + strings.ContainsRune(key, 0) || path.Clean(key) != key || key == "." || strings.HasPrefix(key, "../") || key == ".." { + return fmt.Errorf("storage: %q isn't a usable file name", key) + } + for _, part := range strings.Split(key, "/") { + if part == "." || part == ".." || part == "" { + return fmt.Errorf("storage: %q isn't a usable file name", key) + } + } + return nil +} + +// checkPrefix allows "" (everything), or a key's leading part. +func checkPrefix(prefix string) error { + if prefix == "" { + return nil + } + return CheckKey(strings.TrimSuffix(prefix, "/") + "/x") +} + +// Open opens the store the settings name: a folder, or an S3 bucket. +func Open(s config.Storage) (Store, error) { + if s.S3() { + return OpenS3(s) + } + return OpenDir(s.Dir) +} + +// Check writes, reads and deletes a small file, to show the store works +// (the S3 server is reachable, and the key may write to the bucket). +func Check(ctx context.Context, st Store) error { + const key = ".supermarket-check" + want := "checked " + time.Now().UTC().Format(time.RFC3339Nano) + if err := st.Put(ctx, key, strings.NewReader(want), int64(len(want))); err != nil { + return fmt.Errorf("writing to %s: %w", st, err) + } + r, err := st.Get(ctx, key) + if err != nil { + return fmt.Errorf("reading from %s: %w", st, err) + } + got, err := io.ReadAll(r) + r.Close() + if err != nil { + return fmt.Errorf("reading from %s: %w", st, err) + } + if string(got) != want { + return fmt.Errorf("%s gave back something else than was written", st) + } + if err := st.Delete(ctx, key); err != nil { + return fmt.Errorf("deleting from %s: %w", st, err) + } + return nil +} diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.go new file mode 100644 index 0000000..88673cc --- /dev/null +++ b/internal/storage/storage_test.go @@ -0,0 +1,185 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "io" + "net/url" + "os" + "strings" + "testing" + "time" + + "supermarket/internal/config" +) + +// TestS3 names an S3 bucket to test on, as +// http://ACCESS_KEY:SECRET_KEY@host:port/bucket, e.g. a Garage in Docker. +// Each run uses its own prefix in it, and empties it afterwards. +const TestS3 = "SUPERMARKET_TEST_S3" + +func stores(t *testing.T) map[string]Store { + t.Helper() + out := map[string]Store{} + d, err := OpenDir(t.TempDir()) + if err != nil { + t.Fatal(err) + } + out["folder"] = d + if raw := os.Getenv(TestS3); raw != "" { + u, err := url.Parse(raw) + if err != nil || u.User == nil { + t.Fatalf("%s: %v", TestS3, err) + } + pw, _ := u.User.Password() + s, err := OpenS3(config.Storage{ + Endpoint: u.Scheme + "://" + u.Host, Bucket: strings.Trim(u.Path, "/"), Region: "garage", + Prefix: fmt.Sprintf("test-%d-%d", os.Getpid(), time.Now().UnixNano()), + AccessKey: u.User.Username(), SecretKey: pw, + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + ctx := context.Background() + all, _ := s.List(ctx, "") + for _, f := range all { + s.Delete(ctx, f.Key) + } + }) + out["s3"] = s + } + return out +} + +func read(t *testing.T, st Store, key string) string { + t.Helper() + r, err := st.Get(context.Background(), key) + if err != nil { + t.Fatalf("get %s: %v", key, err) + } + defer r.Close() + b, err := io.ReadAll(r) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// Every store behaves the same. +func TestStores(t *testing.T) { + ctx := context.Background() + for name, st := range stores(t) { + t.Run(name, func(t *testing.T) { + if err := Check(ctx, st); err != nil { + t.Fatal(err) + } + if err := st.Put(ctx, "exports/a.txt", strings.NewReader("first"), 5); err != nil { + t.Fatal(err) + } + if err := st.Put(ctx, "exports/a.txt", strings.NewReader("second, longer"), -1); err != nil { // replaced; size unknown + t.Fatal(err) + } + st.Put(ctx, "exports/2026/b.bin", strings.NewReader(strings.Repeat("x", 70000)), 70000) + st.Put(ctx, "uploads/c.png", strings.NewReader("png"), 3) + if got := read(t, st, "exports/a.txt"); got != "second, longer" { + t.Errorf("read %q", got) + } + info, err := st.Stat(ctx, "exports/2026/b.bin") + if err != nil || info.Size != 70000 || info.Key != "exports/2026/b.bin" || time.Since(info.Modified) > time.Hour { + t.Errorf("stat: %+v %v", info, err) + } + list, err := st.List(ctx, "exports/") + if err != nil { + t.Fatal(err) + } + var keys []string + for _, f := range list { + keys = append(keys, f.Key) + } + if strings.Join(keys, " ") != "exports/2026/b.bin exports/a.txt" { + t.Errorf("list: %v", keys) + } + if all, _ := st.List(ctx, ""); len(all) != 3 { + t.Errorf("everything: %v (the check file should be gone)", all) + } + + // Missing files. + if _, err := st.Get(ctx, "exports/none"); !errors.Is(err, ErrNotExist) { + t.Errorf("get missing: %v", err) + } + if _, err := st.Stat(ctx, "exports"); !errors.Is(err, ErrNotExist) { // a folder isn't a file + t.Errorf("stat folder: %v", err) + } + if err := st.Delete(ctx, "exports/a.txt"); err != nil { + t.Fatal(err) + } + if err := st.Delete(ctx, "exports/a.txt"); err != nil { + t.Errorf("deleting twice: %v", err) + } + if _, err := st.Stat(ctx, "exports/a.txt"); !errors.Is(err, ErrNotExist) { + t.Errorf("after delete: %v", err) + } + + // Names that would reach outside the store. + for _, bad := range []string{"", "/etc/passwd", "../x", "a/../../x", "a//b", "a/./b", "a/", `a\b`, ".."} { + if err := st.Put(ctx, bad, strings.NewReader("x"), 1); err == nil { + t.Errorf("put %q accepted", bad) + } + } + if _, err := st.List(ctx, "../"); err == nil { + t.Error("list ../ accepted") + } + }) + } +} + +// A folder store's files are the user's only, and a half-written file is +// never seen. +func TestDirFiles(t *testing.T) { + root := t.TempDir() + "/files" + d, err := OpenDir(root) + if err != nil { + t.Fatal(err) + } + d.Put(context.Background(), "a/b.txt", strings.NewReader("x"), 1) + for _, p := range []string{root, root + "/a", root + "/a/b.txt"} { + fi, err := os.Stat(p) + if err != nil { + t.Fatal(err) + } + if fi.Mode().Perm()&0o077 != 0 { + t.Errorf("%s is %v", p, fi.Mode().Perm()) + } + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := d.Put(ctx, "a/c.txt", strings.NewReader("never"), 5); err == nil { + t.Error("a cancelled write went through") + } + if list, _ := d.List(context.Background(), ""); len(list) != 1 { + t.Errorf("left behind: %v", list) + } + d.Delete(context.Background(), "a/b.txt") + if _, err := os.Stat(root + "/a"); !os.IsNotExist(err) { + t.Error("the empty folder stayed") + } +} + +// A wrong key is caught by Check, saying where. +func TestS3WrongKey(t *testing.T) { + raw := os.Getenv(TestS3) + if raw == "" { + t.Skip("set " + TestS3) + } + u, _ := url.Parse(raw) + s, err := OpenS3(config.Storage{Endpoint: u.Scheme + "://" + u.Host, Bucket: strings.Trim(u.Path, "/"), Region: "garage", + AccessKey: u.User.Username(), SecretKey: "wrong"}) + if err != nil { + t.Fatal(err) + } + if err := Check(context.Background(), s); err == nil || !strings.Contains(err.Error(), "writing to s3://") { + t.Fatalf("check: %v", err) + } +} diff --git a/internal/web/server.go b/internal/web/server.go index c8779ec..1e789de 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -15,6 +15,7 @@ import ( "strconv" "strings" "supermarket/internal/config" + "supermarket/internal/storage" "sync" "time" "unicode" @@ -48,7 +49,8 @@ type Server struct { Secrets *secrets.Store Core *core.Core // nil without a Core DataDir string - PublicURL string // e.g. http://localhost:8470, for OAuth redirect URIs + Files storage.Store // exports and uploads: a folder or S3; nil in tests + PublicURL string // e.g. http://localhost:8470, for OAuth redirect URIs Version string MCPToken string MCPSocket string // the MCP socket's path on the host, for Hermes' config