| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | |
| 12 | "the-valley/exactjson" |
| 13 | ) |
| 14 | |
| 15 | // The registry as the schema exports it (schema/identity.cue), every field |
| 16 | // of it. The export is read with exactjson, which refuses a key that no |
| 17 | // json tag here spells exactly. The derived fields the schema uses to hold |
| 18 | // the floor โ genesisGovernance, externalGovernance, readScopes โ and a |
| 19 | // principal's external identity are checked by `cue vet` and read by nobody |
| 20 | // here, so they are taken as raw JSON. |
| 21 | // |
| 22 | // The fields that carry read access are taken as raw JSON too, because no |
| 23 | // artifact is rendered from them: an edge read boundary's destination, the |
| 24 | // projects a grant at one names, and anyone, the reader with no |
| 25 | // credential, who holds read grants alone. The web publisher reads them |
| 26 | // through readaccess/. |
| 27 | type registry struct { |
| 28 | Boundaries map[string]boundary `json:"boundaries"` |
| 29 | Principals map[string]principal `json:"principals"` |
| 30 | Genesis string `json:"genesis"` |
| 31 | Anyone json.RawMessage `json:"anyone"` |
| 32 | GenesisGovernance json.RawMessage `json:"genesisGovernance"` |
| 33 | ExternalGovernance json.RawMessage `json:"externalGovernance"` |
| 34 | ReadScopes json.RawMessage `json:"readScopes"` |
| 35 | } |
| 36 | |
| 37 | type boundary struct { |
| 38 | Kind string `json:"kind"` |
| 39 | Destination json.RawMessage `json:"destination"` |
| 40 | } |
| 41 | |
| 42 | type principal struct { |
| 43 | Kind string `json:"kind"` |
| 44 | Keys []key `json:"keys"` |
| 45 | Grants map[string]grant `json:"grants"` |
| 46 | External json.RawMessage `json:"external"` |
| 47 | Expires string `json:"expires"` |
| 48 | } |
| 49 | |
| 50 | type key struct { |
| 51 | Class string `json:"class"` |
| 52 | Bound string `json:"bound"` |
| 53 | Public string `json:"public"` |
| 54 | Signs string `json:"signs"` |
| 55 | Attestation *attestation `json:"attestation"` |
| 56 | } |
| 57 | |
| 58 | type grant struct { |
| 59 | Boundary string `json:"boundary"` |
| 60 | Projects json.RawMessage `json:"projects"` |
| 61 | } |
| 62 | |
| 63 | const ( |
| 64 | // boundaryGitPush is the boundary kind the authorized_keys artifact is |
| 65 | // rendered from: sshd on a host serving the instance's repositories. |
| 66 | boundaryGitPush = "git-push" |
| 67 | |
| 68 | // boundaryRegistry is the boundary kind that admits a change to the |
| 69 | // registry document itself. A render leaving nobody there is refused. |
| 70 | boundaryRegistry = "registry" |
| 71 | |
| 72 | // boundaryApprove is a boundary kind the grants artifact is rendered |
| 73 | // from: the pre-receive hook's check of writes to the integration |
| 74 | // request namespace (valleyhook/). boundaryRequest is the same kind |
| 75 | // under the name it had first, and a registry may use either. |
| 76 | boundaryApprove = "approve" |
| 77 | boundaryRequest = "request" |
| 78 | |
| 79 | // boundaryRestack is the other: the pre-receive hook's check of the |
| 80 | // host restacker's writes, a version added to another principal's |
| 81 | // ready change and a restack report (valleyhook/). |
| 82 | boundaryRestack = "restack" |
| 83 | ) |
| 84 | |
| 85 | // readRegistry takes the registry out of the object oid, which the caller |
| 86 | // read ref as holding, vets it, and exports it. |
| 87 | // |
| 88 | // The tip is taken apart with ls-tree and show rather than checked out, the |
| 89 | // same way the integrator reads the floor: a worktree would write into a |
| 90 | // repository this program has no business writing, and reading is the whole |
| 91 | // of what it needs. cue is shelled out to for the same reason the rest of |
| 92 | // the machinery shells out to it โ one pinned tool, one behaviour. |
| 93 | // |
| 94 | // Nothing is written outside the scratch directory, so every failure here |
| 95 | // leaves the artifacts as they were. |
| 96 | func readRegistry(repo, ref, oid, dir, schema string) (registry, string, error) { |
| 97 | var r registry |
| 98 | |
| 99 | // Everything reads the commit the ref was resolved to. Reading through |
| 100 | // the ref again would let a push landing mid-read mix two registries, |
| 101 | // compiled under the first one's commit. |
| 102 | commit, err := git(repo, "rev-parse", "--verify", "--end-of-options", oid+"^{commit}") |
| 103 | if err != nil { |
| 104 | return r, "", fmt.Errorf("%s in %s is not a commit: %w", ref, repo, err) |
| 105 | } |
| 106 | |
| 107 | tree := commit + ":" + dir |
| 108 | listing, err := git(repo, "ls-tree", "--name-only", tree) |
| 109 | if err != nil { |
| 110 | return r, "", fmt.Errorf("no registry: %s has no %s/ at %s: %w", repo, dir, ref, err) |
| 111 | } |
| 112 | |
| 113 | scratch, err := os.MkdirTemp("", "valley-identity") |
| 114 | if err != nil { |
| 115 | return r, "", err |
| 116 | } |
| 117 | defer os.RemoveAll(scratch) |
| 118 | |
| 119 | // The registry is a CUE package: the directory is the enumeration, and |
| 120 | // the documents directly in it are what unify. |
| 121 | var files []string |
| 122 | for _, name := range strings.Split(strings.TrimSpace(listing), "\n") { |
| 123 | if !strings.HasSuffix(name, ".cue") { |
| 124 | continue |
| 125 | } |
| 126 | body, err := git(repo, "show", tree+"/"+name) |
| 127 | if err != nil { |
| 128 | return r, "", fmt.Errorf("reading %s/%s from %s at %s: %w", dir, name, repo, ref, err) |
| 129 | } |
| 130 | path := filepath.Join(scratch, name) |
| 131 | if err := os.WriteFile(path, []byte(body), 0o644); err != nil { |
| 132 | return r, "", err |
| 133 | } |
| 134 | files = append(files, path) |
| 135 | } |
| 136 | if len(files) == 0 { |
| 137 | return r, "", fmt.Errorf("no registry: %s holds no *.cue in %s/ at %s", repo, dir, ref) |
| 138 | } |
| 139 | |
| 140 | if out, err := cue(append([]string{"vet", "-c", schema}, files...)); err != nil { |
| 141 | return r, "", fmt.Errorf("the registry at %s does not satisfy %s:\n%s", commit, schema, out) |
| 142 | } |
| 143 | out, err := cue(append([]string{"export", schema}, files...)) |
| 144 | if err != nil { |
| 145 | return r, "", fmt.Errorf("exporting the registry at %s:\n%s", commit, out) |
| 146 | } |
| 147 | // encoding/json alone matches a key to a field without regard to case. |
| 148 | // A registry that reopens a schema definition could then hold a grant |
| 149 | // under a field spelled another way, beside the empty grants a |
| 150 | // reviewer reads. |
| 151 | if err := exactjson.Decode([]byte(out), &r); err != nil { |
| 152 | return r, "", fmt.Errorf("the exported registry is not the shape this program reads: %w", err) |
| 153 | } |
| 154 | return r, commit, nil |
| 155 | } |
| 156 | |
| 157 | // git runs git over the instance repository with replacement refs off. A |
| 158 | // replacement ref makes one object stand in for another wherever git looks |
| 159 | // it up, so a refs/replace/<blob> pushed to the instance repository could |
| 160 | // swap in a registry that authorizes any key it liked without moving the |
| 161 | // ref this program reads. The repository is read as it is. |
| 162 | func git(repo string, args ...string) (string, error) { |
| 163 | cmd := exec.Command("git", append([]string{"--no-replace-objects", "-C", repo}, args...)...) |
| 164 | cmd.Env = gitEnvironment(os.Environ()) |
| 165 | out, err := cmd.Output() |
| 166 | if err != nil { |
| 167 | return "", commandError(err) |
| 168 | } |
| 169 | return strings.TrimRight(string(out), "\n"), nil |
| 170 | } |
| 171 | |
| 172 | // resolveRef reads the object ID that ref, a full ref name, holds in repo. |
| 173 | // It reads that one ref, with git show-ref. ok is false when repo holds no |
| 174 | // ref of that name. An error is a repository git could not read. |
| 175 | // |
| 176 | // git rev-parse is not used, because it does not stop at the name it is |
| 177 | // given. When repo holds no refs/heads/registry, rev-parse goes on to try |
| 178 | // other names, refs/heads/refs/heads/registry among them, and a pusher can |
| 179 | // make that branch. The registry it holds would then be compiled into the |
| 180 | // keys and grants. |
| 181 | func resolveRef(repo, ref string) (oid string, ok bool, err error) { |
| 182 | // show-ref --exists exits 2 for a ref that is missing, and with |
| 183 | // another status for a failure to read. |
| 184 | _, err = git(repo, "show-ref", "--exists", "--end-of-options", ref) |
| 185 | var exit *exec.ExitError |
| 186 | if errors.As(err, &exit) && exit.ExitCode() == 2 { |
| 187 | return "", false, nil |
| 188 | } else if err != nil { |
| 189 | return "", false, err |
| 190 | } |
| 191 | oid, err = git(repo, "show-ref", "--verify", "--hash", "--end-of-options", ref) |
| 192 | if err != nil { |
| 193 | return "", false, err |
| 194 | } |
| 195 | return oid, true, nil |
| 196 | } |
| 197 | |
| 198 | // gitEnvironment is the environment git runs in: the caller's, less every |
| 199 | // GIT_ variable, and with git's own configuration fixed the way sigverify |
| 200 | // fixes it. A GIT_DIR, GIT_OBJECT_DIRECTORY or GIT_CONFIG_PARAMETERS in the |
| 201 | // caller's environment could point git at other objects or change how it |
| 202 | // reads them, and system and user configuration are not read. What is not |
| 203 | // git's own is inherited. |
| 204 | func gitEnvironment(environ []string) []string { |
| 205 | var env []string |
| 206 | for _, kv := range environ { |
| 207 | if !strings.HasPrefix(kv, "GIT_") { |
| 208 | env = append(env, kv) |
| 209 | } |
| 210 | } |
| 211 | return append(env, |
| 212 | "GIT_CONFIG_NOSYSTEM=1", |
| 213 | "GIT_CONFIG_SYSTEM=/dev/null", |
| 214 | "GIT_CONFIG_GLOBAL=/dev/null", |
| 215 | "GIT_NO_REPLACE_OBJECTS=1", |
| 216 | "GIT_ATTR_NOSYSTEM=1", |
| 217 | "GIT_TERMINAL_PROMPT=0", |
| 218 | ) |
| 219 | } |
| 220 | |
| 221 | // cue returns combined output, because its diagnosis is the error message |
| 222 | // worth passing on. |
| 223 | func cue(args []string) (string, error) { |
| 224 | out, err := exec.Command("cue", args...).CombinedOutput() |
| 225 | return strings.TrimRight(string(out), "\n"), err |
| 226 | } |
| 227 | |
| 228 | // commandError carries what a failing command said, which is otherwise |
| 229 | // dropped by exec's "exit status 1". |
| 230 | func commandError(err error) error { |
| 231 | var ee *exec.ExitError |
| 232 | if errors.As(err, &ee) && len(ee.Stderr) > 0 { |
| 233 | return fmt.Errorf("%w: %s", err, strings.TrimSpace(string(ee.Stderr))) |
| 234 | } |
| 235 | return err |
| 236 | } |