gunk-dev/the-valley

valley.go

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