From 5dd6e18fb0bc238916af235fe3ae6aaa1cf9739d Mon Sep 17 00:00:00 2001 From: Graham Savage Date: Wed, 25 Nov 2026 10:49:29 +0000 Subject: [PATCH 01/12] feat(snapshot s3)!: name a single-object artifact after the bucket A bucket holding one object was reported as an artifact named after that object, while a bucket holding several was reported as an artifact named after the bucket. Adding a second file to a bucket therefore renamed the artifact, and a one-object snapshot did not say which bucket it was taken from. The team decided that an S3 snapshot always reports the bucket as its one artifact. The fingerprint is calculated as before: a single object is still fingerprinted as that file, so it keeps matching an artifact attested with --artifact-type file. Only the name changes. BREAKING CHANGE: a snapshot of a bucket holding a single object now names its artifact after the bucket instead of after the object. Co-Authored-By: Claude Fable 5.2 --- internal/aws/aws.go | 12 +++--- internal/aws/aws_test.go | 62 +++++++++++------------------ internal/aws/s3_fingerprint_test.go | 6 +-- internal/aws/s3_metadata_test.go | 4 +- 4 files changed, 35 insertions(+), 49 deletions(-) diff --git a/internal/aws/aws.go b/internal/aws/aws.go index 1a11e6f40..345903160 100644 --- a/internal/aws/aws.go +++ b/internal/aws/aws.go @@ -672,8 +672,8 @@ func fingerprintS3Objects(downloader S3DownloadAPI, bucket string, objects []s3O // 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. Either way the +// artifact is named after the bucket. // // The root .kosli_ignore is always downloaded, whatever the source, because its // rules decide which other objects are fetched at all. @@ -706,8 +706,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 +723,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{artifactName: bucket, sha256: sha256, fingerprinted: objects, read: 1}, nil } var rules []string @@ -786,7 +786,7 @@ 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.artifactName, fingerprint.sha256 = bucket, file.Sha256 return fingerprint, nil } sha256, err := digest.VirtualDirSha256(files, rules, logger) diff --git a/internal/aws/aws_test.go b/internal/aws/aws_test.go index e31ca0d22..787ffff0a 100644 --- a/internal/aws/aws_test.go +++ b/internal/aws/aws_test.go @@ -426,11 +426,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() { @@ -1011,27 +1010,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 +1044,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 +1061,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 +1070,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 +1079,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 +1088,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 +1097,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 +1106,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", @@ -1222,14 +1211,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) diff --git a/internal/aws/s3_fingerprint_test.go b/internal/aws/s3_fingerprint_test.go index d05066cf8..9c93523c8 100644 --- a/internal/aws/s3_fingerprint_test.go +++ b/internal/aws/s3_fingerprint_test.go @@ -105,9 +105,9 @@ func (suite *S3FingerprintTestSuite) TestPinnedFingerprints() { wantFingerprint: "c26910cdb177dde3c6493d18ba1e916b04715cdfc535e4552b5f9831590e933a", }, { - name: "a single object is the file, named by its base name", + name: "a single object is fingerprinted as the file, named after the bucket", objects: map[string][]byte{"only/one/file.bin": []byte("solo")}, - wantArtifactName: "file.bin", + wantArtifactName: fakeS3TestBucketName, wantFingerprint: "5364f2f2fc4f54e9d47ad29cfb08ef430c8153394bf2a0dff5cbe77a0ffef861", }, } { @@ -154,7 +154,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_test.go b/internal/aws/s3_metadata_test.go index 7c36826ad..f1bab6c63 100644 --- a/internal/aws/s3_metadata_test.go +++ b/internal/aws/s3_metadata_test.go @@ -137,9 +137,9 @@ func (suite *S3MetadataTestSuite) TestPinnedFingerprints() { wantFingerprint: "c26910cdb177dde3c6493d18ba1e916b04715cdfc535e4552b5f9831590e933a", }, { - name: "a single object is the file, named by its base name", + name: "a single object is fingerprinted as the file, named after the bucket", objects: map[string][]byte{"only/one/file.bin": []byte("solo")}, - wantArtifactName: "file.bin", + wantArtifactName: fakeS3TestBucketName, wantFingerprint: "5364f2f2fc4f54e9d47ad29cfb08ef430c8153394bf2a0dff5cbe77a0ffef861", }, } { From 70c2e5356b4a769218890cb9ede2c15266ea2c9a Mon Sep 17 00:00:00 2001 From: Graham Savage Date: Wed, 25 Nov 2026 10:49:47 +0000 Subject: [PATCH 02/12] refactor(snapshot s3): drop the artifact name from the fingerprint result The artifact is now always named after the bucket, which the caller already holds, so the fingerprint pipeline no longer needs to decide a name and hand it back. Co-Authored-By: Claude Fable 5.2 --- internal/aws/aws.go | 20 +++++++++----------- internal/aws/s3_parallel_test.go | 19 +++++++++---------- 2 files changed, 18 insertions(+), 21 deletions(-) diff --git a/internal/aws/aws.go b/internal/aws/aws.go index 345903160..e643b5db5 100644 --- a/internal/aws/aws.go +++ b/internal/aws/aws.go @@ -528,7 +528,7 @@ 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 } @@ -641,9 +641,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 +663,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. Either way the -// artifact is named after the bucket. +// 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. @@ -723,7 +721,7 @@ func fingerprintS3Tree(downloader S3DownloadAPI, source s3DigestSource, bucket s if err != nil { return s3Fingerprint{}, err } - return s3Fingerprint{artifactName: bucket, sha256: sha256, fingerprinted: objects, read: 1}, nil + return s3Fingerprint{sha256: sha256, fingerprinted: objects, read: 1}, nil } var rules []string @@ -786,14 +784,14 @@ func fingerprintS3Tree(downloader S3DownloadAPI, source s3DigestSource, bucket s return fingerprint, nil } if file, ok := digest.SingleVirtualFile(files); ok { - fingerprint.artifactName, fingerprint.sha256 = bucket, 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/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") From 99f5573a1f34de7ad448a9a4a14416dd2259f1af Mon Sep 17 00:00:00 2001 From: Graham Savage Date: Wed, 25 Nov 2026 10:50:44 +0000 Subject: [PATCH 03/12] feat(digest): fingerprint a virtual tree of no files as an empty directory VirtualDirSha256 refused an empty file list, although DirSha256 accepts an empty directory and returns the sha256 of no input. An S3 bucket with nothing to fingerprint is about to be reported as an artifact rather than failing the snapshot, and its fingerprint should be the one `kosli fingerprint --artifact-type dir` gives for an empty directory, so the virtual calculation now agrees with the on-disk one for that case too. The value is pinned in the test because snapshots will carry it. Co-Authored-By: Claude Fable 5.2 --- internal/digest/virtualdir.go | 7 ++----- internal/digest/virtualdir_test.go | 20 +++++++++++++++----- 2 files changed, 17 insertions(+), 10 deletions(-) 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{ From 6853cef9a3163041e861497e2263c08f7dd864cf Mon Sep 17 00:00:00 2001 From: Graham Savage Date: Wed, 25 Nov 2026 10:52:13 +0000 Subject: [PATCH 04/12] feat(snapshot s3)!: report an empty bucket instead of failing A bucket that listed no objects, or only folder markers, failed the snapshot with "no matching file or dirs in bucket". When a bucket that was being snapshotted was emptied, every later snapshot failed, so Kosli kept showing the last content the bucket held and the loss of the files was never recorded. An empty bucket is a valid state, so it is now reported like any other: one artifact named after the bucket. Its fingerprint is that of an empty directory, the value `kosli fingerprint --artifact-type dir` gives for one, so the calculation is the one already used for a bucket with content. No object supplies a modification time, so the timestamp is 0, which keeps repeated snapshots of an empty bucket identical. A line on stdout says the bucket held no objects. A filter that leaves nothing still fails; that changes next. BREAKING CHANGE: snapshotting an S3 bucket that holds no objects now succeeds and reports the bucket as an empty artifact, where it used to exit with an error. Co-Authored-By: Claude Fable 5.2 --- internal/aws/aws.go | 19 ++++++++++++- internal/aws/aws_test.go | 47 ++++++++++++++++++++++++++------ internal/aws/s3_metadata_test.go | 12 ++------ 3 files changed, 59 insertions(+), 19 deletions(-) diff --git a/internal/aws/aws.go b/internal/aws/aws.go index e643b5db5..6f3945b9e 100644 --- a/internal/aws/aws.go +++ b/internal/aws/aws.go @@ -504,7 +504,12 @@ 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) + filtersSet := len(includePaths)+len(includeRegex)+len(excludePaths)+len(excludeRegex) > 0 + if filtersSet { + return s3Data, fmt.Errorf("no matching file or dirs in bucket: [%s]", bucket) + } + logger.Info("bucket [%s] holds no objects; reporting it as an empty bucket", bucket) + return emptyS3Bucket(bucket, logger) } newest := newestS3Modification(objects) @@ -533,6 +538,18 @@ func getS3DataWithSource(client S3API, source s3DigestSource, bucket string, inc 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 { diff --git a/internal/aws/aws_test.go b/internal/aws/aws_test.go index 787ffff0a..11e14c54a 100644 --- a/internal/aws/aws_test.go +++ b/internal/aws/aws_test.go @@ -1136,14 +1136,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{ @@ -1224,6 +1216,45 @@ 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. +func (suite *AWSTestSuite) TestGetS3DataFromClientReportsNothingToFingerprintAsAnEmptyBucket() { + const emptyBucketLog = "bucket [" + fakeS3TestBucketName + "] holds no objects; 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}, + } { + 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_metadata_test.go b/internal/aws/s3_metadata_test.go index f1bab6c63..67fc60788 100644 --- a/internal/aws/s3_metadata_test.go +++ b/internal/aws/s3_metadata_test.go @@ -95,6 +95,7 @@ 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}}, } { suite.Run(t.name, func() { content, err := getS3DataFromClient(checksummedBucket(t.objects), fakeS3TestBucketName, nil, nil, t.excludePaths, nil, @@ -104,6 +105,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") }) } @@ -294,11 +296,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, @@ -535,11 +532,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) { From 74c6718beb209857137b226c16c2ab97c69a0798 Mon Sep 17 00:00:00 2001 From: Graham Savage Date: Wed, 25 Nov 2026 10:52:29 +0000 Subject: [PATCH 05/12] feat(snapshot s3)!: treat filters that leave nothing as an empty bucket When --include, --include-regex, --exclude or --exclude-regex left no object to fingerprint, the snapshot failed with "no matching file or dirs in bucket". The check dates from when the filters were added, on the reasoning that nothing left to report most likely meant a mistyped filter. The team decided that the filters define what the snapshot sees of the bucket, so a filtered view with nothing in it is reported the same way as a bucket with nothing in it: one artifact named after the bucket, with the empty-directory fingerprint. Failing instead would leave Kosli showing the content from the last successful snapshot after the matching objects had been removed. A mistyped filter is still a real risk, so this case logs a warning rather than the plain line an unfiltered empty bucket gets. BREAKING CHANGE: snapshotting an S3 bucket with include or exclude filters that match no object now succeeds, with a warning, and reports the bucket as an empty artifact, where it used to exit with an error. Co-Authored-By: Claude Fable 5.2 --- internal/aws/aws.go | 6 ++++-- internal/aws/aws_test.go | 24 +++++++++++++----------- internal/aws/s3_metadata_test.go | 1 + 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/internal/aws/aws.go b/internal/aws/aws.go index 6f3945b9e..ad6dd675d 100644 --- a/internal/aws/aws.go +++ b/internal/aws/aws.go @@ -504,11 +504,13 @@ func getS3DataWithSource(client S3API, source s3DigestSource, bucket string, inc return s3Data, err } if len(objects) == 0 { + // 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 { - return s3Data, fmt.Errorf("no matching file or dirs in bucket: [%s]", bucket) + logger.Warn("no object in bucket [%s] is left by the include and exclude filters; reporting it as an empty bucket", bucket) + } else { + logger.Info("bucket [%s] holds no objects; reporting it as an empty bucket", bucket) } - logger.Info("bucket [%s] holds no objects; reporting it as an empty bucket", bucket) return emptyS3Bucket(bucket, logger) } diff --git a/internal/aws/aws_test.go b/internal/aws/aws_test.go index 11e14c54a..dd06e2766 100644 --- a/internal/aws/aws_test.go +++ b/internal/aws/aws_test.go @@ -1136,15 +1136,6 @@ func (suite *AWSTestSuite) TestGetS3DataFromClient() { excludePaths: []string{"skip.txt"}, wantLastModified: later.Unix(), }, - { - 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{ @@ -1221,9 +1212,15 @@ func (suite *AWSTestSuite) TestGetS3DataFromClient() { const fakeEmptyBucketSha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" // A bucket with nothing to fingerprint is still the one artifact of the -// snapshot. +// 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() { - const emptyBucketLog = "bucket [" + fakeS3TestBucketName + "] holds no objects; reporting it as an empty bucket\n" + 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 + "] is left by the include and exclude filters; reporting it as an empty bucket\n" + ) for _, t := range []struct { name string objects map[string][]byte @@ -1236,6 +1233,11 @@ func (suite *AWSTestSuite) TestGetS3DataFromClientReportsNothingToFingerprintAsA }{ {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} diff --git a/internal/aws/s3_metadata_test.go b/internal/aws/s3_metadata_test.go index 67fc60788..8ce0a7dd8 100644 --- a/internal/aws/s3_metadata_test.go +++ b/internal/aws/s3_metadata_test.go @@ -96,6 +96,7 @@ func (suite *S3MetadataTestSuite) TestMatchesContentMode() { 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, From 3054e5c4986dcaac897f116d17ecbd239e91c39d Mon Sep 17 00:00:00 2001 From: Graham Savage Date: Wed, 25 Nov 2026 10:53:05 +0000 Subject: [PATCH 06/12] feat(snapshot s3)!: report a bucket with every checksum skipped as empty With --fingerprint-source metadata and --skip-unusable-checksums, a bucket in which no object had a usable SHA256 checksum was reported as a snapshot with no artifacts. That was the only case in which an S3 snapshot carried an empty artifact list, and it left nothing in the snapshot to say which bucket had been read. An S3 snapshot now always carries exactly one artifact, the bucket, so this case is reported like an empty bucket: named after the bucket, with the empty-directory fingerprint. The warning naming the skipped objects is unchanged. BREAKING CHANGE: with --skip-unusable-checksums, a bucket whose objects are all skipped is now reported as one artifact with the empty-directory fingerprint instead of as an empty artifact list. Co-Authored-By: Claude Fable 5.2 --- internal/aws/aws.go | 4 ++-- internal/aws/s3_metadata.go | 4 ++-- internal/aws/s3_metadata_test.go | 10 ++++++---- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/internal/aws/aws.go b/internal/aws/aws.go index ad6dd675d..c94de8e03 100644 --- a/internal/aws/aws.go +++ b/internal/aws/aws.go @@ -526,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() { 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 8ce0a7dd8..26d3292cd 100644 --- a/internal/aws/s3_metadata_test.go +++ b/internal/aws/s3_metadata_test.go @@ -504,7 +504,7 @@ func (suite *S3MetadataTestSuite) TestSkippingUnusableWarnsWithTheSkippedKeys() }) } -func (suite *S3MetadataTestSuite) TestSkippingEveryObjectReportsAnEmptySnapshot() { +func (suite *S3MetadataTestSuite) TestSkippingEveryObjectReportsAnEmptyBucket() { for _, t := range []struct { name string objects map[string][]byte @@ -515,11 +515,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") }) } } From 0bff1c472e2d483947407835e38a686c1b2b7579 Mon Sep 17 00:00:00 2001 From: Graham Savage Date: Wed, 25 Nov 2026 10:54:30 +0000 Subject: [PATCH 07/12] docs(snapshot s3): describe the bucket as the one artifact The help text said only that the content is reported as one artifact, and that skipping every checksum gives an empty snapshot. Both are out of date now that the artifact is always named after the bucket and a bucket with nothing to report is an empty-directory artifact rather than an error or an empty list. The long description now states the name, which `kosli fingerprint` artifact type the fingerprint corresponds to, and what is reported when nothing is left, including the fingerprint value so it can be recognised in Kosli. The --skip-unusable-checksums flag text follows. The fingerprint ADR described the single-object artifact as named after the object; it gains a dated note recording what has changed rather than being rewritten, since the calculation it records stands. Co-Authored-By: Claude Fable 5.2 --- cmd/kosli/root.go | 2 +- cmd/kosli/snapshotS3.go | 6 ++++-- docs/adr/20260911-s3-fingerprint-from-virtual-tree.md | 8 ++++++++ 3 files changed, 13 insertions(+), 3 deletions(-) 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/docs/adr/20260911-s3-fingerprint-from-virtual-tree.md b/docs/adr/20260911-s3-fingerprint-from-virtual-tree.md index 5487d1b0a..039d491a8 100644 --- a/docs/adr/20260911-s3-fingerprint-from-virtual-tree.md +++ b/docs/adr/20260911-s3-fingerprint-from-virtual-tree.md @@ -43,6 +43,14 @@ The fingerprint format itself is fixed. An S3 snapshot must match the fingerprin ## 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. From 3550452aee887ef94ef37c0e2acc567921c59e7d Mon Sep 17 00:00:00 2001 From: Graham Savage Date: Wed, 25 Nov 2026 10:56:09 +0000 Subject: [PATCH 08/12] test(snapshot s3): drop the unused artifact name from the real-AWS smoke test No case in TestGetS3Data ever set wantArtifactName, so it always fell back to the bucket name. The artifact is now always named after the bucket, so the field and its fallback say nothing and are removed. The "includePaths is a file" case looked its fingerprint up under the bucket name while the artifact was named README.md, so it could not have passed against real AWS before the naming change. It is skipped without AWS credentials and has not been run here. Co-Authored-By: Claude Fable 5.2 --- internal/aws/aws_test.go | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/internal/aws/aws_test.go b/internal/aws/aws_test.go index dd06e2766..ac1634525 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", @@ -438,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]) } } }) From 1609fdb9bfa8c298930166efe096b3e1d51ce0f1 Mon Sep 17 00:00:00 2001 From: Graham Savage Date: Wed, 25 Nov 2026 13:05:35 +0000 Subject: [PATCH 09/12] test(snapshot s3): cover the empty-bucket outcomes at the command level The command suite still expected --include matching nothing to fail, and the old wording for a bucket whose every checksum was skipped. Both now expect the bucket to be reported as empty, and an --exclude-regex that removes every object is covered alongside them. A new case snapshots a bucket holding only a folder marker, from both fingerprint sources. Because the suite reports to the local Kosli server, it also shows that the server accepts what an empty bucket is reported with: the empty-directory fingerprint and a timestamp of 0. Co-Authored-By: Claude Fable 5.2 --- cmd/kosli/snapshotS3_test.go | 46 +++++++++++++++++++++++++++++++----- 1 file changed, 40 insertions(+), 6 deletions(-) diff --git a/cmd/kosli/snapshotS3_test.go b/cmd/kosli/snapshotS3_test.go index 3250fa7c6..482a14e8b 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] is left by the include and exclude filters; 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] is left by the include and exclude filters; 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) { From 6552b0019053257292ecf87577a237ad96feaf7b Mon Sep 17 00:00:00 2001 From: Graham Savage Date: Wed, 25 Nov 2026 14:35:21 +0000 Subject: [PATCH 10/12] fix(snapshot s3): stop the filter warning claiming the filters emptied the bucket The warning fires whenever a filter is set and no object is left, but that does not show the filters removed anything: the bucket may have been empty, or held only folder markers, before any filter ran. Saying "no object is left by the filters" then points someone debugging at their filters when the bucket itself is the cause. Reword the warning to say that no object matches the filters or the bucket is empty. Counting the objects seen before filtering would let the message be exact, but the reported snapshot is the same either way, so the wording change is enough. Co-Authored-By: Claude Fable 5.2 --- cmd/kosli/snapshotS3_test.go | 4 ++-- internal/aws/aws.go | 2 +- internal/aws/aws_test.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cmd/kosli/snapshotS3_test.go b/cmd/kosli/snapshotS3_test.go index 482a14e8b..b36665f0d 100644 --- a/cmd/kosli/snapshotS3_test.go +++ b/cmd/kosli/snapshotS3_test.go @@ -114,13 +114,13 @@ func (suite *SnapshotS3TestSuite) TestSnapshotS3Cmd() { { 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] is left by the include and exclude filters; reporting it as an empty bucket\n" + + 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] is left by the include and exclude filters; reporting it as an empty bucket\n" + + 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", }, { diff --git a/internal/aws/aws.go b/internal/aws/aws.go index c94de8e03..0db626f05 100644 --- a/internal/aws/aws.go +++ b/internal/aws/aws.go @@ -507,7 +507,7 @@ func getS3DataWithSource(client S3API, source s3DigestSource, bucket string, inc // 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] is left by the include and exclude filters; reporting it as an empty bucket", bucket) + 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) } diff --git a/internal/aws/aws_test.go b/internal/aws/aws_test.go index ac1634525..fcc2632ba 100644 --- a/internal/aws/aws_test.go +++ b/internal/aws/aws_test.go @@ -1215,7 +1215,7 @@ func (suite *AWSTestSuite) TestGetS3DataFromClientReportsNothingToFingerprintAsA 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 + "] is left by the include and exclude filters; 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 From 9c859ef9d3c4d1b02c3c90e4ffd20e8e2056c840 Mon Sep 17 00:00:00 2001 From: Graham Savage Date: Thu, 26 Nov 2026 08:59:09 +0000 Subject: [PATCH 11/12] test(snapshot s3): drop the artifact name from the pinned-fingerprint cases Every S3 snapshot now names its one artifact after the bucket, so the wantArtifactName field held the same value in every case of both TestPinnedFingerprints tables and told the reader nothing. Assert the bucket name directly instead, which leaves the fingerprint as the only thing each case pins. Co-Authored-By: Claude Fable 5.2 --- internal/aws/s3_fingerprint_test.go | 25 ++++++++----------- internal/aws/s3_metadata_test.go | 37 +++++++++++++---------------- 2 files changed, 26 insertions(+), 36 deletions(-) diff --git a/internal/aws/s3_fingerprint_test.go b/internal/aws/s3_fingerprint_test.go index 9c93523c8..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 fingerprinted as the file, named after the bucket", - objects: map[string][]byte{"only/one/file.bin": []byte("solo")}, - wantArtifactName: fakeS3TestBucketName, - 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) }) } diff --git a/internal/aws/s3_metadata_test.go b/internal/aws/s3_metadata_test.go index 26d3292cd..9eecf982a 100644 --- a/internal/aws/s3_metadata_test.go +++ b/internal/aws/s3_metadata_test.go @@ -116,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 fingerprinted as the file, named after the bucket", - objects: map[string][]byte{"only/one/file.bin": []byte("solo")}, - wantArtifactName: fakeS3TestBucketName, - 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) }) } } From 03db74600615e87704a24c097c56e6032223b0e7 Mon Sep 17 00:00:00 2001 From: Graham Savage Date: Thu, 26 Nov 2026 08:59:09 +0000 Subject: [PATCH 12/12] docs(adr): mark the remaining basename references as superseded The amendment note under Guarantees says a single object is now named after the bucket, but two other sentences in the record still described the artifact name as the object's basename without pointing at it. A reader landing on either one would take the old naming as current. Annotate both in place rather than rewrite them, so the record still shows what was decided at the time. Co-Authored-By: Claude Fable 5.2 --- docs/adr/20260911-s3-fingerprint-from-virtual-tree.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/adr/20260911-s3-fingerprint-from-virtual-tree.md b/docs/adr/20260911-s3-fingerprint-from-virtual-tree.md index 039d491a8..64c1ce5ab 100644 --- a/docs/adr/20260911-s3-fingerprint-from-virtual-tree.md +++ b/docs/adr/20260911-s3-fingerprint-from-virtual-tree.md @@ -39,7 +39,7 @@ 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 @@ -53,7 +53,7 @@ The fingerprint format itself is fixed. An S3 snapshot must match the fingerprin 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.