gunk-dev/the-valley

compile.go

source07a678c03476main's published tip history
5.9 KiB
1package main
2
3import (
4 "bytes"
5 "flag"
6 "fmt"
7 "os"
8 "path/filepath"
9 "regexp"
10 "strings"
11 "time"
12)
13
14func compile(args []string) error {
15 fs := flag.NewFlagSet("compile", flag.ExitOnError)
16 fs.Usage = func() { fmt.Fprint(os.Stderr, usage) }
17 repo := fs.String("repo", "", "the bare instance repository carrying the registry")
18 ref := fs.String("ref", "refs/heads/main", "the ref whose tip is read")
19 dir := fs.String("dir", "identity", "the registry's directory in that tip")
20 schema := fs.String("schema", os.Getenv("VALLEY_IDENTITY_SCHEMA"), "the identity schema")
21 knownSigners := fs.String("known-signers", "", "where the verifier keys are written")
22 authorizedKeys := fs.String("authorized-keys", "", "where the tagged authorized_keys is written")
23 grantsFile := fs.String("grants", "", "where the grants the pre-receive hook checks are written")
24 approvalSignersFile := fs.String("approval-signers", "", "where the verifier keys of every approval key are written")
25 approvalHardwareFile := fs.String("approval-signers-hardware", "", "where the verifier keys of the hardware approval keys are written")
26 declaredKeys := fs.String("declared-keys", "", "the authorized_keys lines the host declares by hand")
27 now := fs.String("now", "", "the day expiry and certificate validity are judged against")
28 if err := fs.Parse(args); err != nil {
29 return err
30 }
31 for _, required := range []struct{ flag, value string }{
32 {"repo", *repo},
33 {"schema", *schema},
34 {"known-signers", *knownSigners},
35 {"authorized-keys", *authorizedKeys},
36 {"grants", *grantsFile},
37 } {
38 if required.value == "" {
39 return fmt.Errorf("--%s is required", required.flag)
40 }
41 }
42
43 // The day expiry is judged against. A flag rather than the clock alone,
44 // so a compilation can be reproduced and a check can pin one.
45 day := time.Now().UTC().Truncate(24 * time.Hour)
46 if *now != "" {
47 parsed, err := time.Parse(dateLayout, *now)
48 if err != nil {
49 return fmt.Errorf("--now %q is not a calendar day", *now)
50 }
51 day = parsed
52 }
53
54 var declared map[string]string
55 if *declaredKeys != "" {
56 var err error
57 if declared, err = readDeclaredKeys(*declaredKeys); err != nil {
58 return err
59 }
60 }
61 r, commit, err := readRegistry(*repo, *ref, *dir, *schema)
62 if err != nil {
63 return err
64 }
65 a, err := render(r, day, declared)
66 if err != nil {
67 return fmt.Errorf("the registry at %s does not compile: %w", commit, err)
68 }
69
70 // The omissions, before the artifacts are written: an entry that has
71 // aged out is the compiler doing its job, and it is not a silent one.
72 for _, note := range a.notes {
73 fmt.Fprintf(os.Stderr, "identity: %s\n", note)
74 }
75
76 signersWritten, err := writeArtifact(*knownSigners, a.knownSigners)
77 if err != nil {
78 return err
79 }
80 keysWritten, err := writeArtifact(*authorizedKeys, a.authorizedKeys)
81 if err != nil {
82 return err
83 }
84 grantsWritten, err := writeArtifact(*grantsFile, a.grants)
85 if err != nil {
86 return err
87 }
88
89 // The approval files are written only where the caller names them.
90 // Every render computes both, so a registry whose approval keys do not
91 // compile fails the whole compilation either way.
92 approval := ""
93 for _, f := range []struct {
94 path string
95 content []byte
96 count int
97 what string
98 }{
99 {*approvalSignersFile, a.approvalSigners, a.approvers, "approval signer(s)"},
100 {*approvalHardwareFile, a.approvalHardware, a.hardware, "hardware approval signer(s)"},
101 } {
102 if f.path == "" {
103 continue
104 }
105 written, err := writeArtifact(f.path, f.content)
106 if err != nil {
107 return err
108 }
109 approval += fmt.Sprintf(", %d %s%s", f.count, f.what, changed(written))
110 }
111
112 fmt.Fprintf(os.Stderr, "identity: %s at %s: %d verifier key(s)%s, %d authorized key(s)%s, %d grant(s)%s%s\n",
113 *ref, commit, a.signers, changed(signersWritten), a.authorized, changed(keysWritten),
114 a.granted, changed(grantsWritten), approval)
115 return nil
116}
117
118// readDeclaredKeys reads the authorized_keys lines the host declares by
119// hand, and maps each key to the principal its entry is tagged with.
120func readDeclaredKeys(path string) (map[string]string, error) {
121 body, err := os.ReadFile(path)
122 if err != nil {
123 return nil, err
124 }
125 declared := map[string]string{}
126 for _, line := range strings.Split(string(body), "\n") {
127 blob := keyBlob(line)
128 if blob == "" {
129 continue
130 }
131 tag := ""
132 if m := principalTag.FindStringSubmatch(line); m != nil {
133 tag = m[1]
134 }
135 declared[blob] = tag
136 }
137 return declared, nil
138}
139
140// principalTag is the option a tagged entry carries.
141var principalTag = regexp.MustCompile(`environment="` + principalEnv + `=([^"]*)"`)
142
143// keyBlob is the base64 key in an authorized_keys line: the field after the
144// first one naming a key type.
145func keyBlob(line string) string {
146 fields := strings.Fields(line)
147 for i, f := range fields[:max(len(fields)-1, 0)] {
148 if strings.HasPrefix(f, "ssh-") || strings.HasPrefix(f, "ecdsa-") || strings.HasPrefix(f, "sk-") {
149 return fields[i+1]
150 }
151 }
152 return ""
153}
154
155func changed(written bool) string {
156 if written {
157 return " written"
158 }
159 return " unchanged"
160}
161
162// writeArtifact replaces one file by rename, and only when its content
163// differs. Every artifact is rendered before any is written, so the only
164// way to see one of them newer than another is a crash between two renames
165// — and none can ever be seen half-written.
166func writeArtifact(path string, content []byte) (bool, error) {
167 if old, err := os.ReadFile(path); err == nil && bytes.Equal(old, content) {
168 return false, nil
169 }
170 dir := filepath.Dir(path)
171 f, err := os.CreateTemp(dir, filepath.Base(path)+".tmp")
172 if err != nil {
173 return false, err
174 }
175 defer os.Remove(f.Name())
176 if _, err := f.Write(content); err != nil {
177 f.Close()
178 return false, err
179 }
180 // sshd reads the authorized_keys file and refuses one anybody but its
181 // owner can write, so the mode is stated rather than left to CreateTemp.
182 if err := f.Chmod(0o644); err != nil {
183 f.Close()
184 return false, err
185 }
186 if err := f.Close(); err != nil {
187 return false, err
188 }
189 return true, os.Rename(f.Name(), path)
190}