gunk-dev/the-valley

valley.go

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