| 1 | package readaccess |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "path" |
| 12 | "path/filepath" |
| 13 | "regexp" |
| 14 | "slices" |
| 15 | "strconv" |
| 16 | "strings" |
| 17 | "time" |
| 18 | |
| 19 | "the-valley/exactjson" |
| 20 | ) |
| 21 | |
| 22 | // PolicyDir is where a project keeps its consent: the *.cue documents |
| 23 | // directly in this directory of its main. |
| 24 | const PolicyDir = "policy/read" |
| 25 | |
| 26 | // ErrMissing is the error for a commit that holds no document where one is |
| 27 | // read: no *.cue file directly in the directory, or no directory. |
| 28 | var ErrMissing = errors.New("no document") |
| 29 | |
| 30 | // InvalidError is the error for a document that is there and is not valid: |
| 31 | // cue refused it under its schema, or it is past the bounds, malformed, or |
| 32 | // for another project. An invalid document consents to nothing. Every |
| 33 | // other error of a Reader's is a failure to read, which consents to |
| 34 | // nothing either, and which a caller reports rather than acting on. |
| 35 | type InvalidError struct{ Err error } |
| 36 | |
| 37 | func (e *InvalidError) Error() string { return e.Err.Error() } |
| 38 | func (e *InvalidError) Unwrap() error { return e.Err } |
| 39 | |
| 40 | func invalid(format string, args ...any) error { |
| 41 | return &InvalidError{fmt.Errorf(format, args...)} |
| 42 | } |
| 43 | |
| 44 | // Reader reads the two consents out of git commits, with git and cue. It |
| 45 | // reads a document's *.cue files with git ls-tree and cat-file, never a |
| 46 | // checkout, copies them into a scratch directory with no cue.mod, so cue |
| 47 | // resolves no import beyond its standard library, and exports them as JSON |
| 48 | // with cue under the document's schema. It decodes the JSON with |
| 49 | // exactjson, which refuses a key that is not one of the schema's fields |
| 50 | // spelled exactly, and a key twice in one object. Then it holds the names, |
| 51 | // identities and scopes it acts on to the schema's rules again, so a |
| 52 | // document that redeclares a definition of the schema widens nothing. |
| 53 | type Reader struct { |
| 54 | // ReadSchema is schema/read.cue, and IdentitySchema is |
| 55 | // schema/identity.cue. |
| 56 | ReadSchema, IdentitySchema string |
| 57 | |
| 58 | // CueTimeout bounds each cue run. Zero is a minute. |
| 59 | CueTimeout time.Duration |
| 60 | } |
| 61 | |
| 62 | // The bounds on a document: how many files it may have, how large each may |
| 63 | // be, and how much cue may print for it. A document past them is invalid. |
| 64 | // A registry carries keys and attestations, so its bounds are larger. |
| 65 | type bounds struct { |
| 66 | files int |
| 67 | file int64 |
| 68 | output int |
| 69 | } |
| 70 | |
| 71 | var ( |
| 72 | policyBounds = bounds{files: 32, file: 64 << 10, output: 1 << 20} |
| 73 | registryBounds = bounds{files: 64, file: 1 << 20, output: 8 << 20} |
| 74 | ) |
| 75 | |
| 76 | // The bounds on what git and cue print. git's output past maxGitOutput |
| 77 | // fails the call, and what a program prints on stderr past maxStderr is |
| 78 | // dropped. |
| 79 | const ( |
| 80 | maxGitOutput = 4 << 20 |
| 81 | maxStderr = 64 << 10 |
| 82 | ) |
| 83 | |
| 84 | // cueRefused is the exit status cue ends with when it reports an error in |
| 85 | // what it was given, as when a schema refuses a document. A Go program that |
| 86 | // panics exits 2, and one the kernel kills has no status. |
| 87 | const cueRefused = 1 |
| 88 | |
| 89 | // CheckSchemas holds each schema to loading on its own, before any |
| 90 | // document is read under it. Without it a schema that cannot be read would |
| 91 | // make every document invalid, and so withdraw every consent. |
| 92 | func (r *Reader) CheckSchemas(ctx context.Context) error { |
| 93 | dir, err := os.MkdirTemp("", "readaccess-") |
| 94 | if err != nil { |
| 95 | return err |
| 96 | } |
| 97 | defer os.RemoveAll(dir) |
| 98 | for _, schema := range []string{r.ReadSchema, r.IdentitySchema} { |
| 99 | if schema == "" { |
| 100 | return errors.New("no schema given") |
| 101 | } |
| 102 | if _, err := r.cue(ctx, dir, 0, "vet", "-c=false", schema); err != nil { |
| 103 | return fmt.Errorf("the schema %s does not load: %w", schema, err) |
| 104 | } |
| 105 | } |
| 106 | return nil |
| 107 | } |
| 108 | |
| 109 | // policyDoc is a policy/read as cue exports it under schema/read.cue. |
| 110 | type policyDoc struct { |
| 111 | Project string `json:"project"` |
| 112 | Identity string `json:"identity"` |
| 113 | Readers map[string]bool `json:"readers"` |
| 114 | } |
| 115 | |
| 116 | // Consent reads the consent of the project at a commit of repo: its |
| 117 | // policy/read under ReadSchema. A policy that names another project than |
| 118 | // the one it is read from is invalid. |
| 119 | func (r *Reader) Consent(ctx context.Context, repo, commit, project string) (Consent, error) { |
| 120 | var doc policyDoc |
| 121 | if err := r.read(ctx, repo, commit, PolicyDir, r.ReadSchema, policyBounds, &doc); err != nil { |
| 122 | return Consent{}, err |
| 123 | } |
| 124 | switch { |
| 125 | case !validProject(doc.Project): |
| 126 | return Consent{}, invalid("%s names the project %q, which is not a project name", PolicyDir, doc.Project) |
| 127 | case doc.Project != project: |
| 128 | return Consent{}, invalid("%s is for the project %q, and was read from %q", PolicyDir, doc.Project, project) |
| 129 | case !identityPattern.MatchString(doc.Identity): |
| 130 | return Consent{}, invalid("%s declares the identity %q, which is not a publication identity", PolicyDir, doc.Identity) |
| 131 | } |
| 132 | c := Consent{Project: doc.Project, Identity: doc.Identity, Readers: []string{}} |
| 133 | for reader, ok := range doc.Readers { |
| 134 | if !ok || !namePattern.MatchString(reader) { |
| 135 | return Consent{}, invalid("%s names the reader %q, which is not a principal name", PolicyDir, reader) |
| 136 | } |
| 137 | c.Readers = append(c.Readers, reader) |
| 138 | } |
| 139 | slices.Sort(c.Readers) |
| 140 | return c, nil |
| 141 | } |
| 142 | |
| 143 | // registryDoc is the identity registry as cue exports it under |
| 144 | // schema/identity.cue. The parts the read grants do not depend on are |
| 145 | // taken as raw JSON, and exactjson holds every other field to the |
| 146 | // schema's. |
| 147 | type registryDoc struct { |
| 148 | Boundaries map[string]struct { |
| 149 | Kind string `json:"kind"` |
| 150 | Destination string `json:"destination"` |
| 151 | } `json:"boundaries"` |
| 152 | Principals map[string]struct { |
| 153 | Kind string `json:"kind"` |
| 154 | Keys json.RawMessage `json:"keys"` |
| 155 | Grants map[string]grantDoc `json:"grants"` |
| 156 | External json.RawMessage `json:"external"` |
| 157 | Expires string `json:"expires"` |
| 158 | } `json:"principals"` |
| 159 | Anyone *struct { |
| 160 | Grants map[string]grantDoc `json:"grants"` |
| 161 | } `json:"anyone"` |
| 162 | Genesis string `json:"genesis"` |
| 163 | GenesisGovernance json.RawMessage `json:"genesisGovernance"` |
| 164 | ExternalGovernance json.RawMessage `json:"externalGovernance"` |
| 165 | ReadScopes json.RawMessage `json:"readScopes"` |
| 166 | } |
| 167 | |
| 168 | type grantDoc struct { |
| 169 | Boundary string `json:"boundary"` |
| 170 | Projects json.RawMessage `json:"projects"` |
| 171 | } |
| 172 | |
| 173 | // edgeRead is the boundary kind that checks read grants. |
| 174 | const edgeRead = "edge-read" |
| 175 | |
| 176 | // Grants reads the instance's read grants at the destination: the grants |
| 177 | // at every edge read boundary that names it, from the registry in dir at a |
| 178 | // commit of the instance repository, under IdentitySchema. A principal |
| 179 | // whose expiry has arrived on day holds none, as the identity compiler |
| 180 | // omits it from every artifact. |
| 181 | func (r *Reader) Grants(ctx context.Context, repo, commit, dir, destination string, day time.Time) (Grants, error) { |
| 182 | if !validDir(dir) { |
| 183 | return nil, fmt.Errorf("%q is not a directory a commit can hold", dir) |
| 184 | } |
| 185 | if !namePattern.MatchString(destination) { |
| 186 | return nil, fmt.Errorf("%q is not a destination name", destination) |
| 187 | } |
| 188 | var doc registryDoc |
| 189 | if err := r.read(ctx, repo, commit, dir, r.IdentitySchema, registryBounds, &doc); err != nil { |
| 190 | return nil, err |
| 191 | } |
| 192 | y, m, d := day.UTC().Date() |
| 193 | today := time.Date(y, m, d, 0, 0, 0, 0, time.UTC) |
| 194 | |
| 195 | g := Grants{} |
| 196 | add := func(principal, name string, grant grantDoc) error { |
| 197 | b, ok := doc.Boundaries[grant.Boundary] |
| 198 | switch { |
| 199 | case !ok: |
| 200 | return invalid("the grant %s.%s names the boundary %q, which the registry does not declare", principal, name, grant.Boundary) |
| 201 | case b.Kind != edgeRead && principal == Anyone: |
| 202 | return invalid("anyone holds the grant %s at a boundary of kind %q; anyone holds read grants alone", name, b.Kind) |
| 203 | case b.Kind != edgeRead && grant.Projects != nil: |
| 204 | return invalid("the grant %s.%s names projects at a boundary of kind %q", principal, name, b.Kind) |
| 205 | case b.Kind != edgeRead: |
| 206 | return nil |
| 207 | case !namePattern.MatchString(b.Destination): |
| 208 | return invalid("the boundary %s names the destination %q, which is not a name", grant.Boundary, b.Destination) |
| 209 | } |
| 210 | s, err := parseScope(grant.Projects) |
| 211 | if err != nil { |
| 212 | return invalid("the grant %s.%s: %w", principal, name, err) |
| 213 | } |
| 214 | if b.Destination == destination { |
| 215 | g[principal] = append(g[principal], s) |
| 216 | } |
| 217 | return nil |
| 218 | } |
| 219 | for principal, p := range doc.Principals { |
| 220 | if principal == Anyone || !namePattern.MatchString(principal) { |
| 221 | return nil, invalid("the registry names the principal %q, which is reserved or not a principal name", principal) |
| 222 | } |
| 223 | if p.Expires != "" { |
| 224 | end, err := time.Parse(time.DateOnly, p.Expires) |
| 225 | if err != nil { |
| 226 | return nil, invalid("%s expires %q, which is not a calendar day", principal, p.Expires) |
| 227 | } |
| 228 | if !today.Before(end) { |
| 229 | continue |
| 230 | } |
| 231 | } |
| 232 | for name, grant := range p.Grants { |
| 233 | if err := add(principal, name, grant); err != nil { |
| 234 | return nil, err |
| 235 | } |
| 236 | } |
| 237 | } |
| 238 | if doc.Anyone != nil { |
| 239 | for name, grant := range doc.Anyone.Grants { |
| 240 | if err := add(Anyone, name, grant); err != nil { |
| 241 | return nil, err |
| 242 | } |
| 243 | } |
| 244 | } |
| 245 | return g, nil |
| 246 | } |
| 247 | |
| 248 | // parseScope reads a read grant's projects: "all", or an object of project |
| 249 | // names and publication identities. |
| 250 | func parseScope(raw json.RawMessage) (Scope, error) { |
| 251 | var all string |
| 252 | if err := json.Unmarshal(raw, &all); err == nil { |
| 253 | if all != "all" { |
| 254 | return Scope{}, fmt.Errorf("its projects are %q, which is neither \"all\" nor a set of projects", all) |
| 255 | } |
| 256 | return Scope{All: true}, nil |
| 257 | } |
| 258 | s := Scope{Projects: map[string]string{}} |
| 259 | if err := json.Unmarshal(raw, &s.Projects); err != nil || s.Projects == nil { |
| 260 | return Scope{}, errors.New("its projects are neither \"all\" nor a set of projects") |
| 261 | } |
| 262 | for project, identity := range s.Projects { |
| 263 | if !validProject(project) || !identityPattern.MatchString(identity) { |
| 264 | return Scope{}, fmt.Errorf("it names the project %q with the identity %q, and not a project name with a publication identity", project, identity) |
| 265 | } |
| 266 | } |
| 267 | return s, nil |
| 268 | } |
| 269 | |
| 270 | var ( |
| 271 | namePattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]*$`) |
| 272 | identityPattern = regexp.MustCompile(`^[0-9a-f]{32}$`) |
| 273 | ) |
| 274 | |
| 275 | // validProject reports whether name is a project name: the principal-name |
| 276 | // pattern, at most 64 bytes, as schema/read.cue holds it. |
| 277 | func validProject(name string) bool { |
| 278 | return len(name) <= 64 && namePattern.MatchString(name) |
| 279 | } |
| 280 | |
| 281 | // validDir reports whether dir is a relative path to a directory below a |
| 282 | // commit's root, written plainly. |
| 283 | func validDir(dir string) bool { |
| 284 | return dir != "" && dir != "." && path.Clean(dir) == dir && !path.IsAbs(dir) && |
| 285 | dir != ".." && !strings.HasPrefix(dir, "../") |
| 286 | } |
| 287 | |
| 288 | // ValidRef reports whether ref is a full ref name, which the registry can be |
| 289 | // read at: it opens with refs/, and git check-ref-format accepts it. So no |
| 290 | // component is empty, opens with a dot or ends with .lock, and the name |
| 291 | // holds no "..", no "@{", no control character, space, ~, ^, :, ?, *, [ |
| 292 | // or backslash, and does not end with a dot. |
| 293 | func ValidRef(ref string) bool { |
| 294 | if !strings.HasPrefix(ref, "refs/") || strings.HasSuffix(ref, ".") || |
| 295 | strings.Contains(ref, "..") || strings.Contains(ref, "@{") || |
| 296 | strings.ContainsFunc(ref, func(r rune) bool { return r < 0x20 || r == 0x7f || strings.ContainsRune(" ~^:?*[\\", r) }) { |
| 297 | return false |
| 298 | } |
| 299 | for _, part := range strings.Split(ref, "/") { |
| 300 | if part == "" || strings.HasPrefix(part, ".") || strings.HasSuffix(part, ".lock") { |
| 301 | return false |
| 302 | } |
| 303 | } |
| 304 | return true |
| 305 | } |
| 306 | |
| 307 | // ResolveRef reads the object ID that ref, a full ref name, holds in repo. |
| 308 | // It reads that one ref, with git show-ref. ok is false when repo holds no |
| 309 | // ref of that name. An error is a repository git could not read. |
| 310 | // |
| 311 | // git rev-parse is not used, because it does not stop at the name it is |
| 312 | // given. When repo holds no refs/heads/registry, rev-parse goes on to try |
| 313 | // other names, refs/heads/refs/heads/registry among them, and any pusher |
| 314 | // can make that branch. So a protected ref that is missing would resolve to |
| 315 | // a ref that no protection covers. Read what the ref holds through the |
| 316 | // object ID ResolveRef returns, never through the name again. |
| 317 | func ResolveRef(ctx context.Context, repo, ref string) (oid string, ok bool, err error) { |
| 318 | if !ValidRef(ref) { |
| 319 | return "", false, fmt.Errorf("%q is not a full ref name", ref) |
| 320 | } |
| 321 | // show-ref --exists exits 2 for a ref that is missing, and with |
| 322 | // another status for a failure to read. |
| 323 | _, err = git(ctx, repo, "show-ref", "--exists", "--end-of-options", ref) |
| 324 | var exit *exec.ExitError |
| 325 | if errors.As(err, &exit) && exit.ExitCode() == 2 { |
| 326 | return "", false, nil |
| 327 | } else if err != nil { |
| 328 | return "", false, err |
| 329 | } |
| 330 | out, err := git(ctx, repo, "show-ref", "--verify", "--hash", "--end-of-options", ref) |
| 331 | if err != nil { |
| 332 | return "", false, err |
| 333 | } |
| 334 | return strings.TrimSpace(string(out)), true, nil |
| 335 | } |
| 336 | |
| 337 | // plainName reports whether name is one plain path component: not empty, |
| 338 | // not . or .., and with no slash. |
| 339 | func plainName(name string) bool { |
| 340 | return name != "" && name != "." && name != ".." && !strings.Contains(name, "/") |
| 341 | } |
| 342 | |
| 343 | // treeEntry is one entry of a tree, as git ls-tree lists it. |
| 344 | type treeEntry struct{ mode, kind, oid, name string } |
| 345 | |
| 346 | // listTree lists the entries of a tree in repo, as they are stored: a tree |
| 347 | // written literally can name an entry twice, or with a directory part. dir |
| 348 | // is where the tree is, for messages. |
| 349 | func listTree(ctx context.Context, repo, tree, dir string) ([]treeEntry, error) { |
| 350 | listing, err := git(ctx, repo, "ls-tree", "-z", tree) |
| 351 | if errors.Is(err, errTooLong) { |
| 352 | return nil, invalid("%s lists more than %d bytes of entries", dir, maxGitOutput) |
| 353 | } else if err != nil { |
| 354 | return nil, err |
| 355 | } |
| 356 | var entries []treeEntry |
| 357 | for _, e := range strings.Split(strings.TrimSuffix(string(listing), "\x00"), "\x00") { |
| 358 | if e == "" { |
| 359 | continue |
| 360 | } |
| 361 | meta, name, _ := strings.Cut(e, "\t") |
| 362 | f := strings.Fields(meta) |
| 363 | if len(f) != 3 { |
| 364 | return nil, fmt.Errorf("git ls-tree listed %q in %s, which is not an entry", e, dir) |
| 365 | } |
| 366 | entries = append(entries, treeEntry{f[0], f[1], f[2], name}) |
| 367 | } |
| 368 | return entries, nil |
| 369 | } |
| 370 | |
| 371 | // findDir finds the tree at dir in a commit of repo, one path component at |
| 372 | // a time. git ls-tree given the path would take the first of two entries |
| 373 | // of one name, and a tree written literally can hold two: one that |
| 374 | // consents, and one that does not. So each component is matched by its |
| 375 | // name exactly, among every entry of the tree above it, and two entries of |
| 376 | // that name make the document invalid. A component that is not a |
| 377 | // directory on the way there means there is no document; the directory |
| 378 | // itself that is not one is invalid. |
| 379 | func findDir(ctx context.Context, repo, commit, dir string) (string, error) { |
| 380 | tree, at := commit, "the commit's root" |
| 381 | parts := strings.Split(dir, "/") |
| 382 | for i, part := range parts { |
| 383 | if !plainName(part) { |
| 384 | return "", fmt.Errorf("%q is not a directory a commit can hold", dir) |
| 385 | } |
| 386 | entries, err := listTree(ctx, repo, tree, at) |
| 387 | if err != nil { |
| 388 | return "", err |
| 389 | } |
| 390 | var found []treeEntry |
| 391 | for _, e := range entries { |
| 392 | if e.name == part { |
| 393 | found = append(found, e) |
| 394 | } |
| 395 | } |
| 396 | at = path.Join(parts[:i+1]...) |
| 397 | switch { |
| 398 | case len(found) == 0: |
| 399 | return "", ErrMissing |
| 400 | case len(found) > 1: |
| 401 | return "", invalid("%s is named by %d entries of its parent, so which is the document is ambiguous", at, len(found)) |
| 402 | case found[0].kind != "tree" && i < len(parts)-1: |
| 403 | return "", ErrMissing |
| 404 | case found[0].kind != "tree": |
| 405 | return "", invalid("%s is not a directory", dir) |
| 406 | } |
| 407 | tree = found[0].oid |
| 408 | } |
| 409 | return tree, nil |
| 410 | } |
| 411 | |
| 412 | // read reads the document in dir at a commit of repo, exports it with cue |
| 413 | // under schema, and decodes the JSON into doc, which must take every field |
| 414 | // cue exported. Its error is ErrMissing when the commit holds no document |
| 415 | // there, an *InvalidError when the document is invalid, and any other |
| 416 | // error when git or cue could not be run over it. |
| 417 | func (r *Reader) read(ctx context.Context, repo, commit, dir, schema string, lim bounds, doc any) error { |
| 418 | tree, err := findDir(ctx, repo, commit, dir) |
| 419 | if err != nil { |
| 420 | return err |
| 421 | } |
| 422 | entries, err := listTree(ctx, repo, tree, dir) |
| 423 | if err != nil { |
| 424 | return err |
| 425 | } |
| 426 | |
| 427 | // A tree git wrote itself never names an entry with a directory part, |
| 428 | // nor two entries alike, but one written literally can. Such a |
| 429 | // directory is no document: copied out by name, an entry like ../x.cue |
| 430 | // would land outside the scratch directory. |
| 431 | type document struct{ name, oid string } |
| 432 | var docs []document |
| 433 | seen := map[string]bool{} |
| 434 | for _, e := range entries { |
| 435 | if !plainName(e.name) { |
| 436 | return invalid("%s holds an entry named %q, which is not a plain file name", dir, e.name) |
| 437 | } |
| 438 | if seen[e.name] { |
| 439 | return invalid("%s holds two entries named %q", dir, e.name) |
| 440 | } |
| 441 | seen[e.name] = true |
| 442 | if !strings.HasSuffix(e.name, ".cue") || e.kind != "blob" || (e.mode != "100644" && e.mode != "100755") { |
| 443 | continue |
| 444 | } |
| 445 | docs = append(docs, document{e.name, e.oid}) |
| 446 | } |
| 447 | if len(docs) == 0 { |
| 448 | return ErrMissing |
| 449 | } |
| 450 | if len(docs) > lim.files { |
| 451 | return invalid("%s holds %d documents, more than the %d it may have", dir, len(docs), lim.files) |
| 452 | } |
| 453 | |
| 454 | scratch, err := os.MkdirTemp("", "readaccess-") |
| 455 | if err != nil { |
| 456 | return err |
| 457 | } |
| 458 | defer os.RemoveAll(scratch) |
| 459 | files := []string{"export", "--out", "json", schema} |
| 460 | for _, d := range docs { |
| 461 | out, err := git(ctx, repo, "cat-file", "-s", d.oid) |
| 462 | if err != nil { |
| 463 | return err |
| 464 | } |
| 465 | size, err := strconv.ParseInt(strings.TrimSpace(string(out)), 10, 64) |
| 466 | if err != nil { |
| 467 | return fmt.Errorf("git cat-file -s %s: %w", d.oid, err) |
| 468 | } |
| 469 | if size > lim.file { |
| 470 | return invalid("%s/%s is %d bytes, more than the %d a document may be", dir, d.name, size, lim.file) |
| 471 | } |
| 472 | body, err := git(ctx, repo, "cat-file", "blob", d.oid) |
| 473 | if err != nil { |
| 474 | return err |
| 475 | } |
| 476 | file := filepath.Join(scratch, d.name) |
| 477 | if err := os.WriteFile(file, body, 0o600); err != nil { |
| 478 | return err |
| 479 | } |
| 480 | files = append(files, file) |
| 481 | } |
| 482 | |
| 483 | out, err := r.cue(ctx, scratch, lim.output, files...) |
| 484 | if err != nil { |
| 485 | return err |
| 486 | } |
| 487 | // encoding/json alone matches a key to a field without regard to case. |
| 488 | // A document that reopens a definition of its schema could then carry |
| 489 | // anyone.Grants beside an empty anyone.grants, and be read as granting |
| 490 | // what a reviewer reading grants does not see. |
| 491 | if err := exactjson.Decode(out, doc); err != nil { |
| 492 | return invalid("%s is not what its schema exports: %w", dir, err) |
| 493 | } |
| 494 | return nil |
| 495 | } |
| 496 | |
| 497 | // cue runs cue with args in dir, and returns what it printed, up to limit |
| 498 | // bytes, or maxGitOutput when limit is zero. Only what the files decide is |
| 499 | // an *InvalidError: a run that ends with cueRefused, and a run that prints |
| 500 | // more than limit. Every other failure is an error of its own: a cue that |
| 501 | // could not be started, that crashed, that was killed or that ran past the |
| 502 | // timeout, and a read that was cancelled. |
| 503 | func (r *Reader) cue(ctx context.Context, dir string, limit int, args ...string) ([]byte, error) { |
| 504 | timeout := r.CueTimeout |
| 505 | if timeout <= 0 { |
| 506 | timeout = time.Minute |
| 507 | } |
| 508 | cueCtx, cancel := context.WithTimeout(ctx, timeout) |
| 509 | defer cancel() |
| 510 | cmd := exec.CommandContext(cueCtx, "cue", args...) |
| 511 | cmd.Dir = dir |
| 512 | cmd.Env = cueEnvironment(os.Environ()) |
| 513 | if limit == 0 { |
| 514 | limit = maxGitOutput |
| 515 | } |
| 516 | stdout := &bounded{max: limit, strict: true} |
| 517 | stderr := &bounded{max: maxStderr} |
| 518 | cmd.Stdout, cmd.Stderr = stdout, stderr |
| 519 | err := cmd.Run() |
| 520 | said := fmt.Sprint(err) |
| 521 | if first, _, _ := strings.Cut(strings.TrimSpace(stderr.buf.String()), "\n"); first != "" { |
| 522 | said += ": " + first |
| 523 | } |
| 524 | var exit *exec.ExitError |
| 525 | switch { |
| 526 | case ctx.Err() != nil: |
| 527 | return nil, ctx.Err() |
| 528 | case stdout.over: |
| 529 | return nil, invalid("cue exported more than %d bytes", limit) |
| 530 | case cueCtx.Err() != nil: |
| 531 | return nil, fmt.Errorf("cue took longer than %v, so the document was not read", timeout) |
| 532 | case errors.As(err, &exit) && exit.ExitCode() == cueRefused: |
| 533 | return nil, invalid("cue %s: %s", args[0], said) |
| 534 | case errors.As(err, &exit): |
| 535 | return nil, fmt.Errorf("cue did not finish reading the document: %s", said) |
| 536 | case err != nil: |
| 537 | return nil, fmt.Errorf("could not run cue: %w", err) |
| 538 | } |
| 539 | return stdout.buf.Bytes(), nil |
| 540 | } |
| 541 | |
| 542 | // cueEnvironment is the caller's environment without CUE's own variables, |
| 543 | // so a document is read the same way whoever reads it. |
| 544 | func cueEnvironment(environ []string) []string { |
| 545 | var env []string |
| 546 | for _, kv := range environ { |
| 547 | if !strings.HasPrefix(kv, "CUE_") { |
| 548 | env = append(env, kv) |
| 549 | } |
| 550 | } |
| 551 | return env |
| 552 | } |
| 553 | |
| 554 | // errTooLong is the error for a program that printed more than its bound. |
| 555 | var errTooLong = errors.New("it printed more than the reader holds of it") |
| 556 | |
| 557 | // git runs git in repo with replacement refs off, pathspecs taken |
| 558 | // literally and no prompt, and returns what it printed, up to |
| 559 | // maxGitOutput. It keeps the caller's GIT_CONFIG_* variables, which carry |
| 560 | // the safe.directory entries a host gives for repositories the caller does |
| 561 | // not own, and drops the ones that would point git at another repository. |
| 562 | func git(ctx context.Context, repo string, args ...string) ([]byte, error) { |
| 563 | cmd := exec.CommandContext(ctx, "git", append([]string{"--no-replace-objects", "--literal-pathspecs", "-C", repo}, args...)...) |
| 564 | var env []string |
| 565 | for _, kv := range os.Environ() { |
| 566 | switch name, _, _ := strings.Cut(kv, "="); name { |
| 567 | case "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", "GIT_PREFIX", |
| 568 | "GIT_NAMESPACE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", |
| 569 | "GIT_TERMINAL_PROMPT", "GIT_NO_REPLACE_OBJECTS": |
| 570 | continue |
| 571 | } |
| 572 | env = append(env, kv) |
| 573 | } |
| 574 | cmd.Env = append(env, "GIT_TERMINAL_PROMPT=0", "GIT_NO_REPLACE_OBJECTS=1") |
| 575 | stdout := &bounded{max: maxGitOutput, strict: true} |
| 576 | stderr := &bounded{max: maxStderr} |
| 577 | cmd.Stdout, cmd.Stderr = stdout, stderr |
| 578 | err := cmd.Run() |
| 579 | if stdout.over { |
| 580 | return nil, fmt.Errorf("git %s: %w", args[0], errTooLong) |
| 581 | } |
| 582 | if err != nil { |
| 583 | return nil, fmt.Errorf("git %s: %w: %s", args[0], err, strings.TrimSpace(stderr.buf.String())) |
| 584 | } |
| 585 | return stdout.buf.Bytes(), nil |
| 586 | } |
| 587 | |
| 588 | // bounded holds what a program prints, up to max bytes. Past max, a write |
| 589 | // fails when strict is set, which ends the program at its next write, and |
| 590 | // is dropped when it is not. It is no io.ReaderFrom, so os/exec copies |
| 591 | // through Write. |
| 592 | type bounded struct { |
| 593 | buf bytes.Buffer |
| 594 | max int |
| 595 | strict bool |
| 596 | over bool |
| 597 | } |
| 598 | |
| 599 | func (b *bounded) Write(p []byte) (int, error) { |
| 600 | room := max(b.max-b.buf.Len(), 0) |
| 601 | if len(p) <= room { |
| 602 | return b.buf.Write(p) |
| 603 | } |
| 604 | b.over = true |
| 605 | b.buf.Write(p[:room]) |
| 606 | if b.strict { |
| 607 | return room, errTooLong |
| 608 | } |
| 609 | return len(p), nil |
| 610 | } |