gunk-dev/the-valley

registry.go

sourceecbe8599c29dmain's published tip history
6.4 KiB
1package main
2
3import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "strings"
11)
12
13// The registry as the schema exports it (schema/identity.cue). The derived
14// fields the schema uses to hold the floor โ€” genesisGovernance,
15// externalGovernance โ€” are checked by `cue vet` and read by nobody here.
16type registry struct {
17 Boundaries map[string]boundary `json:"boundaries"`
18 Principals map[string]principal `json:"principals"`
19 Genesis string `json:"genesis"`
20}
21
22type boundary struct {
23 Kind string `json:"kind"`
24}
25
26type principal struct {
27 Kind string `json:"kind"`
28 Keys []key `json:"keys"`
29 Grants map[string]grant `json:"grants"`
30 Expires string `json:"expires"`
31}
32
33type key struct {
34 Class string `json:"class"`
35 Bound string `json:"bound"`
36 Public string `json:"public"`
37 Signs string `json:"signs"`
38 Attestation *attestation `json:"attestation"`
39}
40
41type grant struct {
42 Boundary string `json:"boundary"`
43}
44
45const (
46 // boundaryGitPush is the boundary kind the authorized_keys artifact is
47 // rendered from: sshd on a host serving the instance's repositories.
48 boundaryGitPush = "git-push"
49
50 // boundaryRegistry is the boundary kind that admits a change to the
51 // registry document itself. A render leaving nobody there is refused.
52 boundaryRegistry = "registry"
53
54 // boundaryApprove is a boundary kind the grants artifact is rendered
55 // from: the pre-receive hook's check of writes to the integration
56 // request namespace (valleyhook/). boundaryRequest is the same kind
57 // under the name it had first, and a registry may use either.
58 boundaryApprove = "approve"
59 boundaryRequest = "request"
60
61 // boundaryRestack is the other: the pre-receive hook's check of the
62 // host restacker's writes, a version added to another principal's
63 // ready change and a restack report (valleyhook/).
64 boundaryRestack = "restack"
65)
66
67// readRegistry takes the registry out of a repository's tip, vets it, and
68// exports it.
69//
70// The tip is taken apart with ls-tree and show rather than checked out, the
71// same way the integrator reads the floor: a worktree would write into a
72// repository this program has no business writing, and reading is the whole
73// of what it needs. cue is shelled out to for the same reason the rest of
74// the machinery shells out to it โ€” one pinned tool, one behaviour.
75//
76// Nothing is written outside the scratch directory, so every failure here
77// leaves the artifacts as they were.
78func readRegistry(repo, ref, dir, schema string) (registry, string, error) {
79 var r registry
80
81 // The ref is resolved once, and everything after reads the commit it
82 // resolved to. Reading through the ref again would let a push landing
83 // mid-read mix two registries, compiled under the first one's commit.
84 commit, err := git(repo, "rev-parse", "--verify", ref+"^{commit}")
85 if err != nil {
86 return r, "", fmt.Errorf("%s has no %s: %w", repo, ref, err)
87 }
88
89 tree := commit + ":" + dir
90 listing, err := git(repo, "ls-tree", "--name-only", tree)
91 if err != nil {
92 return r, "", fmt.Errorf("no registry: %s has no %s/ at %s: %w", repo, dir, ref, err)
93 }
94
95 scratch, err := os.MkdirTemp("", "valley-identity")
96 if err != nil {
97 return r, "", err
98 }
99 defer os.RemoveAll(scratch)
100
101 // The registry is a CUE package: the directory is the enumeration, and
102 // the documents directly in it are what unify.
103 var files []string
104 for _, name := range strings.Split(strings.TrimSpace(listing), "\n") {
105 if !strings.HasSuffix(name, ".cue") {
106 continue
107 }
108 body, err := git(repo, "show", tree+"/"+name)
109 if err != nil {
110 return r, "", fmt.Errorf("reading %s/%s from %s at %s: %w", dir, name, repo, ref, err)
111 }
112 path := filepath.Join(scratch, name)
113 if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
114 return r, "", err
115 }
116 files = append(files, path)
117 }
118 if len(files) == 0 {
119 return r, "", fmt.Errorf("no registry: %s holds no *.cue in %s/ at %s", repo, dir, ref)
120 }
121
122 if out, err := cue(append([]string{"vet", "-c", schema}, files...)); err != nil {
123 return r, "", fmt.Errorf("the registry at %s does not satisfy %s:\n%s", commit, schema, out)
124 }
125 out, err := cue(append([]string{"export", schema}, files...))
126 if err != nil {
127 return r, "", fmt.Errorf("exporting the registry at %s:\n%s", commit, out)
128 }
129 if err := json.Unmarshal([]byte(out), &r); err != nil {
130 return r, "", fmt.Errorf("the exported registry is not the shape this program reads: %w", err)
131 }
132 return r, commit, nil
133}
134
135// git runs git over the instance repository with replacement refs off. A
136// replacement ref makes one object stand in for another wherever git looks
137// it up, so a refs/replace/<blob> pushed to the instance repository could
138// swap in a registry that authorizes any key it liked without moving the
139// ref this program reads. The repository is read as it is.
140func git(repo string, args ...string) (string, error) {
141 cmd := exec.Command("git", append([]string{"--no-replace-objects", "-C", repo}, args...)...)
142 cmd.Env = gitEnvironment(os.Environ())
143 out, err := cmd.Output()
144 if err != nil {
145 return "", commandError(err)
146 }
147 return strings.TrimRight(string(out), "\n"), nil
148}
149
150// gitEnvironment is the environment git runs in: the caller's, less every
151// GIT_ variable, and with git's own configuration fixed the way sigverify
152// fixes it. A GIT_DIR, GIT_OBJECT_DIRECTORY or GIT_CONFIG_PARAMETERS in the
153// caller's environment could point git at other objects or change how it
154// reads them, and system and user configuration are not read. What is not
155// git's own is inherited.
156func gitEnvironment(environ []string) []string {
157 var env []string
158 for _, kv := range environ {
159 if !strings.HasPrefix(kv, "GIT_") {
160 env = append(env, kv)
161 }
162 }
163 return append(env,
164 "GIT_CONFIG_NOSYSTEM=1",
165 "GIT_CONFIG_SYSTEM=/dev/null",
166 "GIT_CONFIG_GLOBAL=/dev/null",
167 "GIT_NO_REPLACE_OBJECTS=1",
168 "GIT_ATTR_NOSYSTEM=1",
169 "GIT_TERMINAL_PROMPT=0",
170 )
171}
172
173// cue returns combined output, because its diagnosis is the error message
174// worth passing on.
175func cue(args []string) (string, error) {
176 out, err := exec.Command("cue", args...).CombinedOutput()
177 return strings.TrimRight(string(out), "\n"), err
178}
179
180// commandError carries what a failing command said, which is otherwise
181// dropped by exec's "exit status 1".
182func commandError(err error) error {
183 var ee *exec.ExitError
184 if errors.As(err, &ee) && len(ee.Stderr) > 0 {
185 return fmt.Errorf("%w: %s", err, strings.TrimSpace(string(ee.Stderr)))
186 }
187 return err
188}