diff --git a/cmd/kosli/root.go b/cmd/kosli/root.go index ca38dcda8..6ed2e1392 100644 --- a/cmd/kosli/root.go +++ b/cmd/kosli/root.go @@ -307,7 +307,7 @@ Paths the list already matches stay excluded whatever is later added there, so k downloadConcurrencyFlag = "[optional] The number of S3 objects to fetch at the same time when fingerprinting the bucket. When downloading, the default, each object in flight may hold up to 40 MB of download buffers in memory, on top of the disk the --download-budget allows. With --fingerprint-source metadata it bounds the checksum reads instead, which hold neither, and defaults to 32." 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." + 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, the bucket is reported as an empty bucket, with the fingerprint of an empty directory." 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 b484b6ded..605ed0c07 100644 --- a/cmd/kosli/snapshotS3.go +++ b/cmd/kosli/snapshotS3.go @@ -12,14 +12,16 @@ 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. +In all cases, the content is reported as one artifact, named after the bucket. If you wish to report separate files/dirs within the same bucket as separate artifacts, you need to run the command twice. +The fingerprint is the one ^kosli fingerprint^ gives for a local copy of the reported content: ^--artifact-type file^ when a single object is reported, ^--artifact-type dir^ otherwise. +A bucket with nothing to report is not an error. Whether it holds no objects or the filters leave none, it is still reported as one artifact named after the bucket, with the fingerprint of an empty directory (^e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855^) and a timestamp of 0. When filters are what left nothing, a warning is logged, since a mistyped filter has the same effect. 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. By default each object's SHA256 comes from downloading the object and hashing it. ^--fingerprint-source metadata^ reads the SHA256 checksum S3 stores for the object instead, which skips the download, the temporary disk and the hashing. Everything else, like the keys, the ^.kosli_ignore^ rules, the way digests combine into the fingerprint, is the same in both modes, so the fingerprint is identical and a snapshot matches the artifact you attested either way. Two conditions apply: - Every contributing object must carry a full-object SHA256 checksum. S3 only stores one when the upload asked for it, for example ^aws s3api put-object --checksum-algorithm SHA256^. Objects without one fail the snapshot, all named in one run. - A multipart upload gets a composite SHA256, which hashes the checksums of the parts rather than the object content, so it cannot serve as the object's fingerprint. Such an object can be collapsed into a single part in place with ^aws s3api copy-object --checksum-algorithm SHA256 --copy-source yourBucket/yourKey --bucket yourBucket --key yourKey^. -^--skip-unusable-checksums^ relaxes both conditions: an object whose SHA256 checksum is missing, composite or undecodable is left out with a warning that names it, and the snapshot is reported from the remaining objects, as if the bucket did not hold the skipped ones. Such a snapshot has a different fingerprint from an artifact attested from the full bucket content, so it does not match that artifact in Kosli until every object carries a usable checksum. When no object is left, an empty snapshot is reported, so the environment shows the bucket as holding no artifact. +^--skip-unusable-checksums^ relaxes both conditions: an object whose SHA256 checksum is missing, composite or undecodable is left out with a warning that names it, and the snapshot is reported from the remaining objects, as if the bucket did not hold the skipped ones. Such a snapshot has a different fingerprint from an artifact attested from the full bucket content, so it does not match that artifact in Kosli until every object carries a usable checksum. When no object is left, the bucket is reported as an empty bucket. A root ^.kosli_ignore^ is still downloaded in this mode, because its rules decide which objects contribute; the objects it excludes are never fetched and need no checksum. Reading a checksum does not need fewer permissions than downloading: AWS requires ^s3:GetObject^ for both, and an SSE-KMS encrypted object additionally needs ^kms:GenerateDataKey^ and ^kms:Decrypt^ either way. ` + kosliIgnoreDescNoExclude diff --git a/cmd/kosli/snapshotS3_test.go b/cmd/kosli/snapshotS3_test.go index 3250fa7c6..b36665f0d 100644 --- a/cmd/kosli/snapshotS3_test.go +++ b/cmd/kosli/snapshotS3_test.go @@ -112,10 +112,16 @@ func (suite *SnapshotS3TestSuite) TestSnapshotS3Cmd() { golden: "bucket kosli-cli-public was reported to environment snapshot-s3-env\n", }, { - wantError: true, - name: "fails when --include does not match any file or dir", - cmd: fmt.Sprintf(`snapshot s3 %s %s --bucket %s --include non-existing.md`, suite.envName, suite.defaultKosliArguments, suite.bucketName), - golden: "Error: no matching file or dirs in bucket: [kosli-cli-public]\n", + name: "reports an empty bucket, with a warning, when --include does not match any file or dir", + cmd: fmt.Sprintf(`snapshot s3 %s %s --bucket %s --include non-existing.md`, suite.envName, suite.defaultKosliArguments, suite.bucketName), + golden: "[warning] no object in bucket [kosli-cli-public] matches the include and exclude filters (or the bucket is empty); reporting it as an empty bucket\n" + + "bucket kosli-cli-public was reported to environment snapshot-s3-env\n", + }, + { + name: "reports an empty bucket, with a warning, when --exclude-regex removes every file", + cmd: fmt.Sprintf(`snapshot s3 %s %s --bucket %s --exclude-regex '.*'`, suite.envName, suite.defaultKosliArguments, suite.bucketName), + golden: "[warning] no object in bucket [kosli-cli-public] matches the include and exclude filters (or the bucket is empty); reporting it as an empty bucket\n" + + "bucket kosli-cli-public was reported to environment snapshot-s3-env\n", }, { name: "can snapshot entire bucket except a subset of files/dirs using --exclude", @@ -179,10 +185,10 @@ func (suite *SnapshotS3TestSuite) TestSnapshotS3Cmd() { "bucket kosli-cli-public was reported to environment snapshot-s3-env\n", }, { - name: "--skip-unusable-checksums reports an empty snapshot when no object has a stored checksum", + name: "--skip-unusable-checksums reports an empty bucket when no object has a stored checksum", cmd: fmt.Sprintf(`snapshot s3 %s %s --bucket %s --include dummy --fingerprint-source metadata --skip-unusable-checksums`, suite.envName, suite.defaultKosliArguments, suite.bucketName), golden: "[warning] skipped 1 of the 1 objects whose checksum was read in bucket [kosli-cli-public]; they have no usable SHA256 checksum, so the fingerprint does not cover them:\n[dummy/dummy_2/template.yml]\n" + - "[warning] no object in bucket [kosli-cli-public] is left to fingerprint; reporting an empty snapshot\n" + + "[warning] no object in bucket [kosli-cli-public] is left to fingerprint; reporting it as an empty bucket\n" + "bucket kosli-cli-public was reported to environment snapshot-s3-env\n", }, { @@ -198,6 +204,34 @@ func (suite *SnapshotS3TestSuite) TestSnapshotS3Cmd() { } } +// Also confirms the server accepts the empty-directory fingerprint and the +// zero timestamp an empty bucket is reported with. +func (suite *SnapshotS3TestSuite) TestSnapshotS3CmdOnAnEmptyBucket() { + bucketName := suite.bucketName + aws.NewS3ClientFunc = func(_ *aws.AWSStaticCreds) (aws.S3API, error) { + return &aws.FakeS3Client{Bucket: bucketName, Objects: map[string][]byte{"dummy/": nil}}, nil + } + + tests := []cmdTestCase{ + { + name: "snapshot s3 reports an empty bucket", + cmd: fmt.Sprintf(`snapshot s3 %s %s --bucket %s`, suite.envName, suite.defaultKosliArguments, suite.bucketName), + golden: "bucket [kosli-cli-public] holds no objects; reporting it as an empty bucket\n" + + "bucket kosli-cli-public was reported to environment snapshot-s3-env\n", + }, + { + name: "snapshot s3 reports an empty bucket with --fingerprint-source metadata", + cmd: fmt.Sprintf(`snapshot s3 %s %s --bucket %s --fingerprint-source metadata`, suite.envName, suite.defaultKosliArguments, suite.bucketName), + golden: "bucket [kosli-cli-public] holds no objects; reporting it as an empty bucket\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/docs/adr/20260911-s3-fingerprint-from-virtual-tree.md b/docs/adr/20260911-s3-fingerprint-from-virtual-tree.md index 5487d1b0a..64c1ce5ab 100644 --- a/docs/adr/20260911-s3-fingerprint-from-virtual-tree.md +++ b/docs/adr/20260911-s3-fingerprint-from-virtual-tree.md @@ -39,13 +39,21 @@ The fingerprint format itself is fixed. An S3 snapshot must match the fingerprin 5. **Downloads may run in parallel**, behind a fixed worker pool and a bytes-in-flight budget derived from listing sizes, with results written by index for determinism and a cancellable context so the first transport error stops in-flight multipart downloads. This is a performance property, not a safety one, and was delivered separately from the change this record describes; see #1167. The defaults are eight objects in flight within 512 MB of listed bytes, tunable with `--download-concurrency` and `--download-budget`, so peak temp disk is the budget rather than one object. -6. **The switch is pinned, not argued.** `TestPinnedFingerprints` in `internal/aws` holds fingerprints of representative fake buckets recorded against the key-layout implementation before it was replaced: unusual key shapes, a `.` sorting before a `/`, nested prefixes with folder markers, and a single object with its basename as artifact name. It was green before the switch and must stay green after it, alongside `TestGetS3DataFromClientKeepsTodaysLayoutForUnusualKeys` from #1155. +6. **The switch is pinned, not argued.** `TestPinnedFingerprints` in `internal/aws` holds fingerprints of representative fake buckets recorded against the key-layout implementation before it was replaced: unusual key shapes, a `.` sorting before a `/`, nested prefixes with folder markers, and a single object with its basename as artifact name (named after the bucket since the 2026-11-25 amendment under Guarantees). It was green before the switch and must stay green after it, alongside `TestGetS3DataFromClientKeepsTodaysLayoutForUnusualKeys` from #1155. ## Guarantees +> **Amended 2026-11-25.** The artifact name and the empty case described in this record have since +> changed; the fingerprint calculation has not. An S3 snapshot now always reports exactly one +> artifact, named after the bucket, including when a single object is reported (previously named +> after the object). A bucket with nothing to fingerprint, because it holds no objects or because +> the filters or skipped checksums leave none, is reported with the fingerprint of an empty +> directory and a timestamp of 0 instead of failing. So "keeps its fingerprint and artifact name" +> below now holds for the fingerprint only in the single-object case. + The attest side is unchanged: `kosli attest artifact --artifact-type dir` still runs `DirSha256` on a real directory, and that defines the format. The snapshot side re-derives the same value from the bucket. Three guarantees follow, each with the test that holds it: -- **Snapshot equals attestation.** `VirtualDirSha256` of the bucket's `(path, sha256)` pairs equals `DirSha256` of the directory those objects were uploaded from, and a single object equals `FileSha256` plus its basename. Held by the materialise-then-compare tests in `internal/digest` (`TestVirtualDirTestSuite`, `TestVirtualIgnoreTestSuite`) and by `TestMatchesAttestedDirectory` in `internal/aws`, which hashes a directory, uploads its files to the fake bucket and snapshots it. +- **Snapshot equals attestation.** `VirtualDirSha256` of the bucket's `(path, sha256)` pairs equals `DirSha256` of the directory those objects were uploaded from, and a single object equals `FileSha256` of that object (its artifact name was its basename, and is the bucket name since the amendment above). Held by the materialise-then-compare tests in `internal/digest` (`TestVirtualDirTestSuite`, `TestVirtualIgnoreTestSuite`) and by `TestMatchesAttestedDirectory` in `internal/aws`, which hashes a directory, uploads its files to the fake bucket and snapshots it. - **Snapshot equals its own history.** Every bucket that snapshotted successfully under the key-layout implementation keeps its fingerprint and artifact name, because the fold rule is what `filepath.Join` did. Held by `TestPinnedFingerprints` and `TestGetS3DataFromClientKeepsTodaysLayoutForUnusualKeys`. - **No object is lost silently.** Every key S3 accepts is representable, whatever the operating system, because the key never becomes a path. Rejections are of two kinds, and each fails the snapshot rather than shorten the manifest. Keys that cannot form a directory tree at all: a `..` segment, two keys folding onto one path, and an object that is also a prefix. S3 permits those, no filesystem does, so no attested directory could match them, and the error names every key involved. And listings the store returned malformed: an entry with no key, a key listed more than once, and no modification time on any matching object. Real S3 produces none of these; an S3-compatible store might, and each is an error rather than a guess. A path deeper than `globSeparatorsLimit` segments is also rejected, which no S3 key can reach, so the exported digest functions carry the bound for other callers. Held by `TestEveryS3KeyIsRepresentable`, which generates keys over S3's full character set, and `TestDownloadsExactlyTheContributingObjects`, which asserts the downloaded set equals the listed objects minus markers and exclusions. diff --git a/internal/aws/aws.go b/internal/aws/aws.go index 1a11e6f40..0db626f05 100644 --- a/internal/aws/aws.go +++ b/internal/aws/aws.go @@ -504,7 +504,14 @@ func getS3DataWithSource(client S3API, source s3DigestSource, bucket string, inc return s3Data, err } if len(objects) == 0 { - return s3Data, fmt.Errorf("no matching file or dirs in bucket: [%s]", bucket) + // A filter that leaves nothing may be mistyped, so that case is a warning. + filtersSet := len(includePaths)+len(includeRegex)+len(excludePaths)+len(excludeRegex) > 0 + if filtersSet { + logger.Warn("no object in bucket [%s] matches the include and exclude filters (or the bucket is empty); reporting it as an empty bucket", bucket) + } else { + logger.Info("bucket [%s] holds no objects; reporting it as an empty bucket", bucket) + } + return emptyS3Bucket(bucket, logger) } newest := newestS3Modification(objects) @@ -519,8 +526,8 @@ func getS3DataWithSource(client S3API, source s3DigestSource, bucket string, inc if len(fingerprint.skipped) > 0 { logger.Warn("%s", skippedS3ObjectsWarning(bucket, fingerprint)) if len(fingerprint.fingerprinted) == 0 { - logger.Warn("no object in bucket [%s] is left to fingerprint; reporting an empty snapshot", bucket) - return s3Data, nil + logger.Warn("no object in bucket [%s] is left to fingerprint; reporting it as an empty bucket", bucket) + return emptyS3Bucket(bucket, logger) } newest = newestS3Modification(fingerprint.fingerprinted) if newest.IsZero() { @@ -528,11 +535,23 @@ func getS3DataWithSource(client S3API, source s3DigestSource, bucket string, inc } } - s3Data = append(s3Data, &S3Data{Digests: map[string]string{fingerprint.artifactName: fingerprint.sha256}, LastModifiedTimestamp: newest.Unix()}) + s3Data = append(s3Data, &S3Data{Digests: map[string]string{bucket: fingerprint.sha256}, LastModifiedTimestamp: newest.Unix()}) return s3Data, nil } +// emptyS3Bucket is what a bucket with nothing to fingerprint is reported as: +// still the one artifact of the snapshot, fingerprinted as an empty directory. +// No object supplies a modification time, so the timestamp is zero, which also +// keeps successive snapshots of an empty bucket identical. +func emptyS3Bucket(bucket string, logger *logger.Logger) ([]*S3Data, error) { + sha256, err := digest.VirtualDirSha256(nil, nil, logger) + if err != nil { + return []*S3Data{}, err + } + return []*S3Data{{Digests: map[string]string{bucket: sha256}, LastModifiedTimestamp: 0}}, nil +} + // newestS3Modification returns the latest modification time among objects, or // the zero time when none reported one. func newestS3Modification(objects []s3Object) time.Time { @@ -641,9 +660,8 @@ type s3DigestSource struct { // s3Fingerprint is the outcome of fingerprinting a bucket's objects. type s3Fingerprint struct { - // artifactName and sha256 are empty when no object was fingerprinted. - artifactName string - sha256 string + // sha256 is empty when no object was fingerprinted. + sha256 string // fingerprinted holds the objects the fingerprint was computed over, in // listing order. fingerprinted []s3Object @@ -664,16 +682,15 @@ func downloadDigests(downloader S3DownloadAPI, bucket string, logger *logger.Log } // fingerprintS3Objects fingerprints the objects with the download source. -func fingerprintS3Objects(downloader S3DownloadAPI, bucket string, objects []s3Object, limits DownloadLimits, logger *logger.Logger) (string, string, error) { +func fingerprintS3Objects(downloader S3DownloadAPI, bucket string, objects []s3Object, limits DownloadLimits, logger *logger.Logger) (string, error) { fingerprint, err := fingerprintS3Tree(downloader, downloadDigests(downloader, bucket, logger), bucket, objects, limits, logger) - return fingerprint.artifactName, fingerprint.sha256, err + return fingerprint.sha256, err } // fingerprintS3Tree fingerprints the objects as the directory their keys // describe, without using a key as a local file name: digest.VirtualDirSha256 // combines the (key, sha256) pairs from source exactly as digest.DirSha256 -// would on disk. A single object is fingerprinted as that file and named -// after it. +// would on disk. A single object is fingerprinted as that file. // // The root .kosli_ignore is always downloaded, whatever the source, because its // rules decide which other objects are fetched at all. @@ -706,8 +723,8 @@ func fingerprintS3Tree(downloader S3DownloadAPI, source s3DigestSource, bucket s files[i].Path = paths[object.key] } - // One object is fingerprinted as that file and named after it, as it was - // when the objects were laid out on disk. + // One object is fingerprinted as that file, as it was when the objects were + // laid out on disk. if file, ok := digest.SingleVirtualFile(files); ok { fetch := source // The ignore file is downloaded even when alone, so no source needs its checksum. @@ -723,7 +740,7 @@ func fingerprintS3Tree(downloader S3DownloadAPI, source s3DigestSource, bucket s if err != nil { return s3Fingerprint{}, err } - return s3Fingerprint{artifactName: file.Name(), sha256: sha256, fingerprinted: objects, read: 1}, nil + return s3Fingerprint{sha256: sha256, fingerprinted: objects, read: 1}, nil } var rules []string @@ -786,14 +803,14 @@ func fingerprintS3Tree(downloader S3DownloadAPI, source s3DigestSource, bucket s return fingerprint, nil } if file, ok := digest.SingleVirtualFile(files); ok { - fingerprint.artifactName, fingerprint.sha256 = file.Name(), file.Sha256 + fingerprint.sha256 = file.Sha256 return fingerprint, nil } sha256, err := digest.VirtualDirSha256(files, rules, logger) if err != nil { return s3Fingerprint{}, ignoreRuleError(err) } - fingerprint.artifactName, fingerprint.sha256 = bucket, sha256 + fingerprint.sha256 = sha256 return fingerprint, nil } diff --git a/internal/aws/aws_test.go b/internal/aws/aws_test.go index e31ca0d22..fcc2632ba 100644 --- a/internal/aws/aws_test.go +++ b/internal/aws/aws_test.go @@ -384,15 +384,14 @@ func (suite *AWSTestSuite) TestGetLambdaPackageData() { // wiring works. func (suite *AWSTestSuite) TestGetS3Data() { for _, t := range []struct { - name string - requireEnvVars bool // indicates that a test case needs real credentials from env vars - creds *AWSStaticCreds - bucketName string - includePaths []string - excludePaths []string - wantFingerprint string - wantArtifactName string - wantErr bool + name string + requireEnvVars bool // indicates that a test case needs real credentials from env vars + creds *AWSStaticCreds + bucketName string + includePaths []string + excludePaths []string + wantFingerprint string + wantErr bool }{ { name: "invalid credentials causes an error", @@ -426,11 +425,10 @@ func (suite *AWSTestSuite) TestGetS3Data() { creds: &AWSStaticCreds{ Region: "eu-central-1", }, - bucketName: "kosli-cli-public", - includePaths: []string{"README.md"}, - requireEnvVars: true, - wantFingerprint: "77b1b4df1eb620e05ce365e9e84d37a7e04fde8a66251c121773d013dfba0ee6", - wantArtifactName: "README.md", + bucketName: "kosli-cli-public", + includePaths: []string{"README.md"}, + requireEnvVars: true, + wantFingerprint: "77b1b4df1eb620e05ce365e9e84d37a7e04fde8a66251c121773d013dfba0ee6", }, } { suite.Run(t.name, func() { @@ -439,13 +437,10 @@ func (suite *AWSTestSuite) TestGetS3Data() { require.False(suite.T(), (err != nil) != t.wantErr, "GetS3Data() error = %v, wantErr %v", err, t.wantErr) if !t.wantErr { - if t.wantArtifactName == "" { - t.wantArtifactName = t.bucketName - } if t.wantFingerprint == "" { - require.Contains(suite.T(), data[0].Digests, t.wantArtifactName) + require.Contains(suite.T(), data[0].Digests, t.bucketName) } else { - require.Equal(suite.T(), t.wantFingerprint, data[0].Digests[t.wantArtifactName]) + require.Equal(suite.T(), t.wantFingerprint, data[0].Digests[t.bucketName]) } } }) @@ -1011,27 +1006,24 @@ func (suite *AWSTestSuite) TestGetS3DataFromClient() { excludeRegex []string listErr error downloadErr error - wantArtifactName string // defaults to the bucket name wantFingerprint string // only asserted when set wantLastModified int64 // only asserted when non-zero wantErr bool wantErrMsg string }{ { - name: "a single object is fingerprinted as a file and named after it", + name: "a single object is fingerprinted as a file and named after the bucket", objects: map[string][]byte{ "README.md": []byte(fakeReadmeBody), }, - wantArtifactName: "README.md", - wantFingerprint: fakeReadmeSha256, + wantFingerprint: fakeReadmeSha256, }, { name: "a single nested object is still fingerprinted as a file", objects: map[string][]byte{ "dummy/dummy_2/template.yml": []byte(fakeTemplateBody), }, - wantArtifactName: "template.yml", - wantFingerprint: fakeTemplateSha256, + wantFingerprint: fakeTemplateSha256, }, { name: "multiple objects are fingerprinted as a directory named after the bucket", @@ -1048,8 +1040,7 @@ func (suite *AWSTestSuite) TestGetS3DataFromClient() { "dummy/dummy_2/": nil, "dummy/README.md": []byte(fakeReadmeBody), }, - wantArtifactName: "README.md", - wantFingerprint: fakeReadmeSha256, + wantFingerprint: fakeReadmeSha256, }, { name: "objects spread over several pages are all downloaded", @@ -1066,9 +1057,8 @@ func (suite *AWSTestSuite) TestGetS3DataFromClient() { "README.md": []byte(fakeReadmeBody), "notes.txt": []byte(fakeNotesBody), }, - includePaths: []string{"README.md"}, - wantArtifactName: "README.md", - wantFingerprint: fakeReadmeSha256, + includePaths: []string{"README.md"}, + wantFingerprint: fakeReadmeSha256, }, { name: "includePaths matches a nested path by prefix", @@ -1076,9 +1066,8 @@ func (suite *AWSTestSuite) TestGetS3DataFromClient() { "README.md": []byte(fakeReadmeBody), "dummy/dummy_2/template.yml": []byte(fakeTemplateBody), }, - includePaths: []string{"dummy/dummy_2"}, - wantArtifactName: "template.yml", - wantFingerprint: fakeTemplateSha256, + includePaths: []string{"dummy/dummy_2"}, + wantFingerprint: fakeTemplateSha256, }, { name: "a leading slash in includePaths is ignored", @@ -1086,9 +1075,8 @@ func (suite *AWSTestSuite) TestGetS3DataFromClient() { "README.md": []byte(fakeReadmeBody), "dummy/dummy_2/template.yml": []byte(fakeTemplateBody), }, - includePaths: []string{"/dummy/dummy_2"}, - wantArtifactName: "template.yml", - wantFingerprint: fakeTemplateSha256, + includePaths: []string{"/dummy/dummy_2"}, + wantFingerprint: fakeTemplateSha256, }, { name: "includeRegex selects matching objects", @@ -1096,9 +1084,8 @@ func (suite *AWSTestSuite) TestGetS3DataFromClient() { "README.md": []byte(fakeReadmeBody), "notes.txt": []byte(fakeNotesBody), }, - includeRegex: []string{`.*\.md$`}, - wantArtifactName: "README.md", - wantFingerprint: fakeReadmeSha256, + includeRegex: []string{`.*\.md$`}, + wantFingerprint: fakeReadmeSha256, }, { name: "excludePaths removes matching objects", @@ -1106,9 +1093,8 @@ func (suite *AWSTestSuite) TestGetS3DataFromClient() { "README.md": []byte(fakeReadmeBody), "notes.txt": []byte(fakeNotesBody), }, - excludePaths: []string{"notes.txt"}, - wantArtifactName: "README.md", - wantFingerprint: fakeReadmeSha256, + excludePaths: []string{"notes.txt"}, + wantFingerprint: fakeReadmeSha256, }, { name: "excludeRegex removes matching objects", @@ -1116,9 +1102,8 @@ func (suite *AWSTestSuite) TestGetS3DataFromClient() { "README.md": []byte(fakeReadmeBody), "notes.txt": []byte(fakeNotesBody), }, - excludeRegex: []string{`.*\.txt$`}, - wantArtifactName: "README.md", - wantFingerprint: fakeReadmeSha256, + excludeRegex: []string{`.*\.txt$`}, + wantFingerprint: fakeReadmeSha256, }, { name: "the reported timestamp is the newest matched object", @@ -1147,23 +1132,6 @@ func (suite *AWSTestSuite) TestGetS3DataFromClient() { excludePaths: []string{"skip.txt"}, wantLastModified: later.Unix(), }, - { - name: "an empty bucket is an error", - objects: map[string][]byte{ - "dummy/": nil, - }, - wantErr: true, - wantErrMsg: "no matching file or dirs in bucket: [" + fakeS3TestBucketName + "]", - }, - { - name: "filtering everything out is an error", - objects: map[string][]byte{ - "README.md": []byte(fakeReadmeBody), - }, - includePaths: []string{"non-existing.md"}, - wantErr: true, - wantErrMsg: "no matching file or dirs in bucket: [" + fakeS3TestBucketName + "]", - }, { name: "an invalid include regex is an error", objects: map[string][]byte{ @@ -1222,14 +1190,11 @@ func (suite *AWSTestSuite) TestGetS3DataFromClient() { require.NoError(suite.T(), err) require.Len(suite.T(), data, 1) - wantArtifactName := t.wantArtifactName - if wantArtifactName == "" { - wantArtifactName = fakeS3TestBucketName - } - require.Contains(suite.T(), data[0].Digests, wantArtifactName) - require.NotEmpty(suite.T(), data[0].Digests[wantArtifactName]) + require.Len(suite.T(), data[0].Digests, 1, "the bucket is the only artifact") + require.Contains(suite.T(), data[0].Digests, fakeS3TestBucketName) + require.NotEmpty(suite.T(), data[0].Digests[fakeS3TestBucketName]) if t.wantFingerprint != "" { - require.Equal(suite.T(), t.wantFingerprint, data[0].Digests[wantArtifactName]) + require.Equal(suite.T(), t.wantFingerprint, data[0].Digests[fakeS3TestBucketName]) } if t.wantLastModified != 0 { require.Equal(suite.T(), t.wantLastModified, data[0].LastModifiedTimestamp) @@ -1238,6 +1203,56 @@ func (suite *AWSTestSuite) TestGetS3DataFromClient() { } } +// fakeEmptyBucketSha256 is the fingerprint of an empty directory, which a +// bucket with nothing to fingerprint is reported with. +const fakeEmptyBucketSha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + +// A bucket with nothing to fingerprint is still the one artifact of the +// snapshot, whether it lists no objects or the filters leave none. Only the +// log line tells the two apart, since a filter that leaves nothing may be +// mistyped. +func (suite *AWSTestSuite) TestGetS3DataFromClientReportsNothingToFingerprintAsAnEmptyBucket() { + readme := map[string][]byte{"README.md": []byte(fakeReadmeBody)} + const ( + emptyBucketLog = "bucket [" + fakeS3TestBucketName + "] holds no objects; reporting it as an empty bucket\n" + filteredLog = "[warning] no object in bucket [" + fakeS3TestBucketName + "] matches the include and exclude filters (or the bucket is empty); reporting it as an empty bucket\n" + ) + for _, t := range []struct { + name string + objects map[string][]byte + includePaths []string + includeRegex []string + excludePaths []string + excludeRegex []string + wantInfo string + wantWarning string + }{ + {name: "no objects at all", objects: map[string][]byte{}, wantInfo: emptyBucketLog}, + {name: "only folder markers", objects: map[string][]byte{"dummy/": nil, "dummy/dummy_2/": nil}, wantInfo: emptyBucketLog}, + {name: "--include matches nothing", objects: readme, includePaths: []string{"non-existing.md"}, wantWarning: filteredLog}, + {name: "--include-regex matches nothing", objects: readme, includeRegex: []string{`.*\.yml$`}, wantWarning: filteredLog}, + {name: "--exclude removes everything", objects: readme, excludePaths: []string{"README.md"}, wantWarning: filteredLog}, + {name: "--exclude-regex removes everything", objects: readme, excludeRegex: []string{`.*\.md$`}, wantWarning: filteredLog}, + {name: "an empty bucket with a filter set", objects: map[string][]byte{}, includePaths: []string{"README.md"}, wantWarning: filteredLog}, + } { + suite.Run(t.name, func() { + client := &FakeS3Client{Bucket: fakeS3TestBucketName, Objects: t.objects} + var info, warnings bytes.Buffer + + data, err := getS3DataFromClient(client, fakeS3TestBucketName, t.includePaths, t.includeRegex, + t.excludePaths, t.excludeRegex, DefaultDownloadLimits, logger.NewLogger(&info, &warnings, false)) + + require.NoError(suite.T(), err) + require.Equal(suite.T(), []*S3Data{{ + Digests: map[string]string{fakeS3TestBucketName: fakeEmptyBucketSha256}, + LastModifiedTimestamp: 0, + }}, data) + require.Equal(suite.T(), t.wantInfo, info.String()) + require.Equal(suite.T(), t.wantWarning, warnings.String()) + }) + } +} + // 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_fingerprint_test.go b/internal/aws/s3_fingerprint_test.go index d05066cf8..545684a2e 100644 --- a/internal/aws/s3_fingerprint_test.go +++ b/internal/aws/s3_fingerprint_test.go @@ -75,45 +75,40 @@ func snapshotFake(t *testing.T, client S3API) (artifactName, fingerprint string) // every existing environment snapshot on the server was computed this way. func (suite *S3FingerprintTestSuite) TestPinnedFingerprints() { for _, t := range []struct { - name string - objects map[string][]byte - wantArtifactName string - wantFingerprint string + name string + objects map[string][]byte + wantFingerprint string }{ { name: "unusual key shapes fold as filepath.Join folded them", objects: map[string][]byte{ "/lead.txt": []byte("u\n"), "a//b": []byte("o\n"), "./c.txt": []byte("t\n"), `d\e.txt`: []byte("n\n"), }, - wantArtifactName: fakeS3TestBucketName, - wantFingerprint: "27e2d8aa07677b7818b8cf101b45c928aa8fbf7d17a8c8efc84469e24a106ec3", + wantFingerprint: "27e2d8aa07677b7818b8cf101b45c928aa8fbf7d17a8c8efc84469e24a106ec3", }, { name: "a dot sorts before a slash", objects: map[string][]byte{ "a.txt": []byte("1"), "a/z": []byte("2"), "a/b/c": []byte("3"), "b": []byte("4"), }, - wantArtifactName: fakeS3TestBucketName, - wantFingerprint: "aaddb8f3e299e12316d42fa9ac36d4ed7d38c34e7ec002239269c86a033bb9fd", + wantFingerprint: "aaddb8f3e299e12316d42fa9ac36d4ed7d38c34e7ec002239269c86a033bb9fd", }, { name: "nested prefixes with folder markers", objects: map[string][]byte{ "dir/": nil, "dir/sub/": nil, "dir/sub/x.yml": []byte("x"), "dir/y.txt": []byte("y"), "README.md": []byte("r"), }, - wantArtifactName: fakeS3TestBucketName, - wantFingerprint: "c26910cdb177dde3c6493d18ba1e916b04715cdfc535e4552b5f9831590e933a", + wantFingerprint: "c26910cdb177dde3c6493d18ba1e916b04715cdfc535e4552b5f9831590e933a", }, { - name: "a single object is the file, named by its base name", - objects: map[string][]byte{"only/one/file.bin": []byte("solo")}, - wantArtifactName: "file.bin", - wantFingerprint: "5364f2f2fc4f54e9d47ad29cfb08ef430c8153394bf2a0dff5cbe77a0ffef861", + name: "a single object is fingerprinted as the file, named after the bucket", + objects: map[string][]byte{"only/one/file.bin": []byte("solo")}, + wantFingerprint: "5364f2f2fc4f54e9d47ad29cfb08ef430c8153394bf2a0dff5cbe77a0ffef861", }, } { suite.Run(t.name, func() { name, sha := snapshotFake(suite.T(), &FakeS3Client{Bucket: fakeS3TestBucketName, Objects: t.objects}) - require.Equal(suite.T(), t.wantArtifactName, name) + require.Equal(suite.T(), fakeS3TestBucketName, name) require.Equal(suite.T(), t.wantFingerprint, sha) }) } @@ -154,7 +149,7 @@ func (suite *S3FingerprintTestSuite) TestMatchesAttestedDirectory() { name, sha := snapshotFake(suite.T(), &FakeS3Client{Bucket: fakeS3TestBucketName, Objects: map[string][]byte{"builds/v1/release.bin": []byte("the release")}}) - require.Equal(suite.T(), "release.bin", name) + require.Equal(suite.T(), fakeS3TestBucketName, name) require.Equal(suite.T(), attestedFile, sha) }) } diff --git a/internal/aws/s3_metadata.go b/internal/aws/s3_metadata.go index f2e53cfdb..e386f8457 100644 --- a/internal/aws/s3_metadata.go +++ b/internal/aws/s3_metadata.go @@ -19,8 +19,8 @@ import ( // Reading one needs s3:GetObject, the same permission as a download. // // With skipUnusableChecksums, an object without such a checksum is left out -// with a warning instead of failing the snapshot, and the result is empty when -// that leaves no object. +// with a warning instead of failing the snapshot, and the bucket is reported +// as empty when that leaves no object. func (staticCreds *AWSStaticCreds) GetS3DataFromMetadata(bucket string, includePaths, includeRegex, excludePaths, excludeRegex []string, limits DownloadLimits, skipUnusableChecksums bool, logger *logger.Logger) ([]*S3Data, error) { client, err := NewS3ClientFunc(staticCreds) if err != nil { diff --git a/internal/aws/s3_metadata_test.go b/internal/aws/s3_metadata_test.go index 7c36826ad..9eecf982a 100644 --- a/internal/aws/s3_metadata_test.go +++ b/internal/aws/s3_metadata_test.go @@ -95,6 +95,8 @@ func (suite *S3MetadataTestSuite) TestMatchesContentMode() { objects: map[string][]byte{"README.md": []byte("r"), "filtered/out.txt": []byte("o"), "keep/in.txt": []byte("i")}, excludePaths: []string{"filtered/"}, }, + {name: "an empty bucket", objects: map[string][]byte{"dir/": nil}}, + {name: "filters that leave nothing", objects: map[string][]byte{"filtered/out.txt": []byte("o")}, excludePaths: []string{"filtered/"}}, } { suite.Run(t.name, func() { content, err := getS3DataFromClient(checksummedBucket(t.objects), fakeS3TestBucketName, nil, nil, t.excludePaths, nil, @@ -104,6 +106,7 @@ func (suite *S3MetadataTestSuite) TestMatchesContentMode() { metadata, err := snapshotMetadata(suite.T(), checksummedBucket(t.objects), t.excludePaths) require.NoError(suite.T(), err) + require.Len(suite.T(), content, 1) require.Equal(suite.T(), content, metadata, "metadata mode must produce exactly what content mode produces") }) } @@ -113,41 +116,36 @@ func (suite *S3MetadataTestSuite) TestMatchesContentMode() { // must reproduce them from checksums alone. func (suite *S3MetadataTestSuite) TestPinnedFingerprints() { for _, t := range []struct { - name string - objects map[string][]byte - wantArtifactName string - wantFingerprint string + name string + objects map[string][]byte + wantFingerprint string }{ { - name: "unusual key shapes fold as filepath.Join folded them", - objects: map[string][]byte{"/lead.txt": []byte("u\n"), "a//b": []byte("o\n"), "./c.txt": []byte("t\n"), `d\e.txt`: []byte("n\n")}, - wantArtifactName: fakeS3TestBucketName, - wantFingerprint: "27e2d8aa07677b7818b8cf101b45c928aa8fbf7d17a8c8efc84469e24a106ec3", + name: "unusual key shapes fold as filepath.Join folded them", + objects: map[string][]byte{"/lead.txt": []byte("u\n"), "a//b": []byte("o\n"), "./c.txt": []byte("t\n"), `d\e.txt`: []byte("n\n")}, + wantFingerprint: "27e2d8aa07677b7818b8cf101b45c928aa8fbf7d17a8c8efc84469e24a106ec3", }, { - name: "a dot sorts before a slash", - objects: map[string][]byte{"a.txt": []byte("1"), "a/z": []byte("2"), "a/b/c": []byte("3"), "b": []byte("4")}, - wantArtifactName: fakeS3TestBucketName, - wantFingerprint: "aaddb8f3e299e12316d42fa9ac36d4ed7d38c34e7ec002239269c86a033bb9fd", + name: "a dot sorts before a slash", + objects: map[string][]byte{"a.txt": []byte("1"), "a/z": []byte("2"), "a/b/c": []byte("3"), "b": []byte("4")}, + wantFingerprint: "aaddb8f3e299e12316d42fa9ac36d4ed7d38c34e7ec002239269c86a033bb9fd", }, { - name: "nested prefixes with folder markers", - objects: map[string][]byte{"dir/": nil, "dir/sub/": nil, "dir/sub/x.yml": []byte("x"), "dir/y.txt": []byte("y"), "README.md": []byte("r")}, - wantArtifactName: fakeS3TestBucketName, - wantFingerprint: "c26910cdb177dde3c6493d18ba1e916b04715cdfc535e4552b5f9831590e933a", + name: "nested prefixes with folder markers", + objects: map[string][]byte{"dir/": nil, "dir/sub/": nil, "dir/sub/x.yml": []byte("x"), "dir/y.txt": []byte("y"), "README.md": []byte("r")}, + wantFingerprint: "c26910cdb177dde3c6493d18ba1e916b04715cdfc535e4552b5f9831590e933a", }, { - name: "a single object is the file, named by its base name", - objects: map[string][]byte{"only/one/file.bin": []byte("solo")}, - wantArtifactName: "file.bin", - wantFingerprint: "5364f2f2fc4f54e9d47ad29cfb08ef430c8153394bf2a0dff5cbe77a0ffef861", + name: "a single object is fingerprinted as the file, named after the bucket", + objects: map[string][]byte{"only/one/file.bin": []byte("solo")}, + wantFingerprint: "5364f2f2fc4f54e9d47ad29cfb08ef430c8153394bf2a0dff5cbe77a0ffef861", }, } { suite.Run(t.name, func() { data, err := snapshotMetadata(suite.T(), checksummedBucket(t.objects), nil) require.NoError(suite.T(), err) require.Len(suite.T(), data, 1) - require.Equal(suite.T(), map[string]string{t.wantArtifactName: t.wantFingerprint}, data[0].Digests) + require.Equal(suite.T(), map[string]string{fakeS3TestBucketName: t.wantFingerprint}, data[0].Digests) }) } } @@ -294,11 +292,6 @@ func (suite *S3MetadataTestSuite) TestErrors() { listErr: errInjected, wantErrMsg: []string{"injected error"}, }, - { - name: "an empty bucket keeps the content-mode message", - objects: map[string][]byte{"dir/": nil}, - wantErrMsg: []string{"no matching file or dirs in bucket: [" + fakeS3TestBucketName + "]"}, - }, } { suite.Run(t.name, func() { client := &FakeS3Client{Bucket: fakeS3TestBucketName, Objects: t.objects, Checksums: t.checksums, @@ -506,7 +499,7 @@ func (suite *S3MetadataTestSuite) TestSkippingUnusableWarnsWithTheSkippedKeys() }) } -func (suite *S3MetadataTestSuite) TestSkippingEveryObjectReportsAnEmptySnapshot() { +func (suite *S3MetadataTestSuite) TestSkippingEveryObjectReportsAnEmptyBucket() { for _, t := range []struct { name string objects map[string][]byte @@ -517,11 +510,13 @@ func (suite *S3MetadataTestSuite) TestSkippingEveryObjectReportsAnEmptySnapshot( suite.Run(t.name, func() { data, warnings, err := snapshotSkippingUnusable(suite.T(), &FakeS3Client{Bucket: fakeS3TestBucketName, Objects: t.objects}) require.NoError(suite.T(), err) - require.Empty(suite.T(), data) - require.NotNil(suite.T(), data, "the payload must carry an empty list, not null") + require.Equal(suite.T(), []*S3Data{{ + Digests: map[string]string{fakeS3TestBucketName: fakeEmptyBucketSha256}, + LastModifiedTimestamp: 0, + }}, data) require.Contains(suite.T(), warnings, fmt.Sprintf("skipped %d of the %d objects", len(t.objects), len(t.objects))) require.Contains(suite.T(), warnings, "[README.md]") - require.Contains(suite.T(), warnings, "[warning] no object in bucket ["+fakeS3TestBucketName+"] is left to fingerprint; reporting an empty snapshot\n") + require.Contains(suite.T(), warnings, "[warning] no object in bucket ["+fakeS3TestBucketName+"] is left to fingerprint; reporting it as an empty bucket\n") }) } } @@ -535,11 +530,6 @@ func (suite *S3MetadataTestSuite) TestSkippingUnusableStillFailsOnOtherErrors() require.ErrorIs(suite.T(), err, errInjected) } }) - - 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") - }) } func TestS3MetadataTestSuite(t *testing.T) { diff --git a/internal/aws/s3_parallel_test.go b/internal/aws/s3_parallel_test.go index dfb630141..4dd4deb3b 100644 --- a/internal/aws/s3_parallel_test.go +++ b/internal/aws/s3_parallel_test.go @@ -93,7 +93,7 @@ func bucketOf(n int, size int, delay time.Duration) (*trackingDownloader, []s3Ob func (suite *S3ParallelTestSuite) TestMakesExactlyOneCallPerObject() { client, listing := bucketOf(60, 8, 0) - _, parallel, err := fingerprintS3Objects(client, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: 8, BytesInFlight: 1 << 30}, logger.NewStandardLogger()) + parallel, err := fingerprintS3Objects(client, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: 8, BytesInFlight: 1 << 30}, logger.NewStandardLogger()) require.NoError(suite.T(), err) require.Len(suite.T(), client.calls, 60) for key, n := range client.calls { @@ -101,14 +101,14 @@ func (suite *S3ParallelTestSuite) TestMakesExactlyOneCallPerObject() { } sequential, _ := bucketOf(60, 8, 0) - _, want, err := fingerprintS3Objects(sequential, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: 1, BytesInFlight: 1 << 30}, logger.NewStandardLogger()) + want, err := fingerprintS3Objects(sequential, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: 1, BytesInFlight: 1 << 30}, logger.NewStandardLogger()) require.NoError(suite.T(), err) require.Equal(suite.T(), want, parallel) } func (suite *S3ParallelTestSuite) TestRespectsTheConcurrencyBound() { client, listing := bucketOf(40, 8, 5*time.Millisecond) - _, _, err := fingerprintS3Objects(client, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: 4, BytesInFlight: 1 << 30}, logger.NewStandardLogger()) + _, err := fingerprintS3Objects(client, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: 4, BytesInFlight: 1 << 30}, logger.NewStandardLogger()) require.NoError(suite.T(), err) require.LessOrEqual(suite.T(), client.maxInFlight, 4) require.GreaterOrEqual(suite.T(), client.maxInFlight, 2, "downloads must actually overlap for the bound to be tested") @@ -118,7 +118,7 @@ func (suite *S3ParallelTestSuite) TestRespectsTheConcurrencyBound() { // eight 100-byte objects, the budget allows two. func (suite *S3ParallelTestSuite) TestRespectsTheByteBudget() { client, listing := bucketOf(20, 100, 5*time.Millisecond) - _, _, err := fingerprintS3Objects(client, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: 8, BytesInFlight: 250}, logger.NewStandardLogger()) + _, err := fingerprintS3Objects(client, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: 8, BytesInFlight: 250}, logger.NewStandardLogger()) require.NoError(suite.T(), err) require.LessOrEqual(suite.T(), client.maxBytesInFlight, int64(250)) require.LessOrEqual(suite.T(), client.maxInFlight, 2) @@ -145,7 +145,7 @@ func (suite *S3ParallelTestSuite) TestAnObjectLargerThanTheBudgetRunsAlone() { return nil } - _, _, err := fingerprintS3Objects(client, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: 8, BytesInFlight: 250}, logger.NewStandardLogger()) + _, err := fingerprintS3Objects(client, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: 8, BytesInFlight: 250}, logger.NewStandardLogger()) require.NoError(suite.T(), err) require.Equal(suite.T(), 1, aloneChecks) require.Equal(suite.T(), 1, client.calls[big]) @@ -182,9 +182,8 @@ func (suite *S3ParallelTestSuite) TestFingerprintIsIndependentOfCompletionOrder( time.Sleep(d) return nil } - name, got, err := fingerprintS3Objects(client, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: 8, BytesInFlight: 1 << 30}, logger.NewStandardLogger()) + got, err := fingerprintS3Objects(client, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: 8, BytesInFlight: 1 << 30}, logger.NewStandardLogger()) require.NoError(suite.T(), err) - require.Equal(suite.T(), fakeS3TestBucketName, name) require.Equal(suite.T(), want, got, "round %d", round) } } @@ -216,7 +215,7 @@ func (suite *S3ParallelTestSuite) TestATransportErrorStopsRemainingWork() { } } - _, _, err := fingerprintS3Objects(client, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: 2, BytesInFlight: 1 << 30}, logger.NewStandardLogger()) + _, err := fingerprintS3Objects(client, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: 2, BytesInFlight: 1 << 30}, logger.NewStandardLogger()) require.Error(suite.T(), err) require.ErrorIs(suite.T(), err, errBoom) require.Contains(suite.T(), err.Error(), fmt.Sprintf("object key [%s]", failingKey)) @@ -251,7 +250,7 @@ func (suite *S3ParallelTestSuite) TestGoroutinesDoNotScaleWithTheBucket() { return nil } - _, _, err := fingerprintS3Objects(client, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: concurrency, BytesInFlight: 1 << 30}, logger.NewStandardLogger()) + _, err := fingerprintS3Objects(client, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: concurrency, BytesInFlight: 1 << 30}, logger.NewStandardLogger()) require.NoError(suite.T(), err) require.Len(suite.T(), client.calls, objects) require.LessOrEqual(suite.T(), peak, before+concurrency+8, @@ -270,7 +269,7 @@ func (suite *S3ParallelTestSuite) TestWorkersAreClampedToTheWork() { return nil } - _, _, err := fingerprintS3Objects(client, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: 50000, BytesInFlight: 1 << 30}, logger.NewStandardLogger()) + _, err := fingerprintS3Objects(client, fakeS3TestBucketName, listing, DownloadLimits{Concurrency: 50000, BytesInFlight: 1 << 30}, logger.NewStandardLogger()) require.NoError(suite.T(), err) require.Len(suite.T(), client.calls, 3) require.LessOrEqual(suite.T(), peak, before+3+8, "workers must be bounded by the objects to download") diff --git a/internal/digest/virtualdir.go b/internal/digest/virtualdir.go index 17f424c6f..c5701661b 100644 --- a/internal/digest/virtualdir.go +++ b/internal/digest/virtualdir.go @@ -44,7 +44,8 @@ func SingleVirtualFile(files []VirtualFile) (VirtualFile, bool) { } // VirtualDirSha256 returns the fingerprint DirSha256 would return for a -// directory containing exactly these files, without touching the disk. +// directory containing exactly these files, without touching the disk. No +// files is an empty directory, whose fingerprint is the sha256 of no input. // // It reproduces calculateDirContentSha256 exactly: walk the tree in // filepath.WalkDir order -- which is lexical by name within each directory, @@ -65,10 +66,6 @@ func SingleVirtualFile(files []VirtualFile) (VirtualFile, bool) { // exclusion list without changing its fingerprint. Callers that hold the file's // content pass its rules here; the file is an ordinary entry of files. func VirtualDirSha256(files []VirtualFile, ignoreRules []string, logger *logger.Logger) (string, error) { - if len(files) == 0 { - return "", fmt.Errorf("cannot calculate a fingerprint: no files were provided") - } - root, err := buildVirtualTree(files) if err != nil { return "", err diff --git a/internal/digest/virtualdir_test.go b/internal/digest/virtualdir_test.go index ee2d5a77e..1116a429b 100644 --- a/internal/digest/virtualdir_test.go +++ b/internal/digest/virtualdir_test.go @@ -105,6 +105,21 @@ func (suite *VirtualDirTestSuite) TestVirtualDirSha256MatchesDirSha256() { } } +// An S3 bucket with nothing to fingerprint is reported with this value, so it +// has to be what an empty directory fingerprints to on disk. +func (suite *VirtualDirTestSuite) TestVirtualDirSha256OfNoFilesMatchesAnEmptyDirectory() { + want, err := DirSha256(suite.tmpDir, []string{}, logger.NewStandardLogger()) + require.NoError(suite.T(), err) + + for _, files := range [][]VirtualFile{nil, {}} { + got, err := VirtualDirSha256(files, nil, logger.NewStandardLogger()) + require.NoError(suite.T(), err) + require.Equal(suite.T(), want, got) + } + require.Equal(suite.T(), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", want, + "the fingerprint of an empty directory must not move") +} + // TestVirtualDirSha256IgnoresInputOrder pins that the result depends on the tree, // not on the order S3 happened to list the objects in. func (suite *VirtualDirTestSuite) TestVirtualDirSha256IgnoresInputOrder() { @@ -134,11 +149,6 @@ func (suite *VirtualDirTestSuite) TestVirtualDirSha256Errors() { files []VirtualFile wantErrMsg string }{ - { - name: "no files", - files: []VirtualFile{}, - wantErrMsg: "no files", - }, { name: "a duplicate path", files: []VirtualFile{