gunk-dev/the-valley

tree.go

sourceb115ae7362ffmain's published tip history
5.7 KiB
1package statement
2
3// valley-tree-v1, the content-addressing scheme a statement's subject is
4// named by.
5//
6// It is SHA-256 over a canonical manifest of a tree's entries. The
7// manifest is
8//
9// "valley-tree-v1\n"
10// for each entry, sorted by path bytes ascending:
11// "<mode> <sha256 of content, hex> <byte length of path> <path>\n"
12//
13// The path's byte length is written out, so the trailing newline is a
14// delimiter no path can forge. Nothing outside the tree enters the
15// manifest: no commit, no author, no time, no store path, no directory
16// entry (a directory is implied by the paths under it, and an empty one is
17// not a thing a tree can hold). Mode is git's: 100644, 100755, or 120000
18// for a symlink, whose content is its target.
19
20import (
21 "bufio"
22 "bytes"
23 "crypto/sha256"
24 "encoding/hex"
25 "errors"
26 "fmt"
27 "io"
28 "os/exec"
29 "sort"
30 "strconv"
31 "strings"
32)
33
34const (
35 // TreeScheme names the scheme in a digest set.
36 TreeScheme = "valley-tree-v1"
37
38 ModeFile = "100644"
39 ModeExec = "100755"
40 ModeSymlink = "120000"
41)
42
43// Entry is one member of a tree: its git mode, its path relative to the
44// tree root, and the SHA-256 of its content.
45type Entry struct {
46 Mode string
47 Path string
48 Sum [32]byte
49}
50
51// TreeManifest renders the canonical bytes valley-tree-v1 digests.
52func TreeManifest(entries []Entry) []byte {
53 sorted := append([]Entry(nil), entries...)
54 sort.Slice(sorted, func(i, j int) bool { return sorted[i].Path < sorted[j].Path })
55
56 var b bytes.Buffer
57 b.WriteString(TreeScheme + "\n")
58 for _, e := range sorted {
59 b.WriteString(e.Mode)
60 b.WriteByte(' ')
61 b.WriteString(hex.EncodeToString(e.Sum[:]))
62 b.WriteByte(' ')
63 b.WriteString(strconv.Itoa(len(e.Path)))
64 b.WriteByte(' ')
65 b.WriteString(e.Path)
66 b.WriteByte('\n')
67 }
68 return b.Bytes()
69}
70
71// TreeDigest is the valley-tree-v1 digest of a tree's entries, in hex.
72func TreeDigest(entries []Entry) string {
73 sum := sha256.Sum256(TreeManifest(entries))
74 return hex.EncodeToString(sum[:])
75}
76
77// GitTree reads the entries of a revision's tree with two git commands,
78// `ls-tree -r -z --full-tree <rev>` and one `cat-file --batch` for every
79// blob, each made by git, which sets the repository and environment it
80// runs in. It reads the revision's tree, never a working tree: the
81// subject of an attestation is a function of committed content alone. A
82// submodule, or any mode but the three the scheme names, is an error.
83func GitTree(git func(args ...string) *exec.Cmd, rev string) ([]Entry, error) {
84 out, err := output(git("ls-tree", "-r", "-z", "--full-tree", rev))
85 if err != nil {
86 return nil, fmt.Errorf("ls-tree %s: %w", rev, err)
87 }
88 var entries []Entry
89 var oids []string
90 for _, rec := range bytes.Split(out, []byte{0}) {
91 if len(rec) == 0 {
92 continue
93 }
94 // "<mode> <type> <oid>\t<path>"
95 tab := bytes.IndexByte(rec, '\t')
96 if tab < 0 {
97 return nil, fmt.Errorf("ls-tree: no path in %q", rec)
98 }
99 fields := bytes.Fields(rec[:tab])
100 if len(fields) != 3 {
101 return nil, fmt.Errorf("ls-tree: malformed record %q", rec[:tab])
102 }
103 mode, path := string(fields[0]), string(rec[tab+1:])
104 switch mode {
105 case ModeFile, ModeExec, ModeSymlink:
106 case "160000":
107 return nil, fmt.Errorf("%s is a submodule; valley-tree-v1 does not name trees that reach outside themselves", path)
108 default:
109 return nil, fmt.Errorf("%s has unsupported mode %s", path, mode)
110 }
111 entries = append(entries, Entry{Mode: mode, Path: path})
112 oids = append(oids, string(fields[2]))
113 }
114 sums, err := blobSums(git("cat-file", "--batch"), oids)
115 if err != nil {
116 return nil, err
117 }
118 for i := range entries {
119 entries[i].Sum = sums[i]
120 }
121 return entries, nil
122}
123
124// output runs cmd and returns its stdout, with its stderr in the error. A
125// command that exits zero has succeeded even when the wait for its output
126// was cut short, as by exec.Cmd.WaitDelay: only something it started can
127// still hold the output then.
128func output(cmd *exec.Cmd) ([]byte, error) {
129 var errb bytes.Buffer
130 cmd.Stderr = &errb
131 out, err := cmd.Output()
132 if err != nil && !errors.Is(err, exec.ErrWaitDelay) {
133 return nil, fmt.Errorf("%w: %s", err, strings.TrimSpace(errb.String()))
134 }
135 return out, nil
136}
137
138// blobSums returns the SHA-256 of each named blob's content, in the order
139// asked for, read through cmd, a `git cat-file --batch`.
140func blobSums(cmd *exec.Cmd, oids []string) ([][32]byte, error) {
141 sums := make([][32]byte, len(oids))
142 if len(oids) == 0 {
143 return sums, nil
144 }
145 cmd.Stdin = strings.NewReader(strings.Join(oids, "\n") + "\n")
146 var errb bytes.Buffer
147 cmd.Stderr = &errb
148 stdout, err := cmd.StdoutPipe()
149 if err != nil {
150 return nil, err
151 }
152 if err := cmd.Start(); err != nil {
153 return nil, err
154 }
155 r := bufio.NewReader(stdout)
156 read := func() error {
157 for i := range oids {
158 header, err := r.ReadString('\n')
159 if err != nil {
160 return fmt.Errorf("cat-file: %w: %s", err, strings.TrimSpace(errb.String()))
161 }
162 fields := strings.Fields(strings.TrimSpace(header))
163 if len(fields) != 3 || fields[1] != "blob" {
164 return fmt.Errorf("cat-file: unexpected header %q for %s", strings.TrimSpace(header), oids[i])
165 }
166 size, err := strconv.Atoi(fields[2])
167 if err != nil {
168 return fmt.Errorf("cat-file: bad size in %q", strings.TrimSpace(header))
169 }
170 h := sha256.New()
171 if _, err := io.CopyN(h, r, int64(size)); err != nil {
172 return fmt.Errorf("cat-file: reading %s: %w", oids[i], err)
173 }
174 if _, err := r.Discard(1); err != nil { // the record's trailing newline
175 return err
176 }
177 copy(sums[i][:], h.Sum(nil))
178 }
179 return nil
180 }
181 if err := read(); err != nil {
182 // What is left unread is discarded, so the command can end.
183 io.Copy(io.Discard, r)
184 cmd.Wait()
185 return nil, err
186 }
187 if err := cmd.Wait(); err != nil && !errors.Is(err, exec.ErrWaitDelay) {
188 return nil, fmt.Errorf("cat-file: %w: %s", err, strings.TrimSpace(errb.String()))
189 }
190 return sums, nil
191}