| 1 | // integrator is the Phase 3 controller that lands changes by verifying |
| 2 | // evidence (archive/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-repo DIR the bare repository carrying the group's floor; the |
| 52 | instance layer is read from its integrated tip |
| 53 | --instance-ref REF the ref whose tip carries it (default refs/heads/main) |
| 54 | --instance-policy P the floor's directory in that tip (default |
| 55 | policy/instance); a floor that is not there is refused |
| 56 | --instance DIR a materialized instance layer, for a host that serves |
| 57 | no instance repository; one of this or --instance-repo |
| 58 | --project-policy P the project policy layer, relative to the target tip |
| 59 | (default policy/project); a target that carries none |
| 60 | is judged under the floor alone |
| 61 | --schema FILE the verification schema |
| 62 | --attest-schema F the attestation schema |
| 63 | --event-schema F the event vocabulary payloads are vetted against |
| 64 | --bus URL nats server to publish outcomes to; empty publishes |
| 65 | nothing and still prints every payload |
| 66 | --publish-queue DIR the host's queue of ref moves to publish: each landing |
| 67 | leaves its target's move there, and the host pushes it |
| 68 | to the mirrors and the bus as it does a pushed one; |
| 69 | empty leaves nothing |
| 70 | --system SYSTEM flake system for closure recomputation |
| 71 | --interval D watch: how long to wait between passes (default 15s) |
| 72 | --now TIME judge as at this RFC 3339 instant, for the effectful |
| 73 | window; defaults to the clock |
| 74 | |
| 75 | Every program the controller runs reads git with replacement refs off. A |
| 76 | replacement ref makes one object stand in for another wherever git looks |
| 77 | it up, so a pushed refs/replace/* could swap the floor, a project's policy |
| 78 | or a change's tree without moving any ref the controller watches. No GIT_ |
| 79 | variable is inherited except the safe.directory entries of command-scope |
| 80 | configuration, and system and user configuration are not read. |
| 81 | |
| 82 | --known-signers is the registry's interim compilation. Identity is a |
| 83 | governed registry (dcr-b87f6e8) whose entries compile into what each |
| 84 | enforcement boundary checks; no compiler exists yet, so the file is |
| 85 | supplied directly and is exactly what dcr-b87f6e8 calls the first |
| 86 | compilation's output. An attestation signed by nobody in it does not |
| 87 | transfer, and that is reported per check rather than treated as a forgery. |
| 88 | ` |
| 89 | |
| 90 | // integrator is one controller: which repository it serves, who it signs |
| 91 | // as, whose evidence it accepts, and where it finds the policy. |
| 92 | type integrator struct { |
| 93 | repo string |
| 94 | project string |
| 95 | out *os.File |
| 96 | |
| 97 | // The programs it drives. Every judgement about a statement or a note |
| 98 | // is attest's, and every judgement about what a policy says is the |
| 99 | // deriver's and cue's. |
| 100 | attest string |
| 101 | valley string |
| 102 | cue string |
| 103 | nats string |
| 104 | |
| 105 | attestSchema string |
| 106 | eventSchema string |
| 107 | policy policySource |
| 108 | |
| 109 | key string |
| 110 | signerName string |
| 111 | keyHash string |
| 112 | knownSigners string |
| 113 | |
| 114 | bus string |
| 115 | publishQueue string |
| 116 | system string |
| 117 | |
| 118 | // clock, when set, is the instant the effectful window is measured |
| 119 | // against. Zero means the wall clock. |
| 120 | clock time.Time |
| 121 | } |
| 122 | |
| 123 | func main() { |
| 124 | if len(os.Args) < 2 { |
| 125 | fmt.Fprint(os.Stderr, usage) |
| 126 | os.Exit(2) |
| 127 | } |
| 128 | // Before anything runs git, so that every git this process starts — its |
| 129 | // own, and the ones attest and the deriver start — inherits the result. |
| 130 | os.Clearenv() |
| 131 | for _, kv := range gitEnvironment(environ) { |
| 132 | name, value, _ := strings.Cut(kv, "=") |
| 133 | os.Setenv(name, value) |
| 134 | } |
| 135 | var err error |
| 136 | switch os.Args[1] { |
| 137 | case "reconcile": |
| 138 | err = run(os.Args[2:], false) |
| 139 | case "watch": |
| 140 | err = run(os.Args[2:], true) |
| 141 | case "help", "-h", "--help": |
| 142 | fmt.Print(usage) |
| 143 | return |
| 144 | default: |
| 145 | fmt.Fprintf(os.Stderr, "integrator: unknown command %q\n\n%s", os.Args[1], usage) |
| 146 | os.Exit(2) |
| 147 | } |
| 148 | if err != nil { |
| 149 | fmt.Fprintf(os.Stderr, "integrator: %v\n", err) |
| 150 | os.Exit(1) |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | func run(args []string, loop bool) error { |
| 155 | fs := flag.NewFlagSet("integrator", flag.ExitOnError) |
| 156 | fs.Usage = func() { fmt.Fprint(os.Stderr, usage) } |
| 157 | repo := fs.String("repo", ".", "the served repository") |
| 158 | project := fs.String("project", "", "the project name events carry") |
| 159 | key := fs.String("key", "", "ed25519 private key") |
| 160 | name := fs.String("name", defaultSignerName(), "the name that key signs under") |
| 161 | known := fs.String("known-signers", "", "verifier keys whose attestations count") |
| 162 | instanceRepo := fs.String("instance-repo", "", "the bare repository carrying the group's floor") |
| 163 | instanceRef := fs.String("instance-ref", "refs/heads/main", "the ref whose tip carries the floor") |
| 164 | instancePolicy := fs.String("instance-policy", "policy/instance", "the floor's directory in that tip") |
| 165 | instance := fs.String("instance", "", "a materialized instance policy layer") |
| 166 | projectPolicy := fs.String("project-policy", "policy/project", "the project policy layer, relative to the target tip") |
| 167 | schema := fs.String("schema", env("VALLEY_VERIFICATION_SCHEMA"), "the verification schema") |
| 168 | attestSchema := fs.String("attest-schema", env("VALLEY_ATTEST_SCHEMA"), "the attestation schema") |
| 169 | eventSchema := fs.String("event-schema", env("VALLEY_EVENT_SCHEMA"), "the event vocabulary") |
| 170 | bus := fs.String("bus", "", "nats server to publish outcomes to") |
| 171 | publishQueue := fs.String("publish-queue", "", "the host's queue of ref moves to publish") |
| 172 | system := fs.String("system", "", "flake system") |
| 173 | interval := fs.Duration("interval", 15*time.Second, "how long to wait between passes") |
| 174 | now := fs.String("now", "", "judge as at this instant") |
| 175 | if err := fs.Parse(args); err != nil { |
| 176 | return err |
| 177 | } |
| 178 | |
| 179 | in := &integrator{ |
| 180 | repo: *repo, |
| 181 | project: *project, |
| 182 | out: os.Stdout, |
| 183 | attestSchema: *attestSchema, |
| 184 | eventSchema: *eventSchema, |
| 185 | key: *key, |
| 186 | signerName: *name, |
| 187 | knownSigners: *known, |
| 188 | bus: *bus, |
| 189 | publishQueue: *publishQueue, |
| 190 | system: *system, |
| 191 | } |
| 192 | for _, missing := range []struct{ flag, value string }{ |
| 193 | {"--key", in.key}, |
| 194 | {"--known-signers", in.knownSigners}, |
| 195 | {"--schema", *schema}, |
| 196 | {"--attest-schema", in.attestSchema}, |
| 197 | } { |
| 198 | if missing.value == "" { |
| 199 | return fmt.Errorf("%s is required", missing.flag) |
| 200 | } |
| 201 | } |
| 202 | var err error |
| 203 | for _, tool := range []struct { |
| 204 | name string |
| 205 | into *string |
| 206 | }{{"attest", &in.attest}, {"valley", &in.valley}, {"cue", &in.cue}, {"nats", &in.nats}} { |
| 207 | if *tool.into, err = exec.LookPath(tool.name); err != nil && tool.name != "nats" { |
| 208 | return fmt.Errorf("%s is not on the path; the integrator drives it rather than reimplementing it", tool.name) |
| 209 | } |
| 210 | } |
| 211 | // The floor comes from the instance repository's integrated tip, or from |
| 212 | // a directory on disk, and never from both — two sources for one layer is |
| 213 | // a question about which one won every time the policy is read. |
| 214 | if (*instanceRepo == "") == (*instance == "") { |
| 215 | return fmt.Errorf("exactly one of --instance-repo and --instance is required: the floor is read from the instance repository's tip, or from a materialized directory for a host that serves none") |
| 216 | } |
| 217 | // abs of an empty path is the working directory, and an empty field is |
| 218 | // how the layer says which of its two sources it is. |
| 219 | layer := instanceLayer{ref: *instanceRef, dir: *instancePolicy} |
| 220 | if *instanceRepo != "" { |
| 221 | layer.repo = abs(*instanceRepo) |
| 222 | } else { |
| 223 | layer.path = abs(*instance) |
| 224 | } |
| 225 | in.policy = policySource{ |
| 226 | schema: abs(*schema), |
| 227 | layer: layer, |
| 228 | projectDir: *projectPolicy, |
| 229 | valley: in.valley, |
| 230 | cue: in.cue, |
| 231 | } |
| 232 | if *now != "" { |
| 233 | if in.clock, err = time.Parse(time.RFC3339, *now); err != nil { |
| 234 | return fmt.Errorf("--now: %w", err) |
| 235 | } |
| 236 | } |
| 237 | if in.repo, err = filepath.Abs(in.repo); err != nil { |
| 238 | return err |
| 239 | } |
| 240 | if in.project == "" { |
| 241 | in.project = projectName(in.repo) |
| 242 | } |
| 243 | if in.keyHash, err = in.readKeyHash(); err != nil { |
| 244 | return err |
| 245 | } |
| 246 | |
| 247 | if !loop { |
| 248 | return in.reconcile() |
| 249 | } |
| 250 | // Only the looping controller sweeps. A one-shot run may be somebody |
| 251 | // running the integrator by hand beside a controller that is already |
| 252 | // watching this repository, and sweeping from there would pull the |
| 253 | // worktree out from under a tick in progress. |
| 254 | sweepScratch(in.repo) |
| 255 | for { |
| 256 | if err := in.reconcile(); err != nil { |
| 257 | fmt.Fprintf(os.Stderr, "integrator: %v\n", err) |
| 258 | } |
| 259 | time.Sleep(*interval) |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | // readKeyHash asks attest for the verifier key this integrator signs under, |
| 264 | // and keeps the key hash: it is the segment that keeps one signer's |
| 265 | // attestation ref from racing another's (dcr-0de694f). |
| 266 | func (in *integrator) readKeyHash() (string, error) { |
| 267 | out, err := exec.Command(in.attest, "key", "--key", in.key, "--name", in.signerName).Output() |
| 268 | if err != nil { |
| 269 | return "", fmt.Errorf("reading the signing key: %w", err) |
| 270 | } |
| 271 | // name+hash+base64, split three ways: the name holds no plus and the |
| 272 | // base64 may. |
| 273 | fields := strings.SplitN(strings.TrimSpace(string(out)), "+", 3) |
| 274 | if len(fields) != 3 { |
| 275 | return "", fmt.Errorf("attest key printed %q", strings.TrimSpace(string(out))) |
| 276 | } |
| 277 | if _, err := strconv.ParseUint(fields[1], 16, 32); err != nil { |
| 278 | return "", fmt.Errorf("attest key printed the hash %q", fields[1]) |
| 279 | } |
| 280 | return fields[1], nil |
| 281 | } |
| 282 | |
| 283 | // projectName is the name the events carry: the repository's directory, |
| 284 | // with a bare repo's .git suffix removed — the same name the post-receive |
| 285 | // hook derives. |
| 286 | func projectName(repo string) string { |
| 287 | if bare, err := gitLine(repo, "rev-parse", "--is-bare-repository"); err == nil && bare == "true" { |
| 288 | dir, _ := gitLine(repo, "rev-parse", "--absolute-git-dir") |
| 289 | return strings.TrimSuffix(filepath.Base(dir), ".git") |
| 290 | } |
| 291 | top, err := gitLine(repo, "rev-parse", "--show-toplevel") |
| 292 | if err != nil { |
| 293 | return filepath.Base(repo) |
| 294 | } |
| 295 | return filepath.Base(top) |
| 296 | } |
| 297 | |
| 298 | // defaultSignerName is the name this machine signs under: its own name and |
| 299 | // the suffix that keeps a key signing attestations distinct from the same |
| 300 | // key signing anything else (dcr-de9d996). |
| 301 | func defaultSignerName() string { |
| 302 | host, err := os.Hostname() |
| 303 | if err != nil || host == "" { |
| 304 | host = "localhost" |
| 305 | } |
| 306 | return host + "/attestations" |
| 307 | } |
| 308 | |
| 309 | func env(name string) string { return os.Getenv(name) } |
| 310 | |
| 311 | // environ is the environment the process started with, read before main |
| 312 | // replaces it. |
| 313 | var environ = os.Environ() |
| 314 | |
| 315 | // gitEnvironment is the environment the controller runs in: the one it |
| 316 | // started with, with git's part of it fixed. |
| 317 | // |
| 318 | // Replacement refs are off. A replacement ref makes one object stand in for |
| 319 | // another wherever git looks it up, so a refs/replace/<blob> pushed to the |
| 320 | // served repository or the instance repository could swap the floor, the |
| 321 | // project's policy or a change's tree for anything its author liked, |
| 322 | // without moving any ref the controller watches. Every judgement here reads |
| 323 | // the repository's own objects. |
| 324 | // |
| 325 | // No other GIT_ variable is inherited, as sigverify inherits none: a GIT_DIR |
| 326 | // or GIT_OBJECT_DIRECTORY could point git at other objects, and a |
| 327 | // GIT_CONFIG_PARAMETERS could change how it reads them. System and user |
| 328 | // configuration are not read either. The one thing kept is command-scope |
| 329 | // configuration naming safe.directory, which is how the unit tells git it |
| 330 | // may read repositories the controller does not own (nix/valley-host.nix). |
| 331 | // Those entries are carried over, renumbered, and no other key is. |
| 332 | func gitEnvironment(inherited []string) []string { |
| 333 | vars := map[string]string{} |
| 334 | var kept []string |
| 335 | for _, kv := range inherited { |
| 336 | name, value, _ := strings.Cut(kv, "=") |
| 337 | if strings.HasPrefix(name, "GIT_") { |
| 338 | vars[name] = value |
| 339 | continue |
| 340 | } |
| 341 | kept = append(kept, kv) |
| 342 | } |
| 343 | |
| 344 | var safe []string |
| 345 | count, _ := strconv.Atoi(vars["GIT_CONFIG_COUNT"]) |
| 346 | for i := 0; i < count; i++ { |
| 347 | if strings.EqualFold(vars[fmt.Sprintf("GIT_CONFIG_KEY_%d", i)], "safe.directory") { |
| 348 | safe = append(safe, vars[fmt.Sprintf("GIT_CONFIG_VALUE_%d", i)]) |
| 349 | } |
| 350 | } |
| 351 | if len(safe) > 0 { |
| 352 | kept = append(kept, fmt.Sprintf("GIT_CONFIG_COUNT=%d", len(safe))) |
| 353 | for i, dir := range safe { |
| 354 | kept = append(kept, |
| 355 | fmt.Sprintf("GIT_CONFIG_KEY_%d=safe.directory", i), |
| 356 | fmt.Sprintf("GIT_CONFIG_VALUE_%d=%s", i, dir)) |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | return append(kept, |
| 361 | "GIT_CONFIG_NOSYSTEM=1", |
| 362 | "GIT_CONFIG_SYSTEM=/dev/null", |
| 363 | "GIT_CONFIG_GLOBAL=/dev/null", |
| 364 | "GIT_NO_REPLACE_OBJECTS=1", |
| 365 | "GIT_ATTR_NOSYSTEM=1", |
| 366 | "GIT_TERMINAL_PROMPT=0", |
| 367 | ) |
| 368 | } |
| 369 | |
| 370 | func abs(path string) string { |
| 371 | if p, err := filepath.Abs(path); err == nil { |
| 372 | return p |
| 373 | } |
| 374 | return path |
| 375 | } |
| 376 | |
| 377 | // gitEnv runs a git command with extra environment, for the one place the |
| 378 | // integrator has to state who authored and who committed. |
| 379 | func (in *integrator) gitEnv(extra map[string]string, args ...string) (string, error) { |
| 380 | cmd := exec.Command("git", args...) |
| 381 | cmd.Dir = in.repo |
| 382 | cmd.Env = os.Environ() |
| 383 | for k, v := range extra { |
| 384 | cmd.Env = append(cmd.Env, k+"="+v) |
| 385 | } |
| 386 | var errb strings.Builder |
| 387 | cmd.Stderr = &errb |
| 388 | out, err := cmd.Output() |
| 389 | if err != nil { |
| 390 | return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String())) |
| 391 | } |
| 392 | return string(out), nil |
| 393 | } |
| 394 | |
| 395 | // writeTemp writes bytes to a file cue will read as JSON — the extension is |
| 396 | // how cue tells a data file from a schema. |
| 397 | func writeTemp(prefix string, body []byte) (string, error) { |
| 398 | dir, err := scratch(prefix) |
| 399 | if err != nil { |
| 400 | return "", err |
| 401 | } |
| 402 | path := filepath.Join(dir, "payload.json") |
| 403 | if err := os.WriteFile(path, body, 0o644); err != nil { |
| 404 | return "", err |
| 405 | } |
| 406 | return path, nil |
| 407 | } |
| 408 | |
| 409 | func removeTemp(path string) { _ = os.RemoveAll(filepath.Dir(path)) } |