gunk-dev/the-valley

valley.go

sourcecb3560859eeamain's published tip history
25.4 KiB
1package main
2
3import (
4 "bytes"
5 "compress/zlib"
6 "context"
7 "crypto/sha1"
8 "crypto/sha256"
9 "encoding/hex"
10 "encoding/json"
11 "errors"
12 "fmt"
13 "io"
14 "os"
15 "os/exec"
16 "path/filepath"
17 "slices"
18 "sort"
19 "strings"
20 "time"
21
22 "the-valley/readaccess"
23 "the-valley/webui/export"
24)
25
26// readAttempts is how many times a pass reads the valley before it gives
27// up on inputs that keep changing under it.
28const readAttempts = 3
29
30// cueTimeout is how long a cue run may take. A run past it fails the pass:
31// how long cue takes depends on the host as much as on what it reads.
32var cueTimeout = time.Minute
33
34// The bounds on what a pass holds of a program's output. A program that
35// prints more than its bound to stdout fails, and what it prints to stderr
36// past its bound is dropped.
37const (
38 maxValleyOutput = 64 << 20
39 maxGitOutput = 4 << 20
40 maxStderr = 64 << 10
41)
42
43// reading is what a pass read: the export, each exported project's mirror,
44// and the projects it keeps private.
45type reading struct {
46 export *export.Export
47 json []byte
48 mirrors map[string]string
49 private []string
50}
51
52// collect reads the valley and builds the export. It fetches the instance
53// repository once, and every read of the pass reads the instance at that
54// fetch. Each knot's detail is read after the plan, so a write to the graph
55// in between makes the two disagree; export.Build says so with
56// ErrInconsistent, and collect reads everything again.
57func (p *publisher) collect(ctx context.Context) (*reading, error) {
58 if err := p.access.CheckSchemas(ctx); err != nil {
59 return nil, err
60 }
61 inst, err := p.fetchInstance(ctx)
62 if err != nil {
63 return nil, err
64 }
65 if err := p.prepareCLICaches(ctx, inst.projects); err != nil {
66 return nil, err
67 }
68 if err := p.preparePointer(ctx); err != nil {
69 return nil, err
70 }
71 for attempt := 1; attempt <= readAttempts; attempt++ {
72 var r *reading
73 r, err = p.read(ctx, inst)
74 if err == nil {
75 return r, nil
76 }
77 if !errors.Is(err, export.ErrInconsistent) {
78 return nil, err
79 }
80 p.warn("%v; reading the valley again", err)
81 }
82 return nil, fmt.Errorf("the valley changed under every one of %d reads: %w", readAttempts, err)
83}
84
85// planListing and pendingListing are what the publisher reads of the
86// valley's JSON itself: which projects there are, each project's knots,
87// and where each can be read. export.Build reads the rest.
88type (
89 planListing struct {
90 Projects []struct {
91 Project string `json:"project"`
92 Knots []struct {
93 ID string `json:"id"`
94 } `json:"knots"`
95 } `json:"projects"`
96 }
97 pendingListing struct {
98 Repos []pendingRepo `json:"repos"`
99 }
100 pendingRepo struct {
101 Repo string `json:"repo"`
102 URL string `json:"url"`
103 Error *string `json:"error"`
104 }
105)
106
107// read is one read of the valley, with the instance as fetchInstance read
108// it. A project is public when anyone may read it at the destination, by
109// the read grants in the instance's registry and the project's own
110// policy/read. It is private when no grant to anyone names it, and when its
111// policy/read is missing, invalid, or does not let anyone read it. Any
112// other failure to read a project a grant names ends the pass: an export
113// without it would take it off the web.
114func (p *publisher) read(ctx context.Context, inst instanceRead) (*reading, error) {
115 grants, err := p.access.Grants(ctx, p.origin, inst.tip, p.cfg.registryDir, p.cfg.destination, p.now())
116 var bad *readaccess.InvalidError
117 switch {
118 case errors.Is(err, readaccess.ErrMissing):
119 case errors.As(err, &bad):
120 p.warn("the instance's identity registry at %s is not valid, so every project is private: %v", short(inst.tip), err)
121 case err != nil:
122 return nil, fmt.Errorf("could not read the instance's identity registry at %s: %w", short(inst.tip), err)
123 }
124
125 planJSON, err := p.valley(ctx, p.pointer, "plan", "--all", "--json")
126 if err != nil {
127 return nil, err
128 }
129 pendingJSON, err := p.valley(ctx, p.pointer, "pending", "--all", "--json")
130 if err != nil {
131 return nil, err
132 }
133 var plan planListing
134 if err := json.Unmarshal(planJSON, &plan); err != nil {
135 return nil, fmt.Errorf("valley plan --all --json: %w", err)
136 }
137 var pending pendingListing
138 if err := json.Unmarshal(pendingJSON, &pending); err != nil {
139 return nil, fmt.Errorf("valley pending --all --json: %w", err)
140 }
141 // The CLI lists what the instance repository publishes, and nothing
142 // else. When discovery fails it lists the repository it runs in alone,
143 // which would publish an export without the other projects.
144 var planned, listed []string
145 for _, proj := range plan.Projects {
146 planned = append(planned, proj.Project)
147 }
148 repos := map[string]pendingRepo{}
149 for _, r := range pending.Repos {
150 listed = append(listed, r.Repo)
151 repos[r.Repo] = r
152 }
153 for _, l := range []struct {
154 command string
155 names []string
156 }{{"valley plan --all", planned}, {"valley pending --all", listed}} {
157 sort.Strings(l.names)
158 if !slices.Equal(l.names, inst.projects) {
159 return nil, fmt.Errorf("%s lists %s, and the instance repository publishes %s at %s, so nothing is published",
160 l.command, listNames(l.names), listNames(inst.projects), projectsRef)
161 }
162 }
163
164 r := &reading{mirrors: map[string]string{}}
165 in := export.Inputs{
166 Plan: planJSON, Pending: pendingJSON,
167 Visibility: map[string]export.Visibility{}, SourceTips: map[string]string{},
168 Principals: p.principals,
169 }
170 for _, proj := range plan.Projects {
171 name := proj.Project
172 public := false
173 if grants.Selects(readaccess.Anyone, name) {
174 if public, err = p.readableByAnyone(ctx, name, repos[name], grants, in.SourceTips, r.mirrors); err != nil {
175 return nil, err
176 }
177 }
178 if !public {
179 r.private = append(r.private, name)
180 continue
181 }
182 in.Visibility[name] = export.Public
183 for _, k := range proj.Knots {
184 detail, err := p.valley(ctx, p.origin, "knot", "show", "--project", name, k.ID, "--json")
185 if err != nil {
186 return nil, err
187 }
188 in.Details = append(in.Details, detail)
189 }
190 }
191 sort.Strings(r.private)
192 if r.export, err = export.Build(in); err != nil {
193 return nil, err
194 }
195 if r.json, err = r.export.Encode(); err != nil {
196 return nil, err
197 }
198 return r, nil
199}
200
201// listNames is a list of projects for a message.
202func listNames(list []string) string {
203 if len(list) == 0 {
204 return "none"
205 }
206 return strings.Join(list, ", ")
207}
208
209// readableByAnyone decides whether a project a read grant to anyone names
210// is public: its own policy/read on main lets anyone read it, under that
211// grant. For a public project it records main's tip and the mirror it was
212// fetched into. A project with no main, or whose policy/read is missing,
213// invalid or does not let anyone read it, is private, and an invalid
214// policy is said. A project that cannot be read is an error.
215func (p *publisher) readableByAnyone(ctx context.Context, name string, repo pendingRepo,
216 grants readaccess.Grants, tips, mirrors map[string]string) (bool, error) {
217 if !export.ValidName(name) {
218 p.warn("%q is not a project name, so it is private", name)
219 return false, nil
220 }
221 if repo.Error != nil {
222 return false, fmt.Errorf("%s: the pending listing could not read it: %s", name, *repo.Error)
223 }
224 if repo.URL == "" {
225 return false, fmt.Errorf("%s: the pending listing gives no URL to read it from", name)
226 }
227 mirror, tip, err := p.fetchMain(ctx, name, repo.URL)
228 if errors.Is(err, errNoMain) {
229 return false, nil
230 }
231 if err != nil {
232 return false, fmt.Errorf("%s: could not read main: %w", name, err)
233 }
234 consent, err := p.access.Consent(ctx, mirror, tip, name)
235 var bad *readaccess.InvalidError
236 switch {
237 case errors.Is(err, readaccess.ErrMissing):
238 return false, nil
239 case errors.As(err, &bad):
240 p.warn("%s: its policy/read at %s is not valid, so it is private: %v", name, short(tip), err)
241 return false, nil
242 case err != nil:
243 return false, fmt.Errorf("%s: could not read its policy/read at %s: %w", name, short(tip), err)
244 case !grants.May(readaccess.Anyone, consent):
245 return false, nil
246 }
247 tips[name], mirrors[name] = tip, mirror
248 return true, nil
249}
250
251// preparePointer makes the repository valley plan and valley pending run
252// in: a bare repository whose origin is itself, and whose main holds one
253// file, policy/valley, naming the instance repository. The CLI finds the
254// instance at policy/valley on origin's main, as it does from any project,
255// and follows it no further. So it reads the projects and the signers the
256// instance repository publishes, and never reads the instance repository's
257// main, where a policy/valley could land and be taken away again while the
258// pass reads. Only the publisher writes to this repository, and main's
259// commit is the same in every pass for the same --instance-repo.
260func (p *publisher) preparePointer(ctx context.Context) error {
261 files, err := sharedFiles(ctx, p.cfg.instanceRepo, nil)
262 if err != nil {
263 return err
264 }
265 // Build the four small Git objects in memory so their compressed sizes
266 // are known before any cache file is written.
267 object := func(kind string, data []byte) []byte {
268 raw := append([]byte(fmt.Sprintf("%s %d\x00", kind, len(data))), data...)
269 h := sha1.New()
270 if strings.Contains(files["config"], "objectformat = sha256") {
271 h = sha256.New()
272 }
273 h.Write(raw)
274 digest := h.Sum(nil)
275 name := hex.EncodeToString(digest)
276 var compressed bytes.Buffer
277 w := zlib.NewWriter(&compressed)
278 _, _ = w.Write(raw)
279 _ = w.Close()
280 files["objects/"+name[:2]+"/"+name[2:]] = compressed.String()
281 return digest
282 }
283 blob := object("blob", []byte(p.cfg.instanceRepo+"\n"))
284 policy := object("tree", append([]byte("100644 valley\x00"), blob...))
285 tree := object("tree", append([]byte("40000 policy\x00"), policy...))
286 commit := object("commit", []byte(fmt.Sprintf("tree %x\nauthor valley-web-publish <operator@example.org> 0 +0000\ncommitter valley-web-publish <operator@example.org> 0 +0000\n\npolicy/valley: the instance the publisher reads\n", tree)))
287 files["refs/heads/main"] = hex.EncodeToString(commit) + "\n"
288 files["config"] = strings.Replace(files["config"], quoteGit(p.cfg.instanceRepo), quoteGit(p.pointer), 1)
289 return p.stageFiles(p.pointer, files)
290}
291
292// prepareCLICaches uses the CLI's URL hash and .git layout (status/list.go).
293// Both the project and instance objects are borrowed: the CLI reads the
294// instance's signers while inspecting each project's records.
295func (p *publisher) prepareCLICaches(ctx context.Context, names []string) error {
296 instance, err := sharedFiles(ctx, p.cfg.instanceRepo, nil)
297 if err != nil {
298 return err
299 }
300 reposDir := p.cliReposDir()
301 if err := os.MkdirAll(reposDir, 0o700); err != nil {
302 return err
303 }
304 // A killed pass may leave the parent sealed. Only the publisher
305 // stages repositories; the CLI may only use the current staged set.
306 if err := os.Chmod(reposDir, 0o700); err != nil {
307 return err
308 }
309 urls := make(map[string]string, len(names))
310 staged := make(map[string]bool, len(names))
311 for _, name := range names {
312 if !export.ValidName(name) {
313 return fmt.Errorf("invalid project name %q", name)
314 }
315 u := strings.TrimRight(p.cfg.instanceRepo, "/")
316 cut := strings.LastIndex(u, "/") + 1
317 suffix := ""
318 if strings.HasSuffix(u[cut:], ".git") {
319 suffix = ".git"
320 }
321 url := u[:cut] + name + suffix
322 urls[name] = url
323 sum := sha256.Sum256([]byte(url))
324 staged[hex.EncodeToString(sum[:8])+"-"+name] = true
325 }
326 entries, err := os.ReadDir(reposDir)
327 if err != nil {
328 return err
329 }
330 for _, entry := range entries {
331 if !staged[entry.Name()] {
332 if err := os.RemoveAll(filepath.Join(reposDir, entry.Name())); err != nil {
333 return err
334 }
335 }
336 }
337 for _, name := range names {
338 url := urls[name]
339 files, err := sharedFiles(ctx, url, nil)
340 if err != nil {
341 return fmt.Errorf("%s: could not prepare CLI cache: %w", name, err)
342 }
343 files["config"] = strings.Replace(files["config"], "bare = true", "bare = false", 1) + "[core]\n\tlogallrefupdates = false\n"
344 files["objects/info/alternates"] += instance["objects/info/alternates"]
345 wrapped := map[string]string{}
346 for path, data := range files {
347 wrapped[".git/"+path] = data
348 }
349 sum := sha256.Sum256([]byte(url))
350 dir := filepath.Join(reposDir, hex.EncodeToString(sum[:8])+"-"+name)
351 if err := p.stageFiles(dir, wrapped); err != nil {
352 return err
353 }
354 }
355 // Each CLI cache can write main and its lock file. Leave room for
356 // those bounded metadata writes before invoking any collection command.
357 p.collectionRoom = int64(len(names)+1) * 4096
358 return p.reserveStorage(p.collectionRoom)
359}
360
361func (p *publisher) cliReposDir() string {
362 return filepath.Join(filepath.Dir(p.cache), "valley", "repos")
363}
364
365// The instance repository's project list, and where the publisher's
366// repository keeps what it fetched of the instance.
367const (
368 projectsRef = "refs/the-valley/projects"
369 originMain = "refs/remotes/origin/main"
370 originProjects = "refs/remotes/origin/projects"
371)
372
373// instanceRead is the instance repository as a pass found it: main's tip,
374// the project list it publishes, and the projects that list names.
375type instanceRead struct {
376 tip, list string
377 projects []string
378}
379
380// fetchInstance fetches the instance repository's main and its project
381// list into the publisher's repository, once a pass. A repository whose
382// main carries no policy/instance is not an instance repository. One whose
383// main carries policy/valley is refused too: it names another instance as
384// its own.
385func (p *publisher) fetchInstance(ctx context.Context) (instanceRead, error) {
386 var r instanceRead
387 if err := p.shareRepository(ctx, p.origin, p.cfg.instanceRepo, map[string]string{
388 originMain: "refs/heads/main", originProjects: projectsRef,
389 }); err != nil {
390 return r, fmt.Errorf("could not read main and %s in the instance repository: %w", projectsRef, err)
391 }
392 var err error
393 if r.tip, err = revParse(ctx, p.origin, originMain+"^{commit}"); err != nil {
394 return r, err
395 }
396 if _, err := git(ctx, p.origin, "cat-file", "-e", r.tip+":policy/instance"); err != nil {
397 return r, fmt.Errorf("%s holds no policy/instance on main, so it is not an instance repository", p.cfg.instanceRepo)
398 }
399 if _, err := git(ctx, p.origin, "cat-file", "-e", r.tip+":policy/valley"); err == nil {
400 return r, fmt.Errorf("%s holds policy/valley on main, which names another instance; an instance repository the publisher reads holds policy/instance and no policy/valley", p.cfg.instanceRepo)
401 }
402 if r.list, err = revParse(ctx, p.origin, originProjects); err != nil {
403 return r, err
404 }
405 list, err := git(ctx, p.origin, "cat-file", "blob", r.list)
406 if err != nil {
407 return r, fmt.Errorf("%s in the instance repository is not a list of projects: %w", projectsRef, err)
408 }
409 for _, name := range strings.Split(string(list), "\n") {
410 if name != "" {
411 r.projects = append(r.projects, name)
412 }
413 }
414 sort.Strings(r.projects)
415 return r, nil
416}
417
418// errNoMain is fetchMain's error for a project with no main.
419var errNoMain = errors.New("no main")
420
421// fetchMain reads main into a cache that borrows the local repository's
422// objects. Borrowing keeps repository history outside the storage budget:
423// the publisher can read the host's objects but cannot write them.
424func (p *publisher) fetchMain(ctx context.Context, name, url string) (string, string, error) {
425 if !filepath.IsAbs(url) {
426 return "", "", fmt.Errorf("repository must be an absolute local path: %q", url)
427 }
428 heads, err := git(ctx, url, "ls-remote", "--end-of-options", url, "refs/heads/main")
429 if err != nil {
430 return "", "", err
431 }
432 if !listsRef(heads, "refs/heads/main") {
433 return "", "", errNoMain
434 }
435
436 mirror := filepath.Join(p.cache, "repos", name+".git")
437 if err := p.shareRepository(ctx, mirror, url, map[string]string{"refs/heads/main": "refs/heads/main"}); err != nil {
438 return "", "", err
439 }
440 tip, err := revParse(ctx, mirror, "refs/heads/main^{commit}")
441 return mirror, tip, err
442}
443
444// shareRepository replaces a disposable cache with refs and an alternate.
445// No fetch transport runs, so even objects added concurrently cannot be
446// copied. All bytes to be written are known before staging starts. Old
447// caches remain counted until the replacement is complete.
448func (p *publisher) shareRepository(ctx context.Context, dir, source string, refs map[string]string) error {
449 files, err := sharedFiles(ctx, source, refs)
450 if err != nil {
451 return err
452 }
453 return p.stageFiles(dir, files)
454}
455
456func quoteGit(s string) string {
457 return strings.NewReplacer("\\", "\\\\", "\"", "\\\"", "\t", "\\t").Replace(s)
458}
459
460func sharedFiles(ctx context.Context, source string, refs map[string]string) (map[string]string, error) {
461 if !filepath.IsAbs(source) || strings.ContainsAny(source, "\n\r") {
462 return nil, fmt.Errorf("repository must be an absolute local path: %q", source)
463 }
464 objects, err := git(ctx, source, "rev-parse", "--path-format=absolute", "--git-path", "objects")
465 if err != nil {
466 return nil, err
467 }
468 format, err := git(ctx, source, "rev-parse", "--show-object-format")
469 if err != nil {
470 return nil, err
471 }
472 config := "[core]\n\tbare = true\n\trepositoryformatversion = 0\n"
473 switch strings.TrimSpace(string(format)) {
474 case "sha1":
475 case "sha256":
476 config = "[core]\n\tbare = true\n\trepositoryformatversion = 1\n[extensions]\n\tobjectformat = sha256\n"
477 default:
478 return nil, fmt.Errorf("unsupported object format %q", format)
479 }
480 quoted := quoteGit(source)
481 config += "[remote \"origin\"]\n\turl = \"" + quoted + "\"\n"
482 files := map[string]string{
483 "HEAD": "ref: refs/heads/main\n", "config": config,
484 "objects/info/alternates": strings.TrimSpace(string(objects)) + "\n",
485 }
486 for dest, ref := range refs {
487 tip, err := revParse(ctx, source, ref)
488 if err != nil {
489 return nil, err
490 }
491 files[dest] = tip + "\n"
492 }
493 return files, nil
494}
495
496func (p *publisher) reserveStorage(added int64) error {
497 used, err := p.storageUsed()
498 if err != nil {
499 return err
500 }
501 if used > int64(p.cfg.maxStorage)-added {
502 return p.overStorage(used + added)
503 }
504 return nil
505}
506
507func (p *publisher) stageFiles(dir string, files map[string]string) error {
508 used, err := p.storageUsed()
509 if err != nil {
510 return err
511 }
512 var added int64
513 for _, content := range files {
514 added += int64(len(content))
515 }
516 if used > int64(p.cfg.maxStorage)-added {
517 return p.overStorage(used + added)
518 }
519 if err := os.MkdirAll(filepath.Dir(dir), 0o700); err != nil {
520 return err
521 }
522 stage, err := os.MkdirTemp(filepath.Dir(dir), ".shared-")
523 if err != nil {
524 return err
525 }
526 defer os.RemoveAll(stage)
527 prefix := stage
528 if _, ok := files[".git/HEAD"]; ok {
529 prefix = filepath.Join(stage, ".git")
530 }
531 if err := os.MkdirAll(filepath.Join(prefix, "refs"), 0o700); err != nil {
532 return err
533 }
534 for name, content := range files {
535 path := filepath.Join(stage, name)
536 if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
537 return err
538 }
539 if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
540 return err
541 }
542 }
543 if err := p.checkStorage(); err != nil {
544 return err
545 }
546 if err := os.RemoveAll(dir); err != nil {
547 return err
548 }
549 return os.Rename(stage, dir)
550}
551
552// listsRef reports whether ls-remote's output lists the ref. ls-remote
553// matches a pattern against the tail of a ref name, so each name listed
554// is compared whole.
555func listsRef(out []byte, ref string) bool {
556 for _, line := range strings.Split(string(out), "\n") {
557 if _, name, ok := strings.Cut(line, "\t"); ok && name == ref {
558 return true
559 }
560 }
561 return false
562}
563
564func revParse(ctx context.Context, repo, rev string) (string, error) {
565 out, err := git(ctx, repo, "rev-parse", "--verify", "--end-of-options", rev)
566 if err != nil {
567 return "", err
568 }
569 return strings.TrimSpace(string(out)), nil
570}
571
572// valley runs one of the CLI's JSON commands in dir, one of the
573// publisher's repositories, and returns what it printed, up to
574// maxValleyOutput. What it says on stderr is passed on.
575func (p *publisher) valley(ctx context.Context, dir string, args ...string) ([]byte, error) {
576 if err := p.reserveStorage(p.collectionRoom); err != nil {
577 return nil, err
578 }
579 // Discovery can see a newly listed project, and knot details can name
580 // an unlisted project. Deny creation in the parent before either can
581 // make an unshared cache and fetch objects. Staged .git directories
582 // remain writable for their bounded ref updates.
583 reposDir := p.cliReposDir()
584 if err := os.Chmod(reposDir, 0o500); err != nil {
585 return nil, err
586 }
587 defer os.Chmod(reposDir, 0o700)
588 cmd := exec.CommandContext(ctx, "valley", args...)
589 cmd.Dir = dir
590 cmd.Env = valleyEnvironment(os.Environ())
591 stdout := &bounded{max: maxValleyOutput, strict: true}
592 cmd.Stdout = stdout
593 cmd.Stderr = p.stderr
594 err := cmd.Run()
595 if budget := p.checkStorage(); budget != nil {
596 return nil, budget
597 }
598 if stdout.over {
599 return nil, fmt.Errorf("valley %s: %w", strings.Join(args, " "), errTooLong)
600 }
601 if err != nil {
602 return nil, fmt.Errorf("valley %s: %w", strings.Join(args, " "), err)
603 }
604 return stdout.Bytes(), nil
605}
606
607// valleyEnvironment is the environment the valley CLI runs in: the
608// caller's, without the variables that would point git at another
609// repository, and without the ones that would give the CLI verification
610// material of their own. The CLI then reads the signers the host publishes,
611// as it reads the projects.
612func valleyEnvironment(environ []string) []string {
613 var env []string
614 for _, kv := range environ {
615 name, _, _ := strings.Cut(kv, "=")
616 if redirectsGit(name) || name == "VALLEY_KNOWN_SIGNERS" || name == "VALLEY_INTEGRATOR_SIGNER" {
617 continue
618 }
619 env = append(env, kv)
620 }
621 return env
622}
623
624// git runs git in repo, unless it is "", and returns what it printed, up
625// to maxGitOutput.
626func git(ctx context.Context, repo string, args ...string) ([]byte, error) {
627 return gitInput(ctx, repo, "", args...)
628}
629
630// gitInput is git with input on its stdin. With no input, stdin is the
631// null device.
632func gitInput(ctx context.Context, repo, input string, args ...string) ([]byte, error) {
633 var stdin io.Reader
634 if input != "" {
635 stdin = strings.NewReader(input)
636 }
637 stdout := &bounded{max: maxGitOutput, strict: true}
638 err := gitStream(ctx, repo, stdin, stdout, args...)
639 if stdout.over {
640 return nil, fmt.Errorf("git %s: %w", gitVerb(args), errTooLong)
641 }
642 if err != nil {
643 return nil, err
644 }
645 return stdout.Bytes(), nil
646}
647
648// gitStream runs git in repo, unless it is "", with stdin and stdout
649// given: with replacement refs off, git held to the transports a URL from
650// data may use, no prompt, and a fixed date for any commit it writes. It
651// keeps the caller's GIT_CONFIG_* variables, which carry the
652// safe.directory entries a host gives the publisher for repositories it
653// does not own.
654func gitStream(ctx context.Context, repo string, stdin io.Reader, stdout io.Writer, args ...string) error {
655 if repo != "" {
656 args = append([]string{"-C", repo}, args...)
657 }
658 cmd := exec.CommandContext(ctx, "git", append([]string{"--no-replace-objects"}, args...)...)
659 cmd.Env = gitEnvironment(os.Environ())
660 stderr := &bounded{max: maxStderr}
661 cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr
662 if err := cmd.Run(); err != nil {
663 return fmt.Errorf("git %s: %w: %s", gitVerb(args), err, strings.TrimSpace(stderr.String()))
664 }
665 return nil
666}
667
668// gitVerb is the git command args run, for messages: the first argument
669// after -C and the options git takes before its command.
670func gitVerb(args []string) string {
671 for i := 0; i < len(args); i++ {
672 switch args[i] {
673 case "-C", "-c":
674 i++
675 default:
676 return args[i]
677 }
678 }
679 return "git"
680}
681
682// errTooLong is the error for a program that printed more than its bound.
683var errTooLong = errors.New("it printed more than the publisher holds of it")
684
685// bounded holds what a program prints, up to max bytes. Past max, a write
686// fails when strict is set, which ends the program at its next write, and
687// is dropped when it is not. It is no io.ReaderFrom, so os/exec copies
688// through Write.
689type bounded struct {
690 buf bytes.Buffer
691 max int
692 strict bool
693 over bool
694}
695
696func (b *bounded) Write(p []byte) (int, error) {
697 room := max(b.max-b.buf.Len(), 0)
698 if len(p) <= room {
699 return b.buf.Write(p)
700 }
701 b.over = true
702 b.buf.Write(p[:room])
703 if b.strict {
704 return room, errTooLong
705 }
706 return len(p), nil
707}
708
709func (b *bounded) Bytes() []byte { return b.buf.Bytes() }
710func (b *bounded) String() string { return b.buf.String() }
711
712func gitEnvironment(environ []string) []string {
713 var env []string
714 for _, kv := range environ {
715 name, _, _ := strings.Cut(kv, "=")
716 switch {
717 case redirectsGit(name), name == "GIT_ALLOW_PROTOCOL", name == "GIT_TERMINAL_PROMPT",
718 name == "GIT_AUTHOR_DATE", name == "GIT_COMMITTER_DATE":
719 continue
720 }
721 env = append(env, kv)
722 }
723 return append(env,
724 "GIT_ALLOW_PROTOCOL=ssh:git:https:file",
725 "GIT_TERMINAL_PROMPT=0",
726 "GIT_NO_REPLACE_OBJECTS=1",
727 "GIT_AUTHOR_DATE=@0 +0000",
728 "GIT_COMMITTER_DATE=@0 +0000",
729 )
730}
731
732// redirectsGit reports whether the variable points git at another
733// repository, another object store or another work tree than the one it
734// is run in.
735func redirectsGit(name string) bool {
736 switch name {
737 case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_PREFIX",
738 "GIT_NAMESPACE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES":
739 return true
740 }
741 return false
742}
743
744// readPrincipals reads the display mapping: a JSON object from principal
745// names to the names an export shows. No file is an empty mapping, under
746// which every principal is shown as export.Unmapped.
747func readPrincipals(path string) (export.Principals, error) {
748 if path == "" {
749 return export.Principals{}, nil
750 }
751 data, err := os.ReadFile(path)
752 if err != nil {
753 return nil, err
754 }
755 dec := json.NewDecoder(bytes.NewReader(data))
756 var m export.Principals
757 if err := dec.Decode(&m); err != nil {
758 return nil, fmt.Errorf("the display mapping %s is not a JSON object of names: %w", path, err)
759 }
760 if err := dec.Decode(&json.RawMessage{}); err != io.EOF {
761 return nil, fmt.Errorf("the display mapping %s holds more than its one object", path)
762 }
763 if m == nil {
764 m = export.Principals{}
765 }
766 return m, nil
767}