carlos / platform Public

store: browser uploads verb, bucket CORS and multipart cleanup

carlos store uploads enable|status|disable and its console door
(POST/GET /api/cli/apps/{account}/{app}/store/uploads, Admin). Enable
re-inspects the bucket under the walk lock for every store, refuses any
CORS or lifecycle configuration whose hash the record does not hold,
re-runs the grant (multipart actions), writes the platform's one CORS
rule and one lifecycle rule, then records both by hash; a failed record
write puts the bucket back. Disable deletes only the platform's own
rules. Host-claim consoles refuse with media.claims_console.

The store user's object Allow gains s3:AbortMultipartUpload and
s3:ListMultipartUploadParts. Default origins come from one shared ready
platform route predicate, also used by scanCallbackHost (pre-flight F25).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 8fe00819f5cb6f74212311d0eb85129c6d68c234 parent 4a9f141
17 files changed, +1,526 −11
  • apimode.go +50 −0
  • docs/parity.md +4 −2
  • internal/console/apistoreuploads.go +485 −0
  • internal/console/apistoreuploads_test.go +572 −0
  • internal/console/claim_invariant_fixtures_test.go +12 −0
  • internal/console/linkedpolicy.go +2 −0
  • internal/console/media_copy.go +8 −0
  • internal/console/routedecls.go +6 −0
  • internal/console/scandeliver.go +52 −9
  • internal/console/testdata/claim-routes.txt +2 −0
  • internal/objstore/aws.go +11 −0
  • internal/objstore/aws_test.go +75 −0
  • parity/cli.tsv +3 −0
  • parity/parity.tsv +1 −0
  • store.go +6 −0
  • store_uploads.go +140 −0
  • store_uploads_test.go +97 −0
