gunk-dev/the-valley

visibility.go

sourced93cce9938afmain's published tip history
7.4 KiB
1package main
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "strconv"
11 "strings"
12 "time"
13
14 "the-valley/exactjson"
15)
16
17// webDir is where a repository keeps its web visibility declaration.
18const webDir = "policy/web"
19
20// The bounds on a declaration: how many documents it may have, how large
21// each may be, and how much cue may print for it. A declaration past them
22// is invalid, so the project is private.
23const (
24 maxDeclarationFiles = 32
25 maxDeclarationFile = 64 << 10
26 maxCueOutput = 1 << 20
27)
28
29// cueTimeout is how long a cue run may take. A run past it fails the pass:
30// how long cue takes depends on the host as much as on the declaration.
31var cueTimeout = time.Minute
32
33// cueRefused is the exit status cue ends with when it reports an error in
34// what it was given, as when the schema refuses a declaration. A Go
35// program that panics exits 2, and one the kernel kills has no status.
36const cueRefused = 1
37
38// errNoDeclaration is readDeclaration's error for a commit with no
39// policy/web/*.cue.
40var errNoDeclaration = errors.New("no policy/web declaration")
41
42// invalidDeclaration is readDeclaration's error for a declaration that is
43// there and is not one: cue ran over it to the end and refused it, or it
44// is past the bounds. A project whose declaration is invalid is private.
45// Any other error of readDeclaration's is a failure to read the
46// declaration, which ends the pass.
47type invalidDeclaration struct{ err error }
48
49func (e *invalidDeclaration) Error() string { return e.err.Error() }
50func (e *invalidDeclaration) Unwrap() error { return e.err }
51
52func invalid(format string, args ...any) error {
53 return &invalidDeclaration{fmt.Errorf(format, args...)}
54}
55
56// declaration is a policy/web declaration as cue exports it under
57// schema/web.cue.
58type declaration struct {
59 Project *visibility `json:"project"`
60 Instance *struct {
61 Projects map[string]visibility `json:"projects"`
62 } `json:"instance"`
63}
64
65type visibility struct {
66 Visibility string `json:"visibility"`
67}
68
69// readDeclaration reads the policy/web declaration at a commit of repo: the
70// *.cue documents directly in policy/web/, taken out with ls-tree and
71// cat-file rather than a checkout, and exported by cue under the schema.
72// Only regular files are read; a symbolic link or a submodule is not a
73// document. Its error is errNoDeclaration when the commit has none, an
74// *invalidDeclaration when the declaration is invalid, and any other error
75// when git or cue could not be run over it.
76func readDeclaration(ctx context.Context, repo, commit, schema string) (*declaration, error) {
77 entry, err := git(ctx, repo, "ls-tree", "-z", commit, "--", webDir)
78 if err != nil {
79 return nil, err
80 }
81 if len(entry) == 0 {
82 return nil, errNoDeclaration
83 }
84 meta, _, _ := strings.Cut(string(entry), "\t")
85 if f := strings.Fields(meta); len(f) != 3 || f[1] != "tree" {
86 return nil, invalid("%s is not a directory", webDir)
87 } else if entry, err = git(ctx, repo, "ls-tree", "-z", f[2]); errors.Is(err, errTooLong) {
88 return nil, invalid("%s lists more than %d bytes of entries", webDir, maxGitOutput)
89 } else if err != nil {
90 return nil, err
91 }
92 type document struct{ name, oid string }
93 var docs []document
94 for _, e := range strings.Split(string(entry), "\x00") {
95 meta, name, ok := strings.Cut(e, "\t")
96 if !ok || !strings.HasSuffix(name, ".cue") {
97 continue
98 }
99 fields := strings.Fields(meta)
100 if len(fields) != 3 || fields[1] != "blob" || (fields[0] != "100644" && fields[0] != "100755") {
101 continue
102 }
103 docs = append(docs, document{name, fields[2]})
104 }
105 if len(docs) == 0 {
106 return nil, errNoDeclaration
107 }
108 if len(docs) > maxDeclarationFiles {
109 return nil, invalid("%s holds %d documents, more than the %d a declaration may have", webDir, len(docs), maxDeclarationFiles)
110 }
111
112 scratch, err := os.MkdirTemp("", "valley-web-publish-")
113 if err != nil {
114 return nil, err
115 }
116 defer os.RemoveAll(scratch)
117 files := []string{schema}
118 for _, d := range docs {
119 out, err := git(ctx, repo, "cat-file", "-s", d.oid)
120 if err != nil {
121 return nil, err
122 }
123 size, err := strconv.ParseInt(strings.TrimSpace(string(out)), 10, 64)
124 if err != nil {
125 return nil, fmt.Errorf("git cat-file -s %s: %w", d.oid, err)
126 }
127 if size > maxDeclarationFile {
128 return nil, invalid("%s/%s is %d bytes, more than the %d a document may be", webDir, d.name, size, maxDeclarationFile)
129 }
130 body, err := git(ctx, repo, "cat-file", "blob", d.oid)
131 if err != nil {
132 return nil, err
133 }
134 path := filepath.Join(scratch, d.name)
135 if err := os.WriteFile(path, body, 0o600); err != nil {
136 return nil, err
137 }
138 files = append(files, path)
139 }
140
141 out, err := cueExport(ctx, scratch, files)
142 if err != nil {
143 return nil, err
144 }
145 var d declaration
146 if err := exactjson.Decode(out, &d); err != nil {
147 return nil, invalid("the declaration is not what schema/web.cue exports: %w", err)
148 }
149 return &d, nil
150}
151
152// cueExport runs cue export --out json over the files, in dir. Only what
153// the files decide is an *invalidDeclaration: a run that ends with
154// cueRefused, and a run that prints more than maxCueOutput. Every other
155// failure is an error of its own, which ends the pass: a cue that could
156// not be started, that crashed, that was killed or that ran past
157// cueTimeout, and a pass that was cancelled.
158func cueExport(ctx context.Context, dir string, files []string) ([]byte, error) {
159 cueCtx, cancel := context.WithTimeout(ctx, cueTimeout)
160 defer cancel()
161 cmd := exec.CommandContext(cueCtx, "cue", append([]string{"export", "--out", "json"}, files...)...)
162 cmd.Dir = dir
163 cmd.Env = cueEnvironment(os.Environ())
164 stdout := &bounded{max: maxCueOutput, strict: true}
165 stderr := &bounded{max: maxStderr}
166 cmd.Stdout, cmd.Stderr = stdout, stderr
167 err := cmd.Run()
168 said := fmt.Sprint(err)
169 if first, _, _ := strings.Cut(strings.TrimSpace(stderr.String()), "\n"); first != "" {
170 said += ": " + first
171 }
172 var exit *exec.ExitError
173 switch {
174 case ctx.Err() != nil:
175 return nil, ctx.Err()
176 case stdout.over:
177 return nil, invalid("cue exported more than %d bytes", maxCueOutput)
178 case cueCtx.Err() != nil:
179 return nil, fmt.Errorf("cue took longer than %v, so the declaration was not read", cueTimeout)
180 case errors.As(err, &exit) && exit.ExitCode() == cueRefused:
181 return nil, invalid("cue export: %s", said)
182 case errors.As(err, &exit):
183 return nil, fmt.Errorf("cue did not finish reading the declaration: %s", said)
184 case err != nil:
185 return nil, fmt.Errorf("could not run cue: %w", err)
186 }
187 return stdout.Bytes(), nil
188}
189
190// checkSchema holds the schema to exporting on its own, as schema/web.cue
191// does, before any declaration is read under it. Without it a schema that
192// cannot be read would make every declaration invalid, and every project
193// private.
194func checkSchema(ctx context.Context, schema string) error {
195 dir, err := os.MkdirTemp("", "valley-web-publish-")
196 if err != nil {
197 return err
198 }
199 defer os.RemoveAll(dir)
200 if _, err := cueExport(ctx, dir, []string{schema}); err != nil {
201 return fmt.Errorf("the schema %s does not load: %w", schema, err)
202 }
203 return nil
204}
205
206// cueEnvironment is the caller's environment without CUE's own variables,
207// so a declaration is read the same way whoever runs the publisher. The
208// documents are copied into a scratch directory with no cue.mod, so cue
209// resolves no import beyond its standard library.
210func cueEnvironment(environ []string) []string {
211 var env []string
212 for _, kv := range environ {
213 if !strings.HasPrefix(kv, "CUE_") {
214 env = append(env, kv)
215 }
216 }
217 return env
218}