gunk-dev/the-valley

valley.go

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