diff --git a/apimode.go b/apimode.go
index 2e3373dc1..b4f1b8f9c 100644
--- a/apimode.go
+++ b/apimode.go
@@ -2492,6 +2492,56 @@ func (s *apiSession) scanRotateCallbackKey(ctx context.Context, a apiAcct, app s
return s.scanCall(ctx, "store scan rotate-webhook-key", apiPath(a, app, "/store/scan/callback-key/rotate"), struct{}{})
}
+// apiUploadsReply is both browser-uploads doors' answer
+// (internal/console/apistoreuploads.go uploadsAnswer).
+type apiUploadsReply struct {
+ Enabled bool `json:"enabled"`
+ Origins []string `json:"origins"`
+ BucketMatches bool `json:"bucket_matches"`
+ Mismatch string `json:"mismatch"`
+}
+
+// storeUploadsCall is one round trip to .../store/uploads: GET when in is
+// nil, else POST.
+func (s *apiSession) storeUploadsCall(ctx context.Context, a apiAcct, app string, in any) (apiUploadsReply, error) {
+ path := apiPath(a, app, "/store/uploads")
+ var status int
+ var body []byte
+ var err error
+ if in == nil {
+ status, body, err = s.getJSON(ctx, path)
+ } else {
+ status, body, err = s.postJSON(ctx, path, in)
+ }
+ if err != nil {
+ return apiUploadsReply{}, err
+ }
+ if status != http.StatusOK {
+ return apiUploadsReply{}, apiErrorFromBody(status, body)
+ }
+ var out apiUploadsReply
+ if err := json.Unmarshal(body, &out); err != nil {
+ return apiUploadsReply{}, fmt.Errorf("store uploads: unreadable response: %w", err)
+ }
+ return out, nil
+}
+
+// storeUploadsSet turns browser uploads on (with origins, none meaning the
+// app's hostnames) or off.
+func (s *apiSession) storeUploadsSet(ctx context.Context, a apiAcct, app string, enabled bool, origins []string) (apiUploadsReply, error) {
+ in := struct {
+ Enabled bool `json:"enabled"`
+ Origins []string `json:"origins,omitempty"`
+ }{enabled, origins}
+ return s.storeUploadsCall(ctx, a, app, in)
+}
+
+// storeUploadsStatus reads browser uploads' state and whether the bucket
+// still holds the rules the platform wrote.
+func (s *apiSession) storeUploadsStatus(ctx context.Context, a apiAcct, app string) (apiUploadsReply, error) {
+ return s.storeUploadsCall(ctx, a, app, nil)
+}
+
// storeCreate asks the console to declare (or re-declare) a store for app,
// under envPrefix ("" takes the console's own default — objstore.
// DefaultEnvPrefix). Mirrors restart's shape (apimode.go:438): postJSON, a
diff --git a/docs/parity.md b/docs/parity.md
index 1e117a830..2b91b911f 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -12,10 +12,10 @@ CLI rows are checked against the command registry (`parity/cli.tsv`).
|---|---:|
| both | 44 |
| partial | 9 |
-| gap | 65 |
+| gap | 66 |
| cli-only | 17 |
| console-only | 17 |
-| Total | 152 |
+| Total | 153 |
## account
@@ -230,6 +230,7 @@ CLI rows are checked against the command registry (`parity/cli.tsv`).
| store-apply | both | `store apply` | `GET /a/{sqid}/settings`<br>`POST /a/{sqid}/store/apply` | | |
| store-rotate | gap | `store rotate` | | [wp-email-storage](#wp-email-storage) | |
| store-scan | gap | `store scan request`<br>`store scan status`<br>`store scan grant`<br>`store scan revoke`<br>`store scan sweep`<br>`store scan enforce`<br>`store scan rotate-webhook-key` | | [wp-email-storage](#wp-email-storage) | |
+| store-uploads | gap | `store uploads enable`<br>`store uploads status`<br>`store uploads disable` | | [wp-email-storage](#wp-email-storage) | |
| store-destroy | console-only | | `POST /a/{sqid}/apps/{app}/store/destroy` | | Needs a passkey. |
## team
@@ -317,6 +318,7 @@ Discussion #737.
- `store-create` (storage), CLI has `store create`
- `store-rotate` (storage), CLI has `store rotate`
- `store-scan` (storage), CLI has `store scan request`, `store scan status`, `store scan grant`, `store scan revoke`, `store scan sweep`, `store scan enforce`, `store scan rotate-webhook-key`
+- `store-uploads` (storage), CLI has `store uploads enable`, `store uploads status`, `store uploads disable`
- `email-enable` (email), CLI has `email enable`
- `email-domains` (email), CLI has `email domains add`, `email domains rm`
- `email-test` (email), CLI has `email test`
diff --git a/internal/console/apistoreuploads.go b/internal/console/apistoreuploads.go
new file mode 100644
index 000000000..a3b553ffe
--- /dev/null
+++ b/internal/console/apistoreuploads.go
@@ -0,0 +1,485 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "log"
+ "net/http"
+ "slices"
+ "strconv"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/objstore"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/storecfg"
+)
+
+// Browser uploads (media conversion spec §5.6, §11 A1): `carlos store uploads
+// enable|status|disable`. A member verb on the app's own store. Enabling
+// writes the platform's one CORS rule (the origins the member names) and its
+// one lifecycle rule (abort incomplete multipart uploads after a day) onto
+// the store's bucket, records both by hash in the store record's conversion
+// block (objstore.Uploads), and re-runs the grant so the store user's policy
+// carries the two multipart actions (storePolicyJSON).
+//
+// The invariant this file exists to keep: the platform never replaces,
+// merges into or deletes a CORS or lifecycle configuration it did not write.
+// Every write is preceded, under the app's store walk lock, by a fresh
+// Inspect of the bucket, whatever the store's verification says: a verified
+// store is trusted for its incarnation tag only (mediaStoreCheck reads
+// nothing else of a verified bucket), so a rule set by hand since then is
+// seen only here. A configuration is the platform's only when its canonical
+// hash is the one the record holds; with nothing recorded, any configuration
+// at all is foreign.
+//
+// Every refusal is jsonErrorCode with the copy deck's message by key
+// (media_copy.go). No SQLite transaction is opened here.
+
+// uploadsMaxOrigins is the most origins one CORS rule carries (spec §5.6).
+const uploadsMaxOrigins = 8
+
+// uploadsBodyLimit caps the POST body: eight origins of at most a 253-byte
+// host each fit several times over.
+const uploadsBodyLimit = 8 << 10
+
+// The codes these doors answer beyond the media door's no_store and
+// store_unverified.
+const (
+ uploadsCodeNotConfigured = "uploads_not_configured"
+ uploadsCodeBadOrigin = "bad_origin"
+ uploadsCodeTooManyOrigins = "too_many_origins"
+ uploadsCodeNoHosts = "no_hosts"
+)
+
+// uploadsBody is the POST body, decoded strictly. Origins is read only when
+// Enabled; none given means the app's ready platform hostnames.
+type uploadsBody struct {
+ Enabled bool `json:"enabled"`
+ Origins []string `json:"origins"`
+}
+
+// uploadsAnswer is both doors' answer. Origins are the recorded ones,
+// sorted. BucketMatches says the bucket holds exactly the rules the record
+// says the platform wrote; Mismatch names the first that differs, in
+// storecfg.Verify's order ("lifecycle", then "cors"), "" when none does.
+type uploadsAnswer struct {
+ Enabled bool `json:"enabled"`
+ Origins []string `json:"origins"`
+ BucketMatches bool `json:"bucket_matches"`
+ Mismatch string `json:"mismatch"`
+}
+
+// uploadsConfigured: this console can read and write its stores' bucket
+// settings (CARLOS_STORE_CONVERSION and its adapter).
+func (s *Server) uploadsConfigured() bool {
+ return s.cfg.StoreConversion && s.cfg.StoreBuckets != nil
+}
+
+// uploadsOrigin is raw as the one form an origin takes in the rule, and
+// whether it is one uploads accept: https:// and a DNS host name (no port,
+// path, query, fragment, user or wildcard), or http://localhost: and a port
+// from 1 to 65535 written without leading zeros. Letters are lowercased
+// first, as browsers send them; nothing else is rewritten, so a trailing
+// slash or a default port is refused rather than dropped.
+func uploadsOrigin(raw string) (string, bool) {
+ o := strings.ToLower(raw)
+ if host, ok := strings.CutPrefix(o, "https://"); ok {
+ return o, uploadsHost(host)
+ }
+ if port, ok := strings.CutPrefix(o, "http://localhost:"); ok {
+ n, err := strconv.Atoi(port)
+ return o, err == nil && n >= 1 && n <= 65535 && strconv.Itoa(n) == port
+ }
+ return o, false
+}
+
+// uploadsHost is a DNS host name in lowercase ASCII: dot-separated labels of
+// letters, digits and hyphens, each 1 to 63 bytes and not starting or ending
+// with a hyphen, at most 253 bytes in all. That leaves no room for a port,
+// a path, a query, credentials or a wildcard.
+func uploadsHost(h string) bool {
+ if h == "" || len(h) > 253 {
+ return false
+ }
+ for _, label := range strings.Split(h, ".") {
+ if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
+ return false
+ }
+ for i := 0; i < len(label); i++ {
+ c := label[i]
+ if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// uploadsOrigins checks every origin given, then drops repeats and counts
+// what is left. It answers them sorted, or the refusal's code and message.
+func uploadsOrigins(raw []string) (origins []string, code, msg string) {
+ for _, r := range raw {
+ o, ok := uploadsOrigin(r)
+ if !ok {
+ return nil, uploadsCodeBadOrigin, mediaText("uploads.bad_origin", r)
+ }
+ origins = append(origins, o)
+ }
+ slices.Sort(origins)
+ origins = slices.Compact(origins)
+ if len(origins) > uploadsMaxOrigins {
+ return nil, uploadsCodeTooManyOrigins, mediaText("uploads.too_many_origins")
+ }
+ return origins, "", ""
+}
+
+// uploadsForeign is the check (storecfg.CheckLifecycle or CheckCORS) whose
+// configuration the bucket holds and the platform did not write, "" when it
+// holds none it did not write. up is what the record says the platform
+// wrote, nil for nothing: then any configuration present is foreign. An
+// absent configuration is never foreign; there is nothing in it to replace.
+func uploadsForeign(f storecfg.Facts, up *objstore.Uploads) string {
+ var lh, ch string
+ if up != nil {
+ lh, ch = up.LifecycleHash, up.CORSHash
+ }
+ if len(f.Lifecycle) > 0 && (lh == "" || storecfg.Hash(f.Lifecycle) != lh) {
+ return storecfg.CheckLifecycle
+ }
+ if len(f.CORS) > 0 && (ch == "" || storecfg.Hash(f.CORS) != ch) {
+ return storecfg.CheckCORS
+ }
+ return ""
+}
+
+// uploadsMismatch compares a bucket with uploads that are on: the check
+// whose configuration is not exactly the recorded one, "" when both are. An
+// absent configuration differs too (browsers cannot upload through a CORS
+// rule that is gone): a recorded hash is always of a non-empty rule set.
+func uploadsMismatch(f storecfg.Facts, up *objstore.Uploads) string {
+ if storecfg.Hash(f.Lifecycle) != up.LifecycleHash {
+ return storecfg.CheckLifecycle
+ }
+ if storecfg.Hash(f.CORS) != up.CORSHash {
+ return storecfg.CheckCORS
+ }
+ return ""
+}
+
+// recordedUploads is the uploads block of a store record, nil when it has
+// none.
+func recordedUploads(rec *objstore.Record) *objstore.Uploads {
+ if rec == nil || rec.Provisioned == nil || rec.Conversion == nil {
+ return nil
+ }
+ return rec.Conversion.Uploads
+}
+
+// uploadsOff is the answer for uploads that are off.
+func uploadsOff() uploadsAnswer {
+ return uploadsAnswer{Origins: []string{}, BucketMatches: true}
+}
+
+// uploadsOn is the answer for a recorded uploads block and the bucket's
+// state against it.
+func uploadsOn(up *objstore.Uploads, mismatch string) uploadsAnswer {
+ return uploadsAnswer{Enabled: true, Origins: append([]string{}, up.Origins...),
+ BucketMatches: mismatch == "", Mismatch: mismatch}
+}
+
+// errUploadsStoreMoved: the store record changed under the walk lock in a
+// way the uploads write cannot follow (another bucket, or another
+// incarnation). Nothing is recorded; the caller undoes its bucket write.
+var errUploadsStoreMoved = errors.New("console: uploads: the store record changed while uploads were written")
+
+// writeUploadsRecord sets the record's uploads block to up (nil clears it),
+// in a write conditional on the record as read, retried on a lost race
+// with another writer of the record (a scan or plan-storage write, which do
+// not take the walk lock). It refuses, with errUploadsStoreMoved, a record
+// whose bucket is no longer bucket or, when inc is not "", whose verified
+// incarnation is no longer inc.
+func (s *Server) writeUploadsRecord(ctx context.Context, sqid, app, bucket, inc string, up *objstore.Uploads) error {
+ var lastErr error
+ for attempt := 0; attempt < 3; attempt++ {
+ rec, etag, err := objstore.GetIn(ctx, s.cfg.Releases, sqid, app, "")
+ if err != nil {
+ return err
+ }
+ if rec == nil || rec.Provisioned == nil || rec.Provisioned.Bucket != bucket {
+ return errUploadsStoreMoved
+ }
+ if rec.Conversion == nil {
+ if up == nil {
+ return nil
+ }
+ return errUploadsStoreMoved
+ }
+ if inc != "" && (rec.Conversion.VerifiedAt == nil || rec.Conversion.Incarnation != inc) {
+ return errUploadsStoreMoved
+ }
+ rec.Conversion.Uploads = up
+ if _, err := objstore.PutIn(ctx, s.cfg.Releases, sqid, app, "", rec, etag); err != nil {
+ if errors.Is(err, release.ErrCASConflict) {
+ lastErr = err
+ continue
+ }
+ return err
+ }
+ return nil
+ }
+ return lastErr
+}
+
+// uploadsInternal logs err and answers the console's plain 500.
+func uploadsInternal(w http.ResponseWriter, what string, err error) {
+ log.Printf("console: store uploads %s: %v", what, err)
+ jsonError(w, http.StatusInternalServerError, "internal error")
+}
+
+// handleAPIStoreUploadsGet is GET /api/cli/apps/{account}/{app}/store/uploads:
+// `carlos store uploads status`. It reads the record and, when uploads are
+// on, Inspects the bucket and compares it with what the record says the
+// platform wrote. It writes nothing and takes no lock.
+func (s *Server) handleAPIStoreUploadsGet(w http.ResponseWriter, r *http.Request) {
+ _, acct, app, ok := s.apiAccountApp(w, r)
+ if !ok {
+ return
+ }
+ if s.cfg.HostClaim {
+ mediaRefuse(w, http.StatusServiceUnavailable, "claims_console", mediaText("media.claims_console"))
+ return
+ }
+ if !s.uploadsConfigured() {
+ mediaRefuse(w, http.StatusServiceUnavailable, uploadsCodeNotConfigured, mediaText("uploads.not_configured"))
+ return
+ }
+ if s.cfg.Releases == nil {
+ storeNoBucket(w)
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), storeTimeout)
+ defer cancel()
+ rec, _, err := objstore.GetIn(ctx, s.cfg.Releases, acct.Sqid, app, "")
+ if err != nil {
+ uploadsInternal(w, "status "+acct.Sqid+"/"+app, err)
+ return
+ }
+ up := recordedUploads(rec)
+ if up == nil {
+ writeJSON(w, http.StatusOK, uploadsOff())
+ return
+ }
+ facts, err := s.cfg.StoreBuckets.Inspect(ctx, rec.Provisioned.Bucket)
+ if err != nil {
+ uploadsInternal(w, "status inspect "+acct.Sqid+"/"+app, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, uploadsOn(up, uploadsMismatch(facts, up)))
+}
+
+// handleAPIStoreUploadsSet is POST /api/cli/apps/{account}/{app}/store/uploads:
+// `carlos store uploads enable` ({"enabled": true}) and `disable`
+// ({"enabled": false}). After apiAccountApp (a stranger meets its 404
+// first), its checks run in this order and stop at the first failure:
+//
+// 1. host-claim console: 503 claims_console (spec §11 A1)
+// 2. no bucket settings adapter: 503 uploads_not_configured
+// 3. the store walk gates (write budget, deployment bucket, backend)
+// 4. body not strict JSON of at most 8 KiB: readJSONStrictLimit's refusal
+// 5. enable: an origin that is not one: 400 bad_origin; more than 8
+// after repeats are dropped: 400 too_many_origins
+//
+// Then disable is handleUploadsDisable, and enable, under the account lock
+// (the regrant's key choice) and the app's store walk lock:
+//
+// 6. no origins given: the app's ready platform hostnames as https://
+// origins; none: 409 no_hosts; more than 8: 400 too_many_origins
+// 7. mediaStoreEligible: 409 no_store, 409 store_unverified
+// 8. Inspect now, whatever 7 said: a lifecycle or CORS configuration the
+// record does not hold the hash of: 409 store_unverified with that
+// check's phrase. Nothing of uploads has been written (7 may have
+// recorded the store's verification, as the media door's check does).
+// 9. the grant re-runs, so the store user's policy carries the multipart
+// actions (before any bucket write, so a failure here leaves nothing
+// half done)
+// 10. PutUploads, then the record's uploads block. A record write that
+// fails puts the bucket back as the record still describes it, so the
+// platform's own rules never stand unrecorded (which would read as
+// foreign to every later check).
+func (s *Server) handleAPIStoreUploadsSet(w http.ResponseWriter, r *http.Request) {
+ addr, acct, app, ok := s.apiAccountApp(w, r)
+ if !ok {
+ return
+ }
+ if s.cfg.HostClaim {
+ mediaRefuse(w, http.StatusServiceUnavailable, "claims_console", mediaText("media.claims_console"))
+ return
+ }
+ if !s.uploadsConfigured() {
+ mediaRefuse(w, http.StatusServiceUnavailable, uploadsCodeNotConfigured, mediaText("uploads.not_configured"))
+ return
+ }
+ p, _ := principalFrom(r.Context())
+ if !s.storeWalkGates(w, p) {
+ return
+ }
+ var body uploadsBody
+ if !readJSONStrictLimit(w, r, &body, uploadsBodyLimit) {
+ return
+ }
+ if !body.Enabled {
+ s.handleUploadsDisable(w, r, acct, app)
+ return
+ }
+ origins, code, msg := uploadsOrigins(body.Origins)
+ if code != "" {
+ mediaRefuse(w, http.StatusBadRequest, code, msg)
+ return
+ }
+
+ // The account lock from the key choice through the regrant (fleet
+ // secrets key spec §5.2.1), then the walk lock, the grant door's order.
+ defer s.lockAccount(acct.Sqid)()
+ sealer, ok := s.scanRegrantSealer(w, r.Context(), acct, app)
+ if !ok {
+ return
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), storeGrantTimeout)
+ defer cancel()
+ defer s.storeWalks.lock(acct.Sqid, app, "")()
+
+ if len(origins) == 0 {
+ hosts, err := s.appReadyPlatformHosts(objstore.AppRef{Account: acct.Sqid, App: app})
+ if err != nil {
+ uploadsInternal(w, "hosts "+acct.Sqid+"/"+app, err)
+ return
+ }
+ for _, h := range hosts {
+ if o, ok := uploadsOrigin("https://" + h); ok {
+ origins = append(origins, o)
+ }
+ }
+ if len(origins) == 0 {
+ mediaRefuse(w, http.StatusConflict, uploadsCodeNoHosts, mediaText("uploads.no_hosts"))
+ return
+ }
+ if len(origins) > uploadsMaxOrigins {
+ mediaRefuse(w, http.StatusBadRequest, uploadsCodeTooManyOrigins, mediaText("uploads.too_many_origins"))
+ return
+ }
+ }
+
+ rec, code, check, err := s.mediaStoreEligible(ctx, acct, app)
+ if err != nil {
+ uploadsInternal(w, "store check "+acct.Sqid+"/"+app, err)
+ return
+ }
+ switch code {
+ case "":
+ case mediaCodeNoStore:
+ mediaRefuse(w, http.StatusConflict, mediaCodeNoStore, mediaText("media.no_store", app, app))
+ return
+ case mediaCodeStoreUnverified:
+ mediaRefuse(w, http.StatusConflict, mediaCodeStoreUnverified, mediaText("media.store_unverified", mediaText("media.check."+check)))
+ return
+ default:
+ uploadsInternal(w, "store check "+acct.Sqid+"/"+app, errors.New("unknown code "+code))
+ return
+ }
+ bucket, inc, prior := rec.Provisioned.Bucket, rec.Conversion.Incarnation, rec.Conversion.Uploads
+
+ // Every store, verified or not: the bucket as it is now.
+ facts, err := s.cfg.StoreBuckets.Inspect(ctx, bucket)
+ if err != nil {
+ uploadsInternal(w, "inspect "+acct.Sqid+"/"+app, err)
+ return
+ }
+ if check := uploadsForeign(facts, prior); check != "" {
+ mediaRefuse(w, http.StatusConflict, mediaCodeStoreUnverified, mediaText("media.store_unverified", mediaText("media.check."+check)))
+ return
+ }
+
+ if err := s.regrantForScanning(ctx, sealer, acct, app, addr); err != nil {
+ uploadsInternal(w, "regrant "+acct.Sqid+"/"+app, err)
+ return
+ }
+ if err := s.cfg.StoreBuckets.PutUploads(ctx, bucket, origins); err != nil {
+ uploadsInternal(w, "put rules "+acct.Sqid+"/"+app, err)
+ return
+ }
+ up := &objstore.Uploads{
+ Origins: origins,
+ CORSHash: storecfg.Hash(storecfg.UploadsCORS(origins)),
+ LifecycleHash: storecfg.Hash(storecfg.UploadsLifecycle()),
+ At: s.now().UTC(),
+ By: addr,
+ }
+ if err := s.writeUploadsRecord(ctx, acct.Sqid, app, bucket, inc, up); err != nil {
+ s.restoreUploads(ctx, bucket, prior)
+ uploadsInternal(w, "record "+acct.Sqid+"/"+app, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, uploadsOn(up, ""))
+}
+
+// restoreUploads puts the bucket's rules back to what prior (the record,
+// still unchanged) describes, after a record write failed: before the
+// write, the bucket held only prior's rules or none (uploadsForeign), so
+// this returns it to a state the record accounts for. Best effort: a
+// failure is logged, and leaves the platform's rules on the bucket
+// unrecorded, which every later check refuses as foreign until an operator
+// removes them.
+func (s *Server) restoreUploads(ctx context.Context, bucket string, prior *objstore.Uploads) {
+ var err error
+ if prior != nil {
+ err = s.cfg.StoreBuckets.PutUploads(ctx, bucket, prior.Origins)
+ } else {
+ err = s.cfg.StoreBuckets.DeleteUploads(ctx, bucket)
+ }
+ if err != nil {
+ log.Printf("console: store uploads: bucket %s holds rules no record names, and putting it back failed: %v", bucket, err)
+ }
+}
+
+// handleUploadsDisable is `carlos store uploads disable`, under the app's
+// store walk lock. With uploads recorded, it Inspects the bucket and calls
+// DeleteUploads only when every configuration the bucket holds is the one
+// recorded (DeleteUploads removes both, so a foreign rule beside the
+// platform's is never deleted with it), then clears the uploads block. A
+// foreign rule is left where it is, and the answer says so (bucket_matches
+// false). With nothing recorded it writes nothing and reads no bucket.
+func (s *Server) handleUploadsDisable(w http.ResponseWriter, r *http.Request, acct *Account, app string) {
+ ctx, cancel := context.WithTimeout(r.Context(), storeGrantTimeout)
+ defer cancel()
+ defer s.storeWalks.lock(acct.Sqid, app, "")()
+ rec, _, err := objstore.GetIn(ctx, s.cfg.Releases, acct.Sqid, app, "")
+ if err != nil {
+ uploadsInternal(w, "disable "+acct.Sqid+"/"+app, err)
+ return
+ }
+ up := recordedUploads(rec)
+ if up == nil {
+ writeJSON(w, http.StatusOK, uploadsOff())
+ return
+ }
+ bucket := rec.Provisioned.Bucket
+ facts, err := s.cfg.StoreBuckets.Inspect(ctx, bucket)
+ if err != nil {
+ uploadsInternal(w, "disable inspect "+acct.Sqid+"/"+app, err)
+ return
+ }
+ answer := uploadsOff()
+ if foreign := uploadsForeign(facts, up); foreign != "" {
+ answer.BucketMatches, answer.Mismatch = false, foreign
+ } else if len(facts.CORS) > 0 || len(facts.Lifecycle) > 0 {
+ if err := s.cfg.StoreBuckets.DeleteUploads(ctx, bucket); err != nil {
+ uploadsInternal(w, "delete rules "+acct.Sqid+"/"+app, err)
+ return
+ }
+ }
+ if err := s.writeUploadsRecord(ctx, acct.Sqid, app, bucket, "", nil); err != nil {
+ uploadsInternal(w, "disable record "+acct.Sqid+"/"+app, err)
+ return
+ }
+ writeJSON(w, http.StatusOK, answer)
+}
diff --git a/internal/console/apistoreuploads_test.go b/internal/console/apistoreuploads_test.go
new file mode 100644
index 000000000..013c0b443
--- /dev/null
+++ b/internal/console/apistoreuploads_test.go
@@ -0,0 +1,572 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "slices"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/objstore"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/storecfg"
+)
+
+// uploadsFixture is a console whose app titogo has a granted store with a
+// bucket that passes every check, and alice's CLI token (a member).
+type uploadsFixture struct {
+ *consoleFixture
+ t *testing.T
+ prov *objstore.MemProvisioner
+ buckets *storecfg.Fake
+ token string
+ bucket string
+}
+
+func newUploads(t *testing.T, code string) *uploadsFixture {
+ t.Helper()
+ fx, prov, buckets, token := grantedMediaStore(t, code)
+ return &uploadsFixture{consoleFixture: fx, t: t, prov: prov, buckets: buckets, token: token, bucket: mediaMintedName(fx)}
+}
+
+func (u *uploadsFixture) url() string { return storeURL(u.consoleFixture, "titogo") + "/uploads" }
+
+// uploadsReply is one answer of either door.
+type uploadsReply struct {
+ status int
+ raw string
+ ans uploadsAnswer
+ err struct{ Error, Code string }
+}
+
+func (u *uploadsFixture) do(method, body string) uploadsReply {
+ u.t.Helper()
+ status, _, raw := rawReq(u.t, method, u.url(), u.token, body)
+ r := uploadsReply{status: status, raw: raw}
+ if status == http.StatusOK {
+ if err := json.Unmarshal([]byte(raw), &r.ans); err != nil {
+ u.t.Fatalf("answer %q: %v", raw, err)
+ }
+ } else {
+ _ = json.Unmarshal([]byte(raw), &r.err)
+ }
+ return r
+}
+
+func (u *uploadsFixture) enable(origins ...string) uploadsReply {
+ u.t.Helper()
+ body := map[string]any{"enabled": true}
+ if origins != nil {
+ body["origins"] = origins
+ }
+ b, _ := json.Marshal(body)
+ return u.do(http.MethodPost, string(b))
+}
+
+func (u *uploadsFixture) disable() uploadsReply {
+ u.t.Helper()
+ return u.do(http.MethodPost, `{"enabled":false}`)
+}
+
+func (u *uploadsFixture) status() uploadsReply {
+ u.t.Helper()
+ return u.do(http.MethodGet, "")
+}
+
+func (u *uploadsFixture) facts() storecfg.Facts { return u.buckets.Facts[u.bucket] }
+
+func (u *uploadsFixture) setFacts(change func(*storecfg.Facts)) {
+ f := u.buckets.Facts[u.bucket]
+ change(&f)
+ u.buckets.Facts[u.bucket] = f
+}
+
+// user is the store's IAM user, whose policy the regrant rewrites.
+func (u *uploadsFixture) user() string { return objstore.UserName(u.sqid, "titogo") }
+
+// stalePolicy makes the user's recorded policy one that predates the
+// multipart actions, so a test can see whether the grant re-ran.
+func (u *uploadsFixture) stalePolicy() {
+ mu := u.prov.Users[u.user()]
+ mu.Policy = "stale"
+ u.prov.Users[u.user()] = mu
+}
+
+func (u *uploadsFixture) wantOK(r uploadsReply) {
+ u.t.Helper()
+ if r.status != http.StatusOK {
+ u.t.Fatalf("status %d %s", r.status, r.raw)
+ }
+}
+
+func (u *uploadsFixture) wantRefused(r uploadsReply, status int, code, msg string) {
+ u.t.Helper()
+ if r.status != status || r.err.Code != code || r.err.Error != msg {
+ u.t.Fatalf("got %d %s, want %d %s %q", r.status, r.raw, status, code, msg)
+ }
+}
+
+func uploadsUnverified(check string) string {
+ return mediaText("media.store_unverified", mediaText("media.check."+check))
+}
+
+// foreignCORS is a CORS rule someone set by hand: any origin may PUT.
+func foreignCORS() []byte {
+ return storecfg.CanonicalCORS([]storecfg.CORSRule{{AllowedMethods: []string{"PUT"}, AllowedOrigins: []string{"*"}}})
+}
+
+// foreignLifecycle is a lifecycle rule someone set by hand: it expires
+// every object after a week.
+func foreignLifecycle() []byte {
+ return storecfg.CanonicalLifecycle([]storecfg.LifecycleRule{{ID: "expire", Status: "Enabled", Other: []string{"expiration"}}})
+}
+
+func TestUploadsOriginsTable(t *testing.T) {
+ for _, tc := range []struct {
+ origin string
+ want string // "" refused
+ }{
+ {"https://shop.example.com", "https://shop.example.com"},
+ {"http://localhost:3000", "http://localhost:3000"},
+ {"https://Shop.Example.com", "https://shop.example.com"},
+ {"http://localhost:65535", "http://localhost:65535"},
+ {"http://localhost:1", "http://localhost:1"},
+ {"http://shop.example.com", ""},
+ {"https://*.example.com", ""},
+ {"https://shop.example.com/", ""},
+ {"https://shop.example.com:8443", ""},
+ {"https://shop.example.com?x=1", ""},
+ {"https://user@shop.example.com", ""},
+ {"https://", ""},
+ {"https://shop..example.com", ""},
+ {"https://-shop.example.com", ""},
+ {"https://shop.example.com.", ""},
+ {"https://" + strings.Repeat("a", 64) + ".example.com", ""},
+ {"https://vidéo.example.com", ""},
+ {"*", ""},
+ {"shop.example.com", ""},
+ {"http://localhost", ""},
+ {"http://localhost:", ""},
+ {"http://localhost:0", ""},
+ {"http://localhost:65536", ""},
+ {"http://localhost:03000", ""},
+ {"http://localhost:+300", ""},
+ {"http://localhost:3000/", ""},
+ {"https://localhost:3000", ""},
+ {"http://127.0.0.1:3000", ""},
+ } {
+ got, ok := uploadsOrigin(tc.origin)
+ if ok != (tc.want != "") || (ok && got != tc.want) {
+ t.Errorf("uploadsOrigin(%q) = %q, %v; want %q", tc.origin, got, ok, tc.want)
+ }
+ }
+
+ nine := []string{}
+ for i := range 9 {
+ nine = append(nine, "https://s"+string(rune('a'+i))+".example.com")
+ }
+ if _, code, msg := uploadsOrigins(nine); code != "too_many_origins" || msg != "uploads accept at most 8 origins" {
+ t.Fatalf("nine origins: %q %q", code, msg)
+ }
+ // Repeats are dropped before counting: eight distinct, given twice.
+ twice := append(append([]string{}, nine[:8]...), nine[:8]...)
+ twice[0] = strings.ToUpper(twice[0])
+ got, code, _ := uploadsOrigins(twice)
+ if code != "" || len(got) != 8 || !slices.IsSorted(got) {
+ t.Fatalf("eight given twice: %v %q", got, code)
+ }
+
+ // At the door: nothing is read or written for a refused origin.
+ u := newUploads(t, "code-uploads-origins")
+ before, etag := rawStoreRecord(t, u.consoleFixture)
+ u.wantRefused(u.enable("https://*.example.com"), http.StatusBadRequest, "bad_origin",
+ `"https://*.example.com" is not an origin uploads accept. use https:// and a host, or http://localhost:<port>`)
+ u.wantRefused(u.enable(nine...), http.StatusBadRequest, "too_many_origins", "uploads accept at most 8 origins")
+ after, etag2 := rawStoreRecord(t, u.consoleFixture)
+ if !bytes.Equal(before, after) || etag != etag2 || len(u.buckets.Calls) != 0 {
+ t.Fatalf("a refused origin touched the store: calls %v", u.buckets.Calls)
+ }
+}
+
+func TestUploadsEnableWritesOneRuleEach(t *testing.T) {
+ u := newUploads(t, "code-uploads-enable")
+ u.stalePolicy()
+ r := u.enable("https://shop.example.com", "http://localhost:3000", "https://shop.example.com")
+ u.wantOK(r)
+ want := []string{"http://localhost:3000", "https://shop.example.com"}
+ if !r.ans.Enabled || !slices.Equal(r.ans.Origins, want) || !r.ans.BucketMatches || r.ans.Mismatch != "" {
+ t.Fatalf("answer = %+v", r.ans)
+ }
+
+ f := u.facts()
+ var cors []storecfg.CORSRule
+ if err := json.Unmarshal(f.CORS, &cors); err != nil || len(cors) != 1 {
+ t.Fatalf("CORS = %s (%v), want one rule", f.CORS, err)
+ }
+ c := cors[0]
+ if !slices.Equal(c.AllowedOrigins, want) || !slices.Equal(c.AllowedMethods, []string{"GET", "HEAD", "PUT"}) ||
+ !slices.Equal(c.AllowedHeaders, []string{"*"}) || !slices.Equal(c.ExposeHeaders, []string{"ETag"}) || c.MaxAgeSeconds != 3600 {
+ t.Fatalf("CORS rule = %+v", c)
+ }
+ var lc []storecfg.LifecycleRule
+ if err := json.Unmarshal(f.Lifecycle, &lc); err != nil || len(lc) != 1 {
+ t.Fatalf("lifecycle = %s (%v), want one rule", f.Lifecycle, err)
+ }
+ if l := lc[0]; l.ID != storecfg.UploadsLifecycleID || l.Prefix != "" || l.Status != "Enabled" ||
+ l.AbortIncompleteMultipartUploadDays != 1 || len(l.Other) != 0 {
+ t.Fatalf("lifecycle rule = %+v", l)
+ }
+
+ rec := storedRecord(t, u.consoleFixture, "titogo")
+ up := rec.Conversion.Uploads
+ if up == nil || !slices.Equal(up.Origins, want) || up.CORSHash != storecfg.Hash(f.CORS) ||
+ up.LifecycleHash != storecfg.Hash(f.Lifecycle) || up.By != "alice@keymail.dev" || up.At.IsZero() {
+ t.Fatalf("recorded uploads = %+v", up)
+ }
+ if !storecfg.ValidIncarnation(rec.Conversion.Incarnation) || rec.Conversion.VerifiedAt == nil {
+ t.Fatalf("conversion block = %+v", rec.Conversion)
+ }
+ if p := u.prov.PolicyFor(u.user()); !strings.Contains(p, "s3:AbortMultipartUpload") || !strings.Contains(p, "s3:ListMultipartUploadParts") {
+ t.Fatalf("the grant did not re-run: policy %q", p)
+ }
+ if n := u.buckets.CallCount("PutUploads"); n != 1 {
+ t.Fatalf("PutUploads calls = %d", n)
+ }
+
+ // Status agrees, and a second enable with other origins replaces the
+ // platform's own rule (its hash is the recorded one).
+ if s := u.status(); s.status != http.StatusOK || !s.ans.Enabled || !s.ans.BucketMatches || !slices.Equal(s.ans.Origins, want) {
+ t.Fatalf("status = %d %s", s.status, s.raw)
+ }
+ u.wantOK(u.enable("https://www.shop.example.com"))
+ if got := u.facts().CORS; !bytes.Equal(got, storecfg.UploadsCORS([]string{"https://www.shop.example.com"})) {
+ t.Fatalf("CORS after update = %s", got)
+ }
+ if up := storedRecord(t, u.consoleFixture, "titogo").Conversion.Uploads; up.CORSHash != storecfg.Hash(u.facts().CORS) {
+ t.Fatalf("record after update = %+v", up)
+ }
+}
+
+func TestUploadsDefaultOriginsArePrinted(t *testing.T) {
+ u := newUploads(t, "code-uploads-default")
+ route := func(host string, mod func(*registry.Route)) registry.Route {
+ r := registry.Route{Host: host, Kind: "instance", Status: "ready", App: "titogo", Account: u.sqid, Platform: true}
+ if mod != nil {
+ mod(&r)
+ }
+ return r
+ }
+ // No ready platform hostname: refused, nothing written.
+ u.addRoute(t, route("custom.example.com", func(r *registry.Route) { r.Platform = false }))
+ u.addRoute(t, route("pending.example.com", func(r *registry.Route) { r.Status = "pending" }))
+ u.addRoute(t, route("canary.example.com", func(r *registry.Route) { r.Canary = true }))
+ u.addRoute(t, route("side.example.com", func(r *registry.Route) { r.Kind = "sidecar" }))
+ u.addRoute(t, route("other.example.com", func(r *registry.Route) { r.App = "other" }))
+ before, _ := rawStoreRecord(t, u.consoleFixture)
+ u.wantRefused(u.enable(), http.StatusConflict, "no_hosts",
+ "this app has no ready platform hostname yet. name the origins with --origin")
+ if after, _ := rawStoreRecord(t, u.consoleFixture); !bytes.Equal(before, after) || len(u.buckets.Calls) != 0 {
+ t.Fatalf("no_hosts touched the store: %v", u.buckets.Calls)
+ }
+
+ u.addRoute(t, route("www.shop.example.com", nil))
+ u.addRoute(t, route("shop.example.com", nil))
+ r := u.enable()
+ u.wantOK(r)
+ want := []string{"https://shop.example.com", "https://www.shop.example.com"}
+ if !slices.Equal(r.ans.Origins, want) {
+ t.Fatalf("default origins = %v, want %v", r.ans.Origins, want)
+ }
+ if got := storedRecord(t, u.consoleFixture, "titogo").Conversion.Uploads.Origins; !slices.Equal(got, want) {
+ t.Fatalf("recorded = %v", got)
+ }
+ if !bytes.Equal(u.facts().CORS, storecfg.UploadsCORS(want)) {
+ t.Fatalf("CORS = %s", u.facts().CORS)
+ }
+}
+
+// The helper both the scan callback and the default origins use (pre-flight
+// F25) admits only ready platform routes of the app.
+func TestUploadsDefaultHostsShareTheCallbackFilter(t *testing.T) {
+ for _, tc := range callbackHostCases() {
+ t.Run(tc.name, func(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.AppsDomain = "carlosapp.dev"
+ for _, r := range tc.routes {
+ fx.addRoute(t, r)
+ }
+ hosts, err := fx.srv.appReadyPlatformHosts(objstore.AppRef{Account: fixtureAcct, App: fixtureApp})
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []string{}
+ for _, r := range tc.routes {
+ if readyPlatformRoute(r, objstore.AppRef{Account: fixtureAcct, App: fixtureApp}) {
+ want = append(want, r.Host)
+ }
+ }
+ slices.Sort(want)
+ if !slices.Equal(hosts, want) || (tc.want != "" && !slices.Contains(hosts, tc.want)) || (tc.want == "" && len(hosts) != 0) {
+ t.Fatalf("hosts = %v, want %v (callback %q)", hosts, want, tc.want)
+ }
+ })
+ }
+}
+
+func TestUploadsRefusesForeignCORS(t *testing.T) {
+ u := newUploads(t, "code-uploads-foreign")
+ if _, code, _, err := eligible(t, u.consoleFixture); err != nil || code != "" {
+ t.Fatalf("verify: %q %v", code, err)
+ }
+ u.setFacts(func(f *storecfg.Facts) { f.CORS = foreignCORS() })
+ u.stalePolicy()
+ before, etag := rawStoreRecord(t, u.consoleFixture)
+ u.wantRefused(u.enable("https://shop.example.com"), http.StatusConflict, "store_unverified", uploadsUnverified("cors"))
+ after, etag2 := rawStoreRecord(t, u.consoleFixture)
+ if !bytes.Equal(before, after) || etag != etag2 {
+ t.Fatal("a refusal wrote the record")
+ }
+ if n := u.buckets.CallCount("PutUploads") + u.buckets.CallCount("DeleteUploads"); n != 0 {
+ t.Fatalf("bucket written %d times", n)
+ }
+ if !bytes.Equal(u.facts().CORS, foreignCORS()) {
+ t.Fatalf("foreign rule replaced: %s", u.facts().CORS)
+ }
+ if p := u.prov.PolicyFor(u.user()); p != "stale" {
+ t.Fatalf("the grant ran for a refused enable: %q", p)
+ }
+}
+
+// Pre-flight F4 and the plan review's binding history: enabling or updating
+// inspects the bucket immediately before writing, for every store, however
+// it was verified.
+func TestUploadsReinspectsMintedAndVerifiedStores(t *testing.T) {
+ t.Run("a store the platform minted, verified at first use", func(t *testing.T) {
+ u := newUploads(t, "code-uploads-minted")
+ if _, code, _, err := eligible(t, u.consoleFixture); err != nil || code != "" {
+ t.Fatalf("verify: %q %v", code, err)
+ }
+ u.setFacts(func(f *storecfg.Facts) { f.Lifecycle = foreignLifecycle() })
+ u.wantRefused(u.enable("https://shop.example.com"), http.StatusConflict, "store_unverified", uploadsUnverified("lifecycle"))
+ if n := u.buckets.CallCount("PutUploads"); n != 0 {
+ t.Fatalf("PutUploads called %d times", n)
+ }
+ if !bytes.Equal(u.facts().Lifecycle, foreignLifecycle()) {
+ t.Fatal("foreign lifecycle replaced")
+ }
+ })
+ t.Run("a store verified earlier, uploads on", func(t *testing.T) {
+ u := newUploads(t, "code-uploads-verified")
+ u.wantOK(u.enable("https://shop.example.com"))
+ u.setFacts(func(f *storecfg.Facts) { f.Lifecycle = foreignLifecycle() })
+ before, _ := rawStoreRecord(t, u.consoleFixture)
+ u.wantRefused(u.enable("https://shop.example.com"), http.StatusConflict, "store_unverified", uploadsUnverified("lifecycle"))
+ if n := u.buckets.CallCount("PutUploads"); n != 1 {
+ t.Fatalf("PutUploads called %d times, want only the first enable's", n)
+ }
+ if after, _ := rawStoreRecord(t, u.consoleFixture); !bytes.Equal(before, after) {
+ t.Fatal("refusal wrote the record")
+ }
+ })
+ t.Run("an origins update after the CORS rule was changed by hand", func(t *testing.T) {
+ u := newUploads(t, "code-uploads-handcors")
+ u.wantOK(u.enable("https://shop.example.com"))
+ // Platform-shaped, but not what the platform recorded writing.
+ hand := storecfg.UploadsCORS([]string{"https://shop.example.com", "https://evil.example.net"})
+ u.setFacts(func(f *storecfg.Facts) { f.CORS = hand })
+ u.wantRefused(u.enable("https://www.shop.example.com"), http.StatusConflict, "store_unverified", uploadsUnverified("cors"))
+ if n := u.buckets.CallCount("PutUploads"); n != 1 {
+ t.Fatalf("PutUploads called %d times", n)
+ }
+ if !bytes.Equal(u.facts().CORS, hand) {
+ t.Fatal("hand-written CORS replaced")
+ }
+ })
+}
+
+func TestUploadsDisableLeavesForeignRules(t *testing.T) {
+ t.Run("the platform's own rules are removed", func(t *testing.T) {
+ u := newUploads(t, "code-uploads-disable")
+ u.wantOK(u.enable("https://shop.example.com"))
+ r := u.disable()
+ u.wantOK(r)
+ if r.ans.Enabled || !r.ans.BucketMatches || r.ans.Mismatch != "" || r.ans.Origins == nil || len(r.ans.Origins) != 0 {
+ t.Fatalf("answer = %s", r.raw)
+ }
+ if f := u.facts(); f.CORS != nil || f.Lifecycle != nil || u.buckets.CallCount("DeleteUploads") != 1 {
+ t.Fatalf("rules left: %s %s", f.CORS, f.Lifecycle)
+ }
+ if up := storedRecord(t, u.consoleFixture, "titogo").Conversion.Uploads; up != nil {
+ t.Fatalf("record kept uploads: %+v", up)
+ }
+ if s := u.status(); s.status != http.StatusOK || s.ans.Enabled {
+ t.Fatalf("status after disable = %s", s.raw)
+ }
+ })
+ t.Run("a hand-changed rule stays, and so does the platform's beside it", func(t *testing.T) {
+ u := newUploads(t, "code-uploads-disable-foreign")
+ u.wantOK(u.enable("https://shop.example.com"))
+ u.setFacts(func(f *storecfg.Facts) { f.CORS = foreignCORS() })
+ r := u.disable()
+ u.wantOK(r)
+ if r.ans.Enabled || r.ans.BucketMatches || r.ans.Mismatch != "cors" {
+ t.Fatalf("answer = %s", r.raw)
+ }
+ if n := u.buckets.CallCount("DeleteUploads"); n != 0 {
+ t.Fatalf("DeleteUploads called %d times beside a foreign rule", n)
+ }
+ if f := u.facts(); !bytes.Equal(f.CORS, foreignCORS()) || !bytes.Equal(f.Lifecycle, storecfg.UploadsLifecycle()) {
+ t.Fatalf("bucket = %s %s", f.CORS, f.Lifecycle)
+ }
+ if up := storedRecord(t, u.consoleFixture, "titogo").Conversion.Uploads; up != nil {
+ t.Fatalf("record kept uploads: %+v", up)
+ }
+ })
+ t.Run("nothing recorded: nothing read, nothing written", func(t *testing.T) {
+ u := newUploads(t, "code-uploads-disable-none")
+ u.setFacts(func(f *storecfg.Facts) { f.CORS = foreignCORS() })
+ before, _ := rawStoreRecord(t, u.consoleFixture)
+ r := u.disable()
+ u.wantOK(r)
+ if r.ans.Enabled || len(u.buckets.Calls) != 0 {
+ t.Fatalf("answer %s, calls %v", r.raw, u.buckets.Calls)
+ }
+ if after, _ := rawStoreRecord(t, u.consoleFixture); !bytes.Equal(before, after) {
+ t.Fatal("disable wrote the record")
+ }
+ })
+}
+
+func TestUploadsStatusComparesWithTheRecord(t *testing.T) {
+ u := newUploads(t, "code-uploads-status")
+ if s := u.status(); s.status != http.StatusOK || s.ans.Enabled || !s.ans.BucketMatches || s.ans.Origins == nil {
+ t.Fatalf("off = %s", s.raw)
+ }
+ if len(u.buckets.Calls) != 0 {
+ t.Fatalf("status of uploads that are off read the bucket: %v", u.buckets.Calls)
+ }
+ u.wantOK(u.enable("https://shop.example.com"))
+ u.setFacts(func(f *storecfg.Facts) { f.CORS = foreignCORS() })
+ if s := u.status(); !s.ans.Enabled || s.ans.BucketMatches || s.ans.Mismatch != "cors" {
+ t.Fatalf("hand-changed CORS = %s", s.raw)
+ }
+ u.setFacts(func(f *storecfg.Facts) {
+ f.CORS = storecfg.UploadsCORS([]string{"https://shop.example.com"})
+ f.Lifecycle = nil
+ })
+ if s := u.status(); s.ans.BucketMatches || s.ans.Mismatch != "lifecycle" {
+ t.Fatalf("removed lifecycle = %s", s.raw)
+ }
+ u.setFacts(func(f *storecfg.Facts) { f.Lifecycle = storecfg.UploadsLifecycle(); f.CORS = nil })
+ if s := u.status(); s.ans.BucketMatches || s.ans.Mismatch != "cors" {
+ t.Fatalf("removed CORS = %s", s.raw)
+ }
+}
+
+func TestUploadsRefusedWithoutConfigurationOrOnClaims(t *testing.T) {
+ u := newUploads(t, "code-uploads-config")
+ u.srv.cfg.StoreConversion = false
+ u.wantRefused(u.enable("https://shop.example.com"), http.StatusServiceUnavailable, "uploads_not_configured",
+ "browser uploads are not set up on this deployment")
+ u.wantRefused(u.status(), http.StatusServiceUnavailable, "uploads_not_configured",
+ "browser uploads are not set up on this deployment")
+ u.srv.cfg.StoreConversion = true
+ u.srv.cfg.HostClaim = true
+ claims := mediaText("media.claims_console")
+ u.wantRefused(u.enable("https://shop.example.com"), http.StatusServiceUnavailable, "claims_console", claims)
+ u.wantRefused(u.disable(), http.StatusServiceUnavailable, "claims_console", claims)
+ u.wantRefused(u.status(), http.StatusServiceUnavailable, "claims_console", claims)
+ if len(u.buckets.Calls) != 0 {
+ t.Fatalf("refusals touched the bucket: %v", u.buckets.Calls)
+ }
+}
+
+func TestUploadsRefusesNoStoreAndUnverifiedStore(t *testing.T) {
+ fx, _, buckets, token := mediaStoreFixture(t, "code-uploads-nostore")
+ u := &uploadsFixture{consoleFixture: fx, t: t, buckets: buckets, token: token, bucket: mediaMintedName(fx)}
+ u.wantRefused(u.enable("https://shop.example.com"), http.StatusConflict, "no_store",
+ mediaText("media.no_store", "titogo", "titogo"))
+
+ v := newUploads(t, "code-uploads-unverified")
+ v.setFacts(func(f *storecfg.Facts) { f.Encryption = "aws:kms" })
+ v.wantRefused(v.enable("https://shop.example.com"), http.StatusConflict, "store_unverified", uploadsUnverified("encryption"))
+ if n := v.buckets.CallCount("PutUploads"); n != 0 {
+ t.Fatalf("PutUploads called %d times", n)
+ }
+}
+
+// The grant runs before any bucket write, so a failed grant leaves the
+// bucket as it was.
+func TestUploadsGrantFailureWritesNoRules(t *testing.T) {
+ u := newUploads(t, "code-uploads-grantfail")
+ u.prov.FailNext["EnsureUser"] = errors.New("iam down")
+ r := u.enable("https://shop.example.com")
+ if r.status != http.StatusInternalServerError {
+ t.Fatalf("status = %d %s", r.status, r.raw)
+ }
+ if n := u.buckets.CallCount("PutUploads"); n != 0 {
+ t.Fatalf("PutUploads called %d times after a failed grant", n)
+ }
+ if up := storedRecord(t, u.consoleFixture, "titogo").Conversion.Uploads; up != nil {
+ t.Fatalf("recorded = %+v", up)
+ }
+ u.wantOK(u.enable("https://shop.example.com"))
+}
+
+// uploadsRecordFailStore fails every write of the store record while armed. On
+// a verified, healthy store the only such write an enable makes is the one
+// after PutUploads.
+type uploadsRecordFailStore struct {
+ release.Store
+ key string
+ armed atomic.Bool
+}
+
+func (s *uploadsRecordFailStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if key == s.key && s.armed.Load() {
+ return "", errors.New("bucket write failed")
+ }
+ return s.Store.Put(ctx, key, body, ifMatch)
+}
+
+// A record write that fails after PutUploads puts the bucket back to what
+// the record still says, so the platform's own rules never stand
+// unrecorded (which every later check would read as foreign).
+func TestUploadsRecordFailurePutsTheBucketBack(t *testing.T) {
+ u := newUploads(t, "code-uploads-recordfail")
+ if _, code, _, err := eligible(t, u.consoleFixture); err != nil || code != "" {
+ t.Fatalf("verify: %q %v", code, err)
+ }
+ fs := &uploadsRecordFailStore{Store: u.srv.cfg.Releases, key: objstore.Key(u.sqid, "titogo")}
+ u.srv.cfg.Releases = fs
+
+ // Nothing recorded before: the rules are removed again.
+ fs.armed.Store(true)
+ if r := u.enable("https://shop.example.com"); r.status != http.StatusInternalServerError {
+ t.Fatalf("status = %d %s", r.status, r.raw)
+ }
+ if f := u.facts(); f.CORS != nil || f.Lifecycle != nil {
+ t.Fatalf("unrecorded rules left: %s %s", f.CORS, f.Lifecycle)
+ }
+ fs.armed.Store(false)
+ u.wantOK(u.enable("https://shop.example.com"))
+
+ // Uploads on before: the recorded rules are put back.
+ fs.armed.Store(true)
+ if r := u.enable("https://www.shop.example.com"); r.status != http.StatusInternalServerError {
+ t.Fatalf("status = %d %s", r.status, r.raw)
+ }
+ fs.armed.Store(false)
+ if got := u.facts().CORS; !bytes.Equal(got, storecfg.UploadsCORS([]string{"https://shop.example.com"})) {
+ t.Fatalf("CORS = %s, want the recorded rule back", got)
+ }
+ if s := u.status(); !s.ans.BucketMatches {
+ t.Fatalf("status after a failed update = %s", s.raw)
+ }
+ u.wantOK(u.enable("https://www.shop.example.com"))
+}
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 78aa94587..db9c4159e 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -2285,6 +2285,18 @@ var claimFixtures = map[string]claimFixture{
do: claimRefusedAPI(http.MethodGet, "/api/cli/apps/bab/shop/media/conversions/0123456789abcdef0123456789abcdef", ""),
status: http.StatusServiceUnavailable, msg: mediaText("media.claims_console"),
}},
+ // Browser uploads (spec §11 A1): both doors refuse on a host-claim
+ // console after apiAccountApp, before the store record or the bucket.
+ "route POST /api/cli/apps/{account}/{app}/store/uploads": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/shop"), setup: claimEnrollShop,
+ do: claimRefusedAPI(http.MethodPost, "/api/cli/apps/bab/shop/store/uploads", `{"enabled":true,"origins":["https://shop.example.com"]}`),
+ status: http.StatusServiceUnavailable, msg: mediaText("media.claims_console"),
+ }},
+ "route GET /api/cli/apps/{account}/{app}/store/uploads": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/shop"), setup: claimEnrollShop,
+ do: claimRefusedAPI(http.MethodGet, "/api/cli/apps/bab/shop/store/uploads", ""),
+ status: http.StatusServiceUnavailable, msg: mediaText("media.claims_console"),
+ }},
"route POST /api/cli/apps/{account}/{app}/pdf/{route...}": {door: &claimDoor{
apps: claimRefs("bab/shop"),
setup: func(t *testing.T, cx *claimCase) {
diff --git a/internal/console/linkedpolicy.go b/internal/console/linkedpolicy.go
index 31a74ab7a..6f930e18c 100644
--- a/internal/console/linkedpolicy.go
+++ b/internal/console/linkedpolicy.go
@@ -259,6 +259,8 @@ var linkedPolicies = map[string]linkedPolicy{
"POST /api/cli/apps/{account}/{app}/store/scan/callback-key/rotate": linkedRefuse,
"POST /api/cli/apps/{account}/{app}/store/scan/object": linkedRefuse,
"GET /api/cli/apps/{account}/{app}/store/scan/object": linkedRefuse,
+ "POST /api/cli/apps/{account}/{app}/store/uploads": linkedRefuse,
+ "GET /api/cli/apps/{account}/{app}/store/uploads": linkedRefuse,
"POST /api/cli/apps/{account}/{app}/pdf/{route...}": linkedRefuse,
"POST /api/cli/apps/{account}/{app}/media/conversions": linkedRefuse,
"GET /api/cli/apps/{account}/{app}/media/conversions/{id}": linkedRefuse,
diff --git a/internal/console/media_copy.go b/internal/console/media_copy.go
index 740be02f9..80bb66ebd 100644
--- a/internal/console/media_copy.go
+++ b/internal/console/media_copy.go
@@ -35,6 +35,14 @@ var mediaCopy = map[string]string{
"media.rate": "this account has asked for more than %d conversions in a minute. try again in a moment",
"media.job_not_found": "this app has no conversion with that id",
+ // Browser uploads (carlos store uploads, JSON). The host-claim refusal
+ // is media.claims_console; no_store and store_unverified are the
+ // door's.
+ "uploads.not_configured": "browser uploads are not set up on this deployment",
+ "uploads.bad_origin": "%q is not an origin uploads accept. use https:// and a host, or http://localhost:<port>",
+ "uploads.too_many_origins": "uploads accept at most 8 origins",
+ "uploads.no_hosts": "this app has no ready platform hostname yet. name the origins with --origin",
+
// Store checks: one fills media.store_unverified.
"media.check.name": "its bucket is not named the way this deployment names buckets",
"media.check.owner": "its bucket belongs to another AWS account",
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go
index af6f6e09f..b66d0b1b8 100644
--- a/internal/console/routedecls.go
+++ b/internal/console/routedecls.go
@@ -988,6 +988,12 @@ var routeDecls = []routeDecl{
{Pattern: "POST /api/cli/apps/{account}/{app}/store/grant", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Admin), Handler: (*Server).handleAPIStoreGrant},
{Pattern: "POST /api/cli/apps/{account}/{app}/store/rotate", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Admin), Handler: (*Server).handleAPIStoreRotate},
{Pattern: "POST /api/cli/apps/{account}/{app}/store/rotate/finish", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Admin), Handler: (*Server).handleAPIStoreRotateFinish},
+ // Browser uploads (apistoreuploads.go, media conversion spec §5.6): a
+ // member verb that writes the platform's CORS and multipart-cleanup rules
+ // onto the store's bucket, never over a rule the platform did not write.
+ // Admin, as every member store verb; refused on a host-claim console.
+ {Pattern: "POST /api/cli/apps/{account}/{app}/store/uploads", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Admin), Handler: (*Server).handleAPIStoreUploadsSet},
+ {Pattern: "GET /api/cli/apps/{account}/{app}/store/uploads", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Admin), Handler: (*Server).handleAPIStoreUploadsGet},
// Account-level storage entitlement doors are person-only. Applying speaks
// for an account owner; approvals spend deployment money and deliberately
// resolve their target without requiring operator membership in it.
diff --git a/internal/console/scandeliver.go b/internal/console/scandeliver.go
index 2c5e05fd3..5c4d2c9a9 100644
--- a/internal/console/scandeliver.go
+++ b/internal/console/scandeliver.go
@@ -8,12 +8,14 @@ import (
"io"
"log"
"net/http"
+ "slices"
"strings"
"sync"
"time"
"github.com/carlosframework/platform/internal/hostops"
"github.com/carlosframework/platform/internal/objstore"
+ "github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
)
@@ -274,6 +276,55 @@ func (p *scanDeliveryPool) post(ctx context.Context, job scanDeliveryJob, target
return retry, nil
}
+// readyPlatformRoute is the one filter for "a platform-assigned name of this
+// app that serves now": a ready route of ref's account and app that the
+// platform named (not a custom domain), and neither a canary nor a sidecar.
+// The scan callback's host and the browser uploads' default origins both
+// pick from it (plan 2 pre-flight F25), so the two cannot drift.
+func readyPlatformRoute(rt registry.Route, ref objstore.AppRef) bool {
+ return rt.App == ref.App && release.RouteAccount(rt) == ref.Account && rt.Status == "ready" &&
+ rt.Platform && !rt.Canary && !rt.IsSidecar()
+}
+
+// readyPlatformRoutes is every route of the registry readyPlatformRoute
+// admits for ref; none when this console has no registry.
+func (s *Server) readyPlatformRoutes(ref objstore.AppRef) ([]registry.Route, error) {
+ if s.cfg.Registry == "" {
+ return nil, nil
+ }
+ reg, err := openRegistry(s.cfg.Registry)
+ if err != nil {
+ return nil, err
+ }
+ routes, err := reg.List()
+ if err != nil {
+ return nil, err
+ }
+ out := routes[:0]
+ for _, rt := range routes {
+ if readyPlatformRoute(rt, ref) {
+ out = append(out, rt)
+ }
+ }
+ return out, nil
+}
+
+// appReadyPlatformHosts is every host readyPlatformRoute admits for ref,
+// sorted and without repeats: the origins `carlos store uploads enable`
+// uses when it is given none (media conversion spec §5.6).
+func (s *Server) appReadyPlatformHosts(ref objstore.AppRef) ([]string, error) {
+ routes, err := s.readyPlatformRoutes(ref)
+ if err != nil {
+ return nil, err
+ }
+ hosts := make([]string, 0, len(routes))
+ for _, rt := range routes {
+ hosts = append(hosts, rt.Host)
+ }
+ slices.Sort(hosts)
+ return slices.Compact(hosts), nil
+}
+
// scanCallbackHost returns only a platform-assigned name that exists in the
// registry: the canonical app.account.apps-domain when it is a ready platform
// route, otherwise the lexicographically first ready platform route of the app.
@@ -281,21 +332,13 @@ func (s *Server) scanCallbackHost(ref objstore.AppRef) (string, error) {
if s.cfg.AppsDomain == "" || s.cfg.Registry == "" {
return "", nil
}
- reg, err := openRegistry(s.cfg.Registry)
- if err != nil {
- return "", err
- }
- routes, err := reg.List()
+ routes, err := s.readyPlatformRoutes(ref)
if err != nil {
return "", err
}
canonical := ref.App + "." + ref.Account + "." + strings.TrimPrefix(s.cfg.AppsDomain, ".")
best := ""
for _, rt := range routes {
- if rt.App != ref.App || release.RouteAccount(rt) != ref.Account || rt.Status != "ready" ||
- !rt.Platform || rt.Canary || rt.IsSidecar() {
- continue
- }
if rt.Host == canonical {
return canonical, nil
}
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 037040197..b5eba2d34 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -129,6 +129,7 @@ route GET /api/cli/apps/{account}/{app}/source
route GET /api/cli/apps/{account}/{app}/store
route GET /api/cli/apps/{account}/{app}/store/scan
route GET /api/cli/apps/{account}/{app}/store/scan/object
+route GET /api/cli/apps/{account}/{app}/store/uploads
route GET /api/cli/apps/{account}/{app}/tags
route GET /api/cli/apps/{account}/{app}/tags/{version}
route GET /api/cli/apps/{account}/{app}/telemetry
@@ -350,6 +351,7 @@ route POST /api/cli/apps/{account}/{app}/store/scan/grant
route POST /api/cli/apps/{account}/{app}/store/scan/object
route POST /api/cli/apps/{account}/{app}/store/scan/revoke
route POST /api/cli/apps/{account}/{app}/store/scan/sweep
+route POST /api/cli/apps/{account}/{app}/store/uploads
route POST /api/cli/apps/{account}/{app}/ttl
route POST /api/cli/billing/house
route POST /api/cli/billing/problems/{id}/close
diff --git a/internal/objstore/aws.go b/internal/objstore/aws.go
index 341b0295f..b186ef1ce 100644
--- a/internal/objstore/aws.go
+++ b/internal/objstore/aws.go
@@ -183,6 +183,16 @@ type policyDocument struct {
// rewrite, not a regression: PutUserPolicy overwrites wholesale and is
// idempotent, so the cost is one extra IAM call per re-walk.
//
+// s3:AbortMultipartUpload and s3:ListMultipartUploadParts are in the object
+// Allow for every store (media conversion spec §5.6): an app's server that
+// starts a multipart upload for a browser must be able to list the parts it
+// has and abandon an upload it gives up on. Creating and completing one, and
+// uploading each part, are authorised as s3:PutObject, so the two Denys below
+// (the tag-key one and, past the storage grace, the write deny) cover them
+// as they cover a simple PUT. Neither new action writes object data or tags.
+// `carlos store uploads enable` re-runs the grant so a store granted before
+// this change gets them; any other re-walk does too.
+//
// The deny is weaker than AWS's own tag-based access control example, which
// denies reads UNLESS an object is tagged clean and so blocks unscanned
// objects too. This one blocks only known-infected objects; unscanned ones
@@ -196,6 +206,7 @@ func storePolicyJSON(bucketARN string, deny *DenyTag, denyWrites bool) string {
{Effect: "Allow", Action: []string{"s3:ListBucket"}, Resource: bucketARN},
{Effect: "Allow", Action: []string{
"s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:GetObjectTagging",
+ "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts",
}, Resource: bucketARN + "/*"},
},
}
diff --git a/internal/objstore/aws_test.go b/internal/objstore/aws_test.go
index 073c835f9..2543efb62 100644
--- a/internal/objstore/aws_test.go
+++ b/internal/objstore/aws_test.go
@@ -641,3 +641,78 @@ func TestEnsureUserOmitsAnEmptyBoundary(t *testing.T) {
t.Fatal("PermissionsBoundary was set from an empty boundary; want the field omitted")
}
}
+
+// TestStorePolicyGrantsMultipartCleanup: browser uploads (media conversion
+// spec §5.6) need an app's server to list an upload's parts and abandon an
+// upload, so every store's object Allow carries both actions, on the
+// bucket's objects only. Nothing else moves: the bucket Allow, the two
+// anti-forgery Denys, the enforcement Deny and the write deny are exactly
+// what they were.
+func TestStorePolicyGrantsMultipartCleanup(t *testing.T) {
+ const arn = "arn:aws:s3:::b"
+ for _, tc := range []struct {
+ deny *DenyTag
+ denyWrites bool
+ }{{nil, false}, {&DenyTag{Key: TagVerdict, Value: string(VerdictInfected)}, false}, {nil, true},
+ {&DenyTag{Key: TagVerdict, Value: string(VerdictInfected)}, true}} {
+ doc := storePolicyJSON(arn, tc.deny, tc.denyWrites)
+ var parsed policyDocument
+ if err := json.Unmarshal([]byte(doc), &parsed); err != nil {
+ t.Fatalf("not valid JSON: %v\n%s", err, doc)
+ }
+ var objectAllow []string
+ for _, st := range parsed.Statement {
+ for _, a := range st.Action {
+ if a != "s3:AbortMultipartUpload" && a != "s3:ListMultipartUploadParts" {
+ continue
+ }
+ if st.Effect != "Allow" || st.Resource != arn+"/*" {
+ t.Fatalf("%s granted outside the object Allow: %+v\n%s", a, st, doc)
+ }
+ }
+ if st.Effect == "Allow" && st.Resource == arn+"/*" {
+ objectAllow = st.Action
+ }
+ }
+ want := []string{"s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:GetObjectTagging",
+ "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts"}
+ if len(objectAllow) != len(want) {
+ t.Fatalf("object Allow = %v, want %v", objectAllow, want)
+ }
+ for i := range want {
+ if objectAllow[i] != want[i] {
+ t.Fatalf("object Allow = %v, want %v", objectAllow, want)
+ }
+ }
+ if got := parsed.Statement[0]; got.Effect != "Allow" || got.Resource != arn || len(got.Action) != 1 || got.Action[0] != "s3:ListBucket" {
+ t.Fatalf("bucket Allow changed: %+v", got)
+ }
+ // The Denys are unchanged: the same statements, byte for byte, as a
+ // policy built without the two actions would hold.
+ var denys []policyStatement
+ for _, st := range parsed.Statement {
+ if st.Effect == "Deny" {
+ denys = append(denys, st)
+ }
+ }
+ wantDenys := 2
+ if tc.deny != nil {
+ wantDenys++
+ }
+ if tc.denyWrites {
+ wantDenys++
+ }
+ if len(denys) != wantDenys || len(parsed.Statement) != 2+wantDenys {
+ t.Fatalf("statements changed: %d Denys of %d statements\n%s", len(denys), len(parsed.Statement), doc)
+ }
+ got, _ := json.Marshal(denys[:2])
+ if string(got) != `[{"Effect":"Deny","Action":["s3:PutObjectTagging","s3:DeleteObjectTagging","s3:PutObjectVersionTagging","s3:DeleteObjectVersionTagging"],"Resource":"arn:aws:s3:::b/*"},`+
+ `{"Effect":"Deny","Action":["s3:PutObject"],"Resource":"arn:aws:s3:::b/*","Condition":{"ForAnyValue:StringEquals":{"s3:RequestObjectTagKeys":["carlos-scan","carlos-scan-version","carlos-scan-at"]}}}]` {
+ t.Fatalf("anti-forgery Denys changed:\n%s", got)
+ }
+ assertNoPutObjectTagging(t, doc)
+ if tc.denyWrites && writeDenyOf(t, doc) == nil {
+ t.Fatalf("write deny lost:\n%s", doc)
+ }
+ }
+}
diff --git a/parity/cli.tsv b/parity/cli.tsv
index cb32f4faf..fd426d02c 100644
--- a/parity/cli.tsv
+++ b/parity/cli.tsv
@@ -248,6 +248,9 @@ store scan rotate-webhook-key customer - - - - -
store scan status customer - - - - -
store scan sweep customer - - - - -
store status customer - - - - -
+store uploads disable customer - - - - -
+store uploads enable customer - - - - -
+store uploads status customer - - - - -
system antivirus disable operator - - - - -
system antivirus enable operator - - - - -
system antivirus rotate-webhook-key operator - - - - -
diff --git a/parity/parity.tsv b/parity/parity.tsv
index 7fcdde519..aede8cde2 100644
--- a/parity/parity.tsv
+++ b/parity/parity.tsv
@@ -127,6 +127,7 @@ store-status storage both store status GET /a/{sqid}/apps/{app}/settings/{sectio
store-apply storage both store apply GET /a/{sqid}/settings ; POST /a/{sqid}/store/apply
store-rotate storage gap store rotate wp-email-storage
store-scan storage gap store scan request ; store scan status ; store scan grant ; store scan revoke ; store scan sweep ; store scan enforce ; store scan rotate-webhook-key wp-email-storage
+store-uploads storage gap store uploads enable ; store uploads status ; store uploads disable wp-email-storage
store-destroy storage console-only POST /a/{sqid}/apps/{app}/store/destroy Needs a passkey.
# email
diff --git a/store.go b/store.go
index 775051e8b..a3a0e384d 100644
--- a/store.go
+++ b/store.go
@@ -86,6 +86,11 @@ const storeUsage = `usage: carlos store <create|status|apply|approvals|approve|d
the sub-verbs. A clean result on a client-encrypted
store means nothing, and the CLI says so rather
than claiming coverage it cannot have.
+ uploads <enable|status|disable> --app <a> [--origin <o>]...
+ Lets browsers on the origins you name upload large
+ files in parts straight to the app's store. With no
+ --origin, it uses and prints the app's hostnames
+ today. disable removes the rules again.
--account <sqid|name> account the app belongs to (default: your only
account, or the configured/chosen one) —
@@ -124,6 +129,7 @@ func storeCommand() *clireg.Node {
raw("approve", op, runStoreApprove),
raw("decline", op, runStoreDecline),
storeScanCommand(),
+ storeUploadsCommand(),
},
Fallback: func(args, consumed []string) {
fmt.Fprint(os.Stderr, storeUsage)
diff --git a/store_uploads.go b/store_uploads.go
new file mode 100644
index 000000000..8c2f06a19
--- /dev/null
+++ b/store_uploads.go
@@ -0,0 +1,140 @@
+// store_uploads.go is `carlos store uploads`: let browsers on the origins a
+// member names upload straight to the app's store (media conversion spec
+// §5.6). API mode only, like the rest of `store`. The console writes the
+// bucket's CORS rule and multipart-cleanup rule and refuses any rule this
+// platform did not write; this file only sends the request and prints the
+// copy deck's lines (docs/superpowers/notes/media-conversion-copy-deck.md,
+// `carlos store uploads`).
+package main
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/clireg"
+)
+
+const storeUploadsUsage = `usage: carlos store uploads <enable|status|disable> --app <a> [flags]
+
+ enable --app <a> [--origin <o>]...
+ status --app <a>
+ disable --app <a>
+
+Lets browsers on the origins you name upload large files in parts straight to the app's store. With no --origin, it uses and prints the app's hostnames today. disable removes the rules again.
+
+Flags: --account/--account-id to disambiguate, --console to pick a console.
+`
+
+// The deck's lines for `carlos store uploads` (cli.uploads.*).
+const (
+ cliUploadsOn = "uploads on"
+ cliUploadsOff = "uploads off"
+ cliUploadsOrigins = "origins %s"
+ cliUploadsDefaultNote = "note these are the app's hostnames today. run enable again for new ones"
+ cliUploadsRulesOK = "rules in place"
+ cliUploadsRulesCORS = "rules changed: the CORS rule is not the one this platform wrote"
+ cliUploadsRulesLifecycle = "rules changed: the multipart cleanup rule is not the one this platform wrote"
+)
+
+// storeUploadsCommand is `carlos store uploads`: three raw leaves sharing
+// runStoreUploads. Bare or any other word is storeUploadsUsage on stderr,
+// exit 1.
+func storeUploadsCommand() *clireg.Node {
+ const cust = clireg.Customer
+ leaf := func(verb string) *clireg.Node {
+ return raw(verb, cust, func(args []string) { runStoreUploads(args, verb) })
+ }
+ return &clireg.Node{
+ Name: "uploads",
+ Audience: cust,
+ Children: []*clireg.Node{leaf("enable"), leaf("status"), leaf("disable")},
+ Fallback: func(args, consumed []string) {
+ fmt.Fprint(os.Stderr, storeUploadsUsage)
+ os.Exit(1)
+ },
+ }
+}
+
+func runStoreUploads(args []string, verb string) {
+ fs := flag.NewFlagSet("store uploads "+verb, flag.ExitOnError)
+ app := appFlag(fs, "app whose store to "+verb+" browser uploads for")
+ var origins multiFlag
+ if verb == "enable" {
+ fs.Var(&origins, "origin", "an origin browsers upload from: https:// and a host, or http://localhost:<port>. Repeat for more, at most 8")
+ }
+ acctRaw, acctIDRaw, _ := accountFlags(fs)
+ consoleFlag := consoleOption(fs, "console origin to act through (API mode only; default: the only logged-in one)")
+ fs.Usage = flagUsage(fs, "")
+ fs.Parse(args)
+
+ name := strings.TrimSpace(*app)
+ usage := "usage: carlos store uploads " + verb + " --app <a> [--account <sqid-or-name>] [--console <origin>]"
+ if name != "" {
+ if err := validAppName(name); err != nil {
+ log.Fatalf("store uploads %s: %v", verb, err)
+ }
+ }
+ sess := requireStoreAPISession(*consoleFlag)
+ printUsing(stdout, sess)
+ acct := resolvedAccount(sess, acctRaw, acctIDRaw)
+ name = resolvedApp(sess, acct, name, usage)
+ if err := runStoreUploadsWith(context.Background(), sess, acct, name, verb, origins, stdout); err != nil {
+ log.Fatalf("store uploads %s: %v", verb, err)
+ }
+}
+
+// runStoreUploadsWith calls the door for verb and prints its answer:
+// enable and status the same block, disable `uploads off`.
+func runStoreUploadsWith(ctx context.Context, s *apiSession, a apiAcct, app, verb string, origins []string, w io.Writer) error {
+ var res apiUploadsReply
+ var err error
+ switch verb {
+ case "enable":
+ var given []string
+ for _, o := range origins {
+ given = append(given, strings.TrimSpace(o))
+ }
+ res, err = s.storeUploadsSet(ctx, a, app, true, given)
+ case "disable":
+ res, err = s.storeUploadsSet(ctx, a, app, false, nil)
+ case "status":
+ res, err = s.storeUploadsStatus(ctx, a, app)
+ default:
+ return fmt.Errorf("unknown verb %q", verb)
+ }
+ if err != nil {
+ return err
+ }
+ if verb == "disable" {
+ res.Enabled = false
+ }
+ printStoreUploads(w, res, verb == "enable" && len(origins) == 0)
+ return nil
+}
+
+// printStoreUploads is the deck's block. note is enable with no --origin:
+// the origins printed are the app's hostnames at this moment.
+func printStoreUploads(w io.Writer, res apiUploadsReply, note bool) {
+ if !res.Enabled {
+ fmt.Fprintln(w, cliUploadsOff)
+ return
+ }
+ fmt.Fprintln(w, cliUploadsOn)
+ fmt.Fprintf(w, cliUploadsOrigins+"\n", strings.Join(res.Origins, ", "))
+ if note {
+ fmt.Fprintln(w, cliUploadsDefaultNote)
+ }
+ switch {
+ case res.BucketMatches:
+ fmt.Fprintln(w, cliUploadsRulesOK)
+ case res.Mismatch == "lifecycle":
+ fmt.Fprintln(w, cliUploadsRulesLifecycle)
+ default:
+ fmt.Fprintln(w, cliUploadsRulesCORS)
+ }
+}
diff --git a/store_uploads_test.go b/store_uploads_test.go
new file mode 100644
index 000000000..902dbdf7d
--- /dev/null
+++ b/store_uploads_test.go
@@ -0,0 +1,97 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+// TestStoreUploadsVerbs: each leaf calls its door with the body the console
+// reads, and prints the copy deck's lines exactly (`carlos store uploads`).
+func TestStoreUploadsVerbs(t *testing.T) {
+ var calls []string
+ answer := `{"enabled":true,"origins":["https://shop.example.com","https://www.shop.example.com"],"bucket_matches":true,"mismatch":""}`
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ b, _ := io.ReadAll(r.Body)
+ calls = append(calls, r.Method+" "+r.URL.RequestURI()+" "+string(b))
+ if r.Method == http.MethodPost && strings.Contains(string(b), `"enabled":false`) {
+ io.WriteString(w, `{"enabled":false,"origins":[],"bucket_matches":true,"mismatch":""}`)
+ return
+ }
+ io.WriteString(w, answer)
+ }))
+ defer ts.Close()
+ s := newTestSession(ts.URL)
+ a := apiAcct{Seg: "bab"}
+ run := func(verb string, origins ...string) string {
+ t.Helper()
+ var out bytes.Buffer
+ if err := runStoreUploadsWith(context.Background(), s, a, "shop", verb, origins, &out); err != nil {
+ t.Fatalf("%s: %v", verb, err)
+ }
+ return out.String()
+ }
+
+ // enable with no --origin: the app's hostnames, and the note.
+ got := run("enable")
+ want := "uploads on\n" +
+ "origins https://shop.example.com, https://www.shop.example.com\n" +
+ "note these are the app's hostnames today. run enable again for new ones\n" +
+ "rules in place\n"
+ if got != want {
+ t.Fatalf("enable:\n%s\nwant:\n%s", got, want)
+ }
+ // enable with origins: no note.
+ answer = `{"enabled":true,"origins":["http://localhost:3000","https://shop.example.com"],"bucket_matches":true,"mismatch":""}`
+ if got := run("enable", "https://shop.example.com", " http://localhost:3000"); got != "uploads on\norigins http://localhost:3000, https://shop.example.com\nrules in place\n" {
+ t.Fatalf("enable --origin:\n%s", got)
+ }
+ // status, with each rules line.
+ answer = `{"enabled":true,"origins":["https://shop.example.com"],"bucket_matches":false,"mismatch":"cors"}`
+ if got := run("status"); got != "uploads on\norigins https://shop.example.com\nrules changed: the CORS rule is not the one this platform wrote\n" {
+ t.Fatalf("status cors:\n%s", got)
+ }
+ answer = `{"enabled":true,"origins":["https://shop.example.com"],"bucket_matches":false,"mismatch":"lifecycle"}`
+ if got := run("status"); got != "uploads on\norigins https://shop.example.com\nrules changed: the multipart cleanup rule is not the one this platform wrote\n" {
+ t.Fatalf("status lifecycle:\n%s", got)
+ }
+ answer = `{"enabled":false,"origins":[],"bucket_matches":true,"mismatch":""}`
+ if got := run("status"); got != "uploads off\n" {
+ t.Fatalf("status off:\n%s", got)
+ }
+ if got := run("disable"); got != "uploads off\n" {
+ t.Fatalf("disable:\n%s", got)
+ }
+
+ wantCalls := []string{
+ `POST /api/cli/apps/bab/shop/store/uploads {"enabled":true}`,
+ `POST /api/cli/apps/bab/shop/store/uploads {"enabled":true,"origins":["https://shop.example.com","http://localhost:3000"]}`,
+ `GET /api/cli/apps/bab/shop/store/uploads `,
+ `GET /api/cli/apps/bab/shop/store/uploads `,
+ `GET /api/cli/apps/bab/shop/store/uploads `,
+ `POST /api/cli/apps/bab/shop/store/uploads {"enabled":false}`,
+ }
+ if strings.Join(calls, "\n") != strings.Join(wantCalls, "\n") {
+ t.Fatalf("calls:\n%s\nwant:\n%s", strings.Join(calls, "\n"), strings.Join(wantCalls, "\n"))
+ }
+}
+
+// A refusal is the console's sentence, unchanged.
+func TestStoreUploadsRefusalIsTheConsolesSentence(t *testing.T) {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusConflict)
+ json.NewEncoder(w).Encode(map[string]string{"code": "no_hosts", "error": "this app has no ready platform hostname yet. name the origins with --origin"})
+ }))
+ defer ts.Close()
+ var out bytes.Buffer
+ err := runStoreUploadsWith(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop", "enable", nil, &out)
+ if err == nil || err.Error() != "this app has no ready platform hostname yet. name the origins with --origin" || out.Len() != 0 {
+ t.Fatalf("err = %v, out %q", err, out.String())
+ }
+}