| 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 | "the-valley/composed" |
| 14 | "the-valley/note" |
| 15 | |
| 16 | "flag" |
| 17 | "fmt" |
| 18 | "io" |
| 19 | "os" |
| 20 | "os/exec" |
| 21 | "path/filepath" |
| 22 | "strconv" |
| 23 | "strings" |
| 24 | "syscall" |
| 25 | "time" |
| 26 | ) |
| 27 | |
| 28 | const usage = `usage: integrator <command> [flags] |
| 29 | |
| 30 | reconcile judge every pending integration request once, and act |
| 31 | watch reconcile at start, when woken and on an interval, |
| 32 | until interrupted |
| 33 | publish-signers publish what clients verify transfer statements with |
| 34 | (integrator publish-signers --help) |
| 35 | help print this message |
| 36 | |
| 37 | The integrator level-triggers over refs. Integration requests are durable |
| 38 | in git — refs/the-valley/integration-requests/<target>/<change>, whose |
| 39 | commit is the change's head — and the bus is a projection over them, so |
| 40 | each pass reads the refs as they are and converges. It publishes its |
| 41 | outcomes to the bus and consumes nothing from it. What starts a pass is |
| 42 | the start, the interval, and, given --woken-by, a mark in its own wake |
| 43 | directory (see below). A mark only starts a pass: it carries nothing, and |
| 44 | what a pass decides comes from the refs it reads. |
| 45 | |
| 46 | The commit rule (dcr-439b771). The delta must apply cleanly to the tip; a |
| 47 | conflict is new authorship, so every check is re-demanded. Then, per check |
| 48 | the policy requires: a pure check transfers when its input-closure digest |
| 49 | recomputed on the landed tree equals the attested one, and an effectful |
| 50 | check transfers while no intervening landing has touched its requiring |
| 51 | class's paths and its observation is inside the validity window the policy |
| 52 | declares. Anything left standing lands; anything invalidated surfaces as |
| 53 | one request-stale event naming exactly those checks, and the request stays |
| 54 | for approving again. |
| 55 | |
| 56 | Before the commit rule, the change records can refuse a request. A request |
| 57 | named c-<change ID> is that change's, and lands only while the record at |
| 58 | refs/the-valley/changes/<target>/<change ID> says ready and lists the |
| 59 | request's head as one of its versions'. A request of any name does not land |
| 60 | while any commit it brings is a version of a change whose record is not |
| 61 | ready. Both refuse with refused-not-ready. A request whose commits from the |
| 62 | merge base to the head include a merge is refused-merge. A refused request |
| 63 | stays where it is, and is decided again on every pass, so a change readied |
| 64 | again is judged on the next one. Every record is read again just before |
| 65 | the target moves, and a record never makes a request land. |
| 66 | |
| 67 | A withdrawn change voids its requests: each pass deletes the requests named |
| 68 | for it or at one of its version heads, as voided-withdrawn, so readying it |
| 69 | again needs a fresh approval. A record that does not read refuses nothing, |
| 70 | and is reported with a WARNING on every pass that reads records. |
| 71 | |
| 72 | flags: |
| 73 | --repo DIR the served repository (default: here) |
| 74 | --project NAME the project name events carry (default: the repo's) |
| 75 | --key PATH ed25519 private key the integrator signs with |
| 76 | --name NAME the name that key signs under (default: this host's) |
| 77 | --known-signers F verifier keys whose attestations count, one per line |
| 78 | --signer-projects F signers whose attestations count only in the projects |
| 79 | listed beside them (see below); read once, at start, so a |
| 80 | changed file counts from the next start |
| 81 | --instance-repo DIR the bare repository carrying the group's floor; the |
| 82 | instance layer is read from its integrated tip |
| 83 | --instance-ref REF the ref whose tip carries it, a full ref name read by |
| 84 | that exact name (default refs/heads/main) |
| 85 | --instance-policy P the floor's directory in that tip (default |
| 86 | policy/instance); a floor that is not there is refused |
| 87 | --instance DIR a materialized instance layer, for a host that serves |
| 88 | no instance repository; one of this or --instance-repo |
| 89 | --project-policy P the project policy layer, relative to the target tip |
| 90 | (default policy/project); a target that carries none |
| 91 | is judged under the floor alone |
| 92 | --schema FILE the verification schema |
| 93 | --attest-schema F the attestation schema |
| 94 | --event-schema F the event vocabulary payloads are vetted against |
| 95 | --bus URL nats server to publish outcomes to; empty publishes |
| 96 | nothing and still prints every payload |
| 97 | --publish-queue DIR the host's queue of ref moves to publish: each landing |
| 98 | leaves its target's move there, and the host pushes it |
| 99 | to the mirrors as it does a pushed one; empty leaves |
| 100 | nothing |
| 101 | --wake DIR the host check worker's wake directory: each landing |
| 102 | creates the empty file DIR/due, before the mirror |
| 103 | queue and the bus, so the worker starts a pass; |
| 104 | empty marks nothing. Output only; --woken-by is what |
| 105 | wakes this controller |
| 106 | --wake-floor-reader DIR |
| 107 | another controller's wake directory, which reads the |
| 108 | floor this one lands: each landing on --instance-ref |
| 109 | creates the empty file DIR/due, after the worker's |
| 110 | mark and before the mirror queue and the bus. Only the |
| 111 | controller serving --instance-repo takes it. Repeat it |
| 112 | for each reader |
| 113 | --woken-by DIR watch: this controller's own wake directory (Linux |
| 114 | only). A pass starts soon after a writer creates |
| 115 | DIR/due, and once more after any pass that lands |
| 116 | something; see below |
| 117 | --system SYSTEM flake system for closure recomputation |
| 118 | --interval D watch: how long to wait after a pass before the next, |
| 119 | when nothing starts one sooner (default 15s) |
| 120 | --now TIME judge as at this RFC 3339 instant, for the effectful |
| 121 | window; defaults to the clock |
| 122 | |
| 123 | Every program the controller runs reads git with replacement refs off. A |
| 124 | replacement ref makes one object stand in for another wherever git looks |
| 125 | it up, so a pushed refs/replace/* could swap the floor, a project's policy |
| 126 | or a change's tree without moving any ref the controller watches. No GIT_ |
| 127 | variable is inherited except the safe.directory entries of command-scope |
| 128 | configuration, and system and user configuration are not read. |
| 129 | |
| 130 | --woken-by is how a controller starts a pass promptly. A writer that moves |
| 131 | a ref the controller reads creates the empty file DIR/due with |
| 132 | O_CREAT|O_EXCL, and a due already there is a mark already made. The |
| 133 | controller watches DIR with inotify, removes due before a pass reads any |
| 134 | ref, and starts the next pass when the pass ends if due is there again, |
| 135 | so a mark made during a pass is never lost. While it watches DIR it holds |
| 136 | a lock on DIR itself, so a second controller given the same DIR consumes |
| 137 | no mark from it and passes at its interval. reconcile never reads DIR. The |
| 138 | interval stays the recovery pass: a missed mark, a |
| 139 | watch that failed and a missing directory are all covered by the next |
| 140 | timer pass. A due that cannot be removed starts no pass until the next |
| 141 | timer pass, and a pass that failed is followed by another no sooner than |
| 142 | 10s later. Each pass opens with the line "pass: REASON", where REASON is |
| 143 | startup, due, timer, follow-up or watcher; a timer pass with nothing else |
| 144 | to say prints nothing. |
| 145 | |
| 146 | One watch serves a repository at a time. watch takes an exclusive lock on |
| 147 | the --repo directory before it sweeps its scratch or judges anything, and |
| 148 | checks before every pass that the path still names the directory it |
| 149 | locked. A second watch over the same repository stops at its start, and a |
| 150 | watch whose repository path comes to name another directory stops. A |
| 151 | reconcile run by hand takes no lock. |
| 152 | |
| 153 | --known-signers is the registry's interim compilation. Identity is a |
| 154 | governed registry (dcr-b87f6e8) whose entries compile into what each |
| 155 | enforcement boundary checks; no compiler exists yet, so the file is |
| 156 | supplied directly and is exactly what dcr-b87f6e8 calls the first |
| 157 | compilation's output. An attestation signed by nobody in it does not |
| 158 | transfer, and that is reported per check rather than treated as a forgery. |
| 159 | |
| 160 | --signer-projects restricts signers to projects. Each line names a signer, |
| 161 | then the projects its attestations count in, separated by spaces: |
| 162 | |
| 163 | worker/attestations the-valley app |
| 164 | |
| 165 | A signer the file names counts only in the projects on its line, where the |
| 166 | project is the name events carry. In any other project its attestations |
| 167 | are reported as signed by no signer the integrator holds. A line with a |
| 168 | name and no project lets that signer count nowhere. A signer the file does |
| 169 | not name counts wherever the known-signers file lets it. Blank lines and |
| 170 | lines that open with # are skipped. Every name and project is a word of |
| 171 | printable ASCII. A file that cannot be read, names a signer twice, holds |
| 172 | a word that is not printable ASCII, names a signer no verifier key can |
| 173 | carry, or names the integrator's own --name stops the integrator before |
| 174 | it judges anything. |
| 175 | |
| 176 | The integrator's own signature never makes a check's attestation count. |
| 177 | It countersigns the attestations a landing carried, and that vouches for |
| 178 | the landing; a countersigned attestation counts, in any project, only |
| 179 | through another signer who counts there. |
| 180 | ` |
| 181 | |
| 182 | // integrator is one controller: which repository it serves, who it signs |
| 183 | // as, whose evidence it accepts, and where it finds the policy. |
| 184 | type integrator struct { |
| 185 | repo string |
| 186 | project string |
| 187 | out io.Writer |
| 188 | timings io.Writer // where timing lines go (timing.go); nil prints none |
| 189 | // sightings is when this process first saw each request, which timing |
| 190 | // lines report and nothing else reads (timing.go). Nil sees none. |
| 191 | sightings *sightings |
| 192 | |
| 193 | // The programs it drives. Every judgement about a statement or a note |
| 194 | // is attest's, and every judgement about what a policy says is the |
| 195 | // deriver's and cue's. |
| 196 | attest string |
| 197 | valley string |
| 198 | cue string |
| 199 | nats string |
| 200 | |
| 201 | attestSchema string |
| 202 | eventSchema string |
| 203 | policy policySource |
| 204 | |
| 205 | key string |
| 206 | signerName string |
| 207 | keyHash string |
| 208 | knownSigners string |
| 209 | |
| 210 | // signerProjects restricts signers in knownSigners to projects |
| 211 | // (note/signerprojects.go). Nil restricts nobody. It is read once, at |
| 212 | // start, and signerProjectsData is the bytes it was read from, which |
| 213 | // the inputs digest covers (inputs.go). |
| 214 | signerProjects note.SignerProjects |
| 215 | signerProjectsData []byte |
| 216 | |
| 217 | bus string |
| 218 | publishQueue string |
| 219 | wake string // the check worker's wake directory, or empty |
| 220 | system string |
| 221 | |
| 222 | // floorReaders are the wake directories of the controllers that read |
| 223 | // the floor this controller lands, marked after a landing on the |
| 224 | // floor's ref (bus.go). Empty for every controller but the instance |
| 225 | // repository's. |
| 226 | floorReaders []string |
| 227 | |
| 228 | // landings counts the landings this process has made, so watch can |
| 229 | // tell a pass that landed something and follow it with another. |
| 230 | landings int |
| 231 | |
| 232 | // clock, when set, is the instant the effectful window is measured |
| 233 | // against. Zero means the wall clock. |
| 234 | clock time.Time |
| 235 | |
| 236 | // evidenceListed, when set, runs once collectEvidence has listed a |
| 237 | // subject's attestation refs, before it reads any of them. Tests set |
| 238 | // it to delete a ref in that window. |
| 239 | evidenceListed func() |
| 240 | } |
| 241 | |
| 242 | func main() { |
| 243 | if len(os.Args) < 2 { |
| 244 | fmt.Fprint(os.Stderr, usage) |
| 245 | os.Exit(2) |
| 246 | } |
| 247 | // Before anything runs git, so that every git this process starts — its |
| 248 | // own, and the ones attest and the deriver start — inherits the result. |
| 249 | os.Clearenv() |
| 250 | for _, kv := range gitEnvironment(environ) { |
| 251 | name, value, _ := strings.Cut(kv, "=") |
| 252 | os.Setenv(name, value) |
| 253 | } |
| 254 | var err error |
| 255 | switch os.Args[1] { |
| 256 | case "reconcile": |
| 257 | err = run(os.Args[2:], false) |
| 258 | case "watch": |
| 259 | err = run(os.Args[2:], true) |
| 260 | case "publish-signers": |
| 261 | err = publishSigners(os.Args[2:]) |
| 262 | case "help", "-h", "--help": |
| 263 | fmt.Print(usage) |
| 264 | return |
| 265 | default: |
| 266 | fmt.Fprintf(os.Stderr, "integrator: unknown command %q\n\n%s", os.Args[1], usage) |
| 267 | os.Exit(2) |
| 268 | } |
| 269 | if err != nil { |
| 270 | fmt.Fprintf(os.Stderr, "integrator: %v\n", err) |
| 271 | os.Exit(1) |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | func run(args []string, loop bool) error { |
| 276 | fs := flag.NewFlagSet("integrator", flag.ExitOnError) |
| 277 | fs.Usage = func() { fmt.Fprint(os.Stderr, usage) } |
| 278 | repo := fs.String("repo", ".", "the served repository") |
| 279 | project := fs.String("project", "", "the project name events carry") |
| 280 | key := fs.String("key", "", "ed25519 private key") |
| 281 | name := fs.String("name", defaultSignerName(), "the name that key signs under") |
| 282 | known := fs.String("known-signers", "", "verifier keys whose attestations count") |
| 283 | signerProjects := fs.String("signer-projects", "", "signers whose attestations count only in the projects listed beside them") |
| 284 | instanceRepo := fs.String("instance-repo", "", "the bare repository carrying the group's floor") |
| 285 | instanceRef := fs.String("instance-ref", "refs/heads/main", "the ref whose tip carries the floor") |
| 286 | instancePolicy := fs.String("instance-policy", "policy/instance", "the floor's directory in that tip") |
| 287 | instance := fs.String("instance", "", "a materialized instance policy layer") |
| 288 | projectPolicy := fs.String("project-policy", "policy/project", "the project policy layer, relative to the target tip") |
| 289 | schema := fs.String("schema", env("VALLEY_VERIFICATION_SCHEMA"), "the verification schema") |
| 290 | attestSchema := fs.String("attest-schema", env("VALLEY_ATTEST_SCHEMA"), "the attestation schema") |
| 291 | eventSchema := fs.String("event-schema", env("VALLEY_EVENT_SCHEMA"), "the event vocabulary") |
| 292 | bus := fs.String("bus", "", "nats server to publish outcomes to") |
| 293 | publishQueue := fs.String("publish-queue", "", "the host's queue of ref moves to publish") |
| 294 | wake := fs.String("wake", "", "the check worker's wake directory, marked due after each landing") |
| 295 | var floorReaders dirList |
| 296 | fs.Var(&floorReaders, "wake-floor-reader", "a floor-reading controller's wake directory, marked due after each floor landing") |
| 297 | wokenBy := fs.String("woken-by", "", "watch: this controller's own wake directory") |
| 298 | system := fs.String("system", "", "flake system") |
| 299 | interval := fs.Duration("interval", 15*time.Second, "how long to wait between passes") |
| 300 | now := fs.String("now", "", "judge as at this instant") |
| 301 | if err := fs.Parse(args); err != nil { |
| 302 | return err |
| 303 | } |
| 304 | |
| 305 | in := &integrator{ |
| 306 | repo: *repo, |
| 307 | project: *project, |
| 308 | out: os.Stdout, |
| 309 | timings: newDroppable(duplicate(syscall.Stdout, "stdout")), |
| 310 | sightings: newSightings(), |
| 311 | attestSchema: *attestSchema, |
| 312 | eventSchema: *eventSchema, |
| 313 | key: *key, |
| 314 | signerName: *name, |
| 315 | knownSigners: *known, |
| 316 | bus: *bus, |
| 317 | publishQueue: *publishQueue, |
| 318 | wake: *wake, |
| 319 | system: *system, |
| 320 | floorReaders: floorReaders, |
| 321 | } |
| 322 | for _, missing := range []struct{ flag, value string }{ |
| 323 | {"--key", in.key}, |
| 324 | {"--known-signers", in.knownSigners}, |
| 325 | {"--schema", *schema}, |
| 326 | {"--attest-schema", in.attestSchema}, |
| 327 | } { |
| 328 | if missing.value == "" { |
| 329 | return fmt.Errorf("%s is required", missing.flag) |
| 330 | } |
| 331 | } |
| 332 | var err error |
| 333 | for _, tool := range []struct { |
| 334 | name string |
| 335 | into *string |
| 336 | }{{"attest", &in.attest}, {"valley", &in.valley}, {"cue", &in.cue}, {"nats", &in.nats}} { |
| 337 | if *tool.into, err = exec.LookPath(tool.name); err != nil && tool.name != "nats" { |
| 338 | return fmt.Errorf("%s is not on the path; the integrator drives it rather than reimplementing it", tool.name) |
| 339 | } |
| 340 | } |
| 341 | // The floor comes from the instance repository's integrated tip, or from |
| 342 | // a directory on disk, and never from both — two sources for one layer is |
| 343 | // a question about which one won every time the policy is read. |
| 344 | if (*instanceRepo == "") == (*instance == "") { |
| 345 | 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") |
| 346 | } |
| 347 | // abs of an empty path is the working directory, and an empty field is |
| 348 | // how the layer says which of its two sources it is. |
| 349 | layer := composed.Floor{Ref: *instanceRef, Dir: *instancePolicy} |
| 350 | if *instanceRepo != "" { |
| 351 | // A full ref name is read by that exact name. Any other name, |
| 352 | // such as main, git would resolve by trying several refs in |
| 353 | // turn, and a pusher can make one of them. |
| 354 | if !strings.HasPrefix(*instanceRef, "refs/") { |
| 355 | return fmt.Errorf("--instance-ref %s is not a full ref name; name it whole, as refs/heads/main", *instanceRef) |
| 356 | } |
| 357 | layer.Repo = abs(*instanceRepo) |
| 358 | } else { |
| 359 | layer.Path = abs(*instance) |
| 360 | } |
| 361 | in.policy = policySource{ |
| 362 | schema: abs(*schema), |
| 363 | layer: layer, |
| 364 | projectDir: *projectPolicy, |
| 365 | valley: in.valley, |
| 366 | cue: in.cue, |
| 367 | } |
| 368 | if *now != "" { |
| 369 | if in.clock, err = time.Parse(time.RFC3339, *now); err != nil { |
| 370 | return fmt.Errorf("--now: %w", err) |
| 371 | } |
| 372 | } |
| 373 | if in.repo, err = filepath.Abs(in.repo); err != nil { |
| 374 | return err |
| 375 | } |
| 376 | if in.project == "" { |
| 377 | in.project = projectName(in.repo) |
| 378 | } |
| 379 | if in.signerProjects, in.signerProjectsData, err = readSignerProjects(*signerProjects, in.signerName); err != nil { |
| 380 | return err |
| 381 | } |
| 382 | if in.keyHash, err = in.readKeyHash(); err != nil { |
| 383 | return err |
| 384 | } |
| 385 | if len(in.floorReaders) > 0 && !landsFloor(in.repo, layer) { |
| 386 | return fmt.Errorf("--wake-floor-reader is for the controller that lands the floor: give it only with --instance-repo naming the repository --repo serves") |
| 387 | } |
| 388 | // A wake directory is consumed by one long-lived controller. A |
| 389 | // reconcile run by hand beside it must not take its marks. |
| 390 | if *wokenBy != "" && !loop { |
| 391 | return fmt.Errorf("--woken-by is watch's: reconcile reads no wake directory") |
| 392 | } |
| 393 | if *wokenBy != "" && !wakeSupported { |
| 394 | return fmt.Errorf("--woken-by: watching a wake directory needs Linux's inotify; run watch without it to pass at --interval") |
| 395 | } |
| 396 | if loop && *interval <= 0 { |
| 397 | return fmt.Errorf("--interval %s: the recovery interval must be positive", *interval) |
| 398 | } |
| 399 | |
| 400 | if !loop { |
| 401 | return in.reconcile(reasonOnce) |
| 402 | } |
| 403 | // Only the looping controller sweeps. A one-shot run may be somebody |
| 404 | // running the integrator by hand beside a controller that is already |
| 405 | // watching this repository, and sweeping from there would pull the |
| 406 | // worktree out from under a tick in progress. |
| 407 | // |
| 408 | // One controller serves a repository (own_unix.go). Its lock comes |
| 409 | // before the sweep, so a second watch over the same repository stops |
| 410 | // before it can sweep a worktree out from under the first, and the lock |
| 411 | // is checked again before every pass. |
| 412 | return serve(in.repo, sweepScratch, func(owned func() error) error { |
| 413 | if *wokenBy == "" { |
| 414 | for reason := reasonStartup; ; reason = reasonTimer { |
| 415 | if err := owned(); err != nil { |
| 416 | return err |
| 417 | } |
| 418 | if err := in.reconcile(reason); err != nil { |
| 419 | fmt.Fprintf(os.Stderr, "integrator: %v\n", err) |
| 420 | } |
| 421 | time.Sleep(*interval) |
| 422 | } |
| 423 | } |
| 424 | l := &wakeLoop{ |
| 425 | dir: abs(*wokenBy), |
| 426 | interval: *interval, |
| 427 | stderr: os.Stderr, |
| 428 | watch: watchDir, |
| 429 | owned: owned, |
| 430 | pass: func(reason passReason) (bool, error) { |
| 431 | in.out = newPassOutput(os.Stdout, reason) |
| 432 | before := in.landings |
| 433 | err := in.reconcile(reason) |
| 434 | return in.landings > before, err |
| 435 | }, |
| 436 | } |
| 437 | return l.run() |
| 438 | }) |
| 439 | } |
| 440 | |
| 441 | // serve is a watch's start: it takes the repository's lock, then sweeps |
| 442 | // the repository's scratch, then runs the loop, which asks owned before |
| 443 | // every pass. A watch that cannot take the lock does neither, and holds |
| 444 | // nothing when it returns. |
| 445 | func serve(repo string, sweep func(string), loop func(owned func() error) error) error { |
| 446 | owner, err := ownRepo(repo) |
| 447 | if err != nil { |
| 448 | return err |
| 449 | } |
| 450 | defer owner.Close() |
| 451 | sweep(repo) |
| 452 | return loop(owner.check) |
| 453 | } |
| 454 | |
| 455 | // dirList is a flag given once per directory. |
| 456 | type dirList []string |
| 457 | |
| 458 | func (d *dirList) String() string { return strings.Join(*d, ",") } |
| 459 | |
| 460 | func (d *dirList) Set(dir string) error { |
| 461 | if dir == "" { |
| 462 | return fmt.Errorf("an empty directory marks nothing") |
| 463 | } |
| 464 | *d = append(*d, abs(dir)) |
| 465 | return nil |
| 466 | } |
| 467 | |
| 468 | // landsFloor says whether the repository this controller serves is the one |
| 469 | // its floor is read from, so a landing there can move the floor. |
| 470 | func landsFloor(repo string, layer composed.Floor) bool { |
| 471 | if layer.Repo == "" { |
| 472 | return false |
| 473 | } |
| 474 | a, err := os.Stat(repo) |
| 475 | if err != nil { |
| 476 | return false |
| 477 | } |
| 478 | b, err := os.Stat(layer.Repo) |
| 479 | return err == nil && os.SameFile(a, b) |
| 480 | } |
| 481 | |
| 482 | // readKeyHash asks attest for the verifier key this integrator signs under, |
| 483 | // and keeps the key hash: it is the segment that keeps one signer's |
| 484 | // attestation ref from racing another's (dcr-0de694f). |
| 485 | func (in *integrator) readKeyHash() (string, error) { |
| 486 | out, err := exec.Command(in.attest, "key", "--key", in.key, "--name", in.signerName).Output() |
| 487 | if err != nil { |
| 488 | return "", fmt.Errorf("reading the signing key: %w", err) |
| 489 | } |
| 490 | // name+hash+base64, split three ways: the name holds no plus and the |
| 491 | // base64 may. |
| 492 | fields := strings.SplitN(strings.TrimSpace(string(out)), "+", 3) |
| 493 | if len(fields) != 3 { |
| 494 | return "", fmt.Errorf("attest key printed %q", strings.TrimSpace(string(out))) |
| 495 | } |
| 496 | if _, err := strconv.ParseUint(fields[1], 16, 32); err != nil { |
| 497 | return "", fmt.Errorf("attest key printed the hash %q", fields[1]) |
| 498 | } |
| 499 | return fields[1], nil |
| 500 | } |
| 501 | |
| 502 | // projectName is the name the events carry: the repository's directory, |
| 503 | // with a bare repo's .git suffix removed — the same name the post-receive |
| 504 | // hook derives. |
| 505 | func projectName(repo string) string { |
| 506 | if bare, err := gitLine(repo, "rev-parse", "--is-bare-repository"); err == nil && bare == "true" { |
| 507 | dir, _ := gitLine(repo, "rev-parse", "--absolute-git-dir") |
| 508 | return strings.TrimSuffix(filepath.Base(dir), ".git") |
| 509 | } |
| 510 | top, err := gitLine(repo, "rev-parse", "--show-toplevel") |
| 511 | if err != nil { |
| 512 | return filepath.Base(repo) |
| 513 | } |
| 514 | return filepath.Base(top) |
| 515 | } |
| 516 | |
| 517 | // defaultSignerName is the name this machine signs under: its own name and |
| 518 | // the suffix that keeps a key signing attestations distinct from the same |
| 519 | // key signing anything else (dcr-de9d996). |
| 520 | func defaultSignerName() string { |
| 521 | host, err := os.Hostname() |
| 522 | if err != nil || host == "" { |
| 523 | host = "localhost" |
| 524 | } |
| 525 | return host + "/attestations" |
| 526 | } |
| 527 | |
| 528 | func env(name string) string { return os.Getenv(name) } |
| 529 | |
| 530 | // environ is the environment the process started with, read before main |
| 531 | // replaces it. |
| 532 | var environ = os.Environ() |
| 533 | |
| 534 | // gitEnvironment is the environment the controller runs in: the one it |
| 535 | // started with, with git's part of it fixed. |
| 536 | // |
| 537 | // Replacement refs are off. A replacement ref makes one object stand in for |
| 538 | // another wherever git looks it up, so a refs/replace/<blob> pushed to the |
| 539 | // served repository or the instance repository could swap the floor, the |
| 540 | // project's policy or a change's tree for anything its author liked, |
| 541 | // without moving any ref the controller watches. Every judgement here reads |
| 542 | // the repository's own objects. |
| 543 | // |
| 544 | // No other GIT_ variable is inherited, as sigverify inherits none: a GIT_DIR |
| 545 | // or GIT_OBJECT_DIRECTORY could point git at other objects, and a |
| 546 | // GIT_CONFIG_PARAMETERS could change how it reads them. System and user |
| 547 | // configuration are not read either. The one thing kept is command-scope |
| 548 | // configuration naming safe.directory, which is how the unit tells git it |
| 549 | // may read repositories the controller does not own (nix/valley-host.nix). |
| 550 | // Those entries are carried over, renumbered, and no other key is. |
| 551 | func gitEnvironment(inherited []string) []string { |
| 552 | vars := map[string]string{} |
| 553 | var kept []string |
| 554 | for _, kv := range inherited { |
| 555 | name, value, _ := strings.Cut(kv, "=") |
| 556 | if strings.HasPrefix(name, "GIT_") { |
| 557 | vars[name] = value |
| 558 | continue |
| 559 | } |
| 560 | kept = append(kept, kv) |
| 561 | } |
| 562 | |
| 563 | var safe []string |
| 564 | count, _ := strconv.Atoi(vars["GIT_CONFIG_COUNT"]) |
| 565 | for i := 0; i < count; i++ { |
| 566 | if strings.EqualFold(vars[fmt.Sprintf("GIT_CONFIG_KEY_%d", i)], "safe.directory") { |
| 567 | safe = append(safe, vars[fmt.Sprintf("GIT_CONFIG_VALUE_%d", i)]) |
| 568 | } |
| 569 | } |
| 570 | if len(safe) > 0 { |
| 571 | kept = append(kept, fmt.Sprintf("GIT_CONFIG_COUNT=%d", len(safe))) |
| 572 | for i, dir := range safe { |
| 573 | kept = append(kept, |
| 574 | fmt.Sprintf("GIT_CONFIG_KEY_%d=safe.directory", i), |
| 575 | fmt.Sprintf("GIT_CONFIG_VALUE_%d=%s", i, dir)) |
| 576 | } |
| 577 | } |
| 578 | |
| 579 | return append(kept, |
| 580 | "GIT_CONFIG_NOSYSTEM=1", |
| 581 | "GIT_CONFIG_SYSTEM=/dev/null", |
| 582 | "GIT_CONFIG_GLOBAL=/dev/null", |
| 583 | "GIT_NO_REPLACE_OBJECTS=1", |
| 584 | "GIT_ATTR_NOSYSTEM=1", |
| 585 | "GIT_TERMINAL_PROMPT=0", |
| 586 | ) |
| 587 | } |
| 588 | |
| 589 | func abs(path string) string { |
| 590 | if p, err := filepath.Abs(path); err == nil { |
| 591 | return p |
| 592 | } |
| 593 | return path |
| 594 | } |
| 595 | |
| 596 | // gitEnv runs a git command with extra environment, for the one place the |
| 597 | // integrator has to state who authored and who committed. |
| 598 | func (in *integrator) gitEnv(extra map[string]string, args ...string) (string, error) { |
| 599 | cmd := exec.Command("git", args...) |
| 600 | cmd.Dir = in.repo |
| 601 | cmd.Env = os.Environ() |
| 602 | for k, v := range extra { |
| 603 | cmd.Env = append(cmd.Env, k+"="+v) |
| 604 | } |
| 605 | var errb strings.Builder |
| 606 | cmd.Stderr = &errb |
| 607 | out, err := cmd.Output() |
| 608 | if err != nil { |
| 609 | return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(errb.String())) |
| 610 | } |
| 611 | return string(out), nil |
| 612 | } |
| 613 | |
| 614 | // writeTemp writes bytes to a file cue will read as JSON — the extension is |
| 615 | // how cue tells a data file from a schema. |
| 616 | func writeTemp(prefix string, body []byte) (string, error) { |
| 617 | dir, err := scratch(prefix) |
| 618 | if err != nil { |
| 619 | return "", err |
| 620 | } |
| 621 | path := filepath.Join(dir, "payload.json") |
| 622 | if err := os.WriteFile(path, body, 0o644); err != nil { |
| 623 | return "", err |
| 624 | } |
| 625 | return path, nil |
| 626 | } |
| 627 | |
| 628 | func removeTemp(path string) { _ = os.RemoveAll(filepath.Dir(path)) } |