gunk-dev/the-valley

valley.go

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