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