gunk-dev/the-valley

visibility.go

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