gunk-dev/the-valley

git.go

source6a7605f70901main's published tip history
7.2 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, in a fixed environment, and
27// killed if attest dies (dieWithParent).
28//
29// A replacement ref makes one object stand in for another wherever git
30// looks it up. Left on, a refs/replace/* in the repository could make the
31// tree this program digests, exports or verifies be some other tree than
32// the revision names — so a verification could pass for a revision that
33// is not the one attested, and a run could check one tree and sign for
34// another.
35//
36// No GIT_ variable is inherited but command-scope configuration naming
37// safe.directory, which a caller that does not own the repository needs
38// (the integrator's unit supplies it this way). A GIT_DIR or
39// GIT_OBJECT_DIRECTORY could point git at other objects, and a
40// GIT_CONFIG_PARAMETERS could change how it reads them. System and user
41// configuration are not read. The integrator's environment is fixed the
42// same way (integrator/main.go), and sigverify's.
43func gitCommand(repo string, args ...string) *exec.Cmd {
44 cmd := exec.Command("git", append([]string{"--no-replace-objects"}, args...)...)
45 cmd.Dir = repo
46 cmd.Env = gitEnvironment(os.Environ())
47 cmd.SysProcAttr = dieWithParent()
48 return cmd
49}
50
51// gitRemote runs a git that talks to a remote: push, ls-remote and fetch.
52// These are the gits this program runs that keep the person's own
53// configuration — how a remote's URL is rewritten, which ssh command
54// reaches it — because nothing they read is signed: what a fetch brings is
55// only kept beside the new notes and pushed back, where the remote's hook
56// checks it. Replacement refs are still off, and the git is killed if
57// attest dies (dieWithParent).
58func gitRemote(repo string, args ...string) (string, error) {
59 cmd := exec.Command("git", append([]string{"--no-replace-objects"}, args...)...)
60 cmd.Dir = repo
61 cmd.Env = append(os.Environ(), "GIT_NO_REPLACE_OBJECTS=1")
62 cmd.SysProcAttr = dieWithParent()
63 var out, errb bytes.Buffer
64 cmd.Stdout = &out
65 cmd.Stderr = &errb
66 if err := cmd.Run(); err != nil {
67 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
68 }
69 return out.String(), nil
70}
71
72// gitEnvironment is the environment gitCommand runs git in: the caller's,
73// less every GIT_ variable but safe.directory entries, with git's own
74// configuration fixed.
75func gitEnvironment(inherited []string) []string {
76 vars := map[string]string{}
77 var kept []string
78 for _, kv := range inherited {
79 name, value, _ := strings.Cut(kv, "=")
80 if strings.HasPrefix(name, "GIT_") {
81 vars[name] = value
82 continue
83 }
84 kept = append(kept, kv)
85 }
86
87 var safe []string
88 count, _ := strconv.Atoi(vars["GIT_CONFIG_COUNT"])
89 for i := 0; i < count; i++ {
90 if strings.EqualFold(vars[fmt.Sprintf("GIT_CONFIG_KEY_%d", i)], "safe.directory") {
91 safe = append(safe, vars[fmt.Sprintf("GIT_CONFIG_VALUE_%d", i)])
92 }
93 }
94 if len(safe) > 0 {
95 kept = append(kept, fmt.Sprintf("GIT_CONFIG_COUNT=%d", len(safe)))
96 for i, dir := range safe {
97 kept = append(kept,
98 fmt.Sprintf("GIT_CONFIG_KEY_%d=safe.directory", i),
99 fmt.Sprintf("GIT_CONFIG_VALUE_%d=%s", i, dir))
100 }
101 }
102
103 return append(kept,
104 "GIT_CONFIG_NOSYSTEM=1",
105 "GIT_CONFIG_SYSTEM=/dev/null",
106 "GIT_CONFIG_GLOBAL=/dev/null",
107 "GIT_NO_REPLACE_OBJECTS=1",
108 "GIT_ATTR_NOSYSTEM=1",
109 "GIT_TERMINAL_PROMPT=0",
110 )
111}
112
113func gitInput(repo string, stdin []byte, args ...string) (string, error) {
114 cmd := gitCommand(repo, args...)
115 if stdin != nil {
116 cmd.Stdin = bytes.NewReader(stdin)
117 }
118 var out, errb bytes.Buffer
119 cmd.Stdout = &out
120 cmd.Stderr = &errb
121 if err := cmd.Run(); err != nil {
122 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String()))
123 }
124 return out.String(), nil
125}
126
127func gitLine(repo string, args ...string) (string, error) {
128 out, err := git(repo, args...)
129 return strings.TrimSpace(out), err
130}
131
132// gitTreeEntries reads the entries of a revision's tree, as valley-tree-v1
133// reads them, with gitCommand's git.
134func gitTreeEntries(repo, rev string) ([]statement.Entry, error) {
135 return statement.GitTree(func(args ...string) *exec.Cmd { return gitCommand(repo, args...) }, rev)
136}
137
138// exportTree writes a revision's tree to dir. Checks run over the exported
139// tree rather than the working tree, so what was checked is exactly what
140// the subject digest names — an uncommitted edit cannot ride along inside
141// an attestation.
142func exportTree(repo, rev, dir string) error {
143 cmd := gitCommand(repo, "archive", "--format=tar", rev)
144 var errb bytes.Buffer
145 cmd.Stderr = &errb
146 stdout, err := cmd.StdoutPipe()
147 if err != nil {
148 return err
149 }
150 if err := cmd.Start(); err != nil {
151 return err
152 }
153 tr := tar.NewReader(stdout)
154 for {
155 h, err := tr.Next()
156 if err == io.EOF {
157 break
158 }
159 if err != nil {
160 return fmt.Errorf("git archive: %w", err)
161 }
162 if h.Typeflag == tar.TypeXGlobalHeader {
163 continue // git archive stamps the commit id here; not a tree entry
164 }
165 target := filepath.Join(dir, filepath.Clean("/"+h.Name))
166 switch h.Typeflag {
167 case tar.TypeDir:
168 if err := os.MkdirAll(target, 0o755); err != nil {
169 return err
170 }
171 case tar.TypeSymlink:
172 if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
173 return err
174 }
175 if err := os.Symlink(h.Linkname, target); err != nil {
176 return err
177 }
178 case tar.TypeReg:
179 if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
180 return err
181 }
182 f, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(h.Mode)&0o777)
183 if err != nil {
184 return err
185 }
186 if _, err := io.Copy(f, tr); err != nil {
187 f.Close()
188 return err
189 }
190 if err := f.Close(); err != nil {
191 return err
192 }
193 default:
194 return fmt.Errorf("git archive: unsupported entry %s", h.Name)
195 }
196 }
197 if err := cmd.Wait(); err != nil {
198 return fmt.Errorf("git archive: %w: %s", err, strings.TrimSpace(errb.String()))
199 }
200 return nil
201}
202
203// writeBlob stores content as a loose object and returns its id.
204func writeBlob(repo string, content []byte) (string, error) {
205 out, err := gitInput(repo, content, "hash-object", "-w", "--stdin")
206 return strings.TrimSpace(out), err
207}
208
209// mkTree builds a tree object from named blobs and subtrees. Deterministic
210// by construction: the attestation ref's value is a function of the
211// statements under it and nothing else, so re-running attest over an
212// unchanged tree produces the identical ref.
213func mkTree(repo string, blobs, trees map[string]string) (string, error) {
214 var lines []string
215 for name, oid := range blobs {
216 lines = append(lines, fmt.Sprintf("100644 blob %s\t%s", oid, name))
217 }
218 for name, oid := range trees {
219 lines = append(lines, fmt.Sprintf("040000 tree %s\t%s", oid, name))
220 }
221 sort.Strings(lines)
222 out, err := gitInput(repo, []byte(strings.Join(lines, "\n")+"\n"), "mktree")
223 return strings.TrimSpace(out), err
224}