store: list store versions through one URL-encoding helper (round 2 P1)
Paul's ruling on Astra round 2's P1 (option 3): objstore.ListObjectVersionsPage is the only way store code lists versions. It asks S3 for URL-encoded keys and decodes every key, marker and prefix exactly once, so a key XML cannot carry (a control character an app planted under another key's prefix) never breaks listing, restore, teardown or the sizing sweep. TestEveryStoreVersionListingUsesTheHelper fails on any other call site. An SDK-level fixture (a fake S3 speaking XML) holds control-character, %, + and space keys and a planted key beside an ordinary one. EmptyVersions deletes a key DeleteObjects' XML body cannot carry by URL.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+524
−15
docs/superpowers/specs/2026-11-22-store-versioning-design.md+27 −1internal/console/apistoreversioning_test.go+3 −0internal/console/economicspass.go+5 −8internal/objstore/aws_versioning.go+20 −5internal/objstore/aws_versioning_test.go+4 −0internal/objstore/versionlist.go+111 −0internal/objstore/versionlist_test.go+353 −0internal/provision/testdata/plan14-root-reads-store-versioning.tsv+1 −1
CI cancelled — superseded by a newer push — run details
CI log
=== gate === go: downloading go1.26.10 (linux/arm64) go version go1.26.10 linux/arm64 opentofu: arm64, tofu 1.13.9, aws 6.73.0, archive 2.8.1 tofu: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/tofu_1.13.9_linux_arm64.tar.gz tofu: downloaded, digest verified aws: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-aws_6.73.0_linux_arm64.zip aws: downloaded, digest verified archive: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-archive_2.8.1_linux_arm64.zip archive: downloaded, digest verified installed in /tmp/carlos-opentofu-8kWuBB .amadan/test-gate.sh go: downloading github.com/aws/aws-sdk-go-v2 v1.44.0 go: downloading github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0 go: downloading github.com/aws/smithy-go v1.28.1 go: downloading github.com/benbjohnson/litestream v0.5.14 go: downloading github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5 go: downloading github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0 go: downloading github.com/superfly/ltx v0.5.1 go: downloading golang.org/x/net v0.62.0 go: downloading modernc.org/sqlite v1.55.0 go: downloading github.com/aws/aws-sdk-go-v2/config v1.32.6 go: downloading github.com/aws/aws-sdk-go-v2/service/sns v1.43.0 go: downloading github.com/aws/aws-sdk-go-v2/service/acm v1.45.0 go: downloading github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.0 go: downloading github.com/aws/aws-sdk-go-v2/service/iam v1.58.2 go: downloading github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi v1.37.0 go: downloading github.com/aws/aws-sdk-go-v2/service/route53 v1.64.1 go: downloading golang.org/x/crypto v0.58.0 go: downloading golang.org/x/sys v0.49.0 go: downloading golang.org/x/mod v0.41.0 go: downloading github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.40 go: downloading github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.40 go: downloading github.com/pion/dtls/v3 v3.1.4 go: downloading github.com/pion/transport/v4 v4.0.2 go: downloading github.com/klauspost/compress v1.20.2 go: downloading github.com/pierrec/lz4/v4 v4.1.22 go: downloading github.com/pion/randutil v0.1.0 go: downloading golang.org/x/text v0.43.0 go: downloading github.com/wlynxg/anet v0.0.5 go: downloading github.com/prometheus/client_golang v1.17.0 go: downloading github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.18 go: downloading github.com/prometheus/common v0.45.0 go: downloading github.com/prometheus/procfs v0.12.0 go: downloading github.com/prometheus/client_model v0.5.0 go: downloading google.golang.org/protobuf v1.36.10 go: downloading github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 go: downloading github.com/klauspost/compress v1.20.2 go: downloading modernc.org/sqlite v1.55.0 go: downloading golang.org/x/crypto/x509roots/fallback v0.0.0-20260209214922-2f26647a795e go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0 go: downloading github.com/pierrec/lz4/v4 v4.1.22 go: downloading modernc.org/libc v1.74.1 go: downloading modernc.org/libc v1.74.1 go: downloading github.com/dustin/go-humanize v1.0.1 go: downloading modernc.org/memory v1.11.0 go: downloading modernc.org/mathutil v1.7.1 go: downloading github.com/google/uuid v1.6.0 go: downloading github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec amadan: job cancelled — a newer push superseded it
diff --git a/docs/superpowers/specs/2026-11-22-store-versioning-design.md b/docs/superpowers/specs/2026-11-22-store-versioning-design.md| index 49f8dfa0d..270f6503e 100644 |
| --- a/docs/superpowers/specs/2026-11-22-store-versioning-design.md |
| +++ b/docs/superpowers/specs/2026-11-22-store-versioning-design.md |
| @@ -17,7 +17,8 @@ listings don't request URL encoding, so a key containing a control |
| character breaks listing and restore) is round 1's "retained versions stay |
| recoverable" family two rounds running, so stopping rule 2 applies and the |
| choice is Paul's (options in the findings file; the recommendation is one |
| -encoded-listing helper with a guard test). The four P2s are fixed. |
| +encoded-listing helper with a guard test). The four P2s are fixed. **Paul ruled option 3 (2026-11-22)**, built for |
| +round 3: §6.6. |
| The census card for this branch is |
| `docs/superpowers/notes/census-proposal-store-versioning.md`; it needs the |
| same reviewer's verdict (AGENTS.md, "The census"). |
| @@ -344,6 +345,31 @@ does not find (`no_version`), a delete marker |
| a version over 5 GiB, `CopyObject`'s limit (`too_large`), and a store whose |
| uploads are denied for its plan (`writes_denied`). |
| +### 6.6 Every version listing goes through one helper (Paul, round 2 ruling) |
| + |
| +S3 accepts keys that XML 1.0 cannot carry (most control characters), and |
| +the SDK parses listings as XML, so a raw listing whose page reaches such a |
| +key fails. An app's credential could plant one under an ordinary key's |
| +prefix and put that key's history out of reach. So |
| +`objstore.ListObjectVersionsPage` is the only way store code lists |
| +versions: it asks for `EncodingType: url` and URL-decodes every key, key |
| +marker and prefix in the answer exactly once (`url.QueryUnescape`; the SDK |
| +does not decode). The listing, `StatVersion`'s current lookup, |
| +`EmptyVersions` and the sizing sweep all use it. |
| +`TestEveryStoreVersionListingUsesTheHelper` fails on any other |
| +`ListObjectVersions` call in `internal/objstore` or `internal/console`. |
| +`TestVersionListingSurvivesHostileKeys` runs a real SDK client against a |
| +fake S3 speaking XML, which answers raw keys unless encoding is asked for |
| +(`TestFakeS3RawListingBreaks` shows the raw listing failing). It plants |
| +`blobs/a\x01planted` beside `blobs/a`, and adds `%`, `+` and space keys |
| +that a double decode would corrupt. |
| + |
| +The same keys cannot travel in `DeleteObjects`' XML body either, so |
| +`EmptyVersions` deletes a key `xmlSafeKey` refuses on its own, with |
| +`DeleteObject` naming the version (the key is in the URL; |
| +`s3:DeleteObjectVersion`, already granted). A destroyed store's bucket |
| +cannot be left standing by one. |
| + |
| ### 6.5 Sizing |
| `sizeStore` takes the record's block into account: a store with one is |
diff --git a/internal/console/apistoreversioning_test.go b/internal/console/apistoreversioning_test.go| index 5ee4a48bb..b8a63cd5a 100644 |
| --- a/internal/console/apistoreversioning_test.go |
| +++ b/internal/console/apistoreversioning_test.go |
| @@ -404,6 +404,9 @@ type stubVersionLister struct { |
| } |
| func (s *stubVersionLister) ListObjectVersions(_ context.Context, in *awss3.ListObjectVersionsInput, _ ...func(*awss3.Options)) (*awss3.ListObjectVersionsOutput, error) { |
| + if in.EncodingType != s3types.EncodingTypeUrl { |
| + panic("the sizing sweep listed versions without URL-encoded keys (objstore.ListObjectVersionsPage)") |
| + } |
| out := s.pages[0] |
| s.pages = s.pages[1:] |
| return out, nil |
diff --git a/internal/console/economicspass.go b/internal/console/economicspass.go| index ccd31fec2..663debe3d 100644 |
| --- a/internal/console/economicspass.go |
| +++ b/internal/console/economicspass.go |
| @@ -1226,12 +1226,6 @@ func (s *Server) sizeStore(ctx context.Context, p *objstore.Provisioned, version |
| return sizeProvisionedStore(ctx, p, s.perf) |
| } |
| -// versionLister is the one call sumVersionBytes makes, so a test can stand a |
| -// stub in for S3. |
| -type versionLister interface { |
| - ListObjectVersions(ctx context.Context, in *awss3.ListObjectVersionsInput, optFns ...func(*awss3.Options)) (*awss3.ListObjectVersionsOutput, error) |
| -} |
| - |
| // sizeVersionedStore is sizeProvisionedStore for a versioned store: the sum |
| // of every version's size, current and noncurrent, from a paginated |
| // ListObjectVersions on the console's own credentials (s3:ListBucketVersions, |
| @@ -1249,11 +1243,14 @@ func sizeVersionedStore(ctx context.Context, p *objstore.Provisioned, rec *perf. |
| // sumVersionBytes sums every version's Size in bucket, following the key and |
| // version markers. A truncated page with no markers ends the walk, as |
| // sizeProvisionedStore's missing continuation token does. |
| -func sumVersionBytes(ctx context.Context, api versionLister, bucket string) (int64, error) { |
| +// |
| +// It lists through objstore.ListObjectVersionsPage, as every store version |
| +// listing must: a key XML cannot carry must not break the sweep. |
| +func sumVersionBytes(ctx context.Context, api objstore.VersionLister, bucket string) (int64, error) { |
| var total int64 |
| var keyMarker, versionMarker *string |
| for { |
| - out, err := api.ListObjectVersions(ctx, &awss3.ListObjectVersionsInput{ |
| + out, err := objstore.ListObjectVersionsPage(ctx, api, &awss3.ListObjectVersionsInput{ |
| Bucket: aws.String(bucket), |
| KeyMarker: keyMarker, |
| VersionIdMarker: versionMarker, |
diff --git a/internal/objstore/aws_versioning.go b/internal/objstore/aws_versioning.go| index 89ad13686..de63b8987 100644 |
| --- a/internal/objstore/aws_versioning.go |
| +++ b/internal/objstore/aws_versioning.go |
| @@ -27,6 +27,8 @@ import ( |
| // PutBucketLifecycleConfiguration s3:PutLifecycleConfiguration |
| // ListObjectVersions s3:ListBucketVersions |
| // DeleteObjects with VersionId s3:DeleteObjectVersion (teardown only) |
| +// DeleteObject with VersionId s3:DeleteObjectVersion (teardown, a key |
| +// XML cannot carry; see xmlSafeKey) |
| // HeadObject naming a VersionId s3:GetObjectVersion (restore's lookup) |
| // CopyObject from a version s3:GetObjectVersion + s3:PutObject |
| // |
| @@ -43,6 +45,7 @@ type s3VersionAPI interface { |
| DeleteObjects(ctx context.Context, in *awss3.DeleteObjectsInput, optFns ...func(*awss3.Options)) (*awss3.DeleteObjectsOutput, error) |
| CopyObject(ctx context.Context, in *awss3.CopyObjectInput, optFns ...func(*awss3.Options)) (*awss3.CopyObjectOutput, error) |
| HeadObject(ctx context.Context, in *awss3.HeadObjectInput, optFns ...func(*awss3.Options)) (*awss3.HeadObjectOutput, error) |
| + DeleteObject(ctx context.Context, in *awss3.DeleteObjectInput, optFns ...func(*awss3.Options)) (*awss3.DeleteObjectOutput, error) |
| } |
| var _ Versioner = (*awsProvisioner)(nil) |
| @@ -214,7 +217,7 @@ func (p *awsProvisioner) ListVersions(ctx context.Context, bucket, key, after st |
| if after != "" { |
| in.KeyMarker, in.VersionIdMarker = aws.String(key), aws.String(after) |
| } |
| - page, err := api.ListObjectVersions(ctx, in) |
| + page, err := ListObjectVersionsPage(ctx, api, in) |
| if err != nil { |
| return nil, "", fmt.Errorf("objstore: list versions of %q in %q: %w", key, bucket, err) |
| } |
| @@ -267,7 +270,7 @@ func (p *awsProvisioner) StatVersion(ctx context.Context, bucket, key, versionID |
| default: |
| return ObjectVersion{}, fmt.Errorf("objstore: head %q version %q in %q: %w", key, versionID, bucket, err) |
| } |
| - latest, err := api.ListObjectVersions(ctx, &awss3.ListObjectVersionsInput{Bucket: aws.String(bucket), Prefix: aws.String(key), MaxKeys: aws.Int32(1)}) |
| + latest, err := ListObjectVersionsPage(ctx, api, &awss3.ListObjectVersionsInput{Bucket: aws.String(bucket), Prefix: aws.String(key), MaxKeys: aws.Int32(1)}) |
| if err != nil { |
| return ObjectVersion{}, fmt.Errorf("objstore: find the current version of %q in %q: %w", key, bucket, err) |
| } |
| @@ -365,7 +368,7 @@ func (p *awsProvisioner) EmptyVersions(ctx context.Context, bucket string) error |
| if err := ctx.Err(); err != nil { |
| return err |
| } |
| - page, err := api.ListObjectVersions(ctx, &awss3.ListObjectVersionsInput{Bucket: aws.String(bucket)}) |
| + page, err := ListObjectVersionsPage(ctx, api, &awss3.ListObjectVersionsInput{Bucket: aws.String(bucket)}) |
| if err != nil { |
| if isNoSuchBucket(err) { |
| return nil |
| @@ -391,8 +394,20 @@ func (p *awsProvisioner) EmptyVersions(ctx context.Context, bucket string) error |
| } |
| } |
| -// deleteIdentifierBatches is deleteObjectBatches for version identifiers. |
| -func deleteIdentifierBatches(ctx context.Context, api s3VersionAPI, bucket string, ids []s3types.ObjectIdentifier) error { |
| +// deleteIdentifierBatches is deleteObjectBatches for version identifiers. A |
| +// key that DeleteObjects' XML body cannot carry is deleted on its own by URL |
| +// instead, so such a key can never leave a destroyed store's bucket standing. |
| +func deleteIdentifierBatches(ctx context.Context, api s3VersionAPI, bucket string, all []s3types.ObjectIdentifier) error { |
| + ids := all[:0:0] |
| + for _, id := range all { |
| + if xmlSafeKey(aws.ToString(id.Key)) { |
| + ids = append(ids, id) |
| + continue |
| + } |
| + if err := deleteVersionByURL(ctx, api, bucket, id); err != nil { |
| + return err |
| + } |
| + } |
| const batchSize = 1000 |
| for start := 0; start < len(ids); start += batchSize { |
| end := min(start+batchSize, len(ids)) |
diff --git a/internal/objstore/aws_versioning_test.go b/internal/objstore/aws_versioning_test.go| index b95ba25ef..c58d71a09 100644 |
| --- a/internal/objstore/aws_versioning_test.go |
| +++ b/internal/objstore/aws_versioning_test.go |
| @@ -30,6 +30,7 @@ type stubS3V struct { |
| deleteObjects func(*awss3.DeleteObjectsInput) (*awss3.DeleteObjectsOutput, error) |
| copyObject func(*awss3.CopyObjectInput) (*awss3.CopyObjectOutput, error) |
| headObject func(*awss3.HeadObjectInput) (*awss3.HeadObjectOutput, error) |
| + deleteObject func(*awss3.DeleteObjectInput) (*awss3.DeleteObjectOutput, error) |
| } |
| func stubCall[I, O any](s *stubS3V, name string, hook func(I) (O, error), in I) (O, error) { |
| @@ -61,6 +62,9 @@ func (s *stubS3V) DeleteObjects(_ context.Context, in *awss3.DeleteObjectsInput, |
| func (s *stubS3V) HeadObject(_ context.Context, in *awss3.HeadObjectInput, _ ...func(*awss3.Options)) (*awss3.HeadObjectOutput, error) { |
| return stubCall(s, "HeadObject", s.headObject, in) |
| } |
| +func (s *stubS3V) DeleteObject(_ context.Context, in *awss3.DeleteObjectInput, _ ...func(*awss3.Options)) (*awss3.DeleteObjectOutput, error) { |
| + return stubCall(s, "DeleteObject", s.deleteObject, in) |
| +} |
| func (s *stubS3V) CopyObject(_ context.Context, in *awss3.CopyObjectInput, _ ...func(*awss3.Options)) (*awss3.CopyObjectOutput, error) { |
| return stubCall(s, "CopyObject", s.copyObject, in) |
| } |
diff --git a/internal/objstore/versionlist.go b/internal/objstore/versionlist.go| new file mode 100644 |
| index 000000000..4d0474425 |
| --- /dev/null |
| +++ b/internal/objstore/versionlist.go |
| @@ -0,0 +1,111 @@ |
| +package objstore |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/url" |
| + "unicode/utf8" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + s3types "github.com/aws/aws-sdk-go-v2/service/s3/types" |
| +) |
| + |
| +// VersionLister is the one S3 call ListObjectVersionsPage makes. |
| +type VersionLister interface { |
| + ListObjectVersions(ctx context.Context, in *awss3.ListObjectVersionsInput, optFns ...func(*awss3.Options)) (*awss3.ListObjectVersionsOutput, error) |
| +} |
| + |
| +// ListObjectVersionsPage is the ONLY way the store code lists a store |
| +// bucket's versions (store versioning spec §6.4; Paul's ruling on Astra |
| +// round 2's P1, 2026-11-22). TestEveryStoreVersionListingUsesTheHelper fails |
| +// on any other ListObjectVersions call in internal/objstore or |
| +// internal/console. |
| +// |
| +// The invariant: a key S3 accepts never breaks a listing. S3 keys may hold |
| +// characters an XML 1.0 document cannot carry (most control characters), |
| +// and the SDK decodes the response as XML, so a raw listing of a bucket |
| +// holding one fails to parse. That is not only the odd key's problem: any |
| +// listing whose page reaches such a key fails, so an app's credential could |
| +// plant one under an ordinary key's prefix and take that key's history out |
| +// of reach. So every listing asks S3 for URL-encoded keys (EncodingType |
| +// url), and every key and key marker in the answer is decoded here exactly |
| +// once, before any caller compares or reuses it. The SDK does not decode |
| +// them itself. Version ids are never encoded. |
| +// |
| +// A backend that ignores the request and answers raw keys (no EncodingType |
| +// in the answer) is taken as raw. A key that does not decode is an error, |
| +// never a guess. |
| +func ListObjectVersionsPage(ctx context.Context, api VersionLister, in *awss3.ListObjectVersionsInput) (*awss3.ListObjectVersionsOutput, error) { |
| + req := *in |
| + req.EncodingType = s3types.EncodingTypeUrl |
| + out, err := api.ListObjectVersions(ctx, &req) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if out.EncodingType != s3types.EncodingTypeUrl { |
| + return out, nil |
| + } |
| + dec := func(p *string) error { |
| + if p == nil { |
| + return nil |
| + } |
| + v, err := url.QueryUnescape(*p) |
| + if err != nil { |
| + return fmt.Errorf("objstore: version listing: key %q is not URL-encoded: %w", *p, err) |
| + } |
| + *p = v |
| + return nil |
| + } |
| + for _, p := range []*string{out.Prefix, out.KeyMarker, out.NextKeyMarker, out.Delimiter} { |
| + if err := dec(p); err != nil { |
| + return nil, err |
| + } |
| + } |
| + for i := range out.Versions { |
| + if err := dec(out.Versions[i].Key); err != nil { |
| + return nil, err |
| + } |
| + } |
| + for i := range out.DeleteMarkers { |
| + if err := dec(out.DeleteMarkers[i].Key); err != nil { |
| + return nil, err |
| + } |
| + } |
| + for i := range out.CommonPrefixes { |
| + if err := dec(out.CommonPrefixes[i].Prefix); err != nil { |
| + return nil, err |
| + } |
| + } |
| + return out, nil |
| +} |
| + |
| +// xmlSafeKey reports whether key can travel in an XML 1.0 request body |
| +// unchanged: valid UTF-8 of XML Chars, with no carriage return (an XML |
| +// parser normalises it to a newline). DeleteObjects carries keys in its XML |
| +// body, so a key that fails this is deleted on its own, by URL, instead. |
| +func xmlSafeKey(key string) bool { |
| + if !utf8.ValidString(key) { |
| + return false |
| + } |
| + for _, r := range key { |
| + switch { |
| + case r == '\t' || r == '\n': |
| + case r < 0x20 || r == 0xFFFE || r == 0xFFFF || (r >= 0xD800 && r <= 0xDFFF): |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// deleteVersionByURL deletes one version of one key with DeleteObject, whose |
| +// key travels in the request path, for a key xmlSafeKey refuses. |
| +func deleteVersionByURL(ctx context.Context, api s3VersionAPI, bucket string, id s3types.ObjectIdentifier) error { |
| + if _, err := api.DeleteObject(ctx, &awss3.DeleteObjectInput{Bucket: aws.String(bucket), Key: id.Key, VersionId: id.VersionId}); err != nil { |
| + if isNoSuchBucket(err) { |
| + return nil |
| + } |
| + return fmt.Errorf("objstore: delete %q version %s in %q: %w", aws.ToString(id.Key), aws.ToString(id.VersionId), bucket, err) |
| + } |
| + return nil |
| +} |
diff --git a/internal/objstore/versionlist_test.go b/internal/objstore/versionlist_test.go| new file mode 100644 |
| index 000000000..f20a82a7f |
| --- /dev/null |
| +++ b/internal/objstore/versionlist_test.go |
| @@ -0,0 +1,353 @@ |
| +package objstore |
| + |
| +import ( |
| + "context" |
| + "encoding/xml" |
| + "fmt" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "os" |
| + "path/filepath" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/credentials" |
| + awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| +) |
| + |
| +// Paul's ruling on Astra round 2's P1 (2026-11-22): every store version |
| +// listing goes through ListObjectVersionsPage, which asks for URL-encoded |
| +// keys and decodes them once. These tests hold that against a real SDK |
| +// client talking XML to a fake S3, because a typed stub never meets the XML |
| +// decoder that a control-character key breaks. |
| + |
| +// fakeVersion is one version or delete marker in the fake bucket. |
| +type fakeVersion struct { |
| + key, id string |
| + size int |
| + marker bool |
| + at time.Time |
| +} |
| + |
| +// fakeS3 is just enough of S3's REST API for the versioning calls: |
| +// ListObjectVersions (raw keys unless encoding-type=url is asked for, as S3 |
| +// does), HeadObject naming a version, CopyObject, DeleteObjects and |
| +// DeleteObject naming a version. |
| +type fakeS3 struct { |
| + mu sync.Mutex |
| + t *testing.T |
| + versions []fakeVersion |
| + next int |
| + sawRaw bool // a listing asked for raw keys |
| +} |
| + |
| +func (f *fakeS3) sorted() []fakeVersion { |
| + vs := append([]fakeVersion(nil), f.versions...) |
| + sort.SliceStable(vs, func(i, j int) bool { |
| + if vs[i].key != vs[j].key { |
| + return vs[i].key < vs[j].key |
| + } |
| + return vs[i].at.After(vs[j].at) |
| + }) |
| + return vs |
| +} |
| + |
| +func (f *fakeS3) latest(key string) string { |
| + for _, v := range f.sorted() { |
| + if v.key == key { |
| + return v.id |
| + } |
| + } |
| + return "" |
| +} |
| + |
| +func (f *fakeS3) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + q := r.URL.Query() |
| + path := strings.TrimPrefix(r.URL.Path, "/b") |
| + key := strings.TrimPrefix(path, "/") |
| + switch { |
| + case r.Method == http.MethodGet && q.Has("versions"): |
| + f.list(w, q) |
| + case r.Method == http.MethodHead: |
| + for _, v := range f.versions { |
| + if v.key == key && v.id == q.Get("versionId") { |
| + if v.marker { |
| + w.WriteHeader(http.StatusMethodNotAllowed) |
| + return |
| + } |
| + w.Header().Set("Content-Length", strconv.Itoa(v.size)) |
| + w.Header().Set("Last-Modified", v.at.UTC().Format(http.TimeFormat)) |
| + return |
| + } |
| + } |
| + w.WriteHeader(http.StatusNotFound) |
| + case r.Method == http.MethodPut && r.Header.Get("X-Amz-Copy-Source") != "": |
| + src, _ := url.PathUnescape(strings.SplitN(r.Header.Get("X-Amz-Copy-Source"), "?", 2)[0]) |
| + if src != "b/"+key { |
| + f.t.Errorf("copy source %q for key %q", src, key) |
| + } |
| + f.next++ |
| + id := fmt.Sprintf("r%d", f.next) |
| + f.versions = append(f.versions, fakeVersion{key: key, id: id, size: 1, at: time.Date(2026, 11, 23, 0, 0, f.next, 0, time.UTC)}) |
| + w.Header().Set("x-amz-version-id", id) |
| + fmt.Fprint(w, `<CopyObjectResult><ETag>"e"</ETag></CopyObjectResult>`) |
| + case r.Method == http.MethodPost && q.Has("delete"): |
| + var body struct { |
| + Objects []struct{ Key, VersionId string } `xml:"Object"` |
| + } |
| + if err := xml.NewDecoder(r.Body).Decode(&body); err != nil { |
| + f.t.Errorf("DeleteObjects body: %v", err) |
| + } |
| + for _, o := range body.Objects { |
| + if !xmlSafeKey(o.Key) { |
| + f.t.Errorf("DeleteObjects carried a key XML cannot hold: %q", o.Key) |
| + } |
| + f.remove(o.Key, o.VersionId) |
| + } |
| + fmt.Fprint(w, `<DeleteResult></DeleteResult>`) |
| + case r.Method == http.MethodDelete: |
| + f.remove(key, q.Get("versionId")) |
| + w.WriteHeader(http.StatusNoContent) |
| + default: |
| + f.t.Errorf("unexpected request %s %s", r.Method, r.URL) |
| + w.WriteHeader(http.StatusNotImplemented) |
| + } |
| +} |
| + |
| +func (f *fakeS3) remove(key, id string) { |
| + out := f.versions[:0] |
| + for _, v := range f.versions { |
| + if v.key != key || v.id != id { |
| + out = append(out, v) |
| + } |
| + } |
| + f.versions = out |
| +} |
| + |
| +// list answers ListObjectVersions. Without encoding-type=url it writes keys |
| +// raw, exactly as S3 would: a control character lands in the XML as is. |
| +func (f *fakeS3) list(w http.ResponseWriter, q url.Values) { |
| + encoded := q.Get("encoding-type") == "url" |
| + if !encoded { |
| + f.sawRaw = true |
| + } |
| + enc := func(s string) string { |
| + if encoded { |
| + return url.QueryEscape(s) |
| + } |
| + return s |
| + } |
| + max := 1000 |
| + if n, err := strconv.Atoi(q.Get("max-keys")); err == nil { |
| + max = n |
| + } |
| + prefix, km, vm := q.Get("prefix"), q.Get("key-marker"), q.Get("version-id-marker") |
| + var page []fakeVersion |
| + started := km == "" |
| + truncated := false |
| + for _, v := range f.sorted() { |
| + if !strings.HasPrefix(v.key, prefix) { |
| + continue |
| + } |
| + if !started { |
| + if v.key == km && v.id == vm { |
| + started = true |
| + } |
| + continue |
| + } |
| + if len(page) == max { |
| + truncated = true |
| + break |
| + } |
| + page = append(page, v) |
| + } |
| + var b strings.Builder |
| + b.WriteString(`<?xml version="1.0" encoding="UTF-8"?><ListVersionsResult>`) |
| + if encoded { |
| + b.WriteString(`<EncodingType>url</EncodingType>`) |
| + } |
| + fmt.Fprintf(&b, `<Prefix>%s</Prefix><IsTruncated>%v</IsTruncated>`, enc(prefix), truncated) |
| + if truncated && len(page) > 0 { |
| + last := page[len(page)-1] |
| + fmt.Fprintf(&b, `<NextKeyMarker>%s</NextKeyMarker><NextVersionIdMarker>%s</NextVersionIdMarker>`, enc(last.key), last.id) |
| + } |
| + for _, v := range page { |
| + latest := f.latest(v.key) == v.id |
| + at := v.at.UTC().Format("2006-01-02T15:04:05.000Z") |
| + if v.marker { |
| + fmt.Fprintf(&b, `<DeleteMarker><Key>%s</Key><VersionId>%s</VersionId><IsLatest>%v</IsLatest><LastModified>%s</LastModified></DeleteMarker>`, enc(v.key), v.id, latest, at) |
| + } else { |
| + fmt.Fprintf(&b, `<Version><Key>%s</Key><VersionId>%s</VersionId><IsLatest>%v</IsLatest><LastModified>%s</LastModified><Size>%d</Size></Version>`, enc(v.key), v.id, latest, at, v.size) |
| + } |
| + } |
| + b.WriteString(`</ListVersionsResult>`) |
| + w.Header().Set("Content-Type", "application/xml") |
| + fmt.Fprint(w, b.String()) |
| +} |
| + |
| +// The bucket: an ordinary key with two versions, a key planted under its |
| +// prefix that holds a control character, and keys with literal % escapes |
| +// and + signs that a double decode or a plus-as-space slip would corrupt. |
| +const plantedKey = "blobs/a\x01planted" |
| + |
| +func newFakeS3(t *testing.T) (*fakeS3, *awsProvisioner) { |
| + t.Helper() |
| + at := func(s int) time.Time { return time.Date(2026, 11, 22, 10, 0, s, 0, time.UTC) } |
| + f := &fakeS3{t: t, versions: []fakeVersion{ |
| + {key: "blobs/a", id: "a1", size: 4, at: at(1)}, |
| + {key: "blobs/a", id: "a2", size: 7, at: at(2)}, |
| + {key: plantedKey, id: "p1", size: 1, at: at(3)}, |
| + {key: "blobs/a%2Fb+c d", id: "e1", size: 2, at: at(4)}, |
| + {key: "blobs/z\x7f\x02", id: "z1", size: 3, at: at(5)}, |
| + {key: "blobs/z\x7f\x02", id: "z2", marker: true, at: at(6)}, |
| + }} |
| + ts := httptest.NewServer(f) |
| + t.Cleanup(ts.Close) |
| + client := awss3.New(awss3.Options{ |
| + Region: "us-east-1", |
| + Credentials: credentials.NewStaticCredentialsProvider("k", "s", ""), |
| + BaseEndpoint: aws.String(ts.URL), |
| + UsePathStyle: true, |
| + RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired, |
| + ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired, |
| + }) |
| + return f, &awsProvisioner{s3v: client} |
| +} |
| + |
| +// The fixture is realistic: a raw listing of this bucket fails to parse, |
| +// which is the failure the helper exists to prevent. |
| +func TestFakeS3RawListingBreaks(t *testing.T) { |
| + _, p := newFakeS3(t) |
| + _, err := p.s3v.ListObjectVersions(context.Background(), &awss3.ListObjectVersionsInput{Bucket: aws.String("b"), Prefix: aws.String("blobs/a")}) |
| + if err == nil { |
| + t.Fatal("a raw listing holding a control-character key parsed; the fixture proves nothing") |
| + } |
| +} |
| + |
| +// Listing and restoring an ordinary key work with a control-character key |
| +// planted under its prefix, and the odd keys themselves list exactly. |
| +func TestVersionListingSurvivesHostileKeys(t *testing.T) { |
| + ctx := context.Background() |
| + f, p := newFakeS3(t) |
| + ids := func(vs []ObjectVersion) string { |
| + var out []string |
| + for _, v := range vs { |
| + out = append(out, fmt.Sprintf("%s:%v:%v", v.VersionID, v.Current, v.DeleteMarker)) |
| + } |
| + return strings.Join(out, " ") |
| + } |
| + for key, want := range map[string]string{ |
| + "blobs/a": "a2:true:false a1:false:false", |
| + plantedKey: "p1:true:false", |
| + "blobs/a%2Fb+c d": "e1:true:false", |
| + "blobs/z\x7f\x02": "z2:true:true z1:false:false", |
| + } { |
| + got, _, err := p.ListVersions(ctx, "b", key, "", 0) |
| + if err != nil || ids(got) != want { |
| + t.Errorf("ListVersions(%q) = %s, %v; want %s", key, ids(got), err, want) |
| + } |
| + } |
| + // Paging past the planted key: one version per page. |
| + page, next, err := p.ListVersions(ctx, "b", "blobs/a", "", 1) |
| + if err != nil || ids(page) != "a2:true:false" || next != "a2" { |
| + t.Fatalf("first page = %s next %q, %v", ids(page), next, err) |
| + } |
| + page, next, err = p.ListVersions(ctx, "b", "blobs/a", next, 1) |
| + if err != nil || ids(page) != "a1:false:false" { |
| + t.Fatalf("second page = %s next %q, %v", ids(page), next, err) |
| + } |
| + // Restore of the ordinary key: the lookup's one-entry listing shares the |
| + // prefix with the planted key. |
| + v, err := p.StatVersion(ctx, "b", "blobs/a", "a1") |
| + if err != nil || v.Current || v.Size != 4 { |
| + t.Fatalf("StatVersion = %+v, %v", v, err) |
| + } |
| + if id, err := p.RestoreVersion(ctx, "b", "blobs/a", "a1"); err != nil || id == "" { |
| + t.Fatalf("RestoreVersion = %q, %v", id, err) |
| + } |
| + if v, err := p.StatVersion(ctx, "b", plantedKey, "p1"); err != nil || !v.Current { |
| + t.Fatalf("StatVersion(planted) = %+v, %v", v, err) |
| + } |
| + if f.sawRaw { |
| + t.Fatal("a listing asked for raw keys") |
| + } |
| +} |
| + |
| +// Teardown empties a bucket holding keys XML cannot carry: those go by URL, |
| +// the rest in a DeleteObjects batch. |
| +func TestEmptyVersionsDeletesHostileKeys(t *testing.T) { |
| + f, p := newFakeS3(t) |
| + if err := p.EmptyVersions(context.Background(), "b"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(f.versions) != 0 { |
| + t.Fatalf("left behind: %+v", f.versions) |
| + } |
| + if f.sawRaw { |
| + t.Fatal("a listing asked for raw keys") |
| + } |
| +} |
| + |
| +func TestXMLSafeKey(t *testing.T) { |
| + for k, want := range map[string]bool{"a/b c": true, "tab\tnl\n": true, "é": true, "\x01": false, "cr\r": false, "\x7f": true, string([]byte{0xff}): false} { |
| + if xmlSafeKey(k) != want { |
| + t.Errorf("xmlSafeKey(%q) = %v", k, !want) |
| + } |
| + } |
| +} |
| + |
| +// The guard: in the store code (internal/objstore, internal/console), the |
| +// only ListObjectVersions call outside tests is the one inside |
| +// ListObjectVersionsPage. internal/release lists the deployment bucket's |
| +// own versions and is not store code. |
| +func TestEveryStoreVersionListingUsesTheHelper(t *testing.T) { |
| + for _, dir := range []string{".", "../console"} { |
| + files, err := filepath.Glob(filepath.Join(dir, "*.go")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, file := range files { |
| + if strings.HasSuffix(file, "_test.go") { |
| + continue |
| + } |
| + src, err := os.ReadFile(file) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fset := token.NewFileSet() |
| + f, err := parser.ParseFile(fset, file, src, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, decl := range f.Decls { |
| + fn, ok := decl.(*ast.FuncDecl) |
| + if !ok || fn.Body == nil { |
| + continue |
| + } |
| + ast.Inspect(fn.Body, func(n ast.Node) bool { |
| + call, ok := n.(*ast.CallExpr) |
| + if !ok { |
| + return true |
| + } |
| + sel, ok := call.Fun.(*ast.SelectorExpr) |
| + if ok && sel.Sel.Name == "ListObjectVersions" && !(filepath.Base(file) == "versionlist.go" && fn.Name.Name == "ListObjectVersionsPage") { |
| + t.Errorf("%s: %s calls ListObjectVersions directly; list store versions through objstore.ListObjectVersionsPage", |
| + fset.Position(call.Pos()), fn.Name.Name) |
| + } |
| + return true |
| + }) |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/provision/testdata/plan14-root-reads-store-versioning.tsv b/internal/provision/testdata/plan14-root-reads-store-versioning.tsv| index 3aa6a6edd..7cf627169 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-store-versioning.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-store-versioning.tsv |
| @@ -10,5 +10,5 @@ infra/modules/region-host/tests/store_versioning.tftest.hcl external legacy acce |
| @coverage . 3a570159813e793927d3552ab984427b47db451cd0b01b5b2558567e18a8c5ad |
| @coverage infra/modules/region-host 81f0a154b0279fb272590524fe9a152900cdd198b9b6428269698ac229c9ddcf |
| @coverage infra/modules/region-host/tests 3d56c7f90b54be1e5f670bea1f9695ae302907e5a19ac11739b88877527503c1 |
| -@coverage internal/objstore c3d46e94f8c374ea5d0a8622ef21680b8c1199b34d04c9de7ca1de110a81f446 |
| +@coverage internal/objstore f31b80faefea63d8c266265f051e4d972c2d911513bd8194c6efb7bdb5c419ca |
| @coverage internal/provision 4e93b34904bd4dc5e46074651f89c9028a0a15783ba4809a74d93d1d72a674ab |