| 1 | // integrator is the Phase 3 controller that lands changes by verifying |
| 2 | // evidence (design/roadmap.md). It is a single writer per target stream and |
| 3 | // the commit point of dcr-439b771: it applies a change's delta to the |
| 4 | // current tip, checks per required check that the contributor's evidence |
| 5 | // still transfers, and either fast-forwards the protected ref or says which |
| 6 | // checks need new evidence. |
| 7 | // |
| 8 | // It runs no check. Verification happens where a change is authored, and |
| 9 | // the serialized section here is digest comparison and a ref write. |
| 10 | package main |
| 11 | |
| 12 | import ( |
| 13 | "flag" |
| 14 | "fmt" |
| 15 | "os" |
| 16 | "os/exec" |
| 17 | "path/filepath" |
| 18 | "strconv" |
| 19 | "strings" |
| 20 | "time" |
| 21 | ) |
| 22 | |
| 23 | const usage = `usage: integrator <command> [flags] |
| 24 | |
| 25 | reconcile judge every pending integration request once, and act |
| 26 | watch reconcile on an interval until interrupted |
| 27 | help print this message |
| 28 | |
| 29 | The integrator polls, deliberately. Integration requests are durable in |
| 30 | git — refs/the-valley/integration-requests/<target>/<change>, whose commit |
| 31 | is the change's head — and the bus is a projection over them, so the |
| 32 | controller level-triggers over the refs and converges. It publishes its |
| 33 | outcomes to the bus and consumes nothing. |
| 34 | |
| 35 | The commit rule (dcr-439b771). The delta must apply cleanly to the tip; a |
| 36 | conflict is new authorship, so every check is re-demanded. Then, per check |
| 37 | the policy requires: a pure check transfers when its input-closure digest |
| 38 | recomputed on the landed tree equals the attested one, and an effectful |
| 39 | check transfers while no intervening landing has touched its requiring |
| 40 | class's paths and its observation is inside the validity window the policy |
| 41 | declares. Anything left standing lands; anything invalidated surfaces as |
| 42 | one request-stale event naming exactly those checks, and the request stays |
| 43 | for resubmission. |
| 44 | |
| 45 | flags: |
| 46 | --repo DIR the served repository (default: here) |
| 47 | --project NAME the project name events carry (default: the repo's) |
| 48 | --key PATH ed25519 private key the integrator signs with |
| 49 | --name NAME the name that key signs under (default: this host's) |
| 50 | --known-signers F verifier keys whose attestations count, one per line |
| 51 | --instance DIR the instance policy layer, from the instance repo |
| 52 | --project-policy P the project policy layer, relative to the target tip |
| 53 | --schema FILE the verification schema |
| 54 | --attest-schema F the attestation schema |
| 55 | --event-schema F the event vocabulary payloads are vetted against |
| 56 | --bus URL nats server to publish outcomes to; empty publishes |
| 57 | nothing and still prints every payload |
| 58 | --system SYSTEM flake system for closure recomputation |
| 59 | --interval D watch: how long to wait between passes (default 15s) |
| 60 | --now TIME judge as at this RFC 3339 instant, for the effectful |
| 61 | window; defaults to the clock |
| 62 | |
| 63 | --known-signers is the registry's interim compilation. Identity is a |
| 64 | governed registry (dcr-b87f6e8) whose entries compile into what each |
| 65 | enforcement boundary checks; no compiler exists yet, so the file is |
| 66 | supplied directly and is exactly what dcr-b87f6e8 calls the first |
| 67 | compilation's output. An attestation signed by nobody in it does not |
| 68 | transfer, and that is reported per check rather than treated as a forgery. |
| 69 | ` |
| 70 | |
| 71 | // integrator is one controller: which repository it serves, who it signs |
| 72 | // as, whose evidence it accepts, and where it finds the policy. |
| 73 | type integrator struct { |
| 74 | repo string |
| 75 | project string |
| 76 | out *os.File |
| 77 | |
| 78 | // The programs it drives. Every judgement about a statement or a note |
| 79 | // is attest's, and every judgement about what a policy says is the |
| 80 | // deriver's and cue's. |
| 81 | attest string |
| 82 | valley string |
| 83 | cue string |
| 84 | nats string |
| 85 | |
| 86 | attestSchema string |
| 87 | eventSchema string |
| 88 | policy policySource |
| 89 | |
| 90 | key string |
| 91 | signerName string |
| 92 | keyHash string |
| 93 | knownSigners string |
| 94 | |
| 95 | bus string |
| 96 | system string |
| 97 | |
| 98 | // clock, when set, is the instant the effectful window is measured |
| 99 | // against. Zero means the wall clock. |
| 100 | clock time.Time |
| 101 | } |
| 102 | |
| 103 | func main() { |
| 104 | if len(os.Args) < 2 { |
| 105 | fmt.Fprint(os.Stderr, usage) |
| 106 | os.Exit(2) |
| 107 | } |
| 108 | var err error |
| 109 | switch os.Args[1] { |
| 110 | case "reconcile": |
| 111 | err = run(os.Args[2:], false) |
| 112 | case "watch": |
| 113 | err = run(os.Args[2:], true) |
| 114 | case "help", "-h", "--help": |
| 115 | fmt.Print(usage) |
| 116 | return |
| 117 | default: |
| 118 | fmt.Fprintf(os.Stderr, "integrator: unknown command %q\n\n%s", os.Args[1], usage) |
| 119 | os.Exit(2) |
| 120 | } |
| 121 | if err != nil { |
| 122 | fmt.Fprintf(os.Stderr, "integrator: %v\n", err) |
| 123 | os.Exit(1) |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | func run(args []string, loop bool) error { |
| 128 | fs := flag.NewFlagSet("integrator", flag.ExitOnError) |
| 129 | fs.Usage = func() { fmt.Fprint(os.Stderr, usage) } |
| 130 | repo := fs.String("repo", ".", "the served repository") |
| 131 | project := fs.String("project", "", "the project name events carry") |
| 132 | key := fs.String("key", "", "ed25519 private key") |
| 133 | name := fs.String("name", defaultSignerName(), "the name that key signs under") |
| 134 | known := fs.String("known-signers", "", "verifier keys whose attestations count") |
| 135 | instance := fs.String("instance", "", "the instance policy layer") |
| 136 | projectPolicy := fs.String("project-policy", "policy", "the project policy layer, relative to the target tip") |
| 137 | schema := fs.String("schema", env("VALLEY_VERIFICATION_SCHEMA"), "the verification schema") |
| 138 | attestSchema := fs.String("attest-schema", env("VALLEY_ATTEST_SCHEMA"), "the attestation schema") |
| 139 | eventSchema := fs.String("event-schema", env("VALLEY_EVENT_SCHEMA"), "the event vocabulary") |
| 140 | bus := fs.String("bus", "", "nats server to publish outcomes to") |
| 141 | system := fs.String("system", "", "flake system") |
| 142 | interval := fs.Duration("interval", 15*time.Second, "how long to wait between passes") |
| 143 | now := fs.String("now", "", "judge as at this instant") |
| 144 | if err := fs.Parse(args); err != nil { |
| 145 | return err |
| 146 | } |
| 147 | |
| 148 | in := &integrator{ |
| 149 | repo: *repo, |
| 150 | project: *project, |
| 151 | out: os.Stdout, |
| 152 | attestSchema: *attestSchema, |
| 153 | eventSchema: *eventSchema, |
| 154 | key: *key, |
| 155 | signerName: *name, |
| 156 | knownSigners: *known, |
| 157 | bus: *bus, |
| 158 | system: *system, |
| 159 | } |
| 160 | for _, missing := range []struct{ flag, value string }{ |
| 161 | {"--key", in.key}, |
| 162 | {"--known-signers", in.knownSigners}, |
| 163 | {"--instance", *instance}, |
| 164 | {"--schema", *schema}, |
| 165 | {"--attest-schema", in.attestSchema}, |
| 166 | } { |
| 167 | if missing.value == "" { |
| 168 | return fmt.Errorf("%s is required", missing.flag) |
| 169 | } |
| 170 | } |
| 171 | var err error |
| 172 | for _, tool := range []struct { |
| 173 | name string |
| 174 | into *string |
| 175 | }{{"attest", &in.attest}, {"valley", &in.valley}, {"cue", &in.cue}, {"nats", &in.nats}} { |
| 176 | if *tool.into, err = exec.LookPath(tool.name); err != nil && tool.name != "nats" { |
| 177 | return fmt.Errorf("%s is not on the path; the integrator drives it rather than reimplementing it", tool.name) |
| 178 | } |
| 179 | } |
| 180 | in.policy = policySource{ |
| 181 | schema: abs(*schema), |
| 182 | instance: abs(*instance), |
| 183 | project: *projectPolicy, |
| 184 | valley: in.valley, |
| 185 | cue: in.cue, |
| 186 | } |
| 187 | if *now != "" { |
| 188 | if in.clock, err = time.Parse(time.RFC3339, *now); err != nil { |
| 189 | return fmt.Errorf("--now: %w", err) |
| 190 | } |
| 191 | } |
| 192 | if in.repo, err = filepath.Abs(in.repo); err != nil { |
| 193 | return err |
| 194 | } |
| 195 | if in.project == "" { |
| 196 | in.project = projectName(in.repo) |
| 197 | } |
| 198 | if in.keyHash, err = in.readKeyHash(); err != nil { |
| 199 | return err |
| 200 | } |
| 201 | |
| 202 | if !loop { |
| 203 | return in.reconcile() |
| 204 | } |
| 205 | // Only the looping controller sweeps. A one-shot run may be somebody |
| 206 | // running the integrator by hand beside a controller that is already |
| 207 | // watching this repository, and sweeping from there would pull the |
| 208 | // worktree out from under a tick in progress. |
| 209 | sweepScratch(in.repo) |
| 210 | for { |
| 211 | if err := in.reconcile(); err != nil { |
| 212 | fmt.Fprintf(os.Stderr, "integrator: %v\n", err) |
| 213 | } |
| 214 | time.Sleep(*interval) |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | // readKeyHash asks attest for the verifier key this integrator signs under, |
| 219 | // and keeps the key hash: it is the segment that keeps one signer's |
| 220 | // attestation ref from racing another's (dcr-0de694f). |
| 221 | func (in *integrator) readKeyHash() (string, error) { |
| 222 | out, err := exec.Command(in.attest, "key", "--key", in.key, "--name", in.signerName).Output() |
| 223 | if err != nil { |
| 224 | return "", fmt.Errorf("reading the signing key: %w", err) |
| 225 | } |
| 226 | // name+hash+base64, split three ways: the name holds no plus and the |
| 227 | // base64 may. |
| 228 | fields := strings.SplitN(strings.TrimSpace(string(out)), "+", 3) |
| 229 | if len(fields) != 3 { |
| 230 | return "", fmt.Errorf("attest key printed %q", strings.TrimSpace(string(out))) |
| 231 | } |
| 232 | if _, err := strconv.ParseUint(fields[1], 16, 32); err != nil { |
| 233 | return "", fmt.Errorf("attest key printed the hash %q", fields[1]) |
| 234 | } |
| 235 | return fields[1], nil |
| 236 | } |
| 237 | |
| 238 | // projectName is the name the events carry: the repository's directory, |
| 239 | // with a bare repo's .git suffix removed — the same name the post-receive |
| 240 | // hook derives. |
| 241 | func projectName(repo string) string { |
| 242 | if bare, err := gitLine(repo, "rev-parse", "--is-bare-repository"); err == nil && bare == "true" { |
| 243 | dir, _ := gitLine(repo, "rev-parse", "--absolute-git-dir") |
| 244 | return strings.TrimSuffix(filepath.Base(dir), ".git") |
| 245 | } |
| 246 | top, err := gitLine(repo, "rev-parse", "--show-toplevel") |
| 247 | if err != nil { |
| 248 | return filepath.Base(repo) |
| 249 | } |
| 250 | return filepath.Base(top) |
| 251 | } |
| 252 | |
| 253 | // defaultSignerName is the name this machine signs under: its own name and |
| 254 | // the suffix that keeps a key signing attestations distinct from the same |
| 255 | // key signing anything else (dcr-de9d996). |
| 256 | func defaultSignerName() string { |
| 257 | host, err := os.Hostname() |
| 258 | if err != nil || host == "" { |
| 259 | host = "localhost" |
| 260 | } |
| 261 | return host + "/attestations" |
| 262 | } |
| 263 | |
| 264 | func env(name string) string { return os.Getenv(name) } |
| 265 | |
| 266 | func abs(path string) string { |
| 267 | if p, err := filepath.Abs(path); err == nil { |
| 268 | return p |
| 269 | } |
| 270 | return path |
| 271 | } |
| 272 | |
| 273 | // gitEnv runs a git command with extra environment, for the one place the |
| 274 | // integrator has to set authorship. |
| 275 | func (in *integrator) gitEnv(extra map[string]string, args ...string) (string, error) { |
| 276 | cmd := exec.Command("git", args...) |
| 277 | cmd.Dir = in.repo |
| 278 | cmd.Env = os.Environ() |
| 279 | for k, v := range extra { |
| 280 | cmd.Env = append(cmd.Env, k+"="+v) |
| 281 | } |
| 282 | var errb strings.Builder |
| 283 | cmd.Stderr = &errb |
| 284 | out, err := cmd.Output() |
| 285 | if err != nil { |
| 286 | return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String())) |
| 287 | } |
| 288 | return string(out), nil |
| 289 | } |
| 290 | |
| 291 | // writeTemp writes bytes to a file cue will read as JSON — the extension is |
| 292 | // how cue tells a data file from a schema. |
| 293 | func writeTemp(prefix string, body []byte) (string, error) { |
| 294 | dir, err := os.MkdirTemp("", prefix) |
| 295 | if err != nil { |
| 296 | return "", err |
| 297 | } |
| 298 | path := filepath.Join(dir, "payload.json") |
| 299 | if err := os.WriteFile(path, body, 0o644); err != nil { |
| 300 | return "", err |
| 301 | } |
| 302 | return path, nil |
| 303 | } |
| 304 | |
| 305 | func removeTemp(path string) { _ = os.RemoveAll(filepath.Dir(path)) } |