From 927880bdfd9fa825ee4ce26ab82ddb22d754b5f0 Mon Sep 17 00:00:00 2001 From: Graham Savage Date: Wed, 25 Nov 2026 10:15:35 +0000 Subject: [PATCH] =?UTF-8?q?Revert=20"feat(snapshot=20s3):=20add=20--allow-?= =?UTF-8?q?empty-bucket=20to=20report=20an=20empty=20bucket=E2=80=A6"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 7cff44f3588331c218d78bb7936e08d13b50c269. --- cmd/kosli/root.go | 1 - cmd/kosli/snapshotS3.go | 21 ------- cmd/kosli/snapshotS3Harvest_test.go | 61 ------------------- cmd/kosli/snapshotS3_test.go | 32 ---------- .../testdata/empty-flag-audit-coverage.json | 1 - internal/aws/aws.go | 15 ----- internal/aws/aws_test.go | 35 ----------- internal/aws/s3_metadata_test.go | 1 - 8 files changed, 167 deletions(-) delete mode 100644 cmd/kosli/snapshotS3Harvest_test.go diff --git a/cmd/kosli/root.go b/cmd/kosli/root.go index 5577fc1d8..ca38dcda8 100644 --- a/cmd/kosli/root.go +++ b/cmd/kosli/root.go @@ -308,7 +308,6 @@ Paths the list already matches stay excluded whatever is later added there, so k downloadBudgetFlag = "[optional] The maximum total size of the S3 objects downloading at the same time, which caps the temporary disk the snapshot uses. A bare number is megabytes; add K, M, G or T (optionally followed by B) to choose the unit, e.g. 512M or 8G. An object larger than the budget still downloads, on its own. Objects are downloaded to the OS temporary directory. Has no effect with --fingerprint-source metadata, which reads stored checksums and uses no temporary disk." s3FingerprintSourceFlag = "[defaulted] Where each object's SHA256 comes from when fingerprinting the bucket. Valid sources are: [" + validS3FingerprintSources + "]. 'content' downloads every contributing object and hashes it. 'metadata' reads the SHA256 checksum S3 stores for each object instead, which skips the download but requires every contributing object to have been uploaded with a full-object SHA256 checksum, unless --skip-unusable-checksums is set. Both produce the same fingerprint and need the same permissions." s3SkipUnusableChecksumsFlag = "[optional] With --fingerprint-source metadata, leave out every object whose SHA256 checksum is missing, multipart (composite) or undecodable instead of failing the snapshot. The skipped objects are named in a warning. The fingerprint then covers the remaining objects only, so it does not match an artifact attested from the full bucket content. When no object is left, an empty snapshot is reported, so the environment shows the bucket as holding no artifact." - s3AllowEmptyBucketFlag = "[optional] Report a bucket that holds no objects as an empty snapshot, with a warning, instead of failing the snapshot. The environment then shows the bucket as holding no artifact. Does not apply when an include or exclude filter leaves no object, which still fails." bucketPathsFlag = "[optional] The comma separated list of file and/or directory paths in the S3 bucket to include when fingerprinting. Paths match by literal prefix. Cannot be used together with --exclude or --exclude-regex." bucketPathsRegexFlag = "[optional] The comma separated list of Go regular expressions matched against object keys in the S3 bucket to include when fingerprinting. Cannot be used together with --exclude or --exclude-regex." excludeBucketPathsFlag = "[optional] The comma separated list of file and/or directory paths in the S3 bucket to exclude when fingerprinting. Paths match by literal prefix. Cannot be used together with --include or --include-regex." diff --git a/cmd/kosli/snapshotS3.go b/cmd/kosli/snapshotS3.go index 0cf66dcf9..b484b6ded 100644 --- a/cmd/kosli/snapshotS3.go +++ b/cmd/kosli/snapshotS3.go @@ -1,7 +1,6 @@ package main import ( - "errors" "fmt" "io" @@ -14,7 +13,6 @@ const snapshotS3ShortDesc = `Report a snapshot of the content of an AWS S3 bucke const snapshotS3LongDesc = snapshotS3ShortDesc + awsAuthDesc + ` You can report the entire bucket content, or filter some of the content using ^--include^ / ^--exclude^ (literal prefix match) or ^--include-regex^ / ^--exclude-regex^ (Go regular expressions matched against the full object key). In all cases, the content is reported as one artifact. If you wish to report separate files/dirs within the same bucket as separate artifacts, you need to run the command twice. -A bucket that holds no objects fails the snapshot. With ^--allow-empty-bucket^ it is reported as an empty snapshot instead, with a warning, so the environment shows the bucket as holding no artifact. The flag does not apply when an include or exclude filter leaves no object: that still fails, since the filter is the likelier cause. Object keys are never used as local file names: by default each object is downloaded to a temporary file, hashed and removed, and the fingerprint is computed from the keys and the content digests, so any key S3 accepts can be fingerprinted on any operating system. Keys that cannot form a directory tree are rejected and fail the snapshot, naming every key involved: a key containing a ^..^ segment, two keys that resolve to the same path (such as ^a//b^ and ^a/b^), or an object whose key is also a prefix of other objects (such as ^a^ beside ^a/b^). A legitimate key of that shape can be left out with ^--exclude-regex^ (anchor and escape it, since the pattern is a regular expression matched against the whole key); when ^--include^ or ^--include-regex^ is set, exclude filters are ignored, so narrow the include filter instead. @@ -91,13 +89,6 @@ kosli snapshot s3 yourEnvironmentName \ --skip-unusable-checksums \ --api-token yourAPIToken \ --org yourOrgName - -# report an AWS S3 bucket that may hold no objects, as an empty snapshot when it does: -kosli snapshot s3 yourEnvironmentName \ - --bucket yourBucketName \ - --allow-empty-bucket \ - --api-token yourAPIToken \ - --org yourOrgName ` const ( @@ -113,7 +104,6 @@ type snapshotS3Options struct { excludeRegex []string fingerprintSource string skipUnusable bool - allowEmptyBucket bool downloadConcurrency int downloadBudget string downloadLimits aws.DownloadLimits @@ -173,7 +163,6 @@ func newSnapshotS3Cmd(out io.Writer) *cobra.Command { cmd.Flags().StringSliceVar(&o.excludeRegex, "exclude-regex", []string{}, excludeBucketPathsRegexFlag) cmd.Flags().StringVar(&o.fingerprintSource, "fingerprint-source", fingerprintSourceContent, s3FingerprintSourceFlag) cmd.Flags().BoolVar(&o.skipUnusable, "skip-unusable-checksums", false, s3SkipUnusableChecksumsFlag) - cmd.Flags().BoolVar(&o.allowEmptyBucket, "allow-empty-bucket", false, s3AllowEmptyBucketFlag) cmd.Flags().IntVar(&o.downloadConcurrency, "download-concurrency", aws.DefaultDownloadLimits.Concurrency, downloadConcurrencyFlag) cmd.Flags().StringVar(&o.downloadBudget, "download-budget", defaultDownloadBudget, downloadBudgetFlag) addAWSAuthFlags(cmd, o.awsStaticCreds) @@ -200,16 +189,6 @@ func (o *snapshotS3Options) run(args []string) error { } func (o *snapshotS3Options) harvest() ([]*aws.S3Data, error) { - s3Data, err := o.harvestObjects() - var empty aws.EmptyBucketError - if o.allowEmptyBucket && errors.As(err, &empty) { - logger.Warn("bucket [%s] holds no objects; reporting an empty snapshot", o.bucket) - return []*aws.S3Data{}, nil - } - return s3Data, err -} - -func (o *snapshotS3Options) harvestObjects() ([]*aws.S3Data, error) { if o.fingerprintSource == fingerprintSourceMetadata { return o.awsStaticCreds.GetS3DataFromMetadata(o.bucket, o.includePaths, o.includeRegex, o.excludePaths, o.excludeRegex, o.downloadLimits, o.skipUnusable, logger) diff --git a/cmd/kosli/snapshotS3Harvest_test.go b/cmd/kosli/snapshotS3Harvest_test.go deleted file mode 100644 index affce6543..000000000 --- a/cmd/kosli/snapshotS3Harvest_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package main - -import ( - "testing" - - "github.com/kosli-dev/cli/internal/aws" - "github.com/stretchr/testify/require" -) - -const harvestTestBucket = "harvest-test-bucket" - -func harvestFrom(t *testing.T, objects map[string][]byte, o *snapshotS3Options) ([]*aws.S3Data, error) { - t.Helper() - aws.NewS3ClientFunc = func(_ *aws.AWSStaticCreds) (aws.S3API, error) { - return &aws.FakeS3Client{Bucket: harvestTestBucket, Objects: objects}, nil - } - t.Cleanup(aws.ResetS3ClientFactory) - o.bucket = harvestTestBucket - o.awsStaticCreds = new(aws.AWSStaticCreds) - o.downloadLimits = aws.DefaultDownloadLimits - return o.harvest() -} - -func TestAllowEmptyBucketReportsAnEmptyBucketAsAnEmptySnapshot(t *testing.T) { - for _, source := range []string{fingerprintSourceContent, fingerprintSourceMetadata} { - t.Run(source, func(t *testing.T) { - data, err := harvestFrom(t, map[string][]byte{"dir/": nil}, - &snapshotS3Options{fingerprintSource: source, allowEmptyBucket: true}) - - require.NoError(t, err) - require.Empty(t, data) - require.NotNil(t, data, "the payload must carry an empty list, not null") - }) - } -} - -func TestAnEmptyBucketFailsWithoutAllowEmptyBucket(t *testing.T) { - for _, source := range []string{fingerprintSourceContent, fingerprintSourceMetadata} { - t.Run(source, func(t *testing.T) { - _, err := harvestFrom(t, map[string][]byte{}, &snapshotS3Options{fingerprintSource: source}) - - require.EqualError(t, err, "no matching file or dirs in bucket: ["+harvestTestBucket+"]") - }) - } -} - -// The flag is about the bucket, not the filters: a filter that leaves nothing -// is more likely mistyped than the bucket is empty. -func TestAllowEmptyBucketDoesNotExcuseAFilterThatMatchesNothing(t *testing.T) { - _, err := harvestFrom(t, map[string][]byte{"README.md": []byte("# readme\n")}, - &snapshotS3Options{fingerprintSource: fingerprintSourceContent, allowEmptyBucket: true, includePaths: []string{"non-existing.md"}}) - - require.EqualError(t, err, "no matching file or dirs in bucket: ["+harvestTestBucket+"]") -} - -func TestAllowEmptyBucketLeavesOtherFailuresAlone(t *testing.T) { - _, err := harvestFrom(t, map[string][]byte{"README.md": []byte("# readme\n")}, - &snapshotS3Options{fingerprintSource: fingerprintSourceMetadata, allowEmptyBucket: true}) - - require.ErrorContains(t, err, "object key [README.md] has no SHA256 checksum") -} diff --git a/cmd/kosli/snapshotS3_test.go b/cmd/kosli/snapshotS3_test.go index 466f39d42..3250fa7c6 100644 --- a/cmd/kosli/snapshotS3_test.go +++ b/cmd/kosli/snapshotS3_test.go @@ -198,38 +198,6 @@ func (suite *SnapshotS3TestSuite) TestSnapshotS3Cmd() { } } -func (suite *SnapshotS3TestSuite) TestSnapshotS3CmdOnAnEmptyBucket() { - bucketName := suite.bucketName - aws.NewS3ClientFunc = func(_ *aws.AWSStaticCreds) (aws.S3API, error) { - return &aws.FakeS3Client{Bucket: bucketName, Objects: map[string][]byte{}}, nil - } - - tests := []cmdTestCase{ - { - wantError: true, - name: "snapshot s3 fails on an empty bucket", - cmd: fmt.Sprintf(`snapshot s3 %s %s --bucket %s`, suite.envName, suite.defaultKosliArguments, suite.bucketName), - golden: "Error: no matching file or dirs in bucket: [kosli-cli-public]\n", - }, - { - name: "--allow-empty-bucket reports an empty bucket as an empty snapshot", - cmd: fmt.Sprintf(`snapshot s3 %s %s --bucket %s --allow-empty-bucket`, suite.envName, suite.defaultKosliArguments, suite.bucketName), - golden: "[warning] bucket [kosli-cli-public] holds no objects; reporting an empty snapshot\n" + - "bucket kosli-cli-public was reported to environment snapshot-s3-env\n", - }, - { - name: "--allow-empty-bucket works with --fingerprint-source metadata", - cmd: fmt.Sprintf(`snapshot s3 %s %s --bucket %s --fingerprint-source metadata --skip-unusable-checksums --allow-empty-bucket`, suite.envName, suite.defaultKosliArguments, suite.bucketName), - golden: "[warning] bucket [kosli-cli-public] holds no objects; reporting an empty snapshot\n" + - "bucket kosli-cli-public was reported to environment snapshot-s3-env\n", - }, - } - - for _, t := range tests { - runTestCmd(suite.T(), []cmdTestCase{t}) - } -} - // In order for 'go test' to run this suite, we need to create // a normal test function and pass our suite to suite.Run func TestSnapshotS3TestSuite(t *testing.T) { diff --git a/cmd/kosli/testdata/empty-flag-audit-coverage.json b/cmd/kosli/testdata/empty-flag-audit-coverage.json index 958254e81..ed285fc82 100644 --- a/cmd/kosli/testdata/empty-flag-audit-coverage.json +++ b/cmd/kosli/testdata/empty-flag-audit-coverage.json @@ -998,7 +998,6 @@ "watch": "bool" }, "snapshot s3": { - "allow-empty-bucket": "bool", "aws-key-id": "string", "aws-region": "string", "aws-secret-key": "string", diff --git a/internal/aws/aws.go b/internal/aws/aws.go index e4b008614..1a11e6f40 100644 --- a/internal/aws/aws.go +++ b/internal/aws/aws.go @@ -504,10 +504,6 @@ func getS3DataWithSource(client S3API, source s3DigestSource, bucket string, inc return s3Data, err } if len(objects) == 0 { - filtersSet := len(includePaths)+len(includeRegex)+len(excludePaths)+len(excludeRegex) > 0 - if !filtersSet { - return s3Data, EmptyBucketError{Bucket: bucket} - } return s3Data, fmt.Errorf("no matching file or dirs in bucket: [%s]", bucket) } @@ -537,17 +533,6 @@ func getS3DataWithSource(client S3API, source s3DigestSource, bucket string, inc return s3Data, nil } -// EmptyBucketError is returned when a bucket lists no objects and no include -// or exclude filter is set, so a caller can tell an empty bucket from a filter -// that matched nothing. Its message is the one both cases have always had. -type EmptyBucketError struct { - Bucket string -} - -func (e EmptyBucketError) Error() string { - return fmt.Sprintf("no matching file or dirs in bucket: [%s]", e.Bucket) -} - // newestS3Modification returns the latest modification time among objects, or // the zero time when none reported one. func newestS3Modification(objects []s3Object) time.Time { diff --git a/internal/aws/aws_test.go b/internal/aws/aws_test.go index 2f33ba715..e31ca0d22 100644 --- a/internal/aws/aws_test.go +++ b/internal/aws/aws_test.go @@ -3,7 +3,6 @@ package aws import ( "bytes" "context" - "errors" "fmt" "io" "regexp" @@ -1239,40 +1238,6 @@ func (suite *AWSTestSuite) TestGetS3DataFromClient() { } } -// Only a bucket that lists nothing with no filter set is an EmptyBucketError, -// which is what --allow-empty-bucket turns into an empty snapshot. -func (suite *AWSTestSuite) TestGetS3DataFromClientTellsAnEmptyBucketFromAFilterThatMatchesNothing() { - readme := map[string][]byte{"README.md": []byte(fakeReadmeBody)} - for _, t := range []struct { - name string - objects map[string][]byte - includePaths []string - includeRegex []string - excludePaths []string - excludeRegex []string - wantEmpty bool - }{ - {name: "no objects at all", objects: map[string][]byte{}, wantEmpty: true}, - {name: "only folder markers", objects: map[string][]byte{"dummy/": nil, "dummy/dummy_2/": nil}, wantEmpty: true}, - {name: "--include matches nothing", objects: readme, includePaths: []string{"non-existing.md"}}, - {name: "--include-regex matches nothing", objects: readme, includeRegex: []string{`.*\.yml$`}}, - {name: "--exclude removes everything", objects: readme, excludePaths: []string{"README.md"}}, - {name: "--exclude-regex removes everything", objects: readme, excludeRegex: []string{`.*\.md$`}}, - {name: "an empty bucket with a filter set", objects: map[string][]byte{}, includePaths: []string{"README.md"}}, - } { - suite.Run(t.name, func() { - client := &FakeS3Client{Bucket: fakeS3TestBucketName, Objects: t.objects} - - _, err := getS3DataFromClient(client, fakeS3TestBucketName, t.includePaths, t.includeRegex, - t.excludePaths, t.excludeRegex, DefaultDownloadLimits, logger.NewStandardLogger()) - - require.EqualError(suite.T(), err, "no matching file or dirs in bucket: ["+fakeS3TestBucketName+"]") - var empty EmptyBucketError - require.Equal(suite.T(), t.wantEmpty, errors.As(err, &empty)) - }) - } -} - // TestGetS3DataFromClientFilterEquivalence asserts that filtering a bucket down // to a subset produces the same fingerprint as a bucket that only ever held // that subset. This pins down what the filters select without hardcoding diff --git a/internal/aws/s3_metadata_test.go b/internal/aws/s3_metadata_test.go index dc30308af..7c36826ad 100644 --- a/internal/aws/s3_metadata_test.go +++ b/internal/aws/s3_metadata_test.go @@ -539,7 +539,6 @@ func (suite *S3MetadataTestSuite) TestSkippingUnusableStillFailsOnOtherErrors() suite.Run("a bucket with no objects", func() { _, _, err := snapshotSkippingUnusable(suite.T(), &FakeS3Client{Bucket: fakeS3TestBucketName, Objects: map[string][]byte{"dir/": nil}}) require.ErrorContains(suite.T(), err, "no matching file or dirs in bucket") - require.ErrorAs(suite.T(), err, &EmptyBucketError{}, "the metadata source reports an empty bucket as the content source does") }) }