gunk-dev/the-valley

registry.go

source6a5da001e070main's published tip history
7.6 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, and everything after reads the commit it
100 // resolved to. Reading through the ref again would let a push landing
101 // mid-read mix two registries, compiled under the first one's commit.
102 commit, err := git(repo, "rev-parse", "--verify", ref+"^{commit}")
103 if err != nil {
104 return r, "", fmt.Errorf("%s has no %s: %w", repo, ref, 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.
162func 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// gitEnvironment is the environment git runs in: the caller's, less every
173// GIT_ variable, and with git's own configuration fixed the way sigverify
174// fixes it. A GIT_DIR, GIT_OBJECT_DIRECTORY or GIT_CONFIG_PARAMETERS in the
175// caller's environment could point git at other objects or change how it
176// reads them, and system and user configuration are not read. What is not
177// git's own is inherited.
178func gitEnvironment(environ []string) []string {
179 var env []string
180 for _, kv := range environ {
181 if !strings.HasPrefix(kv, "GIT_") {
182 env = append(env, kv)
183 }
184 }
185 return append(env,
186 "GIT_CONFIG_NOSYSTEM=1",
187 "GIT_CONFIG_SYSTEM=/dev/null",
188 "GIT_CONFIG_GLOBAL=/dev/null",
189 "GIT_NO_REPLACE_OBJECTS=1",
190 "GIT_ATTR_NOSYSTEM=1",
191 "GIT_TERMINAL_PROMPT=0",
192 )
193}
194
195// cue returns combined output, because its diagnosis is the error message
196// worth passing on.
197func cue(args []string) (string, error) {
198 out, err := exec.Command("cue", args...).CombinedOutput()
199 return strings.TrimRight(string(out), "\n"), err
200}
201
202// commandError carries what a failing command said, which is otherwise
203// dropped by exec's "exit status 1".
204func commandError(err error) error {
205 var ee *exec.ExitError
206 if errors.As(err, &ee) && len(ee.Stderr) > 0 {
207 return fmt.Errorf("%w: %s", err, strings.TrimSpace(string(ee.Stderr)))
208 }
209 return err
210}