gunk-dev/the-valley

valley.go

sourcefce1c319f644main's published tip history
18.3 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. Each knot's detail is
43// read after the plan, so a write to the graph in between makes the two
44// disagree; export.Build says so with ErrInconsistent, and collect reads
45// everything again. It does the same when the instance repository moved
46// during a read.
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 var err error
55 for attempt := 1; attempt <= readAttempts; attempt++ {
56 var r *reading
57 r, err = p.read(ctx)
58 if err == nil {
59 return r, nil
60 }
61 if !errors.Is(err, export.ErrInconsistent) {
62 return nil, err
63 }
64 p.warn("%v; reading the valley again", err)
65 }
66 return nil, fmt.Errorf("the valley changed under every one of %d reads: %w", readAttempts, err)
67}
68
69// planListing and pendingListing are what the publisher reads of the
70// valley's JSON itself: which projects there are, each project's knots,
71// and where each can be read. export.Build reads the rest.
72type (
73 planListing struct {
74 Projects []struct {
75 Project string `json:"project"`
76 Knots []struct {
77 ID string `json:"id"`
78 } `json:"knots"`
79 } `json:"projects"`
80 }
81 pendingListing struct {
82 Repos []pendingRepo `json:"repos"`
83 }
84 pendingRepo struct {
85 Repo string `json:"repo"`
86 URL string `json:"url"`
87 Error *string `json:"error"`
88 }
89)
90
91// read is one read of the valley. A project is private when the instance
92// does not allow it, or when its own declaration is missing, invalid or
93// private. Any other failure to read a project the instance allows ends
94// the pass: an export without it would take it off the web.
95func (p *publisher) read(ctx context.Context) (*reading, error) {
96 inst, err := p.fetchInstance(ctx)
97 if err != nil {
98 return nil, err
99 }
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, "plan", "--all", "--json")
116 if err != nil {
117 return nil, err
118 }
119 pendingJSON, err := p.valley(ctx, "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, "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 if err := p.confirmInstance(ctx, inst); err != nil {
182 return nil, err
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 if _, err := os.Stat(filepath.Join(p.origin, "HEAD")); errors.Is(err, os.ErrNotExist) {
251 if err := os.RemoveAll(p.origin); err != nil {
252 return err
253 }
254 if _, err := git(ctx, "", "init", "--quiet", "--bare", "--template=", p.origin); err != nil {
255 return err
256 }
257 }
258 got, err := git(ctx, p.origin, "config", "--get", "remote.origin.url")
259 if err == nil && strings.TrimSpace(string(got)) == p.cfg.instanceRepo {
260 return nil
261 }
262 _, _ = git(ctx, p.origin, "remote", "remove", "origin")
263 _, err = git(ctx, p.origin, "remote", "add", "--end-of-options", "origin", p.cfg.instanceRepo)
264 return err
265}
266
267// The instance repository's project list, and where the publisher's
268// repository keeps what it fetched of the instance.
269const (
270 projectsRef = "refs/the-valley/projects"
271 originMain = "refs/remotes/origin/main"
272 originProjects = "refs/remotes/origin/projects"
273)
274
275// instanceRead is the instance repository as a read found it: main's tip,
276// the project list it publishes, and the projects that list names.
277type instanceRead struct {
278 tip, list string
279 projects []string
280}
281
282// fetchInstance fetches the instance repository's main and its project
283// list into the publisher's repository. A repository whose main carries no
284// policy/instance is not an instance repository. One whose main carries
285// policy/valley is refused: the valley CLI would follow it to the instance
286// it names, for the projects and for the signers, and the publisher reads
287// through no instance but the one it is given.
288func (p *publisher) fetchInstance(ctx context.Context) (instanceRead, error) {
289 var r instanceRead
290 if _, err := git(ctx, p.origin, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "origin",
291 "+refs/heads/main:"+originMain, "+"+projectsRef+":"+originProjects); err != nil {
292 return r, fmt.Errorf("could not read main and %s in the instance repository: %w", projectsRef, err)
293 }
294 var err error
295 if r.tip, err = revParse(ctx, p.origin, originMain+"^{commit}"); err != nil {
296 return r, err
297 }
298 if _, err := git(ctx, p.origin, "cat-file", "-e", r.tip+":policy/instance"); err != nil {
299 return r, fmt.Errorf("%s holds no policy/instance on main, so it is not an instance repository", p.cfg.instanceRepo)
300 }
301 if _, err := git(ctx, p.origin, "cat-file", "-e", r.tip+":policy/valley"); err == nil {
302 return r, fmt.Errorf("%s holds policy/valley on main, which would point the valley CLI at another instance; an instance repository the publisher reads holds policy/instance and no policy/valley", p.cfg.instanceRepo)
303 }
304 if r.list, err = revParse(ctx, p.origin, originProjects); err != nil {
305 return r, err
306 }
307 list, err := git(ctx, p.origin, "cat-file", "blob", r.list)
308 if err != nil {
309 return r, fmt.Errorf("%s in the instance repository is not a list of projects: %w", projectsRef, err)
310 }
311 for _, name := range strings.Split(string(list), "\n") {
312 if name != "" {
313 r.projects = append(r.projects, name)
314 }
315 }
316 sort.Strings(r.projects)
317 return r, nil
318}
319
320// confirmInstance fetches the instance repository again once a read is
321// done. Each valley command reads main and the project list afresh, so the
322// read holds only when both are where it began; a main that moved may have
323// carried a policy/valley the CLI followed.
324func (p *publisher) confirmInstance(ctx context.Context, began instanceRead) error {
325 now, err := p.fetchInstance(ctx)
326 if err != nil {
327 return err
328 }
329 if now.tip != began.tip || now.list != began.list {
330 return fmt.Errorf("%w: the instance repository's main or project list moved during the read", export.ErrInconsistent)
331 }
332 return nil
333}
334
335// errNoMain is fetchMain's error for a project with no main.
336var errNoMain = errors.New("no main")
337
338// fetchMain brings a project's main into its mirror, a bare repository
339// under the cache that holds main alone, and returns the mirror and main's
340// tip, or errNoMain when the project has none. A mirror is first made by a clone, so it has the project's object
341// format, and the clone is renamed into place only once it is whole. The
342// clone copies objects through the transport, as a fetch does, and never
343// links the project's own files.
344func (p *publisher) fetchMain(ctx context.Context, name, url string) (string, string, error) {
345 heads, err := git(ctx, p.origin, "ls-remote", "--end-of-options", url, "refs/heads/main")
346 if err != nil {
347 return "", "", err
348 }
349 if !listsRef(heads, "refs/heads/main") {
350 return "", "", errNoMain
351 }
352 mirror := filepath.Join(p.cache, "repos", name+".git")
353 if _, err := os.Stat(filepath.Join(mirror, "HEAD")); err == nil {
354 if _, err := git(ctx, mirror, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head",
355 "--end-of-options", url, "+refs/heads/main:refs/heads/main"); err != nil {
356 return "", "", err
357 }
358 } else {
359 if err := os.MkdirAll(filepath.Dir(mirror), 0o700); err != nil {
360 return "", "", err
361 }
362 made, err := os.MkdirTemp(filepath.Dir(mirror), "."+name+".new-")
363 if err != nil {
364 return "", "", err
365 }
366 defer os.RemoveAll(made)
367 clone := filepath.Join(made, "repo.git")
368 if _, err := git(ctx, "", "clone", "--quiet", "--bare", "--no-local", "--no-tags", "--single-branch",
369 "--branch", "main", "--template=", "--end-of-options", url, clone); err != nil {
370 return "", "", err
371 }
372 if err := os.RemoveAll(mirror); err != nil {
373 return "", "", err
374 }
375 if err := os.Rename(clone, mirror); err != nil {
376 return "", "", err
377 }
378 }
379 tip, err := revParse(ctx, mirror, "refs/heads/main^{commit}")
380 return mirror, tip, err
381}
382
383// listsRef reports whether ls-remote's output lists the ref. ls-remote
384// matches a pattern against the tail of a ref name, so each name listed
385// is compared whole.
386func listsRef(out []byte, ref string) bool {
387 for _, line := range strings.Split(string(out), "\n") {
388 if _, name, ok := strings.Cut(line, "\t"); ok && name == ref {
389 return true
390 }
391 }
392 return false
393}
394
395func revParse(ctx context.Context, repo, rev string) (string, error) {
396 out, err := git(ctx, repo, "rev-parse", "--verify", "--end-of-options", rev)
397 if err != nil {
398 return "", err
399 }
400 return strings.TrimSpace(string(out)), nil
401}
402
403// valley runs one of the CLI's JSON commands in the publisher's repository
404// and returns what it printed, up to maxValleyOutput. What it says on
405// stderr is passed on.
406func (p *publisher) valley(ctx context.Context, args ...string) ([]byte, error) {
407 cmd := exec.CommandContext(ctx, "valley", args...)
408 cmd.Dir = p.origin
409 cmd.Env = valleyEnvironment(os.Environ())
410 stdout := &bounded{max: maxValleyOutput, strict: true}
411 cmd.Stdout = stdout
412 cmd.Stderr = p.stderr
413 err := cmd.Run()
414 if stdout.over {
415 return nil, fmt.Errorf("valley %s: %w", strings.Join(args, " "), errTooLong)
416 }
417 if err != nil {
418 return nil, fmt.Errorf("valley %s: %w", strings.Join(args, " "), err)
419 }
420 return stdout.Bytes(), nil
421}
422
423// valleyEnvironment is the environment the valley CLI runs in: the
424// caller's, without the variables that would point git at another
425// repository, and without the ones that would give the CLI verification
426// material of their own. The CLI then reads the signers the host publishes,
427// as it reads the projects.
428func valleyEnvironment(environ []string) []string {
429 var env []string
430 for _, kv := range environ {
431 name, _, _ := strings.Cut(kv, "=")
432 if redirectsGit(name) || name == "VALLEY_KNOWN_SIGNERS" || name == "VALLEY_INTEGRATOR_SIGNER" {
433 continue
434 }
435 env = append(env, kv)
436 }
437 return env
438}
439
440// git runs git in repo, unless it is "", with replacement refs off, git
441// held to the transports a URL from data may use, and no prompt, and
442// returns what it printed, up to maxGitOutput. It keeps the caller's
443// GIT_CONFIG_* variables, which carry the safe.directory entries a host
444// gives the publisher for repositories it does not own.
445func git(ctx context.Context, repo string, args ...string) ([]byte, error) {
446 if repo != "" {
447 args = append([]string{"-C", repo}, args...)
448 }
449 cmd := exec.CommandContext(ctx, "git", append([]string{"--no-replace-objects"}, args...)...)
450 cmd.Env = gitEnvironment(os.Environ())
451 stdout := &bounded{max: maxGitOutput, strict: true}
452 stderr := &bounded{max: maxStderr}
453 cmd.Stdout, cmd.Stderr = stdout, stderr
454 err := cmd.Run()
455 verb := args[0]
456 if verb == "-C" && len(args) > 2 {
457 verb = args[2]
458 }
459 if stdout.over {
460 return nil, fmt.Errorf("git %s: %w", verb, errTooLong)
461 }
462 if err != nil {
463 return nil, fmt.Errorf("git %s: %w: %s", verb, err, strings.TrimSpace(stderr.String()))
464 }
465 return stdout.Bytes(), nil
466}
467
468// errTooLong is the error for a program that printed more than its bound.
469var errTooLong = errors.New("it printed more than the publisher holds of it")
470
471// bounded holds what a program prints, up to max bytes. Past max, a write
472// fails when strict is set, which ends the program at its next write, and
473// is dropped when it is not. It is no io.ReaderFrom, so os/exec copies
474// through Write.
475type bounded struct {
476 buf bytes.Buffer
477 max int
478 strict bool
479 over bool
480}
481
482func (b *bounded) Write(p []byte) (int, error) {
483 room := max(b.max-b.buf.Len(), 0)
484 if len(p) <= room {
485 return b.buf.Write(p)
486 }
487 b.over = true
488 b.buf.Write(p[:room])
489 if b.strict {
490 return room, errTooLong
491 }
492 return len(p), nil
493}
494
495func (b *bounded) Bytes() []byte { return b.buf.Bytes() }
496func (b *bounded) String() string { return b.buf.String() }
497
498func gitEnvironment(environ []string) []string {
499 var env []string
500 for _, kv := range environ {
501 name, _, _ := strings.Cut(kv, "=")
502 if redirectsGit(name) || name == "GIT_ALLOW_PROTOCOL" || name == "GIT_TERMINAL_PROMPT" {
503 continue
504 }
505 env = append(env, kv)
506 }
507 return append(env,
508 "GIT_ALLOW_PROTOCOL=ssh:git:https:file",
509 "GIT_TERMINAL_PROMPT=0",
510 "GIT_NO_REPLACE_OBJECTS=1",
511 )
512}
513
514// redirectsGit reports whether the variable points git at another
515// repository, another object store or another work tree than the one it
516// is run in.
517func redirectsGit(name string) bool {
518 switch name {
519 case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_PREFIX",
520 "GIT_NAMESPACE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES":
521 return true
522 }
523 return false
524}
525
526// readPrincipals reads the display mapping: a JSON object from principal
527// names to the names an export shows. No file is an empty mapping, under
528// which every principal is shown as export.Unmapped.
529func readPrincipals(path string) (export.Principals, error) {
530 if path == "" {
531 return export.Principals{}, nil
532 }
533 data, err := os.ReadFile(path)
534 if err != nil {
535 return nil, err
536 }
537 dec := json.NewDecoder(bytes.NewReader(data))
538 var m export.Principals
539 if err := dec.Decode(&m); err != nil {
540 return nil, fmt.Errorf("the display mapping %s is not a JSON object of names: %w", path, err)
541 }
542 if err := dec.Decode(&json.RawMessage{}); err != io.EOF {
543 return nil, fmt.Errorf("the display mapping %s holds more than its one object", path)
544 }
545 if m == nil {
546 m = export.Principals{}
547 }
548 return m, nil
549}