gunk-dev/the-valley

valley.go

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