gunk-dev/the-valley

visibility.go

source43d938c6651fmain's published tip history
4.5 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, and how long cue may take over them. A declaration past
23// them is invalid, so the project is private.
24const (
25 maxDeclarationFiles = 32
26 maxDeclarationFile = 64 << 10
27 cueTimeout = time.Minute
28)
29
30// errNoDeclaration is readDeclaration's error for a commit with no
31// policy/web/*.cue.
32var errNoDeclaration = errors.New("no policy/web declaration")
33
34// declaration is a policy/web declaration as cue exports it under
35// schema/web.cue.
36type declaration struct {
37 Project *visibility `json:"project"`
38 Instance *struct {
39 Projects map[string]visibility `json:"projects"`
40 } `json:"instance"`
41}
42
43type visibility struct {
44 Visibility string `json:"visibility"`
45}
46
47// readDeclaration reads the policy/web declaration at a commit of repo: the
48// *.cue documents directly in policy/web/, taken out with ls-tree and
49// cat-file rather than a checkout, and exported by cue under the schema.
50// Only regular files are read; a symbolic link or a submodule is not a
51// document. Its error is errNoDeclaration when the commit has none, and
52// another error when the declaration is invalid.
53func readDeclaration(ctx context.Context, repo, commit, schema string) (*declaration, error) {
54 listing, err := git(ctx, repo, "ls-tree", "-z", commit+":"+webDir)
55 if err != nil {
56 if ctx.Err() != nil {
57 return nil, ctx.Err()
58 }
59 return nil, errNoDeclaration // no such directory
60 }
61 type document struct{ name, oid string }
62 var docs []document
63 for _, entry := range strings.Split(string(listing), "\x00") {
64 meta, name, ok := strings.Cut(entry, "\t")
65 if !ok || !strings.HasSuffix(name, ".cue") {
66 continue
67 }
68 fields := strings.Fields(meta)
69 if len(fields) != 3 || fields[1] != "blob" || (fields[0] != "100644" && fields[0] != "100755") {
70 continue
71 }
72 docs = append(docs, document{name, fields[2]})
73 }
74 if len(docs) == 0 {
75 return nil, errNoDeclaration
76 }
77 if len(docs) > maxDeclarationFiles {
78 return nil, fmt.Errorf("%s holds %d documents, more than the %d a declaration may have", webDir, len(docs), maxDeclarationFiles)
79 }
80
81 scratch, err := os.MkdirTemp("", "valley-web-publish-")
82 if err != nil {
83 return nil, err
84 }
85 defer os.RemoveAll(scratch)
86 files := []string{schema}
87 for _, d := range docs {
88 out, err := git(ctx, repo, "cat-file", "-s", d.oid)
89 if err != nil {
90 return nil, err
91 }
92 size, err := strconv.ParseInt(strings.TrimSpace(string(out)), 10, 64)
93 if err != nil {
94 return nil, fmt.Errorf("git cat-file -s %s: %w", d.oid, err)
95 }
96 if size > maxDeclarationFile {
97 return nil, fmt.Errorf("%s/%s is %d bytes, more than the %d a document may be", webDir, d.name, size, maxDeclarationFile)
98 }
99 body, err := git(ctx, repo, "cat-file", "blob", d.oid)
100 if err != nil {
101 return nil, err
102 }
103 path := filepath.Join(scratch, d.name)
104 if err := os.WriteFile(path, body, 0o600); err != nil {
105 return nil, err
106 }
107 files = append(files, path)
108 }
109
110 cueCtx, cancel := context.WithTimeout(ctx, cueTimeout)
111 defer cancel()
112 cmd := exec.CommandContext(cueCtx, "cue", append([]string{"export", "--out", "json"}, files...)...)
113 cmd.Dir = scratch
114 cmd.Env = cueEnvironment(os.Environ())
115 var stdout, stderr bytes.Buffer
116 cmd.Stdout, cmd.Stderr = &stdout, &stderr
117 if err := cmd.Run(); err != nil {
118 if ctx.Err() != nil {
119 return nil, ctx.Err()
120 }
121 first, _, _ := strings.Cut(strings.TrimSpace(stderr.String()), "\n")
122 return nil, fmt.Errorf("cue export: %v: %s", err, first)
123 }
124 dec := json.NewDecoder(&stdout)
125 dec.DisallowUnknownFields()
126 var d declaration
127 if err := dec.Decode(&d); err != nil {
128 return nil, fmt.Errorf("the declaration is not what schema/web.cue exports: %w", err)
129 }
130 if err := dec.Decode(&json.RawMessage{}); err != io.EOF {
131 return nil, errors.New("cue exported more than one document")
132 }
133 return &d, nil
134}
135
136// cueEnvironment is the caller's environment without CUE's own variables,
137// so a declaration is read the same way whoever runs the publisher. The
138// documents are copied into a scratch directory with no cue.mod, so cue
139// resolves no import beyond its standard library.
140func cueEnvironment(environ []string) []string {
141 var env []string
142 for _, kv := range environ {
143 if !strings.HasPrefix(kv, "CUE_") {
144 env = append(env, kv)
145 }
146 }
147 return env
148}