Skip to content
This repository was archived by the owner on Jul 18, 2025. It is now read-only.

Commit 7910587

Browse files
committed
Add SendFileHashes
1 parent 3b7d198 commit 7910587

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

sbom/lsp.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,15 @@
1717
package sbom
1818

1919
import (
20+
"crypto/sha256"
21+
"fmt"
22+
"io"
23+
24+
"github.com/anchore/syft/syft/source"
2025
"github.com/docker/cli/cli/command"
2126
cliflags "github.com/docker/cli/cli/flags"
27+
"github.com/docker/index-cli-plugin/registry"
28+
"github.com/docker/index-cli-plugin/sbom/util"
2229
"github.com/pkg/errors"
2330
)
2431

@@ -41,3 +48,39 @@ func Send(image string, tx chan<- string) error {
4148
close(tx)
4249
return nil
4350
}
51+
52+
func SendFileHashes(image string, tx chan<- string) error {
53+
cmd, err := command.NewDockerCli()
54+
if err != nil {
55+
return errors.Wrap(err, "failed to create docker cli")
56+
}
57+
if err := cmd.Initialize(cliflags.NewClientOptions()); err != nil {
58+
return errors.Wrap(err, "failed to initialize docker cli")
59+
}
60+
cache, err := registry.SaveImage(image, cmd)
61+
if err != nil {
62+
return errors.Wrap(err, "failed to copy image")
63+
}
64+
err = cache.StoreImage()
65+
if err != nil {
66+
return errors.Wrap(err, "failed to save image")
67+
}
68+
for _, layer := range cache.Source.Image.Layers {
69+
res := util.NewSingleLayerResolver(layer)
70+
refs := layer.Tree.AllFiles()
71+
for _, ref := range refs {
72+
content, err := res.FileContentsByLocation(source.NewLocation(string(ref.RealPath)))
73+
if err == nil {
74+
b, _ := io.ReadAll(content)
75+
content.Close()
76+
h := sha256.New()
77+
h.Write(b)
78+
hash := fmt.Sprintf("sha256:%x", h.Sum(nil))
79+
msg := fmt.Sprintf(`{:path "%s" :hash "%s"}`, ref.RealPath, hash)
80+
tx <- msg
81+
}
82+
}
83+
}
84+
close(tx)
85+
return nil
86+
}

sbom/lsp_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,19 @@ func TestSend(t *testing.T) {
3535
t.Errorf("expected 3 transactions, instead got %d", len(transactions))
3636
}
3737
}
38+
39+
func TestSendFileHashes(t *testing.T) {
40+
tx := make(chan string, 100)
41+
transactions := make([]string, 0)
42+
43+
err := SendFileHashes("alpine@sha256:c0d488a800e4127c334ad20d61d7bc21b4097540327217dfab52262adc02380c", tx)
44+
if err != nil {
45+
t.Fail()
46+
}
47+
for elem := range tx {
48+
transactions = append(transactions, elem)
49+
}
50+
if len(transactions) != 88 {
51+
t.Errorf("expected 88 transactions, instead got %d", len(transactions))
52+
}
53+
}

0 commit comments

Comments
 (0)