gunk-dev/the-valley

git.go

source58e68be0d151main's published tip history
7.0 KiB
1package main
2
3import (
4 "archive/tar"
5 "bytes"
6 "fmt"
7 "io"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "sort"
12 "strconv"
13 "strings"
14
15 "the-valley/note/statement"
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// gitTreeEntries reads the entries of a revision's tree, as valley-tree-v1
129// reads them, with gitCommand's git.
130func gitTreeEntries(repo, rev string) ([]statement.Entry, error) {
131 return statement.GitTree(func(args ...string) *exec.Cmd { return gitCommand(repo, args...) }, rev)
132}
133
134// exportTree writes a revision's tree to dir. Checks run over the exported
135// tree rather than the working tree, so what was checked is exactly what
136// the subject digest names — an uncommitted edit cannot ride along inside
137// an attestation.
138func exportTree(repo, rev, dir string) error {
139 cmd := gitCommand(repo, "archive", "--format=tar", rev)
140 var errb bytes.Buffer
141 cmd.Stderr = &errb
142 stdout, err := cmd.StdoutPipe()
143 if err != nil {
144 return err
145 }
146 if err := cmd.Start(); err != nil {
147 return err
148 }
149 tr := tar.NewReader(stdout)
150 for {
151 h, err := tr.Next()
152 if err == io.EOF {
153 break
154 }
155 if err != nil {
156 return fmt.Errorf("git archive: %w", err)
157 }
158 if h.Typeflag == tar.TypeXGlobalHeader {
159 continue // git archive stamps the commit id here; not a tree entry
160 }
161 target := filepath.Join(dir, filepath.Clean("/"+h.Name))
162 switch h.Typeflag {
163 case tar.TypeDir:
164 if err := os.MkdirAll(target, 0o755); err != nil {
165 return err
166 }
167 case tar.TypeSymlink:
168 if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
169 return err
170 }
171 if err := os.Symlink(h.Linkname, target); err != nil {
172 return err
173 }
174 case tar.TypeReg:
175 if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
176 return err
177 }
178 f, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(h.Mode)&0o777)
179 if err != nil {
180 return err
181 }
182 if _, err := io.Copy(f, tr); err != nil {
183 f.Close()
184 return err
185 }
186 if err := f.Close(); err != nil {
187 return err
188 }
189 default:
190 return fmt.Errorf("git archive: unsupported entry %s", h.Name)
191 }
192 }
193 if err := cmd.Wait(); err != nil {
194 return fmt.Errorf("git archive: %w: %s", err, strings.TrimSpace(errb.String()))
195 }
196 return nil
197}
198
199// writeBlob stores content as a loose object and returns its id.
200func writeBlob(repo string, content []byte) (string, error) {
201 out, err := gitInput(repo, content, "hash-object", "-w", "--stdin")
202 return strings.TrimSpace(out), err
203}
204
205// mkTree builds a tree object from named blobs and subtrees. Deterministic
206// by construction: the attestation ref's value is a function of the
207// statements under it and nothing else, so re-running attest over an
208// unchanged tree produces the identical ref.
209func mkTree(repo string, blobs, trees map[string]string) (string, error) {
210 var lines []string
211 for name, oid := range blobs {
212 lines = append(lines, fmt.Sprintf("100644 blob %s\t%s", oid, name))
213 }
214 for name, oid := range trees {
215 lines = append(lines, fmt.Sprintf("040000 tree %s\t%s", oid, name))
216 }
217 sort.Strings(lines)
218 out, err := gitInput(repo, []byte(strings.Join(lines, "\n")+"\n"), "mktree")
219 return strings.TrimSpace(out), err
220}