gunk-dev/the-valley

registry.go

source75b52b3811c7main's published tip history
8.9 KiB
1package main
2
3import (
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/.
27type 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
37type boundary struct {
38 Kind string `json:"kind"`
39 Destination json.RawMessage `json:"destination"`
40}
41
42type 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
50type 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
58type grant struct {
59 Boundary string `json:"boundary"`
60 Projects json.RawMessage `json:"projects"`
61}
62
63const (
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 a repository's tip, vets it, and
86// 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.
96func readRegistry(repo, ref, dir, schema string) (registry, string, error) {
97 var r registry
98
99 // The ref is resolved once, by its exact name, and everything after
100 // reads the commit it resolved to. Reading through the ref again would
101 // let a push landing mid-read mix two registries, compiled under the
102 // first one's commit.
103 oid, ok, err := resolveRef(repo, ref)
104 if err != nil {
105 return r, "", fmt.Errorf("could not read %s in %s: %w", ref, repo, err)
106 } else if !ok {
107 return r, "", fmt.Errorf("%s has no %s", repo, ref)
108 }
109 commit, err := git(repo, "rev-parse", "--verify", "--end-of-options", oid+"^{commit}")
110 if err != nil {
111 return r, "", fmt.Errorf("%s in %s is not a commit: %w", ref, repo, err)
112 }
113
114 tree := commit + ":" + dir
115 listing, err := git(repo, "ls-tree", "--name-only", tree)
116 if err != nil {
117 return r, "", fmt.Errorf("no registry: %s has no %s/ at %s: %w", repo, dir, ref, err)
118 }
119
120 scratch, err := os.MkdirTemp("", "valley-identity")
121 if err != nil {
122 return r, "", err
123 }
124 defer os.RemoveAll(scratch)
125
126 // The registry is a CUE package: the directory is the enumeration, and
127 // the documents directly in it are what unify.
128 var files []string
129 for _, name := range strings.Split(strings.TrimSpace(listing), "\n") {
130 if !strings.HasSuffix(name, ".cue") {
131 continue
132 }
133 body, err := git(repo, "show", tree+"/"+name)
134 if err != nil {
135 return r, "", fmt.Errorf("reading %s/%s from %s at %s: %w", dir, name, repo, ref, err)
136 }
137 path := filepath.Join(scratch, name)
138 if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
139 return r, "", err
140 }
141 files = append(files, path)
142 }
143 if len(files) == 0 {
144 return r, "", fmt.Errorf("no registry: %s holds no *.cue in %s/ at %s", repo, dir, ref)
145 }
146
147 if out, err := cue(append([]string{"vet", "-c", schema}, files...)); err != nil {
148 return r, "", fmt.Errorf("the registry at %s does not satisfy %s:\n%s", commit, schema, out)
149 }
150 out, err := cue(append([]string{"export", schema}, files...))
151 if err != nil {
152 return r, "", fmt.Errorf("exporting the registry at %s:\n%s", commit, out)
153 }
154 // encoding/json alone matches a key to a field without regard to case.
155 // A registry that reopens a schema definition could then hold a grant
156 // under a field spelled another way, beside the empty grants a
157 // reviewer reads.
158 if err := exactjson.Decode([]byte(out), &r); err != nil {
159 return r, "", fmt.Errorf("the exported registry is not the shape this program reads: %w", err)
160 }
161 return r, commit, nil
162}
163
164// git runs git over the instance repository with replacement refs off. A
165// replacement ref makes one object stand in for another wherever git looks
166// it up, so a refs/replace/<blob> pushed to the instance repository could
167// swap in a registry that authorizes any key it liked without moving the
168// ref this program reads. The repository is read as it is.
169func git(repo string, args ...string) (string, error) {
170 cmd := exec.Command("git", append([]string{"--no-replace-objects", "-C", repo}, args...)...)
171 cmd.Env = gitEnvironment(os.Environ())
172 out, err := cmd.Output()
173 if err != nil {
174 return "", commandError(err)
175 }
176 return strings.TrimRight(string(out), "\n"), nil
177}
178
179// resolveRef reads the object ID that ref, a full ref name, holds in repo.
180// It reads that one ref, with git show-ref. ok is false when repo holds no
181// ref of that name. An error is a repository git could not read.
182//
183// git rev-parse is not used, because it does not stop at the name it is
184// given. When repo holds no refs/heads/registry, rev-parse goes on to try
185// other names, refs/heads/refs/heads/registry among them, and a pusher can
186// make that branch. The registry it holds would then be compiled into the
187// keys and grants.
188func resolveRef(repo, ref string) (oid string, ok bool, err error) {
189 // show-ref --exists exits 2 for a ref that is missing, and with
190 // another status for a failure to read.
191 _, err = git(repo, "show-ref", "--exists", "--end-of-options", ref)
192 var exit *exec.ExitError
193 if errors.As(err, &exit) && exit.ExitCode() == 2 {
194 return "", false, nil
195 } else if err != nil {
196 return "", false, err
197 }
198 oid, err = git(repo, "show-ref", "--verify", "--hash", "--end-of-options", ref)
199 if err != nil {
200 return "", false, err
201 }
202 return oid, true, nil
203}
204
205// gitEnvironment is the environment git runs in: the caller's, less every
206// GIT_ variable, and with git's own configuration fixed the way sigverify
207// fixes it. A GIT_DIR, GIT_OBJECT_DIRECTORY or GIT_CONFIG_PARAMETERS in the
208// caller's environment could point git at other objects or change how it
209// reads them, and system and user configuration are not read. What is not
210// git's own is inherited.
211func gitEnvironment(environ []string) []string {
212 var env []string
213 for _, kv := range environ {
214 if !strings.HasPrefix(kv, "GIT_") {
215 env = append(env, kv)
216 }
217 }
218 return append(env,
219 "GIT_CONFIG_NOSYSTEM=1",
220 "GIT_CONFIG_SYSTEM=/dev/null",
221 "GIT_CONFIG_GLOBAL=/dev/null",
222 "GIT_NO_REPLACE_OBJECTS=1",
223 "GIT_ATTR_NOSYSTEM=1",
224 "GIT_TERMINAL_PROMPT=0",
225 )
226}
227
228// cue returns combined output, because its diagnosis is the error message
229// worth passing on.
230func cue(args []string) (string, error) {
231 out, err := exec.Command("cue", args...).CombinedOutput()
232 return strings.TrimRight(string(out), "\n"), err
233}
234
235// commandError carries what a failing command said, which is otherwise
236// dropped by exec's "exit status 1".
237func commandError(err error) error {
238 var ee *exec.ExitError
239 if errors.As(err, &ee) && len(ee.Stderr) > 0 {
240 return fmt.Errorf("%w: %s", err, strings.TrimSpace(string(ee.Stderr)))
241 }
242 return err
243}