gunk-dev/the-valley

registry.go

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