gunk-dev/the-valley

git.go

source57b716740065main's published tip history
8.3 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// gitRemote runs a git that talks to a remote: push, ls-remote and fetch.
50// These are the gits this program runs that keep the person's own
51// configuration — how a remote's URL is rewritten, which ssh command
52// reaches it — because nothing they read is signed: what a fetch brings is
53// only kept beside the new notes and pushed back, where the remote's hook
54// checks it. Replacement refs are still off.
55func gitRemote(repo string, args ...string) (string, error) {
56 cmd := exec.Command("git", append([]string{"--no-replace-objects"}, args...)...)
57 cmd.Dir = repo
58 cmd.Env = append(os.Environ(), "GIT_NO_REPLACE_OBJECTS=1")
59 var out, errb bytes.Buffer
60 cmd.Stdout = &out
61 cmd.Stderr = &errb
62 if err := cmd.Run(); err != nil {
63 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
64 }
65 return out.String(), nil
66}
67
68// gitEnvironment is the environment gitCommand runs git in: the caller's,
69// less every GIT_ variable but safe.directory entries, with git's own
70// configuration fixed.
71func gitEnvironment(inherited []string) []string {
72 vars := map[string]string{}
73 var kept []string
74 for _, kv := range inherited {
75 name, value, _ := strings.Cut(kv, "=")
76 if strings.HasPrefix(name, "GIT_") {
77 vars[name] = value
78 continue
79 }
80 kept = append(kept, kv)
81 }
82
83 var safe []string
84 count, _ := strconv.Atoi(vars["GIT_CONFIG_COUNT"])
85 for i := 0; i < count; i++ {
86 if strings.EqualFold(vars[fmt.Sprintf("GIT_CONFIG_KEY_%d", i)], "safe.directory") {
87 safe = append(safe, vars[fmt.Sprintf("GIT_CONFIG_VALUE_%d", i)])
88 }
89 }
90 if len(safe) > 0 {
91 kept = append(kept, fmt.Sprintf("GIT_CONFIG_COUNT=%d", len(safe)))
92 for i, dir := range safe {
93 kept = append(kept,
94 fmt.Sprintf("GIT_CONFIG_KEY_%d=safe.directory", i),
95 fmt.Sprintf("GIT_CONFIG_VALUE_%d=%s", i, dir))
96 }
97 }
98
99 return append(kept,
100 "GIT_CONFIG_NOSYSTEM=1",
101 "GIT_CONFIG_SYSTEM=/dev/null",
102 "GIT_CONFIG_GLOBAL=/dev/null",
103 "GIT_NO_REPLACE_OBJECTS=1",
104 "GIT_ATTR_NOSYSTEM=1",
105 "GIT_TERMINAL_PROMPT=0",
106 )
107}
108
109func gitInput(repo string, stdin []byte, args ...string) (string, error) {
110 cmd := gitCommand(repo, args...)
111 if stdin != nil {
112 cmd.Stdin = bytes.NewReader(stdin)
113 }
114 var out, errb bytes.Buffer
115 cmd.Stdout = &out
116 cmd.Stderr = &errb
117 if err := cmd.Run(); err != nil {
118 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
119 }
120 return out.String(), nil
121}
122
123func gitLine(repo string, args ...string) (string, error) {
124 out, err := git(repo, args...)
125 return strings.TrimSpace(out), err
126}
127
128// gitBlobSums returns the SHA-256 of each named blob's content, in the
129// order asked for. One `cat-file --batch` serves the whole tree.
130func gitBlobSums(repo string, oids []string) ([][32]byte, error) {
131 sums := make([][32]byte, len(oids))
132 if len(oids) == 0 {
133 return sums, nil
134 }
135 cmd := gitCommand(repo, "cat-file", "--batch")
136 cmd.Stdin = strings.NewReader(strings.Join(oids, "\n") + "\n")
137 var errb bytes.Buffer
138 cmd.Stderr = &errb
139 stdout, err := cmd.StdoutPipe()
140 if err != nil {
141 return nil, err
142 }
143 if err := cmd.Start(); err != nil {
144 return nil, err
145 }
146 r := bufio.NewReader(stdout)
147 for i := range oids {
148 header, err := r.ReadString('\n')
149 if err != nil {
150 return nil, fmt.Errorf("cat-file: %w: %s", err, strings.TrimSpace(errb.String()))
151 }
152 fields := strings.Fields(strings.TrimSpace(header))
153 if len(fields) != 3 || fields[1] != "blob" {
154 return nil, fmt.Errorf("cat-file: unexpected header %q for %s", strings.TrimSpace(header), oids[i])
155 }
156 size, err := strconv.Atoi(fields[2])
157 if err != nil {
158 return nil, fmt.Errorf("cat-file: bad size in %q", strings.TrimSpace(header))
159 }
160 h := sha256.New()
161 if _, err := io.CopyN(h, r, int64(size)); err != nil {
162 return nil, fmt.Errorf("cat-file: reading %s: %w", oids[i], err)
163 }
164 if _, err := r.Discard(1); err != nil { // the record's trailing newline
165 return nil, err
166 }
167 copy(sums[i][:], h.Sum(nil))
168 }
169 if err := cmd.Wait(); err != nil {
170 return nil, fmt.Errorf("cat-file: %w: %s", err, strings.TrimSpace(errb.String()))
171 }
172 return sums, nil
173}
174
175// exportTree writes a revision's tree to dir. Checks run over the exported
176// tree rather than the working tree, so what was checked is exactly what
177// the subject digest names — an uncommitted edit cannot ride along inside
178// an attestation.
179func exportTree(repo, rev, dir string) error {
180 cmd := gitCommand(repo, "archive", "--format=tar", rev)
181 var errb bytes.Buffer
182 cmd.Stderr = &errb
183 stdout, err := cmd.StdoutPipe()
184 if err != nil {
185 return err
186 }
187 if err := cmd.Start(); err != nil {
188 return err
189 }
190 tr := tar.NewReader(stdout)
191 for {
192 h, err := tr.Next()
193 if err == io.EOF {
194 break
195 }
196 if err != nil {
197 return fmt.Errorf("git archive: %w", err)
198 }
199 if h.Typeflag == tar.TypeXGlobalHeader {
200 continue // git archive stamps the commit id here; not a tree entry
201 }
202 target := filepath.Join(dir, filepath.Clean("/"+h.Name))
203 switch h.Typeflag {
204 case tar.TypeDir:
205 if err := os.MkdirAll(target, 0o755); err != nil {
206 return err
207 }
208 case tar.TypeSymlink:
209 if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
210 return err
211 }
212 if err := os.Symlink(h.Linkname, target); err != nil {
213 return err
214 }
215 case tar.TypeReg:
216 if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
217 return err
218 }
219 f, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(h.Mode)&0o777)
220 if err != nil {
221 return err
222 }
223 if _, err := io.Copy(f, tr); err != nil {
224 f.Close()
225 return err
226 }
227 if err := f.Close(); err != nil {
228 return err
229 }
230 default:
231 return fmt.Errorf("git archive: unsupported entry %s", h.Name)
232 }
233 }
234 if err := cmd.Wait(); err != nil {
235 return fmt.Errorf("git archive: %w: %s", err, strings.TrimSpace(errb.String()))
236 }
237 return nil
238}
239
240// writeBlob stores content as a loose object and returns its id.
241func writeBlob(repo string, content []byte) (string, error) {
242 out, err := gitInput(repo, content, "hash-object", "-w", "--stdin")
243 return strings.TrimSpace(out), err
244}
245
246// mkTree builds a tree object from named blobs and subtrees. Deterministic
247// by construction: the attestation ref's value is a function of the
248// statements under it and nothing else, so re-running attest over an
249// unchanged tree produces the identical ref.
250func mkTree(repo string, blobs, trees map[string]string) (string, error) {
251 var lines []string
252 for name, oid := range blobs {
253 lines = append(lines, fmt.Sprintf("100644 blob %s\t%s", oid, name))
254 }
255 for name, oid := range trees {
256 lines = append(lines, fmt.Sprintf("040000 tree %s\t%s", oid, name))
257 }
258 sort.Strings(lines)
259 out, err := gitInput(repo, []byte(strings.Join(lines, "\n")+"\n"), "mktree")
260 return strings.TrimSpace(out), err
261}