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