gunk-dev/the-valley

valley.go

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