gunk-dev/the-valley

registry.go

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