store uploads: platform owns the rules (A4); account lock; copy pass 3
Task 9 fix round 2. Drops the pending-intent machinery and the per-write ownership checks: enable requires an eligible store (the first-use verification refuses foreign rules), converges the policy, writes both rules and records their hashes; disable removes both and clears the record. Hand edits are overwritten; status still reports them read-only, and re-verification still refuses them. Enable and disable take the account lock before the walk lock, so a scan or storage Deny applied meanwhile survives. Applies Luna pass 3.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+330
−610
docs/superpowers/notes/media-conversion-copy-deck.md+17 −14internal/console/apistoreuploads.go+107 −232internal/console/apistoreuploads_test.go+189 −309internal/console/media_copy.go+3 −3internal/console/mediastore.go+7 −37internal/objstore/objstore.go+3 −11store_uploads.go+4 −4
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md| index fa44f17e4..fd3dbfdd1 100644 |
| --- a/docs/superpowers/notes/media-conversion-copy-deck.md |
| +++ b/docs/superpowers/notes/media-conversion-copy-deck.md |
| @@ -339,25 +339,28 @@ $ carlos store uploads status --app shop |
| uploads off |
| ``` |
| -**Pending Luna pass** (added in Task 9 fix round 1; the code reads them by |
| -key: root `storeUploadsCopy`, console `mediaCopy`). Help and usage text is |
| +**Approved, Luna pass 3** (added in Task 9 fix round 1; brief |
| +`LUNA-COPY-BRIEF-media-conversion-3.md`, result |
| +`LUNA-COPY-RESULT-media-conversion-3.md`: four rows changed and applied |
| +verbatim, the rest approved unchanged; the code reads them by key: root |
| +`storeUploadsCopy`, console `mediaCopy`). Help and usage text is |
| `%s`-filled with the sub-verb where shown; `cli.uploads.unreadable` wraps |
| the decoder's error. |
| | Key | Text | |
| |---|---| |
| -| `cli.uploads.usage` | `usage: carlos store uploads <enable\|status\|disable> --app <a> [flags]` | |
| -| `cli.uploads.usage_enable` | ` enable --app <a> [--origin <o>]...` | |
| -| `cli.uploads.usage_status` | ` status --app <a>` | |
| -| `cli.uploads.usage_disable` | ` disable --app <a>` | |
| -| `cli.uploads.usage_verb` | `usage: carlos store uploads %s --app <a> [--account <sqid-or-name>] [--console <origin>]` | |
| -| `cli.uploads.flags` | `Flags: --account/--account-id to disambiguate, --console to pick a console.` | |
| -| `cli.uploads.flag_app` | `app whose store browsers upload to` | |
| -| `cli.uploads.flag_origin` | `an origin browsers upload from: https:// and a host, or http://localhost:<port>. Repeat for more, at most 8` | |
| -| `cli.uploads.unreadable` | `store uploads: unreadable response: %w` | |
| -| `cli.uploads.store_usage` | the `carlos store` usage entry: ` uploads <enable\|status\|disable> --app <a> [--origin <o>]...` then `docs.cli.store_uploads`, wrapped at the usage's 26-column indent | |
| -| `audit.uploads_enable` | `turned on browser uploads from %s (cli)` (the origins, comma separated) | |
| -| `audit.uploads_disable` | `turned off browser uploads (cli)` | |
| +| `cli.uploads.usage` | `usage: carlos store uploads <enable\|status\|disable> --app <a> [flags]` (approved, Luna pass 3) | |
| +| `cli.uploads.usage_enable` | ` enable --app <a> [--origin <o>]...` (approved, Luna pass 3) | |
| +| `cli.uploads.usage_status` | ` status --app <a>` (approved, Luna pass 3) | |
| +| `cli.uploads.usage_disable` | ` disable --app <a>` (approved, Luna pass 3) | |
| +| `cli.uploads.usage_verb` | `usage: carlos store uploads %s --app <a> [--account <sqid-or-name>] [--console <origin>]` (approved, Luna pass 3) | |
| +| `cli.uploads.flags` | `Flags: --account/--account-id to disambiguate, --console to pick a console.` (approved, Luna pass 3) | |
| +| `cli.uploads.flag_app` | `app whose store accepts browser uploads` (approved, Luna pass 3) | |
| +| `cli.uploads.flag_origin` | `origin for browser uploads: https:// followed by a host, or http://localhost:<port> (repeat up to 8 times)` (approved, Luna pass 3) | |
| +| `cli.uploads.unreadable` | `store uploads: unreadable response: %w` (approved, Luna pass 3) | |
| +| `cli.uploads.store_usage` | the `carlos store` usage entry: ` uploads <enable\|status\|disable> --app <a> [--origin <o>]...` then `docs.cli.store_uploads`, wrapped at the usage's 26-column indent (approved, Luna pass 3) | |
| +| `audit.uploads_enable` | `enabled browser uploads from %s (cli)` (the origins, comma separated) (approved, Luna pass 3) | |
| +| `audit.uploads_disable` | `disabled browser uploads (cli)` (approved, Luna pass 3) | |
| The `carlos store uploads` usage block is `cli.uploads.usage`, the three |
| `usage_*` lines, `docs.cli.store_uploads` and `cli.uploads.flags`. |
diff --git a/internal/console/apistoreuploads.go b/internal/console/apistoreuploads.go| index aa05ad8f9..3dfd34125 100644 |
| --- a/internal/console/apistoreuploads.go |
| +++ b/internal/console/apistoreuploads.go |
| @@ -14,24 +14,23 @@ import ( |
| "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, with a write-ahead PendingUploads), and converges |
| -// the store user's policy so it carries the two multipart actions |
| +// Browser uploads (media conversion spec §5.6, §11 A1, A4): `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 converges the store |
| +// user's policy so it carries the two multipart actions |
| // (objstore.ConvergePolicyIn, 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 one the record holds (recorded, or pending from a write that may |
| -// not have finished); with neither, any configuration at all is foreign. |
| +// Ownership (spec §11 A4): the one-time verification of §5.2 (A3) refuses a |
| +// bucket carrying CORS or lifecycle rules the platform did not write. Once |
| +// a store has passed it, the platform owns that store's CORS rule and |
| +// multipart-abort lifecycle rule outright: enable writes them and disable |
| +// removes them, with no per-write ownership proof, and an operator's hand |
| +// edit is overwritten by the next enable or disable. The recorded hashes |
| +// stay so a later re-verification can tell the platform's rules from a |
| +// hand edit, and so status can say the rules changed. |
| // |
| // Every refusal is jsonErrorCode with the copy deck's message by key |
| // (media_copy.go). No SQLite transaction is opened here. |
| @@ -134,49 +133,10 @@ func uploadsOrigins(raw []string) (origins []string, code, msg string) { |
| return origins, "", "" |
| } |
| -// uploadsOurs: a configuration the bucket holds is absent, or its hash is |
| -// one the record accounts for (the recorded rules or the pending ones). |
| -func uploadsOurs(held []byte, hashes ...string) bool { |
| - if len(held) == 0 { |
| - return true |
| - } |
| - h := storecfg.Hash(held) |
| - for _, want := range hashes { |
| - if want != "" && want == h { |
| - return true |
| - } |
| - } |
| - return false |
| -} |
| - |
| -// uploadsForeign is the check (storecfg.CheckLifecycle or CheckCORS) whose |
| -// configuration the bucket holds and the platform did not write, in |
| -// storecfg.Verify's order, "" when it holds none it did not write. A |
| -// configuration is the platform's when its hash is the recorded one or the |
| -// pending one (a write-ahead intent), each judged on its own, since a write |
| -// may have landed one rule and not the other. Nothing recorded and nothing |
| -// pending: any configuration present is foreign. An absent configuration is |
| -// never foreign; there is nothing in it to replace. |
| -func uploadsForeign(f storecfg.Facts, recorded, pending *objstore.Uploads) string { |
| - var lh, ch []string |
| - for _, u := range []*objstore.Uploads{recorded, pending} { |
| - if u != nil { |
| - lh, ch = append(lh, u.LifecycleHash), append(ch, u.CORSHash) |
| - } |
| - } |
| - if !uploadsOurs(f.Lifecycle, lh...) { |
| - return storecfg.CheckLifecycle |
| - } |
| - if !uploadsOurs(f.CORS, ch...) { |
| - return storecfg.CheckCORS |
| - } |
| - return "" |
| -} |
| - |
| // uploadsMismatch compares a bucket with uploads that are on: the check |
| -// whose configuration is not exactly up's, "" 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. |
| +// 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 |
| @@ -187,34 +147,13 @@ func uploadsMismatch(f storecfg.Facts, up *objstore.Uploads) string { |
| return "" |
| } |
| -// pendingLanded: the bucket shows that the pending write landed, at least |
| -// in part, so the pending rules must become the recorded ones before a new |
| -// intent replaces them (else a rule the platform wrote would stand with no |
| -// hash the record holds). The CORS rule is the pending one and not the |
| -// recorded one; or nothing is recorded and the pending lifecycle rule is |
| -// there. |
| -func pendingLanded(f storecfg.Facts, recorded, pending *objstore.Uploads) bool { |
| - if len(f.CORS) > 0 && storecfg.Hash(f.CORS) == pending.CORSHash && (recorded == nil || recorded.CORSHash != pending.CORSHash) { |
| - return true |
| - } |
| - return recorded == nil && len(f.Lifecycle) > 0 && storecfg.Hash(f.Lifecycle) == pending.LifecycleHash |
| -} |
| - |
| -// sameUploads: a and b are both absent, or carry the same two hashes. |
| -func sameUploads(a, b *objstore.Uploads) bool { |
| - if a == nil || b == nil { |
| - return a == b |
| - } |
| - return a.CORSHash == b.CORSHash && a.LifecycleHash == b.LifecycleHash |
| -} |
| - |
| -// uploadsBlocks is the record's recorded and pending uploads blocks, nil |
| -// when it has none. |
| -func uploadsBlocks(rec *objstore.Record) (recorded, pending *objstore.Uploads) { |
| +// 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, nil |
| + return nil |
| } |
| - return rec.Conversion.Uploads, rec.Conversion.PendingUploads |
| + return rec.Conversion.Uploads |
| } |
| // uploadsOff is the answer for uploads that are off. |
| @@ -222,48 +161,36 @@ func uploadsOff() uploadsAnswer { |
| return uploadsAnswer{Origins: []string{}, BucketMatches: true} |
| } |
| -// uploadsOn is the answer for an uploads block and the bucket's state |
| -// against it. |
| +// 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, another incarnation, |
| -// or uploads blocks other than the ones the bucket was checked against). |
| -// Nothing is recorded. |
| +// way the uploads write cannot follow (another bucket, or another |
| +// incarnation). Nothing is recorded. |
| var errUploadsStoreMoved = errors.New("console: uploads: the store record changed while uploads were written") |
| -// mutateUploads applies change to the record's conversion block 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. A record with no conversion block, when inc is "", has |
| -// nothing to change. |
| -func (s *Server) mutateUploads(ctx context.Context, sqid, app, bucket, inc string, change func(c *objstore.Conversion) error) error { |
| +// 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 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 { |
| + if rec == nil || rec.Provisioned == nil || rec.Provisioned.Bucket != bucket || |
| + rec.Conversion == nil || rec.Conversion.VerifiedAt == nil || rec.Conversion.Incarnation != inc { |
| return errUploadsStoreMoved |
| } |
| - if rec.Conversion == nil { |
| - if inc == "" { |
| - return nil |
| - } |
| - return errUploadsStoreMoved |
| - } |
| - if inc != "" && (rec.Conversion.VerifiedAt == nil || rec.Conversion.Incarnation != inc) { |
| - return errUploadsStoreMoved |
| - } |
| - if err := change(rec.Conversion); err != nil { |
| - return err |
| - } |
| + 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 |
| @@ -282,17 +209,34 @@ func uploadsInternal(w http.ResponseWriter, what string, err error) { |
| jsonError(w, http.StatusInternalServerError, "internal error") |
| } |
| -// uploadsRefuseForeign answers 409 store_unverified with check's phrase. |
| -func uploadsRefuseForeign(w http.ResponseWriter, check string) { |
| - mediaRefuse(w, http.StatusConflict, mediaCodeStoreUnverified, mediaText("media.store_unverified", mediaText("media.check."+check))) |
| +// uploadsEligible is mediaStoreEligible answered as the uploads doors |
| +// answer it: the record of an eligible store, or false with the refusal |
| +// written (409 no_store, 409 store_unverified with the failing check's |
| +// phrase, or the plain 500). |
| +func (s *Server) uploadsEligible(ctx context.Context, w http.ResponseWriter, acct *Account, app string) (*objstore.Record, bool) { |
| + rec, code, check, err := s.mediaStoreEligible(ctx, acct, app) |
| + if err != nil { |
| + uploadsInternal(w, "store check "+acct.Sqid+"/"+app, err) |
| + return nil, false |
| + } |
| + switch code { |
| + case "": |
| + return rec, true |
| + case mediaCodeNoStore: |
| + mediaRefuse(w, http.StatusConflict, mediaCodeNoStore, mediaText("media.no_store", app, app)) |
| + case mediaCodeStoreUnverified: |
| + mediaRefuse(w, http.StatusConflict, mediaCodeStoreUnverified, mediaText("media.store_unverified", mediaText("media.check."+check))) |
| + default: |
| + uploadsInternal(w, "store check "+acct.Sqid+"/"+app, errors.New("unknown code "+code)) |
| + } |
| + return nil, false |
| } |
| // handleAPIStoreUploadsGet is GET /api/cli/apps/{account}/{app}/store/uploads: |
| // `carlos store uploads status`. It reads the record and, when uploads are |
| -// on or pending, Inspects the bucket and compares it with the rules the |
| -// record says the platform wrote: the pending ones when the bucket holds |
| -// exactly those (a write that landed and was not confirmed) or nothing is |
| -// recorded, else the recorded ones. It writes nothing and takes no lock. |
| +// on, Inspects the bucket and compares it with the rules the record says |
| +// the platform wrote, so an operator sees a hand edit (`rules changed`). 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 { |
| @@ -317,8 +261,8 @@ func (s *Server) handleAPIStoreUploadsGet(w http.ResponseWriter, r *http.Request |
| uploadsInternal(w, "status "+acct.Sqid+"/"+app, err) |
| return |
| } |
| - recorded, pending := uploadsBlocks(rec) |
| - if recorded == nil && pending == nil { |
| + up := recordedUploads(rec) |
| + if up == nil { |
| writeJSON(w, http.StatusOK, uploadsOff()) |
| return |
| } |
| @@ -327,11 +271,7 @@ func (s *Server) handleAPIStoreUploadsGet(w http.ResponseWriter, r *http.Request |
| uploadsInternal(w, "status inspect "+acct.Sqid+"/"+app, err) |
| return |
| } |
| - ref := recorded |
| - if pending != nil && (recorded == nil || uploadsMismatch(facts, pending) == "") { |
| - ref = pending |
| - } |
| - writeJSON(w, http.StatusOK, uploadsOn(ref, uploadsMismatch(facts, ref))) |
| + writeJSON(w, http.StatusOK, uploadsOn(up, uploadsMismatch(facts, up))) |
| } |
| // handleAPIStoreUploadsSet is POST /api/cli/apps/{account}/{app}/store/uploads: |
| @@ -346,28 +286,29 @@ func (s *Server) handleAPIStoreUploadsGet(w http.ResponseWriter, r *http.Request |
| // 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 app's store |
| -// walk lock: |
| +// Then disable is handleUploadsDisable, and enable runs under the account |
| +// lock and then the app's store walk lock. The account lock serialises it |
| +// with every other writer of the store user's policy (scan enforcement, |
| +// storage-limit convergence), so the policy it writes is computed from a |
| +// record no Deny has changed since: |
| // |
| // 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, whatever 7 said: a lifecycle or CORS configuration whose |
| -// hash the record holds neither as recorded nor as pending: 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 store user's policy is converged (objstore.ConvergePolicyIn: the |
| +// 7. mediaStoreEligible: 409 no_store, 409 store_unverified. Its §5.2 |
| +// verification refuses, at first use, a bucket carrying CORS or |
| +// lifecycle rules the platform did not write; after it, the platform |
| +// owns the store's CORS rule and its multipart-abort lifecycle rule |
| +// (spec §11 A4), so nothing below checks who wrote what is there |
| +// 8. the store user's policy converges (objstore.ConvergePolicyIn: the |
| // multipart actions; no key, no config, no record written) |
| -// 10. Inspect again and the same check, immediately before the writes |
| -// 11. the write-ahead intent: the rules about to be written go into the |
| -// record as pending (a pending write the bucket shows landed becomes |
| -// the recorded one first) |
| -// 12. PutUploads, then pending becomes recorded. |
| +// 9. PutUploads replaces both rules, an operator's hand edit included |
| +// 10. the record's uploads block, by hash: what re-verification compares |
| +// the bucket with, and status reports against. |
| // |
| -// A failure after 11 leaves the pending hashes standing, so whatever the |
| -// bucket was left holding (nothing, one rule, both) is the platform's own |
| -// to the next enable, update or disable, which converge. |
| +// A failure after 9 leaves the bucket holding the platform's rules with the |
| +// record naming earlier ones or none. Status then says the rules changed, |
| +// and a re-verification of the store would refuse them, until the next |
| +// enable or disable, which converge. |
| func (s *Server) handleAPIStoreUploadsSet(w http.ResponseWriter, r *http.Request) { |
| addr, acct, app, ok := s.apiAccountApp(w, r) |
| if !ok { |
| @@ -401,6 +342,7 @@ func (s *Server) handleAPIStoreUploadsSet(w http.ResponseWriter, r *http.Request |
| ctx, cancel := context.WithTimeout(r.Context(), storeGrantTimeout) |
| defer cancel() |
| + defer s.lockAccount(acct.Sqid)() |
| defer s.storeWalks.lock(acct.Sqid, app, "")() |
| if len(origins) == 0 { |
| @@ -424,36 +366,11 @@ func (s *Server) handleAPIStoreUploadsSet(w http.ResponseWriter, r *http.Request |
| } |
| } |
| - 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: |
| - uploadsRefuseForeign(w, check) |
| - return |
| - default: |
| - uploadsInternal(w, "store check "+acct.Sqid+"/"+app, errors.New("unknown code "+code)) |
| + rec, ok := s.uploadsEligible(ctx, w, acct, app) |
| + if !ok { |
| return |
| } |
| bucket, inc := rec.Provisioned.Bucket, rec.Conversion.Incarnation |
| - recorded, pending := rec.Conversion.Uploads, rec.Conversion.PendingUploads |
| - |
| - // The first look: a refusal here has written nothing of uploads. |
| - facts, err := s.cfg.StoreBuckets.Inspect(ctx, bucket) |
| - if err != nil { |
| - uploadsInternal(w, "inspect "+acct.Sqid+"/"+app, err) |
| - return |
| - } |
| - if check := uploadsForeign(facts, recorded, pending); check != "" { |
| - uploadsRefuseForeign(w, check) |
| - return |
| - } |
| if _, err := claimAppCall(s, ctx, acct, app, "store-uploads", func(ctx context.Context) (*objstore.Record, error) { |
| return objstore.ConvergePolicyIn(ctx, s.cfg.Releases, s.cfg.StoreProvisioner, acct.Sqid, app, "") |
| @@ -461,100 +378,58 @@ func (s *Server) handleAPIStoreUploadsSet(w http.ResponseWriter, r *http.Request |
| uploadsInternal(w, "policy "+acct.Sqid+"/"+app, err) |
| return |
| } |
| - |
| - // The second look, immediately before the writes. |
| - facts, err = s.cfg.StoreBuckets.Inspect(ctx, bucket) |
| - if err != nil { |
| - uploadsInternal(w, "inspect "+acct.Sqid+"/"+app, err) |
| - return |
| - } |
| - if check := uploadsForeign(facts, recorded, pending); check != "" { |
| - uploadsRefuseForeign(w, check) |
| + if err := s.cfg.StoreBuckets.PutUploads(ctx, bucket, origins); err != nil { |
| + uploadsInternal(w, "put rules "+acct.Sqid+"/"+app, err) |
| return |
| } |
| - |
| - next := &objstore.Uploads{ |
| + 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.mutateUploads(ctx, acct.Sqid, app, bucket, inc, func(c *objstore.Conversion) error { |
| - if !sameUploads(c.Uploads, recorded) || !sameUploads(c.PendingUploads, pending) { |
| - return errUploadsStoreMoved |
| - } |
| - if pending != nil && pendingLanded(facts, recorded, pending) { |
| - c.Uploads = pending |
| - } |
| - c.PendingUploads = next |
| - return nil |
| - }); err != nil { |
| - uploadsInternal(w, "record intent "+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 |
| - } |
| - if err := s.mutateUploads(ctx, acct.Sqid, app, bucket, inc, func(c *objstore.Conversion) error { |
| - if !sameUploads(c.PendingUploads, next) { |
| - return errUploadsStoreMoved |
| - } |
| - c.Uploads, c.PendingUploads = next, nil |
| - return nil |
| - }); err != nil { |
| + if err := s.writeUploadsRecord(ctx, acct.Sqid, app, bucket, inc, up); err != nil { |
| uploadsInternal(w, "record "+acct.Sqid+"/"+app, err) |
| return |
| } |
| s.audit(acct, app, addr, "store-uploads-enable", mediaText("audit.uploads_enable", strings.Join(origins, ", "))) |
| - writeJSON(w, http.StatusOK, uploadsOn(next, "")) |
| + writeJSON(w, http.StatusOK, uploadsOn(up, "")) |
| } |
| -// handleUploadsDisable is `carlos store uploads disable`, under the app's |
| -// store walk lock. With nothing recorded or pending it writes nothing and |
| -// reads no bucket. Otherwise it Inspects the bucket: a configuration the |
| -// record accounts for neither as recorded nor as pending refuses 409 |
| -// store_unverified with that check's phrase, writing nothing and keeping |
| -// the record (DeleteUploads removes both configurations, so it never runs |
| -// beside a foreign one; once an operator removes the hand-set rule, disable |
| -// works). Else DeleteUploads, when the bucket holds anything, then both |
| -// uploads blocks are cleared. A failure between the two leaves the record |
| -// naming rules that are gone, which the next disable clears. |
| +// handleUploadsDisable is `carlos store uploads disable`, under the account |
| +// lock and then the app's store walk lock. With nothing recorded it writes |
| +// nothing and reads no bucket. Otherwise the store must still be eligible |
| +// (mediaStoreEligible: a recreated bucket is verified afresh, and one |
| +// carrying rules other than the recorded ones is refused store_unverified, |
| +// since they are not this store's platform rules). Then DeleteUploads |
| +// removes both rules, an operator's hand edit included (spec §11 A4), and |
| +// the uploads block is cleared. A failure between the two leaves the record |
| +// naming rules that are gone; the next disable clears it. |
| func (s *Server) handleUploadsDisable(w http.ResponseWriter, r *http.Request, addr string, acct *Account, app string) { |
| ctx, cancel := context.WithTimeout(r.Context(), storeGrantTimeout) |
| defer cancel() |
| + defer s.lockAccount(acct.Sqid)() |
| 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 |
| } |
| - recorded, pending := uploadsBlocks(rec) |
| - if recorded == nil && pending == nil { |
| + if recordedUploads(rec) == 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) |
| + rec, ok := s.uploadsEligible(ctx, w, acct, app) |
| + if !ok { |
| return |
| } |
| - if check := uploadsForeign(facts, recorded, pending); check != "" { |
| - uploadsRefuseForeign(w, check) |
| + bucket, inc := rec.Provisioned.Bucket, rec.Conversion.Incarnation |
| + if err := s.cfg.StoreBuckets.DeleteUploads(ctx, bucket); err != nil { |
| + uploadsInternal(w, "delete rules "+acct.Sqid+"/"+app, err) |
| return |
| } |
| - 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.mutateUploads(ctx, acct.Sqid, app, bucket, "", func(c *objstore.Conversion) error { |
| - c.Uploads, c.PendingUploads = nil, nil |
| - return nil |
| - }); err != nil { |
| + if err := s.writeUploadsRecord(ctx, acct.Sqid, app, bucket, inc, nil); err != nil { |
| uploadsInternal(w, "disable record "+acct.Sqid+"/"+app, err) |
| return |
| } |
diff --git a/internal/console/apistoreuploads_test.go b/internal/console/apistoreuploads_test.go| index 7e321628d..e85419999 100644 |
| --- a/internal/console/apistoreuploads_test.go |
| +++ b/internal/console/apistoreuploads_test.go |
| @@ -11,11 +11,11 @@ import ( |
| "strings" |
| "sync/atomic" |
| "testing" |
| + "time" |
| "github.com/carlosframework/platform/internal/appconfig" |
| "github.com/carlosframework/platform/internal/objstore" |
| "github.com/carlosframework/platform/internal/registry" |
| - "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/storecfg" |
| ) |
| @@ -230,11 +230,11 @@ func TestUploadsEnableWritesOneRuleEach(t *testing.T) { |
| 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 || rec.Conversion.PendingUploads != nil { |
| + if !storecfg.ValidIncarnation(rec.Conversion.Incarnation) || rec.Conversion.VerifiedAt == nil { |
| t.Fatalf("conversion block = %+v", rec.Conversion) |
| } |
| auditedBy(t, u.consoleFixture, "titogo", "store-uploads-enable", "alice@keymail.dev", |
| - "turned on browser uploads from http://localhost:3000, https://shop.example.com (cli)") |
| + "enabled browser uploads from http://localhost:3000, https://shop.example.com (cli)") |
| 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) |
| } |
| @@ -322,78 +322,7 @@ func TestUploadsDefaultHostsShareTheCallbackFilter(t *testing.T) { |
| } |
| } |
| -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) { |
| +func TestUploadsDisableRemovesBothRules(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")) |
| @@ -411,32 +340,20 @@ func TestUploadsDisableLeavesForeignRules(t *testing.T) { |
| if s := u.status(); s.status != http.StatusOK || s.ans.Enabled { |
| t.Fatalf("status after disable = %s", s.raw) |
| } |
| - auditedBy(t, u.consoleFixture, "titogo", "store-uploads-disable", "alice@keymail.dev", "turned off browser uploads (cli)") |
| + auditedBy(t, u.consoleFixture, "titogo", "store-uploads-disable", "alice@keymail.dev", "disabled browser uploads (cli)") |
| }) |
| - t.Run("a hand-set rule refuses, and keeps the record, until it is gone", func(t *testing.T) { |
| - u := newUploads(t, "code-uploads-disable-foreign") |
| + // Spec §11 A4: on a verified store the platform owns both rules, so an |
| + // operator's hand edit is removed with them. |
| + t.Run("an operator's hand edit is removed by disable", func(t *testing.T) { |
| + u := newUploads(t, "code-uploads-disable-hand") |
| u.wantOK(u.enable("https://shop.example.com")) |
| - u.setFacts(func(f *storecfg.Facts) { f.CORS = foreignCORS() }) |
| - before, _ := rawStoreRecord(t, u.consoleFixture) |
| - u.wantRefused(u.disable(), http.StatusConflict, "store_unverified", uploadsUnverified("cors")) |
| - 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 after, _ := rawStoreRecord(t, u.consoleFixture); !bytes.Equal(before, after) { |
| - t.Fatal("a refused disable wrote the record") |
| - } |
| - // An operator removes the hand-set rule: an absent rule is not |
| - // foreign, so disable now removes the platform's own. |
| - u.setFacts(func(f *storecfg.Facts) { f.CORS = nil }) |
| + u.setFacts(func(f *storecfg.Facts) { f.CORS, f.Lifecycle = foreignCORS(), foreignLifecycle() }) |
| u.wantOK(u.disable()) |
| if f := u.facts(); f.CORS != nil || f.Lifecycle != nil { |
| - t.Fatalf("rules left: %s %s", f.CORS, f.Lifecycle) |
| + t.Fatalf("hand edit left: %s %s", f.CORS, f.Lifecycle) |
| } |
| - if c := storedRecord(t, u.consoleFixture, "titogo").Conversion; c.Uploads != nil || c.PendingUploads != nil { |
| - t.Fatalf("record kept uploads: %+v", c) |
| + 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) { |
| @@ -454,6 +371,68 @@ func TestUploadsDisableLeavesForeignRules(t *testing.T) { |
| }) |
| } |
| +// Spec §11 A4: an operator's hand edit to a verified store's rules is |
| +// overwritten by the next enable. Status, read-only, says the rules changed |
| +// until then. |
| +func TestUploadsHandEditIsOverwrittenByEnable(t *testing.T) { |
| + u := newUploads(t, "code-uploads-hand-enable") |
| + u.wantOK(u.enable("https://shop.example.com")) |
| + u.setFacts(func(f *storecfg.Facts) { f.CORS, f.Lifecycle = foreignCORS(), foreignLifecycle() }) |
| + before, _ := rawStoreRecord(t, u.consoleFixture) |
| + if s := u.status(); !s.ans.Enabled || s.ans.BucketMatches || s.ans.Mismatch != "lifecycle" { |
| + t.Fatalf("status of a hand edit = %s", s.raw) |
| + } |
| + if after, _ := rawStoreRecord(t, u.consoleFixture); !bytes.Equal(before, after) || u.buckets.CallCount("PutUploads") != 1 { |
| + t.Fatal("status wrote something") |
| + } |
| + want := []string{"https://www.shop.example.com"} |
| + u.wantOK(u.enable(want...)) |
| + f := u.facts() |
| + if !bytes.Equal(f.CORS, storecfg.UploadsCORS(want)) || !bytes.Equal(f.Lifecycle, storecfg.UploadsLifecycle()) { |
| + t.Fatalf("hand edit not overwritten: %s %s", f.CORS, f.Lifecycle) |
| + } |
| + if up := storedRecord(t, u.consoleFixture, "titogo").Conversion.Uploads; up.CORSHash != storecfg.Hash(f.CORS) || up.LifecycleHash != storecfg.Hash(f.Lifecycle) { |
| + t.Fatalf("record = %+v", up) |
| + } |
| + if s := u.status(); !s.ans.BucketMatches { |
| + t.Fatalf("status after the overwrite = %s", s.raw) |
| + } |
| +} |
| + |
| +// The recorded hashes are what re-verification compares with: a store |
| +// whose bucket must be verified again (its incarnation tag is gone) and |
| +// that carries a hand edit is refused, and one carrying the platform's |
| +// recorded rules passes. A store never verified that carries a foreign |
| +// rule is refused at first use (spec §5.2), with nothing written. |
| +func TestUploadsVerificationTellsHandEditsApart(t *testing.T) { |
| + t.Run("first use with a foreign rule", func(t *testing.T) { |
| + u := newUploads(t, "code-uploads-first-foreign") |
| + u.setFacts(func(f *storecfg.Facts) { f.CORS = foreignCORS() }) |
| + before, _ := rawStoreRecord(t, u.consoleFixture) |
| + u.wantRefused(u.enable("https://shop.example.com"), http.StatusConflict, "store_unverified", uploadsUnverified("cors")) |
| + if after, _ := rawStoreRecord(t, u.consoleFixture); !bytes.Equal(before, after) || u.buckets.CallCount("PutUploads") != 0 { |
| + t.Fatal("a refused first use wrote something") |
| + } |
| + }) |
| + t.Run("re-verification passes the platform's rules", func(t *testing.T) { |
| + u := newUploads(t, "code-uploads-reverify-own") |
| + u.wantOK(u.enable("https://shop.example.com")) |
| + delete(u.buckets.Tags[u.bucket], storecfg.IncarnationTag) |
| + u.wantOK(u.enable("https://www.shop.example.com")) |
| + }) |
| + t.Run("re-verification refuses a hand edit", func(t *testing.T) { |
| + u := newUploads(t, "code-uploads-reverify-hand") |
| + u.wantOK(u.enable("https://shop.example.com")) |
| + u.setFacts(func(f *storecfg.Facts) { f.CORS = foreignCORS() }) |
| + delete(u.buckets.Tags[u.bucket], storecfg.IncarnationTag) |
| + u.wantRefused(u.enable("https://shop.example.com"), http.StatusConflict, "store_unverified", uploadsUnverified("cors")) |
| + u.wantRefused(u.disable(), http.StatusConflict, "store_unverified", uploadsUnverified("cors")) |
| + if !bytes.Equal(u.facts().CORS, foreignCORS()) || u.buckets.CallCount("PutUploads") != 1 || u.buckets.CallCount("DeleteUploads") != 0 { |
| + t.Fatal("a refused re-verification wrote the bucket") |
| + } |
| + }) |
| +} |
| + |
| 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 { |
| @@ -524,7 +503,7 @@ func TestUploadsPolicyFailureWritesNoRules(t *testing.T) { |
| if n := u.buckets.CallCount("PutUploads"); n != 0 { |
| t.Fatalf("PutUploads called %d times after a failed convergence", n) |
| } |
| - if c := storedRecord(t, u.consoleFixture, "titogo").Conversion; c.Uploads != nil || c.PendingUploads != nil { |
| + if c := storedRecord(t, u.consoleFixture, "titogo").Conversion; c.Uploads != nil { |
| t.Fatalf("recorded = %+v", c) |
| } |
| u.wantOK(u.enable("https://shop.example.com")) |
| @@ -544,218 +523,6 @@ func TestUploadsDefaultOriginsAreCapped(t *testing.T) { |
| } |
| } |
| -// uploadsHookBuckets is the fake with PutUploads replaceable, for the |
| -// write-ahead tests. |
| -type uploadsHookBuckets struct { |
| - *storecfg.Fake |
| - put func(ctx context.Context, bucket string, origins []string) error |
| -} |
| - |
| -func (b *uploadsHookBuckets) PutUploads(ctx context.Context, bucket string, origins []string) error { |
| - if b.put != nil { |
| - return b.put(ctx, bucket, origins) |
| - } |
| - return b.Fake.PutUploads(ctx, bucket, origins) |
| -} |
| - |
| -// uploadsHookProvisioner runs a hook before EnsureUser: the convergence step. |
| -type uploadsHookProvisioner struct { |
| - objstore.Provisioner |
| - beforeEnsureUser func() |
| -} |
| - |
| -func (p *uploadsHookProvisioner) EnsureUser(ctx context.Context, name, path, bucketARN string, deny *objstore.DenyTag, denyWrites bool) (string, error) { |
| - if p.beforeEnsureUser != nil { |
| - p.beforeEnsureUser() |
| - } |
| - return p.Provisioner.EnsureUser(ctx, name, path, bucketARN, deny, denyWrites) |
| -} |
| - |
| -// uploadsRecordFailStore fails the store record's writes while armed. |
| -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) |
| -} |
| - |
| -// hooked is newUploads with the hookable buckets and a record store that |
| -// can be made to fail, the store verified first so an enable's only record |
| -// writes are its own. |
| -func hooked(t *testing.T, code string) (*uploadsFixture, *uploadsHookBuckets, *uploadsRecordFailStore) { |
| - t.Helper() |
| - u := newUploads(t, code) |
| - if _, code, _, err := eligible(t, u.consoleFixture); err != nil || code != "" { |
| - t.Fatalf("verify: %q %v", code, err) |
| - } |
| - hb := &uploadsHookBuckets{Fake: u.buckets} |
| - u.srv.cfg.StoreBuckets = hb |
| - fs := &uploadsRecordFailStore{Store: u.srv.cfg.Releases, key: objstore.Key(u.sqid, "titogo")} |
| - u.srv.cfg.Releases = fs |
| - return u, hb, fs |
| -} |
| - |
| -func (u *uploadsFixture) conversion() *objstore.Conversion { |
| - u.t.Helper() |
| - return storedRecord(u.t, u.consoleFixture, "titogo").Conversion |
| -} |
| - |
| -// wantConverged: uploads are on with origins, the bucket holds exactly |
| -// their rules, and nothing is pending. |
| -func (u *uploadsFixture) wantConverged(origins ...string) { |
| - u.t.Helper() |
| - f := u.facts() |
| - if !bytes.Equal(f.CORS, storecfg.UploadsCORS(origins)) || !bytes.Equal(f.Lifecycle, storecfg.UploadsLifecycle()) { |
| - u.t.Fatalf("bucket = %s %s", f.CORS, f.Lifecycle) |
| - } |
| - c := u.conversion() |
| - if c.PendingUploads != nil || c.Uploads == nil || c.Uploads.CORSHash != storecfg.Hash(f.CORS) || c.Uploads.LifecycleHash != storecfg.Hash(f.Lifecycle) { |
| - u.t.Fatalf("record = %+v / %+v", c.Uploads, c.PendingUploads) |
| - } |
| - if s := u.status(); !s.ans.Enabled || !s.ans.BucketMatches || !slices.Equal(s.ans.Origins, origins) { |
| - u.t.Fatalf("status = %s", s.raw) |
| - } |
| -} |
| - |
| -// Fix round 1, ruling 1: a write-ahead intent. Whatever an interrupted |
| -// write leaves on the bucket is the platform's own to the next call. |
| -func TestUploadsWriteAheadIntentHeals(t *testing.T) { |
| - a := []string{"https://shop.example.com"} |
| - b := []string{"https://www.shop.example.com"} |
| - c := []string{"https://cdn.shop.example.com"} |
| - partial := func(u *uploadsFixture) func(context.Context, string, []string) error { |
| - return func(_ context.Context, bucket string, origins []string) error { |
| - u.setFacts(func(f *storecfg.Facts) { f.CORS = storecfg.UploadsCORS(origins) }) |
| - return errors.New("lifecycle write failed") |
| - } |
| - } |
| - landsThenErrs := func(hb *uploadsHookBuckets) func(context.Context, string, []string) error { |
| - return func(ctx context.Context, bucket string, origins []string) error { |
| - if err := hb.Fake.PutUploads(ctx, bucket, origins); err != nil { |
| - return err |
| - } |
| - return errors.New("timed out after it landed") |
| - } |
| - } |
| - |
| - t.Run("the first rule lands and the second fails", func(t *testing.T) { |
| - u, hb, _ := hooked(t, "code-uploads-wal-partial") |
| - hb.put = partial(u) |
| - if r := u.enable(a...); r.status != http.StatusInternalServerError { |
| - t.Fatalf("status = %d %s", r.status, r.raw) |
| - } |
| - if c := u.conversion(); c.Uploads != nil || c.PendingUploads == nil { |
| - t.Fatalf("record after the failure = %+v", c) |
| - } |
| - hb.put = nil |
| - u.wantOK(u.enable(a...)) |
| - u.wantConverged(a...) |
| - }) |
| - t.Run("the write lands and then returns an error", func(t *testing.T) { |
| - u, hb, _ := hooked(t, "code-uploads-wal-lands") |
| - u.wantOK(u.enable(a...)) |
| - hb.put = landsThenErrs(hb) |
| - if r := u.enable(b...); r.status != http.StatusInternalServerError { |
| - t.Fatalf("status = %d %s", r.status, r.raw) |
| - } |
| - // The bucket holds b's rules; the record still says a, b pending. |
| - if s := u.status(); !s.ans.BucketMatches || !slices.Equal(s.ans.Origins, b) { |
| - t.Fatalf("status = %s", s.raw) |
| - } |
| - hb.put = nil |
| - u.wantOK(u.enable(c...)) |
| - u.wantConverged(c...) |
| - }) |
| - t.Run("a crash between the bucket writes and the final record write", func(t *testing.T) { |
| - u, hb, fs := hooked(t, "code-uploads-wal-crash") |
| - u.wantOK(u.enable(a...)) |
| - hb.put = func(ctx context.Context, bucket string, origins []string) error { |
| - err := hb.Fake.PutUploads(ctx, bucket, origins) |
| - fs.armed.Store(true) // the record write that follows never lands |
| - return err |
| - } |
| - if r := u.enable(b...); r.status != http.StatusInternalServerError { |
| - t.Fatalf("status = %d %s", r.status, r.raw) |
| - } |
| - fs.armed.Store(false) |
| - if cv := u.conversion(); cv.Uploads == nil || cv.Uploads.CORSHash != storecfg.Hash(storecfg.UploadsCORS(a)) || |
| - cv.PendingUploads == nil || cv.PendingUploads.CORSHash != storecfg.Hash(storecfg.UploadsCORS(b)) { |
| - t.Fatalf("record after the crash = %+v / %+v", cv.Uploads, cv.PendingUploads) |
| - } |
| - // The next update writes its own intent over b's, and then fails |
| - // before touching the bucket: b's landed rule must have become the |
| - // recorded one, or the call after would call it foreign. |
| - hb.put = func(context.Context, string, []string) error { return errors.New("down") } |
| - if r := u.enable(c...); r.status != http.StatusInternalServerError { |
| - t.Fatalf("status = %d %s", r.status, r.raw) |
| - } |
| - if cv := u.conversion(); cv.Uploads == nil || cv.Uploads.CORSHash != storecfg.Hash(storecfg.UploadsCORS(b)) { |
| - t.Fatalf("b's landed rules were not promoted: %+v", cv.Uploads) |
| - } |
| - hb.put = nil |
| - u.wantOK(u.enable(c...)) |
| - u.wantConverged(c...) |
| - }) |
| - t.Run("disable after an unconfirmed first enable", func(t *testing.T) { |
| - u, hb, _ := hooked(t, "code-uploads-wal-disable") |
| - hb.put = partial(u) |
| - if r := u.enable(a...); r.status != http.StatusInternalServerError { |
| - t.Fatalf("status = %d %s", r.status, r.raw) |
| - } |
| - if s := u.status(); !s.ans.Enabled || s.ans.BucketMatches { |
| - t.Fatalf("status of a half write = %s", s.raw) |
| - } |
| - u.wantOK(u.disable()) |
| - if f := u.facts(); f.CORS != nil || f.Lifecycle != nil { |
| - t.Fatalf("rules left: %s %s", f.CORS, f.Lifecycle) |
| - } |
| - if cv := u.conversion(); cv.Uploads != nil || cv.PendingUploads != nil { |
| - t.Fatalf("record = %+v", cv) |
| - } |
| - }) |
| - t.Run("a store verified again accepts the pending rules", func(t *testing.T) { |
| - u, hb, _ := hooked(t, "code-uploads-wal-reverify") |
| - hb.put = landsThenErrs(hb) |
| - if r := u.enable(a...); r.status != http.StatusInternalServerError { |
| - t.Fatalf("status = %d %s", r.status, r.raw) |
| - } |
| - hb.put = nil |
| - // The bucket loses its incarnation tag, so the next use verifies it |
| - // from its settings: the pending rules are the platform's. |
| - delete(u.buckets.Tags[u.bucket], storecfg.IncarnationTag) |
| - if _, code, check, err := eligible(t, u.consoleFixture); err != nil || code != "" { |
| - t.Fatalf("verify with pending rules: %q %q %v", code, check, err) |
| - } |
| - u.wantOK(u.enable(a...)) |
| - u.wantConverged(a...) |
| - }) |
| -} |
| - |
| -// Fix round 1, ruling 2: the bucket is inspected again after the policy |
| -// converges, immediately before the writes. |
| -func TestUploadsInspectsAgainBeforeWriting(t *testing.T) { |
| - u := newUploads(t, "code-uploads-second-look") |
| - u.srv.cfg.StoreProvisioner = &uploadsHookProvisioner{Provisioner: u.prov, beforeEnsureUser: func() { |
| - u.setFacts(func(f *storecfg.Facts) { f.CORS = foreignCORS() }) |
| - }} |
| - u.wantRefused(u.enable("https://shop.example.com"), http.StatusConflict, "store_unverified", uploadsUnverified("cors")) |
| - if n := u.buckets.CallCount("PutUploads"); n != 0 { |
| - t.Fatalf("PutUploads called %d times", n) |
| - } |
| - if !bytes.Equal(u.facts().CORS, foreignCORS()) { |
| - t.Fatal("foreign rule replaced") |
| - } |
| - if c := u.conversion(); c.Uploads != nil || c.PendingUploads != nil { |
| - t.Fatalf("record = %+v", c) |
| - } |
| -} |
| - |
| // Fix round 1, ruling 3: enable converges the policy only. A store whose |
| // delivery is incomplete keeps its live key and its config as they are, and |
| // a seed's mark on the declaration stays. |
| @@ -803,3 +570,116 @@ func TestUploadsConvergesThePolicyOnly(t *testing.T) { |
| t.Fatalf("policy not converged: %q", p) |
| } |
| } |
| + |
| +// uploadsHookProvisioner runs beforeFirstEnsureUser once, on the first |
| +// EnsureUser it sees (the uploads convergence), and passes every call |
| +// through. |
| +type uploadsHookProvisioner struct { |
| + objstore.Provisioner |
| + fired atomic.Bool |
| + beforeFirstEnsureUser func() |
| +} |
| + |
| +func (p *uploadsHookProvisioner) EnsureUser(ctx context.Context, name, path, bucketARN string, deny *objstore.DenyTag, denyWrites bool) (string, error) { |
| + if p.beforeFirstEnsureUser != nil && p.fired.CompareAndSwap(false, true) { |
| + p.beforeFirstEnsureUser() |
| + } |
| + return p.Provisioner.EnsureUser(ctx, name, path, bucketARN, deny, denyWrites) |
| +} |
| + |
| +// interleave runs other in the window between the uploads convergence's |
| +// read of the record and its policy write, and gives it up to half a |
| +// second to finish there. Serialised by the account lock, it cannot: it |
| +// waits, and runs once enable is done. done carries other's error. |
| +func interleave(u *uploadsFixture, other func() error) (done chan error) { |
| + done = make(chan error, 1) |
| + u.srv.cfg.StoreProvisioner = &uploadsHookProvisioner{Provisioner: u.prov, beforeFirstEnsureUser: func() { |
| + finished := make(chan error, 1) |
| + go func() { finished <- other() }() |
| + select { |
| + case err := <-finished: |
| + done <- err |
| + case <-time.After(500 * time.Millisecond): |
| + go func() { done <- <-finished }() |
| + } |
| + }} |
| + return done |
| +} |
| + |
| +// Astra P1-3: enable holds the account lock, as every other writer of the |
| +// store user's policy does, so a Deny another door applies while uploads |
| +// converge survives. |
| +func TestUploadsKeepsADenyAppliedMeanwhile(t *testing.T) { |
| + t.Run("scan enforcement", func(t *testing.T) { |
| + u := newUploads(t, "code-uploads-race-scan") |
| + u.srv.cfg.StoreScanner = objstore.NewMemScanner() |
| + enableDeploymentScanning(t, u.consoleFixture) |
| + requestScanning(t, u.consoleFixture, u.token, false) |
| + if st, out := postJSON(t, scanURL(u.consoleFixture, "titogo")+"/grant", map[string]any{}, u.token); st != http.StatusOK { |
| + t.Fatalf("scan grant = %d %v", st, out) |
| + } |
| + done := interleave(u, func() error { |
| + req, _ := http.NewRequest(http.MethodPost, scanURL(u.consoleFixture, "titogo")+"/enforce", strings.NewReader(`{"on":true}`)) |
| + req.Header.Set("Content-Type", "application/json") |
| + req.Header.Set("Authorization", "Bearer "+u.token) |
| + res, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + return err |
| + } |
| + res.Body.Close() |
| + if res.StatusCode != http.StatusOK { |
| + return errors.New(res.Status) |
| + } |
| + return nil |
| + }) |
| + u.wantOK(u.enable("https://shop.example.com")) |
| + if err := <-done; err != nil { |
| + t.Fatalf("enforce: %v", err) |
| + } |
| + if p := u.prov.PolicyFor(u.user()); !strings.Contains(p, "s3:ExistingObjectTag/") { |
| + t.Fatalf("the enforcement Deny was lost:\n%s", p) |
| + } |
| + }) |
| + t.Run("storage limit", func(t *testing.T) { |
| + u := newUploads(t, "code-uploads-race-storage") |
| + u.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + acct := u.account(t) |
| + st := storageRow(acct, 2_000_000_000, 1_500_000_000, planNow.Add(-10*24*time.Hour)) |
| + st.NoticeAt = planNow.Add(-9 * 24 * time.Hour) |
| + done := interleave(u, func() error { |
| + return u.srv.convergeStorageDeny(context.Background(), acct, st, true, planNow) |
| + }) |
| + u.wantOK(u.enable("https://shop.example.com")) |
| + if err := <-done; err != nil { |
| + t.Fatalf("storage convergence: %v", err) |
| + } |
| + if rec := storedRecord(t, u.consoleFixture, "titogo"); rec.WritesDenied == nil { |
| + t.Fatal("the storage convergence did not deny writes") |
| + } |
| + if !uploadsPolicyDeniesWrites(t, u.prov.PolicyFor(u.user())) { |
| + t.Fatalf("the write Deny was lost:\n%s", u.prov.PolicyFor(u.user())) |
| + } |
| + }) |
| +} |
| + |
| +// uploadsPolicyDeniesWrites: the policy holds the unconditional |
| +// s3:PutObject Deny of a store past its storage grace. |
| +func uploadsPolicyDeniesWrites(t *testing.T, doc string) bool { |
| + t.Helper() |
| + var p struct { |
| + Statement []struct { |
| + Effect string |
| + Action []string |
| + Condition map[string]any |
| + } |
| + } |
| + if err := json.Unmarshal([]byte(doc), &p); err != nil { |
| + t.Fatalf("policy %q: %v", doc, err) |
| + } |
| + for _, st := range p.Statement { |
| + if st.Effect == "Deny" && len(st.Action) == 1 && st.Action[0] == "s3:PutObject" && st.Condition == nil { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
diff --git a/internal/console/media_copy.go b/internal/console/media_copy.go| index a8e810648..c9d724f9f 100644 |
| --- a/internal/console/media_copy.go |
| +++ b/internal/console/media_copy.go |
| @@ -42,9 +42,9 @@ var mediaCopy = map[string]string{ |
| "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", |
| - // Audit rows (pending Luna pass): enable's origins, comma separated. |
| - "audit.uploads_enable": "turned on browser uploads from %s (cli)", |
| - "audit.uploads_disable": "turned off browser uploads (cli)", |
| + // Audit rows (Luna pass 3): enable's origins, comma separated. |
| + "audit.uploads_enable": "enabled browser uploads from %s (cli)", |
| + "audit.uploads_disable": "disabled browser uploads (cli)", |
| // Store checks: one fills media.store_unverified. |
| "media.check.name": "its bucket is not named the way this deployment names buckets", |
diff --git a/internal/console/mediastore.go b/internal/console/mediastore.go| index 367878862..9d6e1632c 100644 |
| --- a/internal/console/mediastore.go |
| +++ b/internal/console/mediastore.go |
| @@ -88,11 +88,14 @@ func (s *Server) mediaStoreCheck(ctx context.Context, sqid, app string) (rec *ob |
| Account: s.cfg.StoreAccountID, |
| Region: rec.Provisioned.Region, |
| } |
| - var uploads, pending *objstore.Uploads |
| + var uploads *objstore.Uploads |
| if rec.Conversion != nil { |
| - uploads, pending = rec.Conversion.Uploads, rec.Conversion.PendingUploads |
| + uploads = rec.Conversion.Uploads |
| } |
| - if failed := verifyUploadsEither(facts, want, uploads, pending); failed != "" { |
| + if uploads != nil { |
| + want.LifecycleHash, want.CORSHash = uploads.LifecycleHash, uploads.CORSHash |
| + } |
| + if failed := storecfg.Verify(facts, want); failed != "" { |
| return rec, mediaCodeStoreUnverified, failed, nil |
| } |
| inc, err := storecfg.NewIncarnation() |
| @@ -107,46 +110,13 @@ func (s *Server) mediaStoreCheck(ctx context.Context, sqid, app string) (rec *ob |
| return nil, "", "", fmt.Errorf("console: media store %s/%s: %w", sqid, app, err) |
| } |
| now := s.now().UTC() |
| - rec.Conversion = &objstore.Conversion{Incarnation: inc, VerifiedAt: &now, Uploads: uploads, PendingUploads: pending} |
| + rec.Conversion = &objstore.Conversion{Incarnation: inc, VerifiedAt: &now, Uploads: uploads} |
| if _, err := objstore.PutIn(ctx, s.cfg.Releases, sqid, app, "", rec, etag); err != nil { |
| return nil, "", "", fmt.Errorf("console: media store %s/%s: record verification: %w", sqid, app, err) |
| } |
| return rec, "", "", nil |
| } |
| -// verifyUploadsEither is storecfg.Verify with the uploads rules the record |
| -// accounts for: each of the bucket's lifecycle and CORS configurations may |
| -// carry the recorded hash or the pending one (a write-ahead intent from |
| -// apistoreuploads.go), independently, since a write may have landed one |
| -// rule and not the other. It answers Verify's first failure with the |
| -// recorded hashes when no pairing passes. |
| -func verifyUploadsEither(f storecfg.Facts, want storecfg.Want, uploads, pending *objstore.Uploads) string { |
| - var lifecycle, cors []string |
| - for _, u := range []*objstore.Uploads{uploads, pending} { |
| - if u != nil { |
| - lifecycle, cors = append(lifecycle, u.LifecycleHash), append(cors, u.CORSHash) |
| - } |
| - } |
| - if len(lifecycle) == 0 { |
| - return storecfg.Verify(f, want) |
| - } |
| - first := "" |
| - for _, l := range lifecycle { |
| - for _, c := range cors { |
| - w := want |
| - w.LifecycleHash, w.CORSHash = l, c |
| - failed := storecfg.Verify(f, w) |
| - if failed == "" { |
| - return "" |
| - } |
| - if first == "" { |
| - first = failed |
| - } |
| - } |
| - } |
| - return first |
| -} |
| - |
| // mediaStoreFacts is mediaStoreCheck in the shape dispatch re-checks |
| // (mediajobs.StoreGuard.Current): the console's StoreGuard answers Current |
| // with this, under the same walk lock, outside any transaction. A store |
diff --git a/internal/objstore/objstore.go b/internal/objstore/objstore.go| index 8d1b5dc38..8e1a3c56a 100644 |
| --- a/internal/objstore/objstore.go |
| +++ b/internal/objstore/objstore.go |
| @@ -185,18 +185,10 @@ type Record struct { |
| // back the same value, so a bucket made again under the same name, which |
| // carries no tag, is verified afresh and never inherits an old store's |
| // media jobs, whatever state this record was left in. |
| -// |
| -// PendingUploads is the uploads configuration the console is about to write |
| -// (write-ahead intent): recorded before the bucket is written, promoted to |
| -// Uploads once both rules are written. While it stands, a rule on the bucket |
| -// with its hash is the platform's own, so a write that crashed, landed |
| -// halfway, or landed and then reported an error is never mistaken for a |
| -// foreign rule. Additive, like the rest of the block. |
| type Conversion struct { |
| - Incarnation string `json:"incarnation"` |
| - VerifiedAt *time.Time `json:"verified_at,omitempty"` |
| - Uploads *Uploads `json:"uploads,omitempty"` |
| - PendingUploads *Uploads `json:"pending_uploads,omitempty"` |
| + Incarnation string `json:"incarnation"` |
| + VerifiedAt *time.Time `json:"verified_at,omitempty"` |
| + Uploads *Uploads `json:"uploads,omitempty"` |
| } |
| // Uploads records the CORS and lifecycle configuration the platform wrote |
diff --git a/store_uploads.go b/store_uploads.go| index e6e52dc30..50ac9f247 100644 |
| --- a/store_uploads.go |
| +++ b/store_uploads.go |
| @@ -21,8 +21,8 @@ import ( |
| // storeUploadsCopy is this verb's text by copy deck key |
| // (docs/superpowers/notes/media-conversion-copy-deck.md, `carlos store |
| -// uploads`). The rows marked pending there await the Luna pass; apply its |
| -// result here verbatim. |
| +// uploads`), approved in Luna pass 3. Apply later edits through copy |
| +// review, not by hand. |
| var storeUploadsCopy = map[string]string{ |
| "cli.uploads.usage": "usage: carlos store uploads <enable|status|disable> --app <a> [flags]", |
| "cli.uploads.usage_enable": " enable --app <a> [--origin <o>]...", |
| @@ -30,8 +30,8 @@ var storeUploadsCopy = map[string]string{ |
| "cli.uploads.usage_disable": " disable --app <a>", |
| "cli.uploads.usage_verb": "usage: carlos store uploads %s --app <a> [--account <sqid-or-name>] [--console <origin>]", |
| "cli.uploads.flags": "Flags: --account/--account-id to disambiguate, --console to pick a console.", |
| - "cli.uploads.flag_app": "app whose store browsers upload to", |
| - "cli.uploads.flag_origin": "an origin browsers upload from: https:// and a host, or http://localhost:<port>. Repeat for more, at most 8", |
| + "cli.uploads.flag_app": "app whose store accepts browser uploads", |
| + "cli.uploads.flag_origin": "origin for browser uploads: https:// followed by a host, or http://localhost:<port> (repeat up to 8 times)", |
| "cli.uploads.unreadable": "store uploads: unreadable response: %w", |
| "cli.uploads.store_usage": " uploads <enable|status|disable> --app <a> [--origin <o>]...\n" + |
| " Lets browsers on the origins you name upload large\n" + |