objstore: store incarnation and conversion provenance
Media conversion plan 2, Task 3 (spec §5.2). The store record gains a conversion block: a random incarnation, Minted when this deployment's grant walk itself created the bucket, VerifiedAt when the console checked an existing bucket instead, and the uploads rules by hash. objstore: BucketCreator (CreateNewBucket) on the AWS and in-memory provisioners. Only a CreateBucket success outside us-east-1, on the first grant of a minted name with no adopt, earns Minted; an adopted bucket, a pre-existing bucket under the minted name and a re-run all stay unminted. The step-6 CAS retry carries the minted block. storecfg: Facts, the Buckets seam, the canonical CORS and lifecycle rules, Hash, Verify (name, owner, region, encryption, versioning, policy, lifecycle, cors) and a Fake. console: Config.StoreConversion, StoreBuckets, StoreAccountID and mediaStoreEligible, which verifies an unminted store once under the walk lock and records the pass; a refusal writes nothing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
13 files changed,
+1,461
−8
internal/console/mediastore.go+88 −0internal/console/mediastore_test.go+337 −0internal/console/server.go+13 −0internal/objstore/aws.go+18 −3internal/objstore/aws_test.go+50 −0internal/objstore/memprovisioner.go+22 −2internal/objstore/objstore.go+48 −1internal/objstore/provisioner.go+17 −0internal/objstore/walk.go+36 −2internal/objstore/walk_test.go+322 −0internal/storecfg/fake.go+82 −0internal/storecfg/storecfg.go+241 −0internal/storecfg/storecfg_test.go+187 −0
diff --git a/internal/console/mediastore.go b/internal/console/mediastore.go| new file mode 100644 |
| index 000000000..75a15838b |
| --- /dev/null |
| +++ b/internal/console/mediastore.go |
| @@ -0,0 +1,88 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + |
| + "github.com/carlosframework/platform/internal/objstore" |
| + "github.com/carlosframework/platform/internal/storecfg" |
| +) |
| + |
| +// The door codes mediaStoreEligible answers (media conversion spec §5.2). |
| +// Their messages are the copy deck's media.no_store and |
| +// media.store_unverified, the latter filled with the media.check.<check> |
| +// phrase; the doors that call this own the wording. |
| +const ( |
| + mediaCodeNoStore = "no_store" |
| + mediaCodeStoreUnverified = "store_unverified" |
| +) |
| + |
| +// errStoreBucketsUnset: a store that needs verifying, on a console with no |
| +// way to read bucket settings. A deployment fault, not the member's. |
| +var errStoreBucketsUnset = errors.New("console: store verification is not configured (no StoreBuckets)") |
| + |
| +// mediaStoreEligible says whether the app's own store may be used for media |
| +// conversion and browser uploads, and answers its record when it may. The |
| +// caller holds the app's store walk lock (storeWalks.lock(acct, app, "")), |
| +// so a teardown cannot run between this check and what the caller does |
| +// next; no SQLite transaction may be open, because Inspect is a network |
| +// call. |
| +// |
| +// - no record, or no Provisioned block: code no_store. |
| +// - a Conversion block that is Minted (the grant walk created the bucket) |
| +// or already verified: eligible, with nothing read from the bucket. |
| +// - otherwise the bucket's settings are read and checked once |
| +// (storecfg.Verify). A pass records Conversion{a new incarnation, |
| +// VerifiedAt now}, keeping any Uploads block, in a write conditional on |
| +// the record as read; a lost race is an error, and the next call checks |
| +// again. A failure is code store_unverified with the failing check, and |
| +// writes nothing, so the next call checks again too. |
| +// |
| +// code is "" when eligible. err is for a failure to find out (a record that |
| +// cannot be read, a bucket that cannot be inspected, a lost write); the |
| +// caller answers it as an internal error, never as a refusal. |
| +func (s *Server) mediaStoreEligible(ctx context.Context, acct *Account, app string) (rec *objstore.Record, code, check string, err error) { |
| + rec, etag, err := objstore.GetIn(ctx, s.cfg.Releases, acct.Sqid, app, "") |
| + if err != nil { |
| + return nil, "", "", fmt.Errorf("console: media store %s/%s: read record: %w", acct.Sqid, app, err) |
| + } |
| + if rec == nil || rec.Provisioned == nil { |
| + return rec, mediaCodeNoStore, "", nil |
| + } |
| + if c := rec.Conversion; c != nil && (c.Minted || c.VerifiedAt != nil) { |
| + return rec, "", "", nil |
| + } |
| + if s.cfg.StoreBuckets == nil { |
| + return nil, "", "", errStoreBucketsUnset |
| + } |
| + bucket := rec.Provisioned.Bucket |
| + facts, err := s.cfg.StoreBuckets.Inspect(ctx, bucket) |
| + if err != nil { |
| + return nil, "", "", fmt.Errorf("console: media store %s/%s: inspect bucket %s: %w", acct.Sqid, app, bucket, err) |
| + } |
| + want := storecfg.Want{ |
| + Bucket: bucket, |
| + MintedName: objstore.MintedBucketIn(s.cfg.StoreDeployment, acct.Sqid, app, ""), |
| + Account: s.cfg.StoreAccountID, |
| + Region: rec.Provisioned.Region, |
| + } |
| + var uploads *objstore.Uploads |
| + if rec.Conversion != nil { |
| + uploads = rec.Conversion.Uploads |
| + } |
| + want.Uploads = uploads |
| + if failed := storecfg.Verify(facts, want); failed != "" { |
| + return rec, mediaCodeStoreUnverified, failed, nil |
| + } |
| + inc, err := objstore.NewIncarnation() |
| + if err != nil { |
| + return nil, "", "", err |
| + } |
| + now := s.now().UTC() |
| + rec.Conversion = &objstore.Conversion{Incarnation: inc, VerifiedAt: &now, Uploads: uploads} |
| + if _, err := objstore.PutIn(ctx, s.cfg.Releases, acct.Sqid, app, "", rec, etag); err != nil { |
| + return nil, "", "", fmt.Errorf("console: media store %s/%s: record verification: %w", acct.Sqid, app, err) |
| + } |
| + return rec, "", "", nil |
| +} |
diff --git a/internal/console/mediastore_test.go b/internal/console/mediastore_test.go| new file mode 100644 |
| index 000000000..3fc849e9e |
| --- /dev/null |
| +++ b/internal/console/mediastore_test.go |
| @@ -0,0 +1,337 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "regexp" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/objstore" |
| + "github.com/carlosframework/platform/internal/storecfg" |
| +) |
| + |
| +const mediaTestAccountID = "123456789012" |
| + |
| +var mediaHex32 = regexp.MustCompile(`^[0-9a-f]{32}$`) |
| + |
| +// mediaStoreFixture is storeArmed plus a storecfg.Fake and the deployment's |
| +// account id. preExisting puts a bucket under the minted name before the |
| +// grant, so the walk does not mint and the store has to be verified. |
| +func mediaStoreFixture(t *testing.T, code string, preExisting bool) (*consoleFixture, *objstore.MemProvisioner, *storecfg.Fake, string) { |
| + t.Helper() |
| + fx, prov, token, _ := storeArmed(t, code) |
| + buckets := storecfg.NewFake() |
| + fx.srv.cfg.StoreConversion = true |
| + fx.srv.cfg.StoreBuckets = buckets |
| + fx.srv.cfg.StoreAccountID = mediaTestAccountID |
| + if preExisting { |
| + prov.PreExisting = map[string]bool{mediaMintedName(fx): true} |
| + } |
| + return fx, prov, buckets, token |
| +} |
| + |
| +func mediaMintedName(fx *consoleFixture) string { |
| + return objstore.MintedBucketIn(fx.srv.cfg.StoreDeployment, fx.sqid, "titogo", "") |
| +} |
| + |
| +func mediaAcct(fx *consoleFixture) *Account { return &Account{ID: OpsAccountID, Sqid: fx.sqid} } |
| + |
| +// goodBucket is a bucket that passes every check. |
| +func goodBucket() storecfg.Facts { |
| + return storecfg.Facts{Owner: mediaTestAccountID, Region: "eu-west-1", Encryption: "AES256"} |
| +} |
| + |
| +// rawStoreRecord is the record's exact bytes and ETag, to prove a refusal |
| +// wrote nothing. |
| +func rawStoreRecord(t *testing.T, fx *consoleFixture) ([]byte, string) { |
| + t.Helper() |
| + b, etag, err := fx.srv.cfg.Releases.Get(context.Background(), objstore.Key(fx.sqid, "titogo")) |
| + if err != nil { |
| + t.Fatalf("read store.json: %v", err) |
| + } |
| + return b, etag |
| +} |
| + |
| +func eligible(t *testing.T, fx *consoleFixture) (*objstore.Record, string, string, error) { |
| + t.Helper() |
| + defer fx.srv.storeWalks.lock(fx.sqid, "titogo", "")() |
| + return fx.srv.mediaStoreEligible(context.Background(), mediaAcct(fx), "titogo") |
| +} |
| + |
| +func TestEligibleNoStore(t *testing.T) { |
| + fx, _, buckets, token := mediaStoreFixture(t, "code-media-nostore", false) |
| + if _, code, _, err := eligible(t, fx); err != nil || code != "no_store" { |
| + t.Fatalf("no record: code %q, %v; want no_store", code, err) |
| + } |
| + declareStore(t, fx, token) |
| + if _, code, _, err := eligible(t, fx); err != nil || code != "no_store" { |
| + t.Fatalf("declared only: code %q, %v; want no_store", code, err) |
| + } |
| + if n := buckets.CallCount("Inspect"); n != 0 { |
| + t.Fatalf("no_store inspected the bucket %d times", n) |
| + } |
| +} |
| + |
| +// A store the walk minted is eligible with nothing read from the bucket. |
| +func TestEligibleMintedNeedsNoCheck(t *testing.T) { |
| + fx, _, buckets, token := mediaStoreFixture(t, "code-media-minted", false) |
| + grantStore(t, fx, token) |
| + before := storedRecord(t, fx, "titogo") |
| + if before.Conversion == nil || !before.Conversion.Minted { |
| + t.Fatalf("fixture: grant did not mint: %+v", before.Conversion) |
| + } |
| + rec, code, check, err := eligible(t, fx) |
| + if err != nil || code != "" || check != "" { |
| + t.Fatalf("minted store: %q %q %v", code, check, err) |
| + } |
| + if rec.Conversion.Incarnation != before.Conversion.Incarnation { |
| + t.Fatalf("incarnation changed: %q -> %q", before.Conversion.Incarnation, rec.Conversion.Incarnation) |
| + } |
| + if n := buckets.CallCount("Inspect"); n != 0 { |
| + t.Fatalf("minted store inspected %d times", n) |
| + } |
| +} |
| + |
| +// An unminted store is checked once; the pass is recorded, and the next |
| +// call reads nothing from the bucket and keeps the incarnation. |
| +func TestEligibleVerifiesOnceAndRecords(t *testing.T) { |
| + fx, _, buckets, token := mediaStoreFixture(t, "code-media-verify", true) |
| + grantStore(t, fx, token) |
| + buckets.Facts[mediaMintedName(fx)] = goodBucket() |
| + at := time.Date(2026, 11, 17, 10, 0, 0, 0, time.UTC) |
| + fx.srv.opNow = func() time.Time { return at } |
| + |
| + rec, code, check, err := eligible(t, fx) |
| + if err != nil || code != "" || check != "" { |
| + t.Fatalf("first check: %q %q %v", code, check, err) |
| + } |
| + c := rec.Conversion |
| + if c == nil || c.Minted || c.VerifiedAt == nil || !c.VerifiedAt.Equal(at) || !mediaHex32.MatchString(c.Incarnation) { |
| + t.Fatalf("conversion = %+v", c) |
| + } |
| + stored := storedRecord(t, fx, "titogo") |
| + if stored.Conversion == nil || stored.Conversion.Incarnation != c.Incarnation || stored.Provisioned == nil || |
| + stored.Provisioned.KeyID != rec.Provisioned.KeyID { |
| + t.Fatalf("stored = %+v / %+v", stored.Conversion, stored.Provisioned) |
| + } |
| + |
| + // The next call trusts the record: no Inspect, same incarnation, even |
| + // though the bucket has since changed. |
| + buckets.Facts[mediaMintedName(fx)] = storecfg.Facts{Encryption: "aws:kms"} |
| + rec2, code, _, err := eligible(t, fx) |
| + if err != nil || code != "" { |
| + t.Fatalf("second call: %q %v", code, err) |
| + } |
| + if rec2.Conversion.Incarnation != c.Incarnation { |
| + t.Fatalf("incarnation changed on the second call: %q -> %q", c.Incarnation, rec2.Conversion.Incarnation) |
| + } |
| + if n := buckets.CallCount("Inspect"); n != 1 { |
| + t.Fatalf("Inspect calls = %d, want 1", n) |
| + } |
| +} |
| + |
| +// A store that already carries the platform's own uploads rules (recorded |
| +// in an Uploads block) passes, and the pass keeps that block. |
| +func TestEligibleKeepsUploads(t *testing.T) { |
| + fx, _, buckets, token := mediaStoreFixture(t, "code-media-keep-uploads", true) |
| + grantStore(t, fx, token) |
| + origins := []string{"https://shop.example.com"} |
| + f := goodBucket() |
| + f.CORS, f.Lifecycle = storecfg.UploadsCORS(origins), storecfg.UploadsLifecycle() |
| + buckets.Facts[mediaMintedName(fx)] = f |
| + up := &objstore.Uploads{Origins: origins, CORSHash: storecfg.Hash(f.CORS), LifecycleHash: storecfg.Hash(f.Lifecycle), |
| + At: time.Now().UTC().Truncate(time.Second), By: "alice@keymail.dev"} |
| + rec, etag, err := objstore.Get(context.Background(), fx.srv.cfg.Releases, fx.sqid, "titogo") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec.Conversion = &objstore.Conversion{Incarnation: "stale", Uploads: up} |
| + if _, err := objstore.Put(context.Background(), fx.srv.cfg.Releases, fx.sqid, "titogo", rec, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + got, code, check, err := eligible(t, fx) |
| + if err != nil || code != "" { |
| + t.Fatalf("store with our uploads rules: %q %q %v", code, check, err) |
| + } |
| + c := storedRecord(t, fx, "titogo").Conversion |
| + if c == nil || c.VerifiedAt == nil || c.Uploads == nil || c.Uploads.CORSHash != up.CORSHash || |
| + c.Uploads.LifecycleHash != up.LifecycleHash || !c.Uploads.At.Equal(up.At) || c.Uploads.By != up.By { |
| + t.Fatalf("stored conversion = %+v", c) |
| + } |
| + if c.Incarnation == "stale" || c.Incarnation != got.Conversion.Incarnation { |
| + t.Fatalf("incarnation = %q, want a new one", c.Incarnation) |
| + } |
| +} |
| + |
| +// Every refusal and every failure to find out leaves the record byte for |
| +// byte as it was, and the next call checks again. |
| +func TestEligibleRefusalWritesNothing(t *testing.T) { |
| + fx, _, buckets, token := mediaStoreFixture(t, "code-media-refuse", true) |
| + grantStore(t, fx, token) |
| + name := mediaMintedName(fx) |
| + before, beforeTag := rawStoreRecord(t, fx) |
| + unchanged := func(t *testing.T) { |
| + t.Helper() |
| + after, afterTag := rawStoreRecord(t, fx) |
| + if afterTag != beforeTag || !bytes.Equal(after, before) { |
| + t.Fatalf("the record changed:\n%s\n->\n%s", before, after) |
| + } |
| + } |
| + |
| + versioned := goodBucket() |
| + versioned.Versioning = "Enabled" |
| + buckets.Facts[name] = versioned |
| + for i := 0; i < 2; i++ { |
| + rec, code, check, err := eligible(t, fx) |
| + if err != nil || code != "store_unverified" || check != "versioning" { |
| + t.Fatalf("versioned bucket, call %d: %q %q %v", i, code, check, err) |
| + } |
| + if rec == nil || rec.Conversion != nil { |
| + t.Fatalf("refusal answered %+v", rec) |
| + } |
| + unchanged(t) |
| + } |
| + if n := buckets.CallCount("Inspect"); n != 2 { |
| + t.Fatalf("Inspect calls = %d, want 2 (a refusal is checked again)", n) |
| + } |
| + |
| + t.Run("unset-account", func(t *testing.T) { |
| + buckets.Facts[name] = goodBucket() |
| + fx.srv.cfg.StoreAccountID = "" |
| + defer func() { fx.srv.cfg.StoreAccountID = mediaTestAccountID }() |
| + if _, code, check, err := eligible(t, fx); err != nil || code != "store_unverified" || check != "owner" { |
| + t.Fatalf("no account id: %q %q %v", code, check, err) |
| + } |
| + unchanged(t) |
| + }) |
| + |
| + t.Run("inspect-error", func(t *testing.T) { |
| + buckets.Facts[name] = goodBucket() |
| + buckets.Fail["Inspect"] = errors.New("injected: throttled") |
| + if _, code, _, err := eligible(t, fx); err == nil || code != "" { |
| + t.Fatalf("inspect error: code %q, err %v; want an error and no code", code, err) |
| + } |
| + unchanged(t) |
| + }) |
| + |
| + t.Run("no-buckets", func(t *testing.T) { |
| + fx.srv.cfg.StoreBuckets = nil |
| + defer func() { fx.srv.cfg.StoreBuckets = buckets }() |
| + if _, _, _, err := eligible(t, fx); !errors.Is(err, errStoreBucketsUnset) { |
| + t.Fatalf("no StoreBuckets: %v", err) |
| + } |
| + unchanged(t) |
| + }) |
| + |
| + t.Run("lost-write", func(t *testing.T) { |
| + buckets.Facts[name] = goodBucket() |
| + fx.srv.cfg.StoreBuckets = racingBuckets{Buckets: buckets, race: func() { |
| + // Another door writes the record while the bucket is inspected. |
| + rec, etag, err := objstore.Get(context.Background(), fx.srv.cfg.Releases, fx.sqid, "titogo") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec.Declared.By = "someone-else@example.com" |
| + if _, err := objstore.Put(context.Background(), fx.srv.cfg.Releases, fx.sqid, "titogo", rec, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + }} |
| + defer func() { fx.srv.cfg.StoreBuckets = buckets }() |
| + if _, code, _, err := eligible(t, fx); err == nil || code != "" { |
| + t.Fatalf("lost write: code %q, err %v; want an error", code, err) |
| + } |
| + if c := storedRecord(t, fx, "titogo"); c.Conversion != nil || c.Declared.By != "someone-else@example.com" { |
| + t.Fatalf("after a lost write: %+v, declared by %q", c.Conversion, c.Declared.By) |
| + } |
| + }) |
| +} |
| + |
| +type racingBuckets struct { |
| + storecfg.Buckets |
| + race func() |
| +} |
| + |
| +func (r racingBuckets) Inspect(ctx context.Context, bucket string) (storecfg.Facts, error) { |
| + r.race() |
| + return r.Buckets.Inspect(ctx, bucket) |
| +} |
| + |
| +// F3: a bucket already there under the minted name, granted with no adopt. |
| +// The walk does not mint, and the console's check refuses it for what it |
| +// holds: SSE-KMS first, then, once that is fixed, a foreign policy. |
| +func TestPreExistingMintedNameIsNotMinted(t *testing.T) { |
| + fx, prov, buckets, token := mediaStoreFixture(t, "code-media-preexisting", true) |
| + grantStore(t, fx, token) |
| + name := mediaMintedName(fx) |
| + rec := storedRecord(t, fx, "titogo") |
| + if rec.Provisioned == nil || rec.Provisioned.Bucket != name || rec.Conversion != nil { |
| + t.Fatalf("pre-existing minted name: provisioned %+v, conversion %+v", rec.Provisioned, rec.Conversion) |
| + } |
| + if _, ok := prov.Buckets[name]; !ok { |
| + t.Fatalf("fixture: no bucket %q", name) |
| + } |
| + |
| + kms := goodBucket() |
| + kms.Encryption, kms.HasPolicy = "aws:kms", true |
| + buckets.Facts[name] = kms |
| + if _, code, check, err := eligible(t, fx); err != nil || code != "store_unverified" || check != "encryption" { |
| + t.Fatalf("SSE-KMS bucket: %q %q %v", code, check, err) |
| + } |
| + policy := goodBucket() |
| + policy.HasPolicy = true |
| + buckets.Facts[name] = policy |
| + if _, code, check, err := eligible(t, fx); err != nil || code != "store_unverified" || check != "policy" { |
| + t.Fatalf("foreign policy: %q %q %v", code, check, err) |
| + } |
| + if storedRecord(t, fx, "titogo").Conversion != nil { |
| + t.Fatal("a refused store recorded provenance") |
| + } |
| + buckets.Facts[name] = goodBucket() |
| + if _, code, check, err := eligible(t, fx); err != nil || code != "" { |
| + t.Fatalf("fixed bucket: %q %q %v", code, check, err) |
| + } |
| +} |
| + |
| +// Teardown deletes the record, so the store made again under the same app is |
| +// a new incarnation, minted or verified. |
| +func TestRecreatedStoreHasANewIncarnation(t *testing.T) { |
| + for name, preExisting := range map[string]bool{"verified": true, "minted": false} { |
| + t.Run(name, func(t *testing.T) { |
| + fx, prov, buckets, token := mediaStoreFixture(t, "code-media-recreate-"+name, preExisting) |
| + grantStore(t, fx, token) |
| + buckets.Facts[mediaMintedName(fx)] = goodBucket() |
| + first, code, _, err := eligible(t, fx) |
| + if err != nil || code != "" { |
| + t.Fatalf("first store: %q %v", code, err) |
| + } |
| + if first.Conversion.Minted == preExisting { |
| + t.Fatalf("fixture: minted = %v with preExisting %v", first.Conversion.Minted, preExisting) |
| + } |
| + |
| + func() { |
| + defer fx.srv.storeWalks.lock(fx.sqid, "titogo", "")() |
| + if err := objstore.Teardown(context.Background(), fx.srv.cfg.Releases, prov, nil, fx.sqid, "titogo"); err != nil { |
| + t.Fatalf("teardown: %v", err) |
| + } |
| + }() |
| + if storedRecord(t, fx, "titogo") != nil { |
| + t.Fatal("teardown left the record") |
| + } |
| + if _, code, _, err := eligible(t, fx); err != nil || code != "no_store" { |
| + t.Fatalf("after teardown: %q %v", code, err) |
| + } |
| + |
| + grantStore(t, fx, token) |
| + second, code, _, err := eligible(t, fx) |
| + if err != nil || code != "" { |
| + t.Fatalf("second store: %q %v", code, err) |
| + } |
| + if second.Conversion.Incarnation == first.Conversion.Incarnation || !mediaHex32.MatchString(second.Conversion.Incarnation) { |
| + t.Fatalf("incarnation %q, first was %q", second.Conversion.Incarnation, first.Conversion.Incarnation) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index 48624b1e1..5c93736fa 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -68,6 +68,7 @@ import ( |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/replicas" |
| "github.com/carlosframework/platform/internal/status" |
| + "github.com/carlosframework/platform/internal/storecfg" |
| "github.com/carlosframework/platform/internal/svcrole" |
| "github.com/carlosframework/platform/internal/telemetry" |
| "github.com/carlosframework/platform/internal/usage" |
| @@ -853,6 +854,18 @@ type Config struct { |
| // lives — a walk that guessed would create the next bucket somewhere |
| // else, and the record would say so afterwards. |
| StoreDeployment objstore.Deployment |
| + // StoreConversion is CARLOS_STORE_CONVERSION=1: this deployment can read |
| + // and set its stores' bucket settings, which media conversion and |
| + // browser uploads need (media conversion spec §5.2, §5.6). Off, the |
| + // uploads verbs refuse. |
| + StoreConversion bool |
| + // StoreBuckets reads a store's bucket settings for the provenance check |
| + // (mediaStoreEligible) and writes the uploads rules. nil when |
| + // StoreConversion is off. Never called inside a SQLite transaction. |
| + StoreBuckets storecfg.Buckets |
| + // StoreAccountID is the deployment's cloud account id, the owner every |
| + // store bucket must have to pass verification. "" fails that check. |
| + StoreAccountID string |
| // StoreMaxPerApp caps how many ENVIRONMENT stores one app may have |
| // (CARLOS_STORE_MAX_PER_APP; 0 = storeMaxPerAppDefault). The app's own |
| // store is not one of them and is never capped. |
diff --git a/internal/objstore/aws.go b/internal/objstore/aws.go| index 341b0295f..a03193f9b 100644 |
| --- a/internal/objstore/aws.go |
| +++ b/internal/objstore/aws.go |
| @@ -291,8 +291,22 @@ func isNoSuchBucket(err error) bool { |
| // from "someone else got the name first", and only the former is safe to |
| // swallow. |
| func (p *awsProvisioner) EnsureBucket(ctx context.Context, name string) (string, error) { |
| + region, _, err := p.CreateNewBucket(ctx, name) |
| + return region, err |
| +} |
| + |
| +var _ BucketCreator = (*awsProvisioner)(nil) |
| + |
| +// CreateNewBucket is EnsureBucket that also says whether this call created |
| +// the bucket. Only a success from CreateBucket outside us-east-1 counts: |
| +// there, an existing bucket of ours answers BucketAlreadyOwnedByYou. In |
| +// us-east-1 (and with no region, which lands there) AWS answers a bare |
| +// success to an owner creating its own bucket again, so a success proves |
| +// nothing and is created == false. |
| +func (p *awsProvisioner) CreateNewBucket(ctx context.Context, name string) (string, bool, error) { |
| in := &awss3.CreateBucketInput{Bucket: aws.String(name)} |
| - if p.region != "" && p.region != "us-east-1" { |
| + located := p.region != "" && p.region != "us-east-1" |
| + if located { |
| in.CreateBucketConfiguration = &s3types.CreateBucketConfiguration{ |
| LocationConstraint: s3types.BucketLocationConstraint(p.region), |
| } |
| @@ -300,10 +314,11 @@ func (p *awsProvisioner) EnsureBucket(ctx context.Context, name string) (string, |
| if _, err := p.s3.CreateBucket(ctx, in); err != nil { |
| var owned *s3types.BucketAlreadyOwnedByYou |
| if !errors.As(err, &owned) { |
| - return "", fmt.Errorf("objstore: create bucket %q: %w", name, err) |
| + return "", false, fmt.Errorf("objstore: create bucket %q: %w", name, err) |
| } |
| + return p.region, false, nil |
| } |
| - return p.region, nil |
| + return p.region, located, nil |
| } |
| // EmptyBucket deletes every object in name, paginating ListObjectsV2 and |
diff --git a/internal/objstore/aws_test.go b/internal/objstore/aws_test.go| index 073c835f9..0477f74ac 100644 |
| --- a/internal/objstore/aws_test.go |
| +++ b/internal/objstore/aws_test.go |
| @@ -641,3 +641,53 @@ func TestEnsureUserOmitsAnEmptyBoundary(t *testing.T) { |
| t.Fatal("PermissionsBoundary was set from an empty boundary; want the field omitted") |
| } |
| } |
| + |
| +// CreateNewBucket answers created only for a success that proves this call |
| +// made the bucket. us-east-1 (and no region, which lands there) answers a |
| +// bare success to an owner re-creating its own bucket, so that proves |
| +// nothing; BucketAlreadyOwnedByYou is the owned bucket, not a new one. |
| +func TestAWSCreateNewBucketTable(t *testing.T) { |
| + owned := func(*awss3.CreateBucketInput) (*awss3.CreateBucketOutput, error) { |
| + return nil, &s3types.BucketAlreadyOwnedByYou{Message: aws.String("already yours")} |
| + } |
| + ok := func(*awss3.CreateBucketInput) (*awss3.CreateBucketOutput, error) { |
| + return &awss3.CreateBucketOutput{}, nil |
| + } |
| + taken := func(*awss3.CreateBucketInput) (*awss3.CreateBucketOutput, error) { |
| + return nil, &s3types.BucketAlreadyExists{Message: aws.String("someone else's")} |
| + } |
| + for _, tc := range []struct { |
| + name, region string |
| + create func(*awss3.CreateBucketInput) (*awss3.CreateBucketOutput, error) |
| + created bool |
| + wantErr bool |
| + }{ |
| + {"success", "eu-west-1", ok, true, false}, |
| + {"already-owned", "eu-west-1", owned, false, false}, |
| + {"us-east-1-success", "us-east-1", ok, false, false}, |
| + {"no-region-success", "", ok, false, false}, |
| + {"us-east-1-already-owned", "us-east-1", owned, false, false}, |
| + {"taken", "eu-west-1", taken, false, true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + p := &awsProvisioner{region: tc.region, s3: &stubS3{t: t, createBucket: tc.create}} |
| + region, created, err := p.CreateNewBucket(context.Background(), "b1") |
| + if tc.wantErr { |
| + if err == nil || created { |
| + t.Fatalf("CreateNewBucket = %v, %v; want an error and not created", created, err) |
| + } |
| + return |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if created != tc.created || region != tc.region { |
| + t.Fatalf("CreateNewBucket = (%q, %v), want (%q, %v)", region, created, tc.region, tc.created) |
| + } |
| + // EnsureBucket answers the same, without the flag. |
| + if r, err := p.EnsureBucket(context.Background(), "b1"); err != nil || r != tc.region { |
| + t.Fatalf("EnsureBucket = %q, %v", r, err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/objstore/memprovisioner.go b/internal/objstore/memprovisioner.go| index 233e3b18a..b040e2147 100644 |
| --- a/internal/objstore/memprovisioner.go |
| +++ b/internal/objstore/memprovisioner.go |
| @@ -40,6 +40,10 @@ type MemProvisioner struct { |
| // with a secret it cannot deliver (a real backend picks the bytes, so |
| // a walk must not assume they are renderable). |
| MintSecret string |
| + // PreExisting names buckets that exist before any walk runs, as a |
| + // bucket made by hand under the name the deployment would mint does. |
| + // CreateNewBucket answers created == false for them. |
| + PreExisting map[string]bool |
| } |
| // NewMemProvisioner returns an empty fake that answers region for every |
| @@ -65,15 +69,31 @@ func (p *MemProvisioner) takeFailure(method string) error { |
| } |
| func (p *MemProvisioner) EnsureBucket(ctx context.Context, name string) (string, error) { |
| + region, _, err := p.createBucket(name) |
| + return region, err |
| +} |
| + |
| +var _ BucketCreator = (*MemProvisioner)(nil) |
| + |
| +// CreateNewBucket is EnsureBucket answering whether this call made the |
| +// bucket: false when it already existed, in Buckets or in PreExisting. |
| +// It is the same bucket step, so FailNext["EnsureBucket"] fails it too. |
| +func (p *MemProvisioner) CreateNewBucket(ctx context.Context, name string) (string, bool, error) { |
| + return p.createBucket(name) |
| +} |
| + |
| +func (p *MemProvisioner) createBucket(name string) (string, bool, error) { |
| p.mu.Lock() |
| defer p.mu.Unlock() |
| if err := p.takeFailure("EnsureBucket"); err != nil { |
| - return "", err |
| + return "", false, err |
| } |
| + created := false |
| if p.Buckets[name] == nil { |
| p.Buckets[name] = map[string][]byte{} |
| + created = !p.PreExisting[name] |
| } |
| - return p.region, nil |
| + return p.region, created, nil |
| } |
| func (p *MemProvisioner) EnsureUser(ctx context.Context, name, path, bucketARN string, deny *DenyTag, denyWrites bool) (string, error) { |
diff --git a/internal/objstore/objstore.go b/internal/objstore/objstore.go| index 8da2a32b0..7a00b9d32 100644 |
| --- a/internal/objstore/objstore.go |
| +++ b/internal/objstore/objstore.go |
| @@ -7,6 +7,8 @@ package objstore |
| import ( |
| "context" |
| + "crypto/rand" |
| + "encoding/hex" |
| "encoding/json" |
| "errors" |
| "fmt" |
| @@ -141,7 +143,8 @@ type ScanBlock struct { |
| // |
| // `scanning` is such an additive change: release's local struct ignores keys |
| // it has never heard of, which TestPurgeGuardIgnoresScanningBlock asserts |
| -// directly. That freedom does NOT extend to `grant` and `provisioned`. |
| +// directly; `conversion` is another (TestPurgeGuardIgnoresConversionBlock). |
| +// That freedom does NOT extend to `grant` and `provisioned`. |
| type Record struct { |
| Schema int `json:"schema"` |
| App string `json:"app"` |
| @@ -167,6 +170,50 @@ type Record struct { |
| // lets a regrant that failed after the record changed be retried |
| // (Astra plans-4b finding 1). |
| WritesDenyApplied *bool `json:"writes_deny_applied,omitempty"` |
| + // Conversion is the store's provenance for media conversion and browser |
| + // uploads (media conversion spec §5.2). Absent until the grant walk |
| + // records a bucket it created itself, or the console verifies one. |
| + // Additive, like Scanning: release.PurgeApp's local struct ignores it |
| + // (TestPurgeGuardIgnoresConversionBlock). |
| + Conversion *Conversion `json:"conversion,omitempty"` |
| +} |
| + |
| +// Conversion says why a store's bucket may be used for conversion, and |
| +// which incarnation of the store this is. |
| +// |
| +// Incarnation is random and minted with the block. Teardown deletes the |
| +// record, so a store made again under the same app gets a new incarnation |
| +// and never inherits the old store's media jobs. |
| +// |
| +// Minted is true only when this deployment's grant walk itself created the |
| +// bucket (CreateNewBucket answered created on the first grant of a minted |
| +// name). VerifiedAt is set when the console checked an existing bucket's |
| +// settings instead. A block with neither is not yet eligible. |
| +type Conversion struct { |
| + Incarnation string `json:"incarnation"` |
| + Minted bool `json:"minted,omitempty"` |
| + VerifiedAt *time.Time `json:"verified_at,omitempty"` |
| + Uploads *Uploads `json:"uploads,omitempty"` |
| +} |
| + |
| +// Uploads records the CORS and lifecycle configuration the platform wrote |
| +// for browser uploads (spec §5.6), by hash, so a later check can tell the |
| +// platform's own rules from anyone else's. |
| +type Uploads struct { |
| + Origins []string `json:"origins"` |
| + CORSHash string `json:"cors_hash"` |
| + LifecycleHash string `json:"lifecycle_hash"` |
| + At time.Time `json:"at"` |
| + By string `json:"by"` |
| +} |
| + |
| +// NewIncarnation is 32 hex characters from 16 bytes of crypto/rand. |
| +func NewIncarnation() (string, error) { |
| + var b [16]byte |
| + if _, err := rand.Read(b[:]); err != nil { |
| + return "", fmt.Errorf("objstore: incarnation: %w", err) |
| + } |
| + return hex.EncodeToString(b[:]), nil |
| } |
| // WritesDenied says why a store refuses uploads, and since when. |
diff --git a/internal/objstore/provisioner.go b/internal/objstore/provisioner.go| index d5b0b8da5..867bbb46c 100644 |
| --- a/internal/objstore/provisioner.go |
| +++ b/internal/objstore/provisioner.go |
| @@ -33,3 +33,20 @@ type Provisioner interface { |
| // DeleteUser removes the user's keys and inline policy first. |
| DeleteUser(ctx context.Context, user string) error |
| } |
| + |
| +// BucketCreator is an optional Provisioner capability: create a bucket and |
| +// say whether THIS call created it. The grant walk uses it to record that |
| +// a store's bucket is one this deployment made (Conversion.Minted, media |
| +// conversion spec §5.2), which no other evidence can establish. |
| +// |
| +// created must be true only when the backend answered that this very call |
| +// made the bucket. "Already owned by you", or any success the backend also |
| +// gives to an owner creating an existing bucket again, is created == false: |
| +// the bucket may predate the walk, and its settings are then unknown. When |
| +// unsure, answer false; the cost is a verification, never a refusal. |
| +// |
| +// A Provisioner that does not implement it is treated as never creating |
| +// one, so every store it backs is verified before conversion uses it. |
| +type BucketCreator interface { |
| + CreateNewBucket(ctx context.Context, name string) (region string, created bool, err error) |
| +} |
diff --git a/internal/objstore/walk.go b/internal/objstore/walk.go| index f0aa74a42..1cf68ae90 100644 |
| --- a/internal/objstore/walk.go |
| +++ b/internal/objstore/walk.go |
| @@ -282,6 +282,11 @@ func claimRawGrantIn(ctx context.Context, s release.Store, p Provisioner, d Depl |
| if clearMark { |
| rec.Declared.Seed = "" |
| } |
| + // Whether this run is the one choosing the bucket, for step 3's |
| + // provenance: only a first grant of a minted name can be a walk that |
| + // made its own bucket. A re-run cannot tell its earlier self's create |
| + // from a bucket that was already there, so it never claims one. |
| + minting := rec.Grant == nil && adoptBucket == "" && bucket == MintedBucketIn(d, acct, app, env) |
| if rec.Grant == nil || clearMark { |
| if rec.Grant == nil { |
| rec.Grant = &GrantBlock{Backend: d.Backend, Bucket: bucket, Source: source, At: now, By: actor} |
| @@ -327,11 +332,35 @@ func claimRawGrantIn(ctx context.Context, s release.Store, p Provisioner, d Depl |
| } else if healthy { |
| return rec, nil |
| } |
| - // 3. the bucket |
| - region, err := p.EnsureBucket(ctx, bucket) |
| + // 3. the bucket. A provisioner that can say so reports whether this call |
| + // created it; any other counts as not having created it. |
| + var region string |
| + created := false |
| + if bc, ok := p.(BucketCreator); ok { |
| + region, created, err = bc.CreateNewBucket(ctx, bucket) |
| + } else { |
| + region, err = p.EnsureBucket(ctx, bucket) |
| + } |
| if err != nil { |
| return nil, fmt.Errorf("objstore: ensure bucket %s: %w", bucket, err) |
| } |
| + // Provenance (media conversion spec §5.2): a bucket this walk created, |
| + // under the name it minted, on the first grant, holds the settings a new |
| + // bucket gets and nothing else, so it is eligible for conversion without |
| + // a check. Everything else (an adopted bucket, a bucket already there |
| + // under the minted name, a re-run after the create) stays unminted and |
| + // is verified by the console before first use. The block rides the next |
| + // record write, step 6; a walk that fails before then loses it, and the |
| + // re-run that follows does not mint, which is the safe direction. |
| + var minted *Conversion |
| + if created && minting && rec.Conversion == nil { |
| + inc, err := NewIncarnation() |
| + if err != nil { |
| + return nil, err |
| + } |
| + minted = &Conversion{Incarnation: inc, Minted: true} |
| + rec.Conversion = minted |
| + } |
| // 4. key. Reap first: reaching here means delivery is missing, so any |
| // existing CURRENT key is either undelivered (its secret died with a |
| // failed config write — unrecoverable) or stranded by a crash between mint |
| @@ -396,6 +425,11 @@ func claimRawGrantIn(ctx context.Context, s release.Store, p Provisioner, d Depl |
| return nil, err |
| } |
| fresh.Provisioned = rec.Provisioned |
| + // The provenance step 3 minted is this walk's too. A block the |
| + // competing writer recorded meanwhile is theirs and stays. |
| + if minted != nil && fresh.Conversion == nil { |
| + fresh.Conversion = minted |
| + } |
| if _, perr := PutIn(ctx, s, acct, app, env, fresh, freshEtag); perr != nil { |
| return nil, perr |
| } |
diff --git a/internal/objstore/walk_test.go b/internal/objstore/walk_test.go| index 2bf057e83..42f08d955 100644 |
| --- a/internal/objstore/walk_test.go |
| +++ b/internal/objstore/walk_test.go |
| @@ -1,12 +1,15 @@ |
| package objstore |
| import ( |
| + "bytes" |
| "context" |
| "crypto/ecdh" |
| "crypto/ed25519" |
| "crypto/rand" |
| + "encoding/json" |
| "errors" |
| "os" |
| + "regexp" |
| "strings" |
| "testing" |
| "time" |
| @@ -1579,3 +1582,322 @@ func TestGrantRefusesRetryAgainstAnotherProvision(t *testing.T) { |
| t.Fatalf("the competing grant was clobbered: %+v, %v", stored.Provisioned, err) |
| } |
| } |
| + |
| +// ---- conversion provenance (media conversion spec §5.2) ------------------- |
| + |
| +var hex32 = regexp.MustCompile(`^[0-9a-f]{32}$`) |
| + |
| +func grantOnce(t *testing.T, s release.Store, p Provisioner, pub *ecdh.PublicKey, adopt string) (*Record, error) { |
| + t.Helper() |
| + return Grant(context.Background(), s, p, testDeployment(), storeTestSealer(pub, "bab", "titogo"), |
| + "bab", "titogo", "op", GrantSourceOperator, adopt, time.Now().UTC()) |
| +} |
| + |
| +func storedConversion(t *testing.T, s release.Store) *Conversion { |
| + t.Helper() |
| + rec, _, err := Get(context.Background(), s, "bab", "titogo") |
| + if err != nil || rec == nil { |
| + t.Fatalf("re-read: %+v, %v", rec, err) |
| + } |
| + return rec.Conversion |
| +} |
| + |
| +// The first grant of a minted name, whose bucket the walk itself created, |
| +// records that in the walk's next write: Minted, a fresh incarnation, no |
| +// verification time. |
| +func TestFirstGrantRecordsMinted(t *testing.T) { |
| + _, pub := testSealKeypair(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + p := NewMemProvisioner("eu-west-1") |
| + declare(t, s, "bab", "titogo", "TITO_S3") |
| + |
| + rec, err := grantOnce(t, s, p, pub, "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c := rec.Conversion |
| + if c == nil || !c.Minted || c.VerifiedAt != nil || c.Uploads != nil || !hex32.MatchString(c.Incarnation) { |
| + t.Fatalf("conversion = %+v, want minted with a 32-hex incarnation", c) |
| + } |
| + stored := storedConversion(t, s) |
| + if stored == nil || *stored != *c { |
| + t.Fatalf("stored conversion = %+v, want %+v", stored, c) |
| + } |
| + |
| + // A healthy re-run is a no-op, and a re-run that walks the whole |
| + // sequence again keeps the block it found: same incarnation. |
| + if _, err := grantOnce(t, s, p, pub, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := appconfig.Apply(context.Background(), s, "bab", "titogo", nil, []string{"TITO_S3_BUCKET"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := grantOnce(t, s, p, pub, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if again := storedConversion(t, s); again == nil || *again != *c { |
| + t.Fatalf("re-run changed the conversion block: %+v, want %+v", again, c) |
| + } |
| +} |
| + |
| +// An adopted bucket never earns Minted, even when it carries the name the |
| +// deployment would mint and the walk happened to create it. |
| +func TestAdoptedUnderMintedNameIsNotMinted(t *testing.T) { |
| + for name, adopt := range map[string]string{ |
| + "minted-name": MintedBucket(testDeployment(), "bab", "titogo"), |
| + "other-name": "titogo-uploads", |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + _, pub := testSealKeypair(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + p := NewMemProvisioner("eu-west-1") |
| + declare(t, s, "bab", "titogo", "TITO_S3") |
| + rec, err := grantOnce(t, s, p, pub, adopt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, ok := p.Buckets[adopt]; !ok { |
| + t.Fatalf("fixture: bucket %q not made", adopt) |
| + } |
| + if rec.Conversion != nil || storedConversion(t, s) != nil { |
| + t.Fatalf("adopted bucket recorded provenance: %+v", rec.Conversion) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A bucket that was already there under the minted name (made by hand, say) |
| +// is not one this walk created, so it stays unminted and is verified. |
| +func TestPreExistingMintedNameIsNotMinted(t *testing.T) { |
| + _, pub := testSealKeypair(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + p := NewMemProvisioner("eu-west-1") |
| + minted := MintedBucket(testDeployment(), "bab", "titogo") |
| + p.PreExisting = map[string]bool{minted: true} |
| + declare(t, s, "bab", "titogo", "TITO_S3") |
| + |
| + rec, err := grantOnce(t, s, p, pub, "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec.Provisioned == nil || rec.Provisioned.Bucket != minted { |
| + t.Fatalf("provisioned = %+v, want the minted name", rec.Provisioned) |
| + } |
| + if rec.Conversion != nil || storedConversion(t, s) != nil { |
| + t.Fatalf("pre-existing bucket recorded provenance: %+v", rec.Conversion) |
| + } |
| +} |
| + |
| +// A walk that created the bucket and then failed loses its claim: the re-run |
| +// finds the bucket already there and cannot tell that its earlier self made |
| +// it, so it does not mint. |
| +func TestRerunAfterCreateIsNotMinted(t *testing.T) { |
| + for _, method := range []string{"EnsureUser", "MintKey"} { |
| + t.Run(method, func(t *testing.T) { |
| + _, pub := testSealKeypair(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + p := NewMemProvisioner("eu-west-1") |
| + declare(t, s, "bab", "titogo", "TITO_S3") |
| + if method == "EnsureUser" { |
| + // EnsureUser runs before the bucket step, so fail it on the |
| + // SECOND grant's walk instead: first grant reaches the bucket |
| + // and dies at MintKey, the re-run fails EnsureUser, the third |
| + // run completes. |
| + p.FailNext["MintKey"] = errors.New("injected") |
| + if _, err := grantOnce(t, s, p, pub, ""); err == nil { |
| + t.Fatal("first grant: no error") |
| + } |
| + p.FailNext["EnsureUser"] = errors.New("injected") |
| + if _, err := grantOnce(t, s, p, pub, ""); err == nil { |
| + t.Fatal("second grant: no error") |
| + } |
| + } else { |
| + p.FailNext[method] = errors.New("injected") |
| + if _, err := grantOnce(t, s, p, pub, ""); err == nil { |
| + t.Fatal("first grant: no error") |
| + } |
| + } |
| + if _, ok := p.Buckets[MintedBucket(testDeployment(), "bab", "titogo")]; !ok { |
| + t.Fatal("fixture: the failed walk never created the bucket") |
| + } |
| + rec, err := grantOnce(t, s, p, pub, "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec.Provisioned == nil { |
| + t.Fatal("re-run did not provision") |
| + } |
| + if rec.Conversion != nil || storedConversion(t, s) != nil { |
| + t.Fatalf("re-run after the create recorded provenance: %+v", rec.Conversion) |
| + } |
| + }) |
| + } |
| + |
| + t.Run("delivery", func(t *testing.T) { |
| + _, pub := testSealKeypair(t) |
| + s := &failingStore{Store: release.NewDirStore(t.TempDir()), failKeyOnce: appconfig.Key("bab", "titogo")} |
| + p := NewMemProvisioner("eu-west-1") |
| + declare(t, s, "bab", "titogo", "TITO_S3") |
| + if _, err := grantOnce(t, s, p, pub, ""); err == nil { |
| + t.Fatal("first grant: no error") |
| + } |
| + rec, err := grantOnce(t, s, p, pub, "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec.Conversion != nil || storedConversion(t, s) != nil { |
| + t.Fatalf("re-run after a failed delivery recorded provenance: %+v", rec.Conversion) |
| + } |
| + }) |
| +} |
| + |
| +// A provisioner without BucketCreator (the console's claim wrappers) never |
| +// mints: every store it backs is verified instead. |
| +func TestGrantWithoutBucketCreatorIsNotMinted(t *testing.T) { |
| + _, pub := testSealKeypair(t) |
| + s := release.NewDirStore(t.TempDir()) |
| + p := ensureOnly{NewMemProvisioner("eu-west-1")} |
| + declare(t, s, "bab", "titogo", "TITO_S3") |
| + rec, err := grantOnce(t, s, p, pub, "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec.Conversion != nil { |
| + t.Fatalf("conversion = %+v through a plain Provisioner", rec.Conversion) |
| + } |
| +} |
| + |
| +// ensureOnly hides MemProvisioner's CreateNewBucket: embedding the interface |
| +// promotes only Provisioner's methods. |
| +type ensureOnly struct{ Provisioner } |
| + |
| +// racesProvisionedPut lands race on the store record just before the walk's |
| +// step-6 write (the first Put of the record that carries a provisioned block), |
| +// so a first grant's lost CAS can be exercised: the step-1 write goes through. |
| +type racesProvisionedPut struct { |
| + release.Store |
| + race func(inner release.Store) |
| +} |
| + |
| +func (r *racesProvisionedPut) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + if r.race != nil && key == Key("bab", "titogo") && bytes.Contains(body, []byte(`"provisioned"`)) { |
| + race := r.race |
| + r.race = nil |
| + race(r.Store) |
| + } |
| + return r.Store.Put(ctx, key, body, ifMatch) |
| +} |
| + |
| +// The step-6 retry carries the block this walk minted, as it carries the |
| +// provisioned block; a first grant that lost its CAS must not lose its |
| +// provenance silently while keeping the store. |
| +func TestFirstGrantMintedSurvivesLostCAS(t *testing.T) { |
| + ctx := context.Background() |
| + _, pub := testSealKeypair(t) |
| + s := &racesProvisionedPut{Store: release.NewDirStore(t.TempDir())} |
| + p := NewMemProvisioner("eu-west-1") |
| + declare(t, s, "bab", "titogo", "TITO_S3") |
| + s.race = func(in release.Store) { |
| + other, etag, err := Get(ctx, in, "bab", "titogo") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + other.Declared.By = "someone-else@example.com" |
| + if _, err := Put(ctx, in, "bab", "titogo", other, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + rec, err := grantOnce(t, s, p, pub, "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + stored, _, err := Get(ctx, s, "bab", "titogo") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if stored.Declared.By != "someone-else@example.com" { |
| + t.Fatal("fixture: the race never landed") |
| + } |
| + if stored.Conversion == nil || !stored.Conversion.Minted || rec.Conversion == nil || |
| + stored.Conversion.Incarnation != rec.Conversion.Incarnation { |
| + t.Fatalf("stored conversion = %+v, returned %+v", stored.Conversion, rec.Conversion) |
| + } |
| +} |
| + |
| +// The conversion block is additive: release.PurgeApp's local struct ignores |
| +// it in both directions, exactly as TestPurgeGuardIgnoresScanningBlock asserts |
| +// for the scanning block. |
| +func TestPurgeGuardIgnoresConversionBlock(t *testing.T) { |
| + ctx := context.Background() |
| + _, pub := testSealKeypair(t) |
| + relPub, _, err := ed25519.GenerateKey(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + backdated := time.Now().Add(-2 * release.TrashCooloff) |
| + verified := time.Now().UTC() |
| + block := &Conversion{Incarnation: "0123456789abcdef0123456789abcdef", VerifiedAt: &verified, |
| + Uploads: &Uploads{Origins: []string{"https://shop.example.com"}, CORSHash: "c", LifecycleHash: "l", At: verified, By: "m@example.com"}} |
| + |
| + t.Run("provisioned-plus-conversion-still-blocks", func(t *testing.T) { |
| + s := release.NewDirStore(t.TempDir()) |
| + p := NewMemProvisioner("eu-west-1") |
| + rotateFixture(t, s, pub, p) |
| + stored, etag, err := Get(ctx, s, "bab", "titogo") |
| + if err != nil || stored == nil { |
| + t.Fatalf("re-read: %+v, %v", stored, err) |
| + } |
| + stored.Conversion = block |
| + if _, err := Put(ctx, s, "bab", "titogo", stored, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := release.TrashApp(ctx, s, "bab", "titogo", "paul@keymail.dev", backdated); err != nil { |
| + t.Fatal(err) |
| + } |
| + err = release.PurgeApp(ctx, s, relPub, "bab", "titogo", time.Now()) |
| + if !errors.Is(err, release.ErrStoreProvisioned) { |
| + t.Fatalf("PurgeApp over provisioned+conversion = %v, want release.ErrStoreProvisioned", err) |
| + } |
| + }) |
| + |
| + t.Run("conversion-alone-names-no-estate", func(t *testing.T) { |
| + s := release.NewDirStore(t.TempDir()) |
| + declare(t, s, "bab", "titogo", "TITO_S3") |
| + stored, etag, err := Get(ctx, s, "bab", "titogo") |
| + if err != nil || stored == nil { |
| + t.Fatalf("re-read: %+v, %v", stored, err) |
| + } |
| + stored.Conversion = block |
| + if _, err := Put(ctx, s, "bab", "titogo", stored, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := release.TrashApp(ctx, s, "bab", "titogo", "paul@keymail.dev", backdated); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := release.PurgeApp(ctx, s, relPub, "bab", "titogo", time.Now()); err != nil { |
| + t.Fatalf("PurgeApp over a declared+conversion record: %v", err) |
| + } |
| + if _, _, err := s.Get(ctx, Key("bab", "titogo")); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("store.json survived the purge: %v", err) |
| + } |
| + }) |
| +} |
| + |
| +// The block's wire names are the brief's, and a record written before it |
| +// existed decodes with none. |
| +func TestConversionBlockWireNames(t *testing.T) { |
| + at := time.Date(2026, 11, 17, 9, 0, 0, 0, time.UTC) |
| + b, err := json.Marshal(Conversion{Incarnation: "i", VerifiedAt: &at, |
| + Uploads: &Uploads{Origins: []string{"https://shop.example.com"}, CORSHash: "c", LifecycleHash: "l", At: at, By: "m"}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := `{"incarnation":"i","verified_at":"2026-11-17T09:00:00Z","uploads":{"origins":["https://shop.example.com"],"cors_hash":"c","lifecycle_hash":"l","at":"2026-11-17T09:00:00Z","by":"m"}}` |
| + if string(b) != want { |
| + t.Fatalf("wire = %s\nwant %s", b, want) |
| + } |
| + var rec Record |
| + if err := json.Unmarshal([]byte(`{"schema":1,"app":"titogo"}`), &rec); err != nil || rec.Conversion != nil { |
| + t.Fatalf("old record: %+v, %v", rec.Conversion, err) |
| + } |
| +} |
diff --git a/internal/storecfg/fake.go b/internal/storecfg/fake.go| new file mode 100644 |
| index 000000000..ec54b84c3 |
| --- /dev/null |
| +++ b/internal/storecfg/fake.go |
| @@ -0,0 +1,82 @@ |
| +package storecfg |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "sync" |
| +) |
| + |
| +// Fake is an in-memory Buckets for tests. Facts maps a bucket name to what |
| +// Inspect answers; a bucket not in it is an error, as a missing bucket is. |
| +// PutUploads and DeleteUploads change the bucket's CORS and Lifecycle the |
| +// way a real backend would. Fail, keyed by method name, fails the next call |
| +// to that method once. Calls records every call as "Method bucket". |
| +type Fake struct { |
| + mu sync.Mutex |
| + Facts map[string]Facts |
| + Fail map[string]error |
| + Calls []string |
| +} |
| + |
| +var _ Buckets = (*Fake)(nil) |
| + |
| +// NewFake answers with no buckets. |
| +func NewFake() *Fake { |
| + return &Fake{Facts: map[string]Facts{}, Fail: map[string]error{}} |
| +} |
| + |
| +// CallCount is how many calls to method the fake has seen. |
| +func (f *Fake) CallCount(method string) int { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + n := 0 |
| + for _, c := range f.Calls { |
| + if len(c) > len(method) && c[:len(method)] == method && c[len(method)] == ' ' { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +func (f *Fake) begin(method, bucket string) (Facts, error) { |
| + f.Calls = append(f.Calls, method+" "+bucket) |
| + if err, ok := f.Fail[method]; ok { |
| + delete(f.Fail, method) |
| + return Facts{}, err |
| + } |
| + facts, ok := f.Facts[bucket] |
| + if !ok { |
| + return Facts{}, fmt.Errorf("storecfg: fake: no bucket %q", bucket) |
| + } |
| + return facts, nil |
| +} |
| + |
| +func (f *Fake) Inspect(ctx context.Context, bucket string) (Facts, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return f.begin("Inspect", bucket) |
| +} |
| + |
| +func (f *Fake) PutUploads(ctx context.Context, bucket string, origins []string) error { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + facts, err := f.begin("PutUploads", bucket) |
| + if err != nil { |
| + return err |
| + } |
| + facts.CORS, facts.Lifecycle = UploadsCORS(origins), UploadsLifecycle() |
| + f.Facts[bucket] = facts |
| + return nil |
| +} |
| + |
| +func (f *Fake) DeleteUploads(ctx context.Context, bucket string) error { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + facts, err := f.begin("DeleteUploads", bucket) |
| + if err != nil { |
| + return err |
| + } |
| + facts.CORS, facts.Lifecycle = nil, nil |
| + f.Facts[bucket] = facts |
| + return nil |
| +} |
diff --git a/internal/storecfg/storecfg.go b/internal/storecfg/storecfg.go| new file mode 100644 |
| index 000000000..5eeca028b |
| --- /dev/null |
| +++ b/internal/storecfg/storecfg.go |
| @@ -0,0 +1,241 @@ |
| +// Package storecfg is the bucket-settings half of a store's provenance for |
| +// media conversion and browser uploads (media conversion spec §5.2, §5.6): |
| +// what a bucket's settings are, whether they are the ones conversion relies |
| +// on, and the one CORS rule and one lifecycle rule the platform writes. |
| +// |
| +// It is provider-neutral. Buckets is the seam; the AWS adapter lives in |
| +// internal/mediaaws (plan 3), and Fake serves the tests. This package |
| +// imports the standard library and internal/objstore only. |
| +package storecfg |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "slices" |
| + |
| + "github.com/carlosframework/platform/internal/objstore" |
| +) |
| + |
| +// Facts is what a bucket holds, as Buckets.Inspect reads it. |
| +// |
| +// Owner is the cloud account that owns the bucket, "" when it is not the |
| +// account the adapter asked about. Region is where the bucket lives. |
| +// Encryption is the default encryption rule's algorithm: "", "AES256" |
| +// (SSE-S3) or "aws:kms" (any KMS variant). Versioning is "", "Enabled" or |
| +// "Suspended" ("" only for a bucket that was never versioned). CORS and |
| +// Lifecycle are the canonical JSON (CanonicalCORS, CanonicalLifecycle) of |
| +// what the bucket holds, nil when it holds none. |
| +type Facts struct { |
| + Owner, Region, Encryption, Versioning string |
| + HasPolicy bool |
| + CORS, Lifecycle []byte |
| +} |
| + |
| +// Buckets reads and writes the settings Verify and the uploads verbs need. |
| +// No method may be called inside a SQLite transaction. |
| +type Buckets interface { |
| + Inspect(ctx context.Context, bucket string) (Facts, error) |
| + // PutUploads writes UploadsCORS(origins) and UploadsLifecycle(), |
| + // replacing whatever CORS and lifecycle configuration the bucket held. |
| + // The caller has checked that what it replaces is the platform's own. |
| + PutUploads(ctx context.Context, bucket string, origins []string) error |
| + // DeleteUploads removes the bucket's CORS and lifecycle configuration. |
| + DeleteUploads(ctx context.Context, bucket string) error |
| +} |
| + |
| +// CORSRule is one CORS rule in canonical form. It carries every field an S3 |
| +// CORS rule has, so an adapter can convert what a bucket holds losslessly. |
| +type CORSRule struct { |
| + ID string `json:"id,omitempty"` |
| + AllowedHeaders []string `json:"allowed_headers"` |
| + AllowedMethods []string `json:"allowed_methods"` |
| + AllowedOrigins []string `json:"allowed_origins"` |
| + ExposeHeaders []string `json:"expose_headers"` |
| + MaxAgeSeconds int `json:"max_age_seconds"` |
| +} |
| + |
| +// LifecycleRule is one lifecycle rule in canonical form. Prefix is the |
| +// rule's prefix filter (the deprecated top-level prefix and the filter's |
| +// prefix are the same thing). Other names every setting the rule carries |
| +// beyond those modelled here (an expiration, a transition, a tag or size |
| +// filter, a noncurrent-version action), one name each, so that a rule with |
| +// any of them can never canonicalise to the platform's own rule. An adapter |
| +// that meets a setting it cannot name must still add an entry for it. |
| +type LifecycleRule struct { |
| + ID string `json:"id"` |
| + Prefix string `json:"prefix"` |
| + Status string `json:"status"` |
| + AbortIncompleteMultipartUploadDays int `json:"abort_incomplete_multipart_upload_days,omitempty"` |
| + Other []string `json:"other,omitempty"` |
| +} |
| + |
| +// CanonicalCORS is the canonical JSON of a bucket's CORS rules: the rules in |
| +// the order the bucket holds them, each list inside a rule sorted, so the |
| +// order a backend reports values in cannot change the bytes. No rules is nil. |
| +func CanonicalCORS(rules []CORSRule) []byte { |
| + if len(rules) == 0 { |
| + return nil |
| + } |
| + out := make([]CORSRule, len(rules)) |
| + for i, r := range rules { |
| + out[i] = CORSRule{ |
| + ID: r.ID, |
| + AllowedHeaders: sortedCopy(r.AllowedHeaders), |
| + AllowedMethods: sortedCopy(r.AllowedMethods), |
| + AllowedOrigins: sortedCopy(r.AllowedOrigins), |
| + ExposeHeaders: sortedCopy(r.ExposeHeaders), |
| + MaxAgeSeconds: r.MaxAgeSeconds, |
| + } |
| + } |
| + return mustJSON(out) |
| +} |
| + |
| +// CanonicalLifecycle is the canonical JSON of a bucket's lifecycle rules, in |
| +// the order the bucket holds them, each rule's Other sorted. No rules is nil. |
| +func CanonicalLifecycle(rules []LifecycleRule) []byte { |
| + if len(rules) == 0 { |
| + return nil |
| + } |
| + out := make([]LifecycleRule, len(rules)) |
| + for i, r := range rules { |
| + r.Other = sortedCopy(r.Other) |
| + if len(r.Other) == 0 { |
| + r.Other = nil |
| + } |
| + out[i] = r |
| + } |
| + return mustJSON(out) |
| +} |
| + |
| +// UploadsLifecycleID names the platform's one lifecycle rule. |
| +const UploadsLifecycleID = "carlos-abort-multipart" |
| + |
| +// UploadsCORSRules is the platform's one CORS rule for browser uploads |
| +// (spec §5.6): GET, HEAD and PUT from the given origins, any request header, |
| +// ETag exposed (a multipart upload reads each part's ETag back), cached for |
| +// an hour. |
| +func UploadsCORSRules(origins []string) []CORSRule { |
| + return []CORSRule{{ |
| + AllowedHeaders: []string{"*"}, |
| + AllowedMethods: []string{"GET", "HEAD", "PUT"}, |
| + AllowedOrigins: sortedCopy(origins), |
| + ExposeHeaders: []string{"ETag"}, |
| + MaxAgeSeconds: 3600, |
| + }} |
| +} |
| + |
| +// UploadsLifecycleRules is the platform's one lifecycle rule: abort every |
| +// incomplete multipart upload a day after it started, across the bucket. |
| +func UploadsLifecycleRules() []LifecycleRule { |
| + return []LifecycleRule{{ |
| + ID: UploadsLifecycleID, |
| + Prefix: "", |
| + Status: "Enabled", |
| + AbortIncompleteMultipartUploadDays: 1, |
| + }} |
| +} |
| + |
| +// UploadsCORS is the canonical JSON of UploadsCORSRules(origins). The order |
| +// of origins does not change the bytes. |
| +func UploadsCORS(origins []string) []byte { return CanonicalCORS(UploadsCORSRules(origins)) } |
| + |
| +// UploadsLifecycle is the canonical JSON of UploadsLifecycleRules(). |
| +func UploadsLifecycle() []byte { return CanonicalLifecycle(UploadsLifecycleRules()) } |
| + |
| +// Hash is the hex SHA-256 of b, the form Conversion.Uploads records. |
| +func Hash(b []byte) string { |
| + sum := sha256.Sum256(b) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +// The checks Verify runs, in its order. Each names a media.check.* row of |
| +// the copy deck. |
| +const ( |
| + CheckName = "name" |
| + CheckOwner = "owner" |
| + CheckRegion = "region" |
| + CheckEncryption = "encryption" |
| + CheckVersioning = "versioning" |
| + CheckPolicy = "policy" |
| + CheckLifecycle = "lifecycle" |
| + CheckCORS = "cors" |
| +) |
| + |
| +// Checks lists every check in Verify's order. |
| +var Checks = []string{CheckName, CheckOwner, CheckRegion, CheckEncryption, |
| + CheckVersioning, CheckPolicy, CheckLifecycle, CheckCORS} |
| + |
| +// Want is what a store's bucket must be for conversion. Bucket is the |
| +// bucket the store record names; MintedName the name this deployment would |
| +// mint for the store; Account this deployment's cloud account; Region the |
| +// store's region. Uploads is what the platform recorded writing, nil when |
| +// it wrote nothing. |
| +type Want struct { |
| + Bucket, MintedName, Account, Region string |
| + Uploads *objstore.Uploads |
| +} |
| + |
| +// Verify answers "" when f is a bucket conversion may rely on, else the first |
| +// failing check: the bucket has the name the platform would mint, belongs to |
| +// the deployment's account, is in the store's region, uses SSE-S3 (not |
| +// SSE-KMS, and not none), has never been versioned, has no bucket policy, |
| +// and holds no lifecycle or CORS configuration the platform did not write. |
| +// |
| +// A Want field left empty fails its check rather than matching an empty |
| +// fact: an unset account id must never let a bucket of unknown ownership |
| +// through. |
| +func Verify(f Facts, want Want) (check string) { |
| + switch { |
| + case want.MintedName == "" || want.Bucket != want.MintedName: |
| + return CheckName |
| + case want.Account == "" || f.Owner != want.Account: |
| + return CheckOwner |
| + case want.Region == "" || f.Region != want.Region: |
| + return CheckRegion |
| + case f.Encryption != "AES256": |
| + return CheckEncryption |
| + case f.Versioning != "": |
| + return CheckVersioning |
| + case f.HasPolicy: |
| + return CheckPolicy |
| + } |
| + var lifecycleHash, corsHash string |
| + if want.Uploads != nil { |
| + lifecycleHash, corsHash = want.Uploads.LifecycleHash, want.Uploads.CORSHash |
| + } |
| + if !recorded(f.Lifecycle, lifecycleHash) { |
| + return CheckLifecycle |
| + } |
| + if !recorded(f.CORS, corsHash) { |
| + return CheckCORS |
| + } |
| + return "" |
| +} |
| + |
| +// recorded: the bucket holds no such configuration, or holds exactly what the |
| +// platform recorded writing. |
| +func recorded(held []byte, hash string) bool { |
| + if len(held) == 0 { |
| + return true |
| + } |
| + return hash != "" && Hash(held) == hash |
| +} |
| + |
| +func sortedCopy(v []string) []string { |
| + out := slices.Clone(v) |
| + if out == nil { |
| + out = []string{} |
| + } |
| + slices.Sort(out) |
| + return out |
| +} |
| + |
| +func mustJSON(v any) []byte { |
| + b, err := json.Marshal(v) |
| + if err != nil { |
| + panic("storecfg: canonical json: " + err.Error()) // plain structs of strings and ints |
| + } |
| + return b |
| +} |
diff --git a/internal/storecfg/storecfg_test.go b/internal/storecfg/storecfg_test.go| new file mode 100644 |
| index 000000000..9b669b7cc |
| --- /dev/null |
| +++ b/internal/storecfg/storecfg_test.go |
| @@ -0,0 +1,187 @@ |
| +package storecfg |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/objstore" |
| +) |
| + |
| +const ( |
| + testBucket = "carlos-store-bab-shop" |
| + testAccount = "123456789012" |
| + testRegion = "eu-west-1" |
| +) |
| + |
| +func goodFacts() Facts { |
| + return Facts{Owner: testAccount, Region: testRegion, Encryption: "AES256"} |
| +} |
| + |
| +func goodWant() Want { |
| + return Want{Bucket: testBucket, MintedName: testBucket, Account: testAccount, Region: testRegion} |
| +} |
| + |
| +func recordedUploads(origins []string) *objstore.Uploads { |
| + return &objstore.Uploads{Origins: origins, CORSHash: Hash(UploadsCORS(origins)), LifecycleHash: Hash(UploadsLifecycle())} |
| +} |
| + |
| +// One passing bucket, then one failure per check in Verify's order. Each |
| +// failing case also fails every later check, so the order is what decides |
| +// the answer, not the case's only fault. |
| +func TestVerifyTable(t *testing.T) { |
| + origins := []string{"https://shop.example.com"} |
| + foreignCORS := CanonicalCORS([]CORSRule{{AllowedMethods: []string{"GET"}, AllowedOrigins: []string{"*"}}}) |
| + foreignLifecycle := CanonicalLifecycle([]LifecycleRule{{ID: "expire", Status: "Enabled", Other: []string{"expiration"}}}) |
| + allBad := func(f Facts) Facts { |
| + f.Encryption, f.Versioning, f.HasPolicy = "aws:kms", "Enabled", true |
| + f.CORS, f.Lifecycle = foreignCORS, foreignLifecycle |
| + return f |
| + } |
| + |
| + for _, tc := range []struct { |
| + name string |
| + facts Facts |
| + want Want |
| + check string |
| + }{ |
| + {"passes", goodFacts(), goodWant(), ""}, |
| + {"passes-with-our-uploads", func() Facts { |
| + f := goodFacts() |
| + f.CORS, f.Lifecycle = UploadsCORS(origins), UploadsLifecycle() |
| + return f |
| + }(), func() Want { w := goodWant(); w.Uploads = recordedUploads(origins); return w }(), ""}, |
| + {"name-adopted", allBad(goodFacts()), func() Want { w := goodWant(); w.Bucket = "shop-uploads"; return w }(), CheckName}, |
| + {"name-unset", goodFacts(), func() Want { w := goodWant(); w.MintedName = ""; return w }(), CheckName}, |
| + {"owner-foreign", func() Facts { f := allBad(goodFacts()); f.Owner = "999999999999"; return f }(), goodWant(), CheckOwner}, |
| + {"owner-unknown", func() Facts { f := allBad(goodFacts()); f.Owner = ""; return f }(), goodWant(), CheckOwner}, |
| + {"owner-unset-account", func() Facts { f := goodFacts(); f.Owner = ""; return f }(), func() Want { w := goodWant(); w.Account = ""; return w }(), CheckOwner}, |
| + {"region", func() Facts { f := allBad(goodFacts()); f.Region = "us-east-1"; return f }(), goodWant(), CheckRegion}, |
| + {"region-unset", func() Facts { f := goodFacts(); f.Region = ""; return f }(), func() Want { w := goodWant(); w.Region = ""; return w }(), CheckRegion}, |
| + {"encryption-kms", allBad(goodFacts()), goodWant(), CheckEncryption}, |
| + {"encryption-none", func() Facts { f := goodFacts(); f.Encryption = ""; return f }(), goodWant(), CheckEncryption}, |
| + {"versioning-enabled", func() Facts { f := allBad(goodFacts()); f.Encryption = "AES256"; return f }(), goodWant(), CheckVersioning}, |
| + {"versioning-suspended", func() Facts { f := goodFacts(); f.Versioning = "Suspended"; f.HasPolicy = true; return f }(), goodWant(), CheckVersioning}, |
| + {"policy", func() Facts { |
| + f := goodFacts() |
| + f.HasPolicy, f.CORS, f.Lifecycle = true, foreignCORS, foreignLifecycle |
| + return f |
| + }(), goodWant(), CheckPolicy}, |
| + {"lifecycle-foreign", func() Facts { f := goodFacts(); f.CORS, f.Lifecycle = foreignCORS, foreignLifecycle; return f }(), goodWant(), CheckLifecycle}, |
| + // Our own rule, but nothing recorded says we wrote it: someone else |
| + // may have, and its CORS twin could carry any origin. |
| + {"lifecycle-ours-unrecorded", func() Facts { f := goodFacts(); f.Lifecycle = UploadsLifecycle(); return f }(), goodWant(), CheckLifecycle}, |
| + {"lifecycle-other-than-recorded", func() Facts { f := goodFacts(); f.Lifecycle = foreignLifecycle; return f }(), |
| + func() Want { w := goodWant(); w.Uploads = recordedUploads(origins); return w }(), CheckLifecycle}, |
| + {"cors-foreign", func() Facts { f := goodFacts(); f.CORS = foreignCORS; return f }(), goodWant(), CheckCORS}, |
| + {"cors-other-origins-than-recorded", func() Facts { |
| + f := goodFacts() |
| + f.CORS, f.Lifecycle = UploadsCORS([]string{"https://evil.example.net"}), UploadsLifecycle() |
| + return f |
| + }(), func() Want { w := goodWant(); w.Uploads = recordedUploads(origins); return w }(), CheckCORS}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + if got := Verify(tc.facts, tc.want); got != tc.check { |
| + t.Fatalf("Verify = %q, want %q", got, tc.check) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestChecksAreVerifysOrder(t *testing.T) { |
| + want := []string{"name", "owner", "region", "encryption", "versioning", "policy", "lifecycle", "cors"} |
| + if len(Checks) != len(want) { |
| + t.Fatalf("Checks = %v", Checks) |
| + } |
| + for i := range want { |
| + if Checks[i] != want[i] { |
| + t.Fatalf("Checks = %v, want %v", Checks, want) |
| + } |
| + } |
| +} |
| + |
| +// Origin order does not change the bytes, and the bytes are the rule the |
| +// spec states, exactly. |
| +func TestUploadsCORSIsCanonical(t *testing.T) { |
| + a := UploadsCORS([]string{"https://shop.example.com", "http://localhost:3000", "https://admin.shop.example.com"}) |
| + b := UploadsCORS([]string{"https://admin.shop.example.com", "https://shop.example.com", "http://localhost:3000"}) |
| + if !bytes.Equal(a, b) { |
| + t.Fatalf("origin order changed the bytes:\n%s\n%s", a, b) |
| + } |
| + want := `[{"allowed_headers":["*"],"allowed_methods":["GET","HEAD","PUT"],"allowed_origins":["http://localhost:3000","https://admin.shop.example.com","https://shop.example.com"],"expose_headers":["ETag"],"max_age_seconds":3600}]` |
| + if string(a) != want { |
| + t.Fatalf("UploadsCORS =\n%s\nwant\n%s", a, want) |
| + } |
| + // A backend reporting the methods in another order still canonicalises |
| + // to the same bytes. |
| + shuffled := UploadsCORSRules([]string{"https://shop.example.com"}) |
| + shuffled[0].AllowedMethods = []string{"PUT", "GET", "HEAD"} |
| + if !bytes.Equal(CanonicalCORS(shuffled), UploadsCORS([]string{"https://shop.example.com"})) { |
| + t.Fatal("method order changed the canonical bytes") |
| + } |
| + if CanonicalCORS(nil) != nil || CanonicalLifecycle(nil) != nil { |
| + t.Fatal("no rules must canonicalise to nil") |
| + } |
| +} |
| + |
| +func TestUploadsLifecycleIsTheOneRule(t *testing.T) { |
| + want := `[{"id":"carlos-abort-multipart","prefix":"","status":"Enabled","abort_incomplete_multipart_upload_days":1}]` |
| + if got := string(UploadsLifecycle()); got != want { |
| + t.Fatalf("UploadsLifecycle =\n%s\nwant\n%s", got, want) |
| + } |
| + // The same rule plus any setting it does not model is different bytes. |
| + extra := UploadsLifecycleRules() |
| + extra[0].Other = []string{"expiration"} |
| + if bytes.Equal(CanonicalLifecycle(extra), UploadsLifecycle()) { |
| + t.Fatal("a rule with an expiration canonicalised to the platform's own") |
| + } |
| +} |
| + |
| +func TestHashIsHexSHA256(t *testing.T) { |
| + if got := Hash([]byte("abc")); got != "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" { |
| + t.Fatalf("Hash(abc) = %s", got) |
| + } |
| +} |
| + |
| +func TestFakeUploadsRoundTrip(t *testing.T) { |
| + ctx := context.Background() |
| + f := NewFake() |
| + f.Facts[testBucket] = goodFacts() |
| + origins := []string{"https://shop.example.com"} |
| + if err := f.PutUploads(ctx, testBucket, origins); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := f.Inspect(ctx, testBucket) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if Hash(got.CORS) != Hash(UploadsCORS(origins)) || Hash(got.Lifecycle) != Hash(UploadsLifecycle()) { |
| + t.Fatalf("after PutUploads: %+v", got) |
| + } |
| + w := goodWant() |
| + w.Uploads = recordedUploads(origins) |
| + if c := Verify(got, w); c != "" { |
| + t.Fatalf("Verify after our own uploads = %q", c) |
| + } |
| + if err := f.DeleteUploads(ctx, testBucket); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, _ := f.Inspect(ctx, testBucket); got.CORS != nil || got.Lifecycle != nil { |
| + t.Fatalf("after DeleteUploads: %+v", got) |
| + } |
| + if _, err := f.Inspect(ctx, "absent"); err == nil { |
| + t.Fatal("Inspect of an absent bucket answered") |
| + } |
| + boom := errors.New("injected") |
| + f.Fail["Inspect"] = boom |
| + if _, err := f.Inspect(ctx, testBucket); !errors.Is(err, boom) { |
| + t.Fatalf("Fail: %v", err) |
| + } |
| + if _, err := f.Inspect(ctx, testBucket); err != nil { |
| + t.Fatalf("Fail is one-shot: %v", err) |
| + } |
| + if n := f.CallCount("Inspect"); n != 5 { |
| + t.Fatalf("Inspect calls = %d, want 5", n) |
| + } |
| +} |