gunk-dev/the-valley

valley.go

source122dfe2eac3dmain's published tip history
21.4 KiB
1package main
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "slices"
14 "sort"
15 "strings"
16
17 "the-valley/webui/export"
18)
19
20// readAttempts is how many times a pass reads the valley before it gives
21// up on inputs that keep changing under it.
22const readAttempts = 3
23
24// The bounds on what a pass holds of a program's output. A program that
25// prints more than its bound to stdout fails, and what it prints to stderr
26// past its bound is dropped.
27const (
28 maxValleyOutput = 64 << 20
29 maxGitOutput = 4 << 20
30 maxStderr = 64 << 10
31)
32
33// reading is what a pass read: the export, each exported project's mirror,
34// and the projects it keeps private.
35type reading struct {
36 export *export.Export
37 json []byte
38 mirrors map[string]string
39 private []string
40}
41
42// collect reads the valley and builds the export. It fetches the instance
43// repository once, and every read of the pass reads the instance at that
44// fetch. Each knot's detail is read after the plan, so a write to the graph
45// in between makes the two disagree; export.Build says so with
46// ErrInconsistent, and collect reads everything again.
47func (p *publisher) collect(ctx context.Context) (*reading, error) {
48 if err := checkSchema(ctx, p.cfg.schema); err != nil {
49 return nil, err
50 }
51 inst, err := p.fetchInstance(ctx)
52 if err != nil {
53 return nil, err
54 }
55 if err := p.preparePointer(ctx); err != nil {
56 return nil, err
57 }
58 for attempt := 1; attempt <= readAttempts; attempt++ {
59 var r *reading
60 r, err = p.read(ctx, inst)
61 if err == nil {
62 return r, nil
63 }
64 if !errors.Is(err, export.ErrInconsistent) {
65 return nil, err
66 }
67 p.warn("%v; reading the valley again", err)
68 }
69 return nil, fmt.Errorf("the valley changed under every one of %d reads: %w", readAttempts, err)
70}
71
72// planListing and pendingListing are what the publisher reads of the
73// valley's JSON itself: which projects there are, each project's knots,
74// and where each can be read. export.Build reads the rest.
75type (
76 planListing struct {
77 Projects []struct {
78 Project string `json:"project"`
79 Knots []struct {
80 ID string `json:"id"`
81 } `json:"knots"`
82 } `json:"projects"`
83 }
84 pendingListing struct {
85 Repos []pendingRepo `json:"repos"`
86 }
87 pendingRepo struct {
88 Repo string `json:"repo"`
89 URL string `json:"url"`
90 Error *string `json:"error"`
91 }
92)
93
94// read is one read of the valley, with the instance as fetchInstance read
95// it. A project is private when the instance does not allow it, or when its
96// own declaration is missing, invalid or private. Any other failure to read
97// a project the instance allows ends the pass: an export without it would
98// take it off the web.
99func (p *publisher) read(ctx context.Context, inst instanceRead) (*reading, error) {
100 allowed := map[string]bool{}
101 decl, err := readDeclaration(ctx, p.origin, inst.tip, p.cfg.schema)
102 var bad *invalidDeclaration
103 switch {
104 case errors.Is(err, errNoDeclaration):
105 case errors.As(err, &bad):
106 p.warn("the instance's policy/web at %s is not a valid declaration, so every project is private: %v", short(inst.tip), err)
107 case err != nil:
108 return nil, fmt.Errorf("could not read the instance's policy/web at %s: %w", short(inst.tip), err)
109 case decl.Instance != nil:
110 for name, d := range decl.Instance.Projects {
111 allowed[name] = d.Visibility == string(export.Public)
112 }
113 }
114
115 planJSON, err := p.valley(ctx, p.pointer, "plan", "--all", "--json")
116 if err != nil {
117 return nil, err
118 }
119 pendingJSON, err := p.valley(ctx, p.pointer, "pending", "--all", "--json")
120 if err != nil {
121 return nil, err
122 }
123 var plan planListing
124 if err := json.Unmarshal(planJSON, &plan); err != nil {
125 return nil, fmt.Errorf("valley plan --all --json: %w", err)
126 }
127 var pending pendingListing
128 if err := json.Unmarshal(pendingJSON, &pending); err != nil {
129 return nil, fmt.Errorf("valley pending --all --json: %w", err)
130 }
131 // The CLI lists what the instance repository publishes, and nothing
132 // else. When discovery fails it lists the repository it runs in alone,
133 // which would publish an export without the other projects.
134 var planned, listed []string
135 for _, proj := range plan.Projects {
136 planned = append(planned, proj.Project)
137 }
138 repos := map[string]pendingRepo{}
139 for _, r := range pending.Repos {
140 listed = append(listed, r.Repo)
141 repos[r.Repo] = r
142 }
143 for _, l := range []struct {
144 command string
145 names []string
146 }{{"valley plan --all", planned}, {"valley pending --all", listed}} {
147 sort.Strings(l.names)
148 if !slices.Equal(l.names, inst.projects) {
149 return nil, fmt.Errorf("%s lists %s, and the instance repository publishes %s at %s, so nothing is published",
150 l.command, listNames(l.names), listNames(inst.projects), projectsRef)
151 }
152 }
153
154 r := &reading{mirrors: map[string]string{}}
155 in := export.Inputs{
156 Plan: planJSON, Pending: pendingJSON,
157 Visibility: map[string]export.Visibility{}, SourceTips: map[string]string{},
158 Principals: p.principals,
159 }
160 for _, proj := range plan.Projects {
161 name := proj.Project
162 public := false
163 if allowed[name] {
164 if public, err = p.projectVisibility(ctx, name, repos[name], in.SourceTips, r.mirrors); err != nil {
165 return nil, err
166 }
167 }
168 if !public {
169 r.private = append(r.private, name)
170 continue
171 }
172 in.Visibility[name] = export.Public
173 for _, k := range proj.Knots {
174 detail, err := p.valley(ctx, p.origin, "knot", "show", "--project", name, k.ID, "--json")
175 if err != nil {
176 return nil, err
177 }
178 in.Details = append(in.Details, detail)
179 }
180 }
181 sort.Strings(r.private)
182 if r.export, err = export.Build(in); err != nil {
183 return nil, err
184 }
185 if r.json, err = r.export.Encode(); err != nil {
186 return nil, err
187 }
188 return r, nil
189}
190
191// listNames is a list of projects for a message.
192func listNames(list []string) string {
193 if len(list) == 0 {
194 return "none"
195 }
196 return strings.Join(list, ", ")
197}
198
199// projectVisibility decides whether a project the instance allows is
200// public: its own policy/web on main says public. For a public project it
201// records main's tip and the mirror it was fetched into. A project with no
202// main, or whose declaration is missing, invalid or private, is private,
203// and an invalid declaration is said. A project that cannot be read is an
204// error.
205func (p *publisher) projectVisibility(ctx context.Context, name string, repo pendingRepo,
206 tips, mirrors map[string]string) (bool, error) {
207 if !export.ValidName(name) {
208 p.warn("%q is not a project name, so it is private", name)
209 return false, nil
210 }
211 if repo.Error != nil {
212 return false, fmt.Errorf("%s: the pending listing could not read it: %s", name, *repo.Error)
213 }
214 if repo.URL == "" {
215 return false, fmt.Errorf("%s: the pending listing gives no URL to read it from", name)
216 }
217 mirror, tip, err := p.fetchMain(ctx, name, repo.URL)
218 if errors.Is(err, errNoMain) {
219 return false, nil
220 }
221 if err != nil {
222 return false, fmt.Errorf("%s: could not read main: %w", name, err)
223 }
224 decl, err := readDeclaration(ctx, mirror, tip, p.cfg.schema)
225 var bad *invalidDeclaration
226 switch {
227 case errors.Is(err, errNoDeclaration):
228 return false, nil
229 case errors.As(err, &bad):
230 p.warn("%s: its policy/web at %s is not a valid declaration, so it is private: %v", name, short(tip), err)
231 return false, nil
232 case err != nil:
233 return false, fmt.Errorf("%s: could not read its policy/web at %s: %w", name, short(tip), err)
234 case decl.Project == nil || decl.Project.Visibility != string(export.Public):
235 return false, nil
236 }
237 tips[name], mirrors[name] = tip, mirror
238 return true, nil
239}
240
241// bareWithOrigin makes a bare repository at dir, unless one is there, and
242// sets its origin to url.
243func bareWithOrigin(ctx context.Context, dir, url string) error {
244 if _, err := os.Stat(filepath.Join(dir, "HEAD")); errors.Is(err, os.ErrNotExist) {
245 if err := os.RemoveAll(dir); err != nil {
246 return err
247 }
248 if _, err := git(ctx, "", "init", "--quiet", "--bare", "--template=", dir); err != nil {
249 return err
250 }
251 }
252 got, err := git(ctx, dir, "config", "--get", "remote.origin.url")
253 if err == nil && strings.TrimSpace(string(got)) == url {
254 return nil
255 }
256 _, _ = git(ctx, dir, "remote", "remove", "origin")
257 _, err = git(ctx, dir, "remote", "add", "--end-of-options", "origin", url)
258 return err
259}
260
261// preparePointer makes the repository valley plan and valley pending run
262// in: a bare repository whose origin is itself, and whose main holds one
263// file, policy/valley, naming the instance repository. The CLI finds the
264// instance at policy/valley on origin's main, as it does from any project,
265// and follows it no further. So it reads the projects and the signers the
266// instance repository publishes, and never reads the instance repository's
267// main, where a policy/valley could land and be taken away again while the
268// pass reads. Only the publisher writes to this repository, and main's
269// commit is the same in every pass for the same --instance-repo.
270func (p *publisher) preparePointer(ctx context.Context) error {
271 if err := bareWithOrigin(ctx, p.pointer, p.pointer); err != nil {
272 return err
273 }
274 blob, err := gitInput(ctx, p.pointer, p.cfg.instanceRepo+"\n", "hash-object", "-w", "--stdin")
275 if err != nil {
276 return err
277 }
278 policy, err := gitInput(ctx, p.pointer, "100644 blob "+strings.TrimSpace(string(blob))+"\tvalley\n", "mktree")
279 if err != nil {
280 return err
281 }
282 tree, err := gitInput(ctx, p.pointer, "040000 tree "+strings.TrimSpace(string(policy))+"\tpolicy\n", "mktree")
283 if err != nil {
284 return err
285 }
286 commit, err := gitInput(ctx, p.pointer, "", "-c", "user.name=valley-web-publish", "-c", "user.email=valley-web-publish@localhost",
287 "commit-tree", "-m", "policy/valley: the instance the publisher reads", strings.TrimSpace(string(tree)))
288 if err != nil {
289 return err
290 }
291 _, err = git(ctx, p.pointer, "update-ref", "refs/heads/main", strings.TrimSpace(string(commit)))
292 return err
293}
294
295// The instance repository's project list, and where the publisher's
296// repository keeps what it fetched of the instance.
297const (
298 projectsRef = "refs/the-valley/projects"
299 originMain = "refs/remotes/origin/main"
300 originProjects = "refs/remotes/origin/projects"
301)
302
303// instanceRead is the instance repository as a pass found it: main's tip,
304// the project list it publishes, and the projects that list names.
305type instanceRead struct {
306 tip, list string
307 projects []string
308}
309
310// fetchInstance fetches the instance repository's main and its project
311// list into the publisher's repository, once a pass. A repository whose
312// main carries no policy/instance is not an instance repository. One whose
313// main carries policy/valley is refused too: it names another instance as
314// its own.
315func (p *publisher) fetchInstance(ctx context.Context) (instanceRead, error) {
316 var r instanceRead
317 if err := p.shareRepository(ctx, p.origin, p.cfg.instanceRepo, map[string]string{
318 originMain: "refs/heads/main", originProjects: projectsRef,
319 }); err != nil {
320 return r, fmt.Errorf("could not read main and %s in the instance repository: %w", projectsRef, err)
321 }
322 var err error
323 if r.tip, err = revParse(ctx, p.origin, originMain+"^{commit}"); err != nil {
324 return r, err
325 }
326 if _, err := git(ctx, p.origin, "cat-file", "-e", r.tip+":policy/instance"); err != nil {
327 return r, fmt.Errorf("%s holds no policy/instance on main, so it is not an instance repository", p.cfg.instanceRepo)
328 }
329 if _, err := git(ctx, p.origin, "cat-file", "-e", r.tip+":policy/valley"); err == nil {
330 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)
331 }
332 if r.list, err = revParse(ctx, p.origin, originProjects); err != nil {
333 return r, err
334 }
335 list, err := git(ctx, p.origin, "cat-file", "blob", r.list)
336 if err != nil {
337 return r, fmt.Errorf("%s in the instance repository is not a list of projects: %w", projectsRef, err)
338 }
339 for _, name := range strings.Split(string(list), "\n") {
340 if name != "" {
341 r.projects = append(r.projects, name)
342 }
343 }
344 sort.Strings(r.projects)
345 return r, nil
346}
347
348// errNoMain is fetchMain's error for a project with no main.
349var errNoMain = errors.New("no main")
350
351// fetchMain reads main into a cache that borrows the local repository's
352// objects. Borrowing keeps repository history outside the storage budget:
353// the publisher can read the host's objects but cannot write them.
354func (p *publisher) fetchMain(ctx context.Context, name, url string) (string, string, error) {
355 if !filepath.IsAbs(url) {
356 return "", "", fmt.Errorf("repository must be an absolute local path: %q", url)
357 }
358 heads, err := git(ctx, url, "ls-remote", "--end-of-options", url, "refs/heads/main")
359 if err != nil {
360 return "", "", err
361 }
362 if !listsRef(heads, "refs/heads/main") {
363 return "", "", errNoMain
364 }
365
366 mirror := filepath.Join(p.cache, "repos", name+".git")
367 if err := p.shareRepository(ctx, mirror, url, map[string]string{"refs/heads/main": "refs/heads/main"}); err != nil {
368 return "", "", err
369 }
370 tip, err := revParse(ctx, mirror, "refs/heads/main^{commit}")
371 return mirror, tip, err
372}
373
374// shareRepository replaces a disposable cache with refs and an alternate.
375// No fetch transport runs, so even objects added concurrently cannot be
376// copied. All bytes to be written are known before staging starts. Old
377// caches remain counted until the replacement is complete.
378func (p *publisher) shareRepository(ctx context.Context, dir, source string, refs map[string]string) error {
379 if !filepath.IsAbs(source) || strings.ContainsAny(source, "\n\r") {
380 return fmt.Errorf("repository must be an absolute local path: %q", source)
381 }
382 objects, err := git(ctx, source, "rev-parse", "--path-format=absolute", "--git-path", "objects")
383 if err != nil {
384 return err
385 }
386 format, err := git(ctx, source, "rev-parse", "--show-object-format")
387 if err != nil {
388 return err
389 }
390 config := "[core]\n\tbare = true\n\trepositoryformatversion = 0\n"
391 switch strings.TrimSpace(string(format)) {
392 case "sha1":
393 case "sha256":
394 config = "[core]\n\tbare = true\n\trepositoryformatversion = 1\n[extensions]\n\tobjectformat = sha256\n"
395 default:
396 return fmt.Errorf("unsupported object format %q", format)
397 }
398 quoted := strings.NewReplacer("\\", "\\\\", "\"", "\\\"", "\t", "\\t").Replace(source)
399 config += "[remote \"origin\"]\n\turl = \"" + quoted + "\"\n"
400 files := map[string]string{
401 "HEAD": "ref: refs/heads/main\n", "config": config,
402 "objects/info/alternates": strings.TrimSpace(string(objects)) + "\n",
403 }
404 for dest, ref := range refs {
405 tip, err := revParse(ctx, source, ref)
406 if err != nil {
407 return err
408 }
409 files[dest] = tip + "\n"
410 }
411 used, err := p.storageUsed()
412 if err != nil {
413 return err
414 }
415 var added int64
416 for _, content := range files {
417 added += int64(len(content))
418 }
419 if used > int64(p.cfg.maxStorage)-added {
420 return p.overStorage(used + added)
421 }
422 if err := os.MkdirAll(filepath.Dir(dir), 0o700); err != nil {
423 return err
424 }
425 stage, err := os.MkdirTemp(filepath.Dir(dir), ".shared-")
426 if err != nil {
427 return err
428 }
429 defer os.RemoveAll(stage)
430 for name, content := range files {
431 path := filepath.Join(stage, name)
432 if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
433 return err
434 }
435 if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
436 return err
437 }
438 }
439 if err := p.checkStorage(); err != nil {
440 return err
441 }
442 if err := os.RemoveAll(dir); err != nil {
443 return err
444 }
445 return os.Rename(stage, dir)
446}
447
448// listsRef reports whether ls-remote's output lists the ref. ls-remote
449// matches a pattern against the tail of a ref name, so each name listed
450// is compared whole.
451func listsRef(out []byte, ref string) bool {
452 for _, line := range strings.Split(string(out), "\n") {
453 if _, name, ok := strings.Cut(line, "\t"); ok && name == ref {
454 return true
455 }
456 }
457 return false
458}
459
460func revParse(ctx context.Context, repo, rev string) (string, error) {
461 out, err := git(ctx, repo, "rev-parse", "--verify", "--end-of-options", rev)
462 if err != nil {
463 return "", err
464 }
465 return strings.TrimSpace(string(out)), nil
466}
467
468// valley runs one of the CLI's JSON commands in dir, one of the
469// publisher's repositories, and returns what it printed, up to
470// maxValleyOutput. What it says on stderr is passed on.
471func (p *publisher) valley(ctx context.Context, dir string, args ...string) ([]byte, error) {
472 cmd := exec.CommandContext(ctx, "valley", args...)
473 cmd.Dir = dir
474 cmd.Env = valleyEnvironment(os.Environ())
475 stdout := &bounded{max: maxValleyOutput, strict: true}
476 cmd.Stdout = stdout
477 cmd.Stderr = p.stderr
478 err := cmd.Run()
479 if stdout.over {
480 return nil, fmt.Errorf("valley %s: %w", strings.Join(args, " "), errTooLong)
481 }
482 if err != nil {
483 return nil, fmt.Errorf("valley %s: %w", strings.Join(args, " "), err)
484 }
485 return stdout.Bytes(), nil
486}
487
488// valleyEnvironment is the environment the valley CLI runs in: the
489// caller's, without the variables that would point git at another
490// repository, and without the ones that would give the CLI verification
491// material of their own. The CLI then reads the signers the host publishes,
492// as it reads the projects.
493func valleyEnvironment(environ []string) []string {
494 var env []string
495 for _, kv := range environ {
496 name, _, _ := strings.Cut(kv, "=")
497 if redirectsGit(name) || name == "VALLEY_KNOWN_SIGNERS" || name == "VALLEY_INTEGRATOR_SIGNER" {
498 continue
499 }
500 env = append(env, kv)
501 }
502 return env
503}
504
505// git runs git in repo, unless it is "", and returns what it printed, up
506// to maxGitOutput.
507func git(ctx context.Context, repo string, args ...string) ([]byte, error) {
508 return gitInput(ctx, repo, "", args...)
509}
510
511// gitInput is git with input on its stdin. With no input, stdin is the
512// null device.
513func gitInput(ctx context.Context, repo, input string, args ...string) ([]byte, error) {
514 var stdin io.Reader
515 if input != "" {
516 stdin = strings.NewReader(input)
517 }
518 stdout := &bounded{max: maxGitOutput, strict: true}
519 err := gitStream(ctx, repo, stdin, stdout, args...)
520 if stdout.over {
521 return nil, fmt.Errorf("git %s: %w", gitVerb(args), errTooLong)
522 }
523 if err != nil {
524 return nil, err
525 }
526 return stdout.Bytes(), nil
527}
528
529// gitStream runs git in repo, unless it is "", with stdin and stdout
530// given: with replacement refs off, git held to the transports a URL from
531// data may use, no prompt, and a fixed date for any commit it writes. It
532// keeps the caller's GIT_CONFIG_* variables, which carry the
533// safe.directory entries a host gives the publisher for repositories it
534// does not own.
535func gitStream(ctx context.Context, repo string, stdin io.Reader, stdout io.Writer, args ...string) error {
536 if repo != "" {
537 args = append([]string{"-C", repo}, args...)
538 }
539 cmd := exec.CommandContext(ctx, "git", append([]string{"--no-replace-objects"}, args...)...)
540 cmd.Env = gitEnvironment(os.Environ())
541 stderr := &bounded{max: maxStderr}
542 cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr
543 if err := cmd.Run(); err != nil {
544 return fmt.Errorf("git %s: %w: %s", gitVerb(args), err, strings.TrimSpace(stderr.String()))
545 }
546 return nil
547}
548
549// gitVerb is the git command args run, for messages: the first argument
550// after -C and the options git takes before its command.
551func gitVerb(args []string) string {
552 for i := 0; i < len(args); i++ {
553 switch args[i] {
554 case "-C", "-c":
555 i++
556 default:
557 return args[i]
558 }
559 }
560 return "git"
561}
562
563// errTooLong is the error for a program that printed more than its bound.
564var errTooLong = errors.New("it printed more than the publisher holds of it")
565
566// bounded holds what a program prints, up to max bytes. Past max, a write
567// fails when strict is set, which ends the program at its next write, and
568// is dropped when it is not. It is no io.ReaderFrom, so os/exec copies
569// through Write.
570type bounded struct {
571 buf bytes.Buffer
572 max int
573 strict bool
574 over bool
575}
576
577func (b *bounded) Write(p []byte) (int, error) {
578 room := max(b.max-b.buf.Len(), 0)
579 if len(p) <= room {
580 return b.buf.Write(p)
581 }
582 b.over = true
583 b.buf.Write(p[:room])
584 if b.strict {
585 return room, errTooLong
586 }
587 return len(p), nil
588}
589
590func (b *bounded) Bytes() []byte { return b.buf.Bytes() }
591func (b *bounded) String() string { return b.buf.String() }
592
593func gitEnvironment(environ []string) []string {
594 var env []string
595 for _, kv := range environ {
596 name, _, _ := strings.Cut(kv, "=")
597 switch {
598 case redirectsGit(name), name == "GIT_ALLOW_PROTOCOL", name == "GIT_TERMINAL_PROMPT",
599 name == "GIT_AUTHOR_DATE", name == "GIT_COMMITTER_DATE":
600 continue
601 }
602 env = append(env, kv)
603 }
604 return append(env,
605 "GIT_ALLOW_PROTOCOL=ssh:git:https:file",
606 "GIT_TERMINAL_PROMPT=0",
607 "GIT_NO_REPLACE_OBJECTS=1",
608 "GIT_AUTHOR_DATE=@0 +0000",
609 "GIT_COMMITTER_DATE=@0 +0000",
610 )
611}
612
613// redirectsGit reports whether the variable points git at another
614// repository, another object store or another work tree than the one it
615// is run in.
616func redirectsGit(name string) bool {
617 switch name {
618 case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_PREFIX",
619 "GIT_NAMESPACE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES":
620 return true
621 }
622 return false
623}
624
625// readPrincipals reads the display mapping: a JSON object from principal
626// names to the names an export shows. No file is an empty mapping, under
627// which every principal is shown as export.Unmapped.
628func readPrincipals(path string) (export.Principals, error) {
629 if path == "" {
630 return export.Principals{}, nil
631 }
632 data, err := os.ReadFile(path)
633 if err != nil {
634 return nil, err
635 }
636 dec := json.NewDecoder(bytes.NewReader(data))
637 var m export.Principals
638 if err := dec.Decode(&m); err != nil {
639 return nil, fmt.Errorf("the display mapping %s is not a JSON object of names: %w", path, err)
640 }
641 if err := dec.Decode(&json.RawMessage{}); err != io.EOF {
642 return nil, fmt.Errorf("the display mapping %s holds more than its one object", path)
643 }
644 if m == nil {
645 m = export.Principals{}
646 }
647 return m, nil
648}