gunk-dev/the-valley

valley.go

sourcee0e2aed6532emain's published tip history
29.1 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/web/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.
417//
418// Each ref is read by its exact name with readaccess.ResolveRef, and
419// everything after reads the object ID it held. git rev-parse would try
420// other names for a ref the instance repository lacks: for a missing
421// refs/heads/registry, it would read refs/heads/refs/heads/registry, which
422// any pusher can make.
423func (p *publisher) fetchInstance(ctx context.Context) (instanceRead, error) {
424 var r instanceRead
425 resolve := func(ref string) (string, bool, error) {
426 oid, ok, err := readaccess.ResolveRef(ctx, p.cfg.instanceRepo, ref)
427 if err != nil {
428 return "", false, fmt.Errorf("could not read %s in the instance repository: %w", ref, err)
429 }
430 return oid, ok, nil
431 }
432 main, ok, err := resolve("refs/heads/main")
433 if err != nil {
434 return r, err
435 } else if !ok {
436 return r, fmt.Errorf("%s holds no main, so it is not an instance repository", p.cfg.instanceRepo)
437 }
438 list, ok, err := resolve(projectsRef)
439 if err != nil {
440 return r, err
441 } else if !ok {
442 return r, fmt.Errorf("the instance repository publishes no %s, so it lists no projects", projectsRef)
443 }
444 registry := main
445 if p.cfg.registryRef != "refs/heads/main" {
446 if registry, _, err = resolve(p.cfg.registryRef); err != nil {
447 return r, err
448 }
449 }
450
451 files, err := sharedFiles(ctx, p.cfg.instanceRepo, nil)
452 if err != nil {
453 return r, fmt.Errorf("could not read the instance repository: %w", err)
454 }
455 files[originMain], files[originProjects] = main+"\n", list+"\n"
456 if registry != "" {
457 files[originRegistry] = registry + "\n"
458 }
459 if err := p.stageFiles(p.origin, files); err != nil {
460 return r, fmt.Errorf("could not read the instance repository: %w", err)
461 }
462 if r.tip, err = revParse(ctx, p.origin, main+"^{commit}"); err != nil {
463 return r, fmt.Errorf("main in the instance repository is not a commit: %w", err)
464 }
465 if registry != "" {
466 if r.registry, err = revParse(ctx, p.origin, registry+"^{commit}"); err != nil {
467 return r, fmt.Errorf("%s in the instance repository is not a commit: %w", p.cfg.registryRef, err)
468 }
469 }
470 if _, err := git(ctx, p.origin, "cat-file", "-e", r.tip+":policy/instance"); err != nil {
471 return r, fmt.Errorf("%s holds no policy/instance on main, so it is not an instance repository", p.cfg.instanceRepo)
472 }
473 if _, err := git(ctx, p.origin, "cat-file", "-e", r.tip+":policy/valley"); err == nil {
474 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)
475 }
476 r.list = list
477 data, err := git(ctx, p.origin, "cat-file", "blob", r.list)
478 if err != nil {
479 return r, fmt.Errorf("%s in the instance repository is not a list of projects: %w", projectsRef, err)
480 }
481 for _, name := range strings.Split(string(data), "\n") {
482 if name != "" {
483 r.projects = append(r.projects, name)
484 }
485 }
486 sort.Strings(r.projects)
487 return r, nil
488}
489
490// errNoMain is fetchMain's error for a project with no main.
491var errNoMain = errors.New("no main")
492
493// fetchMain reads main into a cache that borrows the local repository's
494// objects. Borrowing keeps repository history outside the storage budget:
495// the publisher can read the host's objects but cannot write them.
496func (p *publisher) fetchMain(ctx context.Context, name, url string) (string, string, error) {
497 if !filepath.IsAbs(url) {
498 return "", "", fmt.Errorf("repository must be an absolute local path: %q", url)
499 }
500 heads, err := git(ctx, url, "ls-remote", "--end-of-options", url, "refs/heads/main")
501 if err != nil {
502 return "", "", err
503 }
504 if !listsRef(heads, "refs/heads/main") {
505 return "", "", errNoMain
506 }
507
508 mirror := filepath.Join(p.cache, "repos", name+".git")
509 oids, err := p.shareRepository(ctx, mirror, url, map[string]string{"refs/heads/main": "refs/heads/main"})
510 if err != nil {
511 return "", "", err
512 }
513 tip, err := revParse(ctx, mirror, oids["refs/heads/main"]+"^{commit}")
514 return mirror, tip, err
515}
516
517// shareRepository replaces a disposable cache with refs and an alternate.
518// No fetch transport runs, so even objects added concurrently cannot be
519// copied. All bytes to be written are known before staging starts. Old
520// caches remain counted until the replacement is complete. It returns the
521// object ID it staged at each of the cache's refs, which the caller reads
522// from then on.
523func (p *publisher) shareRepository(ctx context.Context, dir, source string, refs map[string]string) (map[string]string, error) {
524 files, err := sharedFiles(ctx, source, refs)
525 if err != nil {
526 return nil, err
527 }
528 if err := p.stageFiles(dir, files); err != nil {
529 return nil, err
530 }
531 oids := map[string]string{}
532 for dest := range refs {
533 oids[dest] = strings.TrimSpace(files[dest])
534 }
535 return oids, nil
536}
537
538func quoteGit(s string) string {
539 return strings.NewReplacer("\\", "\\\\", "\"", "\\\"", "\t", "\\t").Replace(s)
540}
541
542// sharedFiles are the files of a cache that borrows source's objects:
543// HEAD, the config, the alternate, and at each ref of the cache named in
544// refs, the object ID the source ref it maps to holds. Each source ref is
545// read by its exact name with readaccess.ResolveRef, and one source lacks
546// is an error.
547func sharedFiles(ctx context.Context, source string, refs map[string]string) (map[string]string, error) {
548 if !filepath.IsAbs(source) || strings.ContainsAny(source, "\n\r") {
549 return nil, fmt.Errorf("repository must be an absolute local path: %q", source)
550 }
551 objects, err := git(ctx, source, "rev-parse", "--path-format=absolute", "--git-path", "objects")
552 if err != nil {
553 return nil, err
554 }
555 format, err := git(ctx, source, "rev-parse", "--show-object-format")
556 if err != nil {
557 return nil, err
558 }
559 config := "[core]\n\tbare = true\n\trepositoryformatversion = 0\n"
560 switch strings.TrimSpace(string(format)) {
561 case "sha1":
562 case "sha256":
563 config = "[core]\n\tbare = true\n\trepositoryformatversion = 1\n[extensions]\n\tobjectformat = sha256\n"
564 default:
565 return nil, fmt.Errorf("unsupported object format %q", format)
566 }
567 quoted := quoteGit(source)
568 config += "[remote \"origin\"]\n\turl = \"" + quoted + "\"\n"
569 files := map[string]string{
570 "HEAD": "ref: refs/heads/main\n", "config": config,
571 "objects/info/alternates": strings.TrimSpace(string(objects)) + "\n",
572 }
573 for dest, ref := range refs {
574 tip, ok, err := readaccess.ResolveRef(ctx, source, ref)
575 if err != nil {
576 return nil, err
577 } else if !ok {
578 return nil, fmt.Errorf("%s holds no %s", source, ref)
579 }
580 files[dest] = tip + "\n"
581 }
582 return files, nil
583}
584
585func (p *publisher) reserveStorage(added int64) error {
586 used, err := p.storageUsed()
587 if err != nil {
588 return err
589 }
590 if used > int64(p.cfg.maxStorage)-added {
591 return p.overStorage(used + added)
592 }
593 return nil
594}
595
596func (p *publisher) stageFiles(dir string, files map[string]string) error {
597 used, err := p.storageUsed()
598 if err != nil {
599 return err
600 }
601 var added int64
602 for _, content := range files {
603 added += int64(len(content))
604 }
605 if used > int64(p.cfg.maxStorage)-added {
606 return p.overStorage(used + added)
607 }
608 if err := os.MkdirAll(filepath.Dir(dir), 0o700); err != nil {
609 return err
610 }
611 stage, err := os.MkdirTemp(filepath.Dir(dir), ".shared-")
612 if err != nil {
613 return err
614 }
615 defer os.RemoveAll(stage)
616 prefix := stage
617 if _, ok := files[".git/HEAD"]; ok {
618 prefix = filepath.Join(stage, ".git")
619 }
620 if err := os.MkdirAll(filepath.Join(prefix, "refs"), 0o700); err != nil {
621 return err
622 }
623 for name, content := range files {
624 path := filepath.Join(stage, name)
625 if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
626 return err
627 }
628 if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
629 return err
630 }
631 }
632 if err := p.checkStorage(); err != nil {
633 return err
634 }
635 if err := os.RemoveAll(dir); err != nil {
636 return err
637 }
638 return os.Rename(stage, dir)
639}
640
641// listsRef reports whether ls-remote's output lists the ref. ls-remote
642// matches a pattern against the tail of a ref name, so each name listed
643// is compared whole.
644func listsRef(out []byte, ref string) bool {
645 for _, line := range strings.Split(string(out), "\n") {
646 if _, name, ok := strings.Cut(line, "\t"); ok && name == ref {
647 return true
648 }
649 }
650 return false
651}
652
653// revParse resolves rev in repo. rev is an object ID to peel, or a ref the
654// publisher staged itself, never a ref name read from another repository.
655func revParse(ctx context.Context, repo, rev string) (string, error) {
656 out, err := git(ctx, repo, "rev-parse", "--verify", "--end-of-options", rev)
657 if err != nil {
658 return "", err
659 }
660 return strings.TrimSpace(string(out)), nil
661}
662
663// valley runs one of the CLI's JSON commands in dir, one of the
664// publisher's repositories, and returns what it printed, up to
665// maxValleyOutput. What it says on stderr is passed on.
666func (p *publisher) valley(ctx context.Context, dir string, args ...string) ([]byte, error) {
667 if err := p.reserveStorage(p.collectionRoom); err != nil {
668 return nil, err
669 }
670 // Discovery can see a newly listed project, and knot details can name
671 // an unlisted project. Deny creation in the parent before either can
672 // make an unshared cache and fetch objects. Staged .git directories
673 // remain writable for their bounded ref updates.
674 reposDir := p.cliReposDir()
675 if err := os.Chmod(reposDir, 0o500); err != nil {
676 return nil, err
677 }
678 defer os.Chmod(reposDir, 0o700)
679 cmd := exec.CommandContext(ctx, "valley", args...)
680 cmd.Dir = dir
681 cmd.Env = valleyEnvironment(os.Environ())
682 stdout := &bounded{max: maxValleyOutput, strict: true}
683 cmd.Stdout = stdout
684 cmd.Stderr = p.stderr
685 err := cmd.Run()
686 if budget := p.checkStorage(); budget != nil {
687 return nil, budget
688 }
689 if stdout.over {
690 return nil, fmt.Errorf("valley %s: %w", strings.Join(args, " "), errTooLong)
691 }
692 if err != nil {
693 return nil, fmt.Errorf("valley %s: %w", strings.Join(args, " "), err)
694 }
695 return stdout.Bytes(), nil
696}
697
698// valleyEnvironment is the environment the valley CLI runs in: the
699// caller's, without the variables that would point git at another
700// repository, and without the ones that would give the CLI verification
701// material of their own. The CLI then reads the signers the host publishes,
702// as it reads the projects.
703func valleyEnvironment(environ []string) []string {
704 var env []string
705 for _, kv := range environ {
706 name, _, _ := strings.Cut(kv, "=")
707 if redirectsGit(name) || name == "VALLEY_KNOWN_SIGNERS" || name == "VALLEY_INTEGRATOR_SIGNER" {
708 continue
709 }
710 env = append(env, kv)
711 }
712 return env
713}
714
715// git runs git in repo, unless it is "", and returns what it printed, up
716// to maxGitOutput.
717func git(ctx context.Context, repo string, args ...string) ([]byte, error) {
718 return gitInput(ctx, repo, "", args...)
719}
720
721// gitInput is git with input on its stdin. With no input, stdin is the
722// null device.
723func gitInput(ctx context.Context, repo, input string, args ...string) ([]byte, error) {
724 var stdin io.Reader
725 if input != "" {
726 stdin = strings.NewReader(input)
727 }
728 stdout := &bounded{max: maxGitOutput, strict: true}
729 err := gitStream(ctx, repo, stdin, stdout, args...)
730 if stdout.over {
731 return nil, fmt.Errorf("git %s: %w", gitVerb(args), errTooLong)
732 }
733 if err != nil {
734 return nil, err
735 }
736 return stdout.Bytes(), nil
737}
738
739// gitStream runs git in repo, unless it is "", with stdin and stdout
740// given: with replacement refs off, git held to the transports a URL from
741// data may use, no prompt, and a fixed date for any commit it writes. It
742// keeps the caller's GIT_CONFIG_* variables, which carry the
743// safe.directory entries a host gives the publisher for repositories it
744// does not own.
745func gitStream(ctx context.Context, repo string, stdin io.Reader, stdout io.Writer, args ...string) error {
746 if repo != "" {
747 args = append([]string{"-C", repo}, args...)
748 }
749 cmd := exec.CommandContext(ctx, "git", append([]string{"--no-replace-objects"}, args...)...)
750 cmd.Env = gitEnvironment(os.Environ())
751 stderr := &bounded{max: maxStderr}
752 cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr
753 if err := cmd.Run(); err != nil {
754 return fmt.Errorf("git %s: %w: %s", gitVerb(args), err, strings.TrimSpace(stderr.String()))
755 }
756 return nil
757}
758
759// gitVerb is the git command args run, for messages: the first argument
760// after -C and the options git takes before its command.
761func gitVerb(args []string) string {
762 for i := 0; i < len(args); i++ {
763 switch args[i] {
764 case "-C", "-c":
765 i++
766 default:
767 return args[i]
768 }
769 }
770 return "git"
771}
772
773// errTooLong is the error for a program that printed more than its bound.
774var errTooLong = errors.New("it printed more than the publisher holds of it")
775
776// bounded holds what a program prints, up to max bytes. Past max, a write
777// fails when strict is set, which ends the program at its next write, and
778// is dropped when it is not. It is no io.ReaderFrom, so os/exec copies
779// through Write.
780type bounded struct {
781 buf bytes.Buffer
782 max int
783 strict bool
784 over bool
785}
786
787func (b *bounded) Write(p []byte) (int, error) {
788 room := max(b.max-b.buf.Len(), 0)
789 if len(p) <= room {
790 return b.buf.Write(p)
791 }
792 b.over = true
793 b.buf.Write(p[:room])
794 if b.strict {
795 return room, errTooLong
796 }
797 return len(p), nil
798}
799
800func (b *bounded) Bytes() []byte { return b.buf.Bytes() }
801func (b *bounded) String() string { return b.buf.String() }
802
803func gitEnvironment(environ []string) []string {
804 var env []string
805 for _, kv := range environ {
806 name, _, _ := strings.Cut(kv, "=")
807 switch {
808 case redirectsGit(name), name == "GIT_ALLOW_PROTOCOL", name == "GIT_TERMINAL_PROMPT",
809 name == "GIT_AUTHOR_DATE", name == "GIT_COMMITTER_DATE":
810 continue
811 }
812 env = append(env, kv)
813 }
814 return append(env,
815 "GIT_ALLOW_PROTOCOL=ssh:git:https:file",
816 "GIT_TERMINAL_PROMPT=0",
817 "GIT_NO_REPLACE_OBJECTS=1",
818 "GIT_AUTHOR_DATE=@0 +0000",
819 "GIT_COMMITTER_DATE=@0 +0000",
820 )
821}
822
823// redirectsGit reports whether the variable points git at another
824// repository, another object store or another work tree than the one it
825// is run in.
826func redirectsGit(name string) bool {
827 switch name {
828 case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_PREFIX",
829 "GIT_NAMESPACE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES":
830 return true
831 }
832 return false
833}
834
835// readPrincipals reads the display mapping: a JSON object from principal
836// names to the names an export shows. No file is an empty mapping, under
837// which every principal is shown as export.Unmapped.
838func readPrincipals(path string) (export.Principals, error) {
839 if path == "" {
840 return export.Principals{}, nil
841 }
842 data, err := os.ReadFile(path)
843 if err != nil {
844 return nil, err
845 }
846 dec := json.NewDecoder(bytes.NewReader(data))
847 var m export.Principals
848 if err := dec.Decode(&m); err != nil {
849 return nil, fmt.Errorf("the display mapping %s is not a JSON object of names: %w", path, err)
850 }
851 if err := dec.Decode(&json.RawMessage{}); err != io.EOF {
852 return nil, fmt.Errorf("the display mapping %s holds more than its one object", path)
853 }
854 if m == nil {
855 m = export.Principals{}
856 }
857 return m, nil
858}