gunk-dev/the-valley

git.go

source23915b53d9camain's published tip history
8.2 KiB
1package main
2
3import (
4 "archive/tar"
5 "bufio"
6 "bytes"
7 "crypto/sha256"
8 "fmt"
9 "io"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "sort"
14 "strconv"
15 "strings"
16)
17
18// git runs a git command in repo and returns its stdout. Stderr is folded
19// into the error, because a git failure that does not say what git said is
20// a failure the reader has to reproduce by hand.
21func git(repo string, args ...string) (string, error) {
22 return gitInput(repo, nil, args...)
23}
24
25// gitCommand is every git this program runs to read or write the
26// repository: with replacement refs off, and in a fixed environment.
27//
28// A replacement ref makes one object stand in for another wherever git
29// looks it up. Left on, a refs/replace/* in the repository could make the
30// tree this program digests, exports or verifies be some other tree than
31// the revision names — so a verification could pass for a revision that
32// is not the one attested, and a run could check one tree and sign for
33// another.
34//
35// No GIT_ variable is inherited but command-scope configuration naming
36// safe.directory, which a caller that does not own the repository needs
37// (the integrator's unit supplies it this way). A GIT_DIR or
38// GIT_OBJECT_DIRECTORY could point git at other objects, and a
39// GIT_CONFIG_PARAMETERS could change how it reads them. System and user
40// configuration are not read. The integrator's environment is fixed the
41// same way (integrator/main.go), and sigverify's.
42func gitCommand(repo string, args ...string) *exec.Cmd {
43 cmd := exec.Command("git", append([]string{"--no-replace-objects"}, args...)...)
44 cmd.Dir = repo
45 cmd.Env = gitEnvironment(os.Environ())
46 return cmd
47}
48
49// gitPush pushes to a remote. It is the one git this program runs that
50// keeps the person's own configuration — how a remote's URL is rewritten,
51// which ssh command reaches it — because it reads nothing it decides on.
52// Replacement refs are still off.
53func gitPush(repo string, args ...string) (string, error) {
54 cmd := exec.Command("git", append([]string{"--no-replace-objects", "push"}, args...)...)
55 cmd.Dir = repo
56 cmd.Env = append(os.Environ(), "GIT_NO_REPLACE_OBJECTS=1")
57 var out, errb bytes.Buffer
58 cmd.Stdout = &out
59 cmd.Stderr = &errb
60 if err := cmd.Run(); err != nil {
61 return "", fmt.Errorf("git push %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
62 }
63 return out.String(), nil
64}
65
66// gitEnvironment is the environment gitCommand runs git in: the caller's,
67// less every GIT_ variable but safe.directory entries, with git's own
68// configuration fixed.
69func gitEnvironment(inherited []string) []string {
70 vars := map[string]string{}
71 var kept []string
72 for _, kv := range inherited {
73 name, value, _ := strings.Cut(kv, "=")
74 if strings.HasPrefix(name, "GIT_") {
75 vars[name] = value
76 continue
77 }
78 kept = append(kept, kv)
79 }
80
81 var safe []string
82 count, _ := strconv.Atoi(vars["GIT_CONFIG_COUNT"])
83 for i := 0; i < count; i++ {
84 if strings.EqualFold(vars[fmt.Sprintf("GIT_CONFIG_KEY_%d", i)], "safe.directory") {
85 safe = append(safe, vars[fmt.Sprintf("GIT_CONFIG_VALUE_%d", i)])
86 }
87 }
88 if len(safe) > 0 {
89 kept = append(kept, fmt.Sprintf("GIT_CONFIG_COUNT=%d", len(safe)))
90 for i, dir := range safe {
91 kept = append(kept,
92 fmt.Sprintf("GIT_CONFIG_KEY_%d=safe.directory", i),
93 fmt.Sprintf("GIT_CONFIG_VALUE_%d=%s", i, dir))
94 }
95 }
96
97 return append(kept,
98 "GIT_CONFIG_NOSYSTEM=1",
99 "GIT_CONFIG_SYSTEM=/dev/null",
100 "GIT_CONFIG_GLOBAL=/dev/null",
101 "GIT_NO_REPLACE_OBJECTS=1",
102 "GIT_ATTR_NOSYSTEM=1",
103 "GIT_TERMINAL_PROMPT=0",
104 )
105}
106
107func gitInput(repo string, stdin []byte, args ...string) (string, error) {
108 cmd := gitCommand(repo, args...)
109 if stdin != nil {
110 cmd.Stdin = bytes.NewReader(stdin)
111 }
112 var out, errb bytes.Buffer
113 cmd.Stdout = &out
114 cmd.Stderr = &errb
115 if err := cmd.Run(); err != nil {
116 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
117 }
118 return out.String(), nil
119}
120
121func gitLine(repo string, args ...string) (string, error) {
122 out, err := git(repo, args...)
123 return strings.TrimSpace(out), err
124}
125
126// gitBlobSums returns the SHA-256 of each named blob's content, in the
127// order asked for. One `cat-file --batch` serves the whole tree.
128func gitBlobSums(repo string, oids []string) ([][32]byte, error) {
129 sums := make([][32]byte, len(oids))
130 if len(oids) == 0 {
131 return sums, nil
132 }
133 cmd := gitCommand(repo, "cat-file", "--batch")
134 cmd.Stdin = strings.NewReader(strings.Join(oids, "\n") + "\n")
135 var errb bytes.Buffer
136 cmd.Stderr = &errb
137 stdout, err := cmd.StdoutPipe()
138 if err != nil {
139 return nil, err
140 }
141 if err := cmd.Start(); err != nil {
142 return nil, err
143 }
144 r := bufio.NewReader(stdout)
145 for i := range oids {
146 header, err := r.ReadString('\n')
147 if err != nil {
148 return nil, fmt.Errorf("cat-file: %w: %s", err, strings.TrimSpace(errb.String()))
149 }
150 fields := strings.Fields(strings.TrimSpace(header))
151 if len(fields) != 3 || fields[1] != "blob" {
152 return nil, fmt.Errorf("cat-file: unexpected header %q for %s", strings.TrimSpace(header), oids[i])
153 }
154 size, err := strconv.Atoi(fields[2])
155 if err != nil {
156 return nil, fmt.Errorf("cat-file: bad size in %q", strings.TrimSpace(header))
157 }
158 h := sha256.New()
159 if _, err := io.CopyN(h, r, int64(size)); err != nil {
160 return nil, fmt.Errorf("cat-file: reading %s: %w", oids[i], err)
161 }
162 if _, err := r.Discard(1); err != nil { // the record's trailing newline
163 return nil, err
164 }
165 copy(sums[i][:], h.Sum(nil))
166 }
167 if err := cmd.Wait(); err != nil {
168 return nil, fmt.Errorf("cat-file: %w: %s", err, strings.TrimSpace(errb.String()))
169 }
170 return sums, nil
171}
172
173// exportTree writes a revision's tree to dir. Checks run over the exported
174// tree rather than the working tree, so what was checked is exactly what
175// the subject digest names — an uncommitted edit cannot ride along inside
176// an attestation.
177func exportTree(repo, rev, dir string) error {
178 cmd := gitCommand(repo, "archive", "--format=tar", rev)
179 var errb bytes.Buffer
180 cmd.Stderr = &errb
181 stdout, err := cmd.StdoutPipe()
182 if err != nil {
183 return err
184 }
185 if err := cmd.Start(); err != nil {
186 return err
187 }
188 tr := tar.NewReader(stdout)
189 for {
190 h, err := tr.Next()
191 if err == io.EOF {
192 break
193 }
194 if err != nil {
195 return fmt.Errorf("git archive: %w", err)
196 }
197 if h.Typeflag == tar.TypeXGlobalHeader {
198 continue // git archive stamps the commit id here; not a tree entry
199 }
200 target := filepath.Join(dir, filepath.Clean("/"+h.Name))
201 switch h.Typeflag {
202 case tar.TypeDir:
203 if err := os.MkdirAll(target, 0o755); err != nil {
204 return err
205 }
206 case tar.TypeSymlink:
207 if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
208 return err
209 }
210 if err := os.Symlink(h.Linkname, target); err != nil {
211 return err
212 }
213 case tar.TypeReg:
214 if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
215 return err
216 }
217 f, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(h.Mode)&0o777)
218 if err != nil {
219 return err
220 }
221 if _, err := io.Copy(f, tr); err != nil {
222 f.Close()
223 return err
224 }
225 if err := f.Close(); err != nil {
226 return err
227 }
228 default:
229 return fmt.Errorf("git archive: unsupported entry %s", h.Name)
230 }
231 }
232 if err := cmd.Wait(); err != nil {
233 return fmt.Errorf("git archive: %w: %s", err, strings.TrimSpace(errb.String()))
234 }
235 return nil
236}
237
238// writeBlob stores content as a loose object and returns its id.
239func writeBlob(repo string, content []byte) (string, error) {
240 out, err := gitInput(repo, content, "hash-object", "-w", "--stdin")
241 return strings.TrimSpace(out), err
242}
243
244// mkTree builds a tree object from named blobs and subtrees. Deterministic
245// by construction: the attestation ref's value is a function of the
246// statements under it and nothing else, so re-running attest over an
247// unchanged tree produces the identical ref and a create-only push stays
248// idempotent.
249func mkTree(repo string, blobs, trees map[string]string) (string, error) {
250 var lines []string
251 for name, oid := range blobs {
252 lines = append(lines, fmt.Sprintf("100644 blob %s\t%s", oid, name))
253 }
254 for name, oid := range trees {
255 lines = append(lines, fmt.Sprintf("040000 tree %s\t%s", oid, name))
256 }
257 sort.Strings(lines)
258 out, err := gitInput(repo, []byte(strings.Join(lines, "\n")+"\n"), "mktree")
259 return strings.TrimSpace(out), err
260}