gunk-dev/the-valley

registry.go

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