gunk-dev/the-valley

compile.go

source70805f590deemain's published tip history
4.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 declaredKeys := fs.String("declared-keys", "", "the authorized_keys lines the host declares by hand")
25 now := fs.String("now", "", "the day expiry is judged against")
26 if err := fs.Parse(args); err != nil {
27 return err
28 }
29 for _, required := range []struct{ flag, value string }{
30 {"repo", *repo},
31 {"schema", *schema},
32 {"known-signers", *knownSigners},
33 {"authorized-keys", *authorizedKeys},
34 {"grants", *grantsFile},
35 } {
36 if required.value == "" {
37 return fmt.Errorf("--%s is required", required.flag)
38 }
39 }
40
41 // The day expiry is judged against. A flag rather than the clock alone,
42 // so a compilation can be reproduced and a check can pin one.
43 day := time.Now().UTC().Truncate(24 * time.Hour)
44 if *now != "" {
45 parsed, err := time.Parse(dateLayout, *now)
46 if err != nil {
47 return fmt.Errorf("--now %q is not a calendar day", *now)
48 }
49 day = parsed
50 }
51
52 var declared map[string]string
53 if *declaredKeys != "" {
54 var err error
55 if declared, err = readDeclaredKeys(*declaredKeys); err != nil {
56 return err
57 }
58 }
59 r, commit, err := readRegistry(*repo, *ref, *dir, *schema)
60 if err != nil {
61 return err
62 }
63 a, err := render(r, day, declared)
64 if err != nil {
65 return fmt.Errorf("the registry at %s does not compile: %w", commit, err)
66 }
67
68 // The omissions, before the artifacts are written: an entry that has
69 // aged out is the compiler doing its job, and it is not a silent one.
70 for _, note := range a.notes {
71 fmt.Fprintf(os.Stderr, "identity: %s\n", note)
72 }
73
74 signersWritten, err := writeArtifact(*knownSigners, a.knownSigners)
75 if err != nil {
76 return err
77 }
78 keysWritten, err := writeArtifact(*authorizedKeys, a.authorizedKeys)
79 if err != nil {
80 return err
81 }
82 grantsWritten, err := writeArtifact(*grantsFile, a.grants)
83 if err != nil {
84 return err
85 }
86
87 fmt.Fprintf(os.Stderr, "identity: %s at %s: %d verifier key(s)%s, %d authorized key(s)%s, %d grant(s)%s\n",
88 *ref, commit, a.signers, changed(signersWritten), a.authorized, changed(keysWritten),
89 a.granted, changed(grantsWritten))
90 return nil
91}
92
93// readDeclaredKeys reads the authorized_keys lines the host declares by
94// hand, and maps each key to the principal its entry is tagged with.
95func readDeclaredKeys(path string) (map[string]string, error) {
96 body, err := os.ReadFile(path)
97 if err != nil {
98 return nil, err
99 }
100 declared := map[string]string{}
101 for _, line := range strings.Split(string(body), "\n") {
102 blob := keyBlob(line)
103 if blob == "" {
104 continue
105 }
106 tag := ""
107 if m := principalTag.FindStringSubmatch(line); m != nil {
108 tag = m[1]
109 }
110 declared[blob] = tag
111 }
112 return declared, nil
113}
114
115// principalTag is the option a tagged entry carries.
116var principalTag = regexp.MustCompile(`environment="` + principalEnv + `=([^"]*)"`)
117
118// keyBlob is the base64 key in an authorized_keys line: the field after the
119// first one naming a key type.
120func keyBlob(line string) string {
121 fields := strings.Fields(line)
122 for i, f := range fields[:max(len(fields)-1, 0)] {
123 if strings.HasPrefix(f, "ssh-") || strings.HasPrefix(f, "ecdsa-") || strings.HasPrefix(f, "sk-") {
124 return fields[i+1]
125 }
126 }
127 return ""
128}
129
130func changed(written bool) string {
131 if written {
132 return " written"
133 }
134 return " unchanged"
135}
136
137// writeArtifact replaces one file by rename, and only when its content
138// differs. Every artifact is rendered before any is written, so the only
139// way to see one of them newer than another is a crash between two renames
140// — and none can ever be seen half-written.
141func writeArtifact(path string, content []byte) (bool, error) {
142 if old, err := os.ReadFile(path); err == nil && bytes.Equal(old, content) {
143 return false, nil
144 }
145 dir := filepath.Dir(path)
146 f, err := os.CreateTemp(dir, filepath.Base(path)+".tmp")
147 if err != nil {
148 return false, err
149 }
150 defer os.Remove(f.Name())
151 if _, err := f.Write(content); err != nil {
152 f.Close()
153 return false, err
154 }
155 // sshd reads the authorized_keys file and refuses one anybody but its
156 // owner can write, so the mode is stated rather than left to CreateTemp.
157 if err := f.Chmod(0o644); err != nil {
158 f.Close()
159 return false, err
160 }
161 if err := f.Close(); err != nil {
162 return false, err
163 }
164 return true, os.Rename(f.Name(), path)
165}