| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/ed25519" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "the-valley/approval" |
| 15 | "the-valley/change" |
| 16 | "the-valley/note" |
| 17 | ) |
| 18 | |
| 19 | // TestMain lets the test binary stand in for the hook a real push runs: |
| 20 | // a repository whose hooks/pre-receive links to the binary runs |
| 21 | // preReceive with the arguments VALLEYHOOK_TEST_HOOK names. |
| 22 | func TestMain(m *testing.M) { |
| 23 | if args := os.Getenv("VALLEYHOOK_TEST_HOOK"); args != "" { |
| 24 | os.Exit(preReceive(strings.Split(args, "\n"), os.Stdin, os.Stderr, gitRepository{})) |
| 25 | } |
| 26 | os.Exit(m.Run()) |
| 27 | } |
| 28 | |
| 29 | var approvalKey = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize)) |
| 30 | |
| 31 | // approvalNote is a signed approval of version of the change id landing |
| 32 | // on target, by principal. |
| 33 | func approvalNote(t *testing.T, id, target, principal string, version int) string { |
| 34 | t.Helper() |
| 35 | n, err := approval.Sign(approvalStatement(id, target, principal, version), approval.NewKey(approvalKey)) |
| 36 | if err != nil { |
| 37 | t.Fatal(err) |
| 38 | } |
| 39 | return string(n) |
| 40 | } |
| 41 | |
| 42 | // approvalNoteAt is a signed approval of version of changeID at head, |
| 43 | // landing on main, by operator. |
| 44 | func approvalNoteAt(t *testing.T, version int, head string) string { |
| 45 | t.Helper() |
| 46 | s := approvalStatement(changeID, "main", "operator", version) |
| 47 | s.Head = change.HeadPrefix + head |
| 48 | n, err := approval.Sign(s, approval.NewKey(approvalKey)) |
| 49 | if err != nil { |
| 50 | t.Fatal(err) |
| 51 | } |
| 52 | return string(n) |
| 53 | } |
| 54 | |
| 55 | func approvalStatement(id, target, principal string, version int) approval.Statement { |
| 56 | return approval.Statement{ |
| 57 | Instance: strings.Repeat("5f", 32), Project: "project", Target: target, Change: id, |
| 58 | Version: version, Head: change.HeadPrefix + strings.Repeat("2", 40), |
| 59 | Record: change.HeadPrefix + strings.Repeat("3", 40), Principal: principal, |
| 60 | Issued: time.Date(2026, 11, 6, 0, 43, 26, 0, time.UTC), |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | // Only a holder of the approve grant, under either of its names, writes an |
| 65 | // approval: owning the change, the restack grant and a writer list confer |
| 66 | // nothing. An approval ref is named for a change and main, and points at |
| 67 | // one blob holding an approval note about that change and target, held to |
| 68 | // approval.MaxNote bytes before it is read. Whether its key may approve |
| 69 | // anything is not the hook's to judge. |
| 70 | func TestAnApprovalTakesTheApproveGrantAndHoldsOneNote(t *testing.T) { |
| 71 | r := newRecords(t) |
| 72 | r.p.grants["approver"] = map[string]bool{grantApprove: true} |
| 73 | r.p.grants["restacker"] = map[string]bool{grantRestack: true} |
| 74 | ref := approval.Ref("main", changeID) |
| 75 | first := r.blob(approvalNote(t, changeID, "main", "operator", 1)) |
| 76 | second := r.blob(approvalNote(t, changeID, "main", "approver", 2)) |
| 77 | if ref != "refs/the-valley/approvals/main/c-"+changeID { |
| 78 | t.Fatalf("the approval ref is %s", ref) |
| 79 | } |
| 80 | |
| 81 | r.expect("a create by a holder of request", "operator", ref, zeroID, first, "") |
| 82 | r.expect("a create by a holder of approve", "approver", ref, zeroID, second, "") |
| 83 | r.expect("a replacement", "operator", ref, first, second, "") |
| 84 | r.expect("a delete", "approver", ref, first, zeroID, "") |
| 85 | for _, who := range []string{"alice", "restacker"} { |
| 86 | says := "refs/the-valley/approvals/ takes writes only from a principal holding the approve grant (also accepted as request), and " + who + " holds none" |
| 87 | r.expect("a create by "+who, who, ref, zeroID, first, says) |
| 88 | r.expect("a replacement by "+who, who, ref, first, second, says) |
| 89 | r.expect("a delete by "+who, who, ref, first, zeroID, says) |
| 90 | } |
| 91 | r.expect("an untagged key", "", ref, zeroID, first, "a key that names no principal holds no grant") |
| 92 | r.p.push = pushPolicy{Writers: []string{"alice"}, Grants: map[string]refGrant{"all": {Refs: []string{"refs/*"}, Writers: []string{"alice"}}}} |
| 93 | r.expect("a declared writer opened every ref", "alice", ref, zeroID, first, "holds none") |
| 94 | r.p.push = pushPolicy{Refs: []string{approval.RefPrefix + "*"}, Writers: []string{"approver"}} |
| 95 | r.expect("a protected approval", "operator", ref, zeroID, first, "a protected ref of project") |
| 96 | r.expect("a protected approval by its writer", "approver", ref, zeroID, first, "") |
| 97 | r.p.push = pushPolicy{} |
| 98 | |
| 99 | for _, bad := range []string{ |
| 100 | approval.RefPrefix + "main/" + changeID, |
| 101 | approval.RefPrefix + "main/c-" + changeID[:31], |
| 102 | approval.RefPrefix + "main/c-" + strings.ToUpper(changeID), |
| 103 | approval.RefPrefix + "main/c-" + changeID + "/x", |
| 104 | approval.RefPrefix + "c-" + changeID, |
| 105 | approval.RefPrefix + "release/c-" + changeID, |
| 106 | approval.RefPrefix + "main", |
| 107 | } { |
| 108 | r.expect("the malformed "+bad, "operator", bad, zeroID, first, "an approval's ref is refs/the-valley/approvals/main/c-<change ID>") |
| 109 | r.expect("a delete of the malformed "+bad, "operator", bad, first, zeroID, "an approval's ref is") |
| 110 | } |
| 111 | r.p.symrefs = map[string]bool{ref: true} |
| 112 | r.expect("a symbolic ref", "operator", ref, zeroID, first, "symbolic ref") |
| 113 | r.p.symrefs = nil |
| 114 | r.expect("a lookalike", "operator", "refs/"+ref, zeroID, first, "named refs/ followed by a full ref name") |
| 115 | |
| 116 | signedAs := func(text []byte, name string) string { |
| 117 | n, err := note.Sign(text, name, approvalKey) |
| 118 | if err != nil { |
| 119 | t.Fatal(err) |
| 120 | } |
| 121 | return string(n) |
| 122 | } |
| 123 | text, err := approvalStatement(changeID, "main", "operator", 1).Encode() |
| 124 | if err != nil { |
| 125 | t.Fatal(err) |
| 126 | } |
| 127 | twice, err := note.AddSignature([]byte(approvalNote(t, changeID, "main", "operator", 1)), "approver", approvalKey) |
| 128 | if err != nil { |
| 129 | t.Fatal(err) |
| 130 | } |
| 131 | for _, c := range []struct{ what, object, says string }{ |
| 132 | {"a tree", r.git("", "mktree"), "it points at a tree, where an approval holds a blob"}, |
| 133 | {"a commit", r.source("one"), "it points at a commit, where an approval holds a blob"}, |
| 134 | {"an object the push did not bring", strings.Repeat("1", 40), "it names an object the push did not bring"}, |
| 135 | {"an oversized blob", r.blob(strings.Repeat("x", approval.MaxNote+1)), "it is a blob of 2049 bytes, more than the 2048 an approval's may be"}, |
| 136 | {"text", r.blob("approved\n"), "it is not an approval note: this is not a note"}, |
| 137 | {"another kind of statement", r.blob(signedAs([]byte("the-valley/attestation/v1\n"), "operator")), "it is not an approval note: the signed text is not an approval"}, |
| 138 | {"a note signed twice", r.blob(string(twice)), "an approval note carries one signature, and this carries 2"}, |
| 139 | {"a signature under another name", r.blob(signedAs(text, "approver")), "signed with a key of approver, and names operator as its approver"}, |
| 140 | {"another change's approval", r.blob(approvalNote(t, strings.Repeat("k", 32), "main", "operator", 1)), "it approves the change " + strings.Repeat("k", 32) + ", and its ref names " + changeID}, |
| 141 | {"an approval for another target", r.blob(approvalNote(t, changeID, "release", "operator", 1)), "it approves landing on release, and its ref names main"}, |
| 142 | } { |
| 143 | r.expect(c.what, "operator", ref, zeroID, c.object, c.says) |
| 144 | r.expect(c.what+" as a replacement", "operator", ref, first, c.object, c.says) |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | // An approval names the head of the integration request it lands beside, |
| 149 | // whether the push writes that request or the repository holds it, and a |
| 150 | // version the change's record gives that head. An approval with no |
| 151 | // request beside it is not compared, nor is a request the push deletes. |
| 152 | func TestAnApprovalNamesTheHeadOfTheRequestBesideIt(t *testing.T) { |
| 153 | r := newRecords(t) |
| 154 | h1, h2 := r.source("one"), r.source("two") |
| 155 | req := requestPrefix + "main/" + change.RequestName(changeID) |
| 156 | ref := approval.Ref("main", changeID) |
| 157 | v1, v2 := r.blob(approvalNoteAt(t, 1, h1)), r.blob(approvalNoteAt(t, 2, h2)) |
| 158 | r.expect("an approval with no request beside it", "operator", ref, zeroID, v1, "") |
| 159 | r.git("", "update-ref", req, h1) |
| 160 | r.expect("an approval beside a request of a change with no record", "operator", ref, zeroID, v1, |
| 161 | "it approves v1, and the repository holds no record of the change") |
| 162 | record := r.write(encode(t, next(first("alice", h1), "alice", h2)), h1) |
| 163 | r.git("", "update-ref", change.Ref("main", changeID), record) |
| 164 | |
| 165 | r.expect("an approval of the request's head", "operator", ref, zeroID, v1, "") |
| 166 | r.expect("an approval of another head", "operator", ref, zeroID, v2, |
| 167 | "it approves the head "+h2+", and the integration request beside it files "+h1) |
| 168 | r.expect("an approval of another version at the request's head", "operator", ref, zeroID, r.blob(approvalNoteAt(t, 2, h1)), |
| 169 | "it approves v2 at "+h1+", and the change's record gives v2 no such head") |
| 170 | r.expect("an approval of a version the record lacks", "operator", ref, zeroID, r.blob(approvalNoteAt(t, 3, h1)), |
| 171 | "the change's record gives v3 no such head") |
| 172 | |
| 173 | r.p.pushed = map[string]string{req: h2} |
| 174 | r.expect("an approval of the head the push files", "operator", ref, v1, v2, "") |
| 175 | r.expect("an approval of the head the push replaces", "operator", ref, v2, v1, "the integration request beside it files "+h2) |
| 176 | r.p.pushed = map[string]string{req: zeroID} |
| 177 | r.expect("an approval beside a request the push deletes", "operator", ref, zeroID, v2, "") |
| 178 | r.p.pushed = map[string]string{req: h2, change.Ref("main", changeID): r.write(encode(t, first("alice", h1)), h1)} |
| 179 | r.expect("an approval of a version the pushed record lacks", "operator", ref, zeroID, v2, "the change's record gives v2 no such head") |
| 180 | r.p.pushed = nil |
| 181 | } |
| 182 | |
| 183 | // The request an approval lands beside is read by its exact name: refs |
| 184 | // left beneath that name are neither listed nor taken for the request, |
| 185 | // however many there are, and the request itself reads once it is there. |
| 186 | func TestTheRequestBesideAnApprovalIsReadByItsName(t *testing.T) { |
| 187 | r := newRecords(t) |
| 188 | h := r.source("one") |
| 189 | req := requestPrefix + "main/" + change.RequestName(changeID) |
| 190 | var created, deleted strings.Builder |
| 191 | for i := 0; i < 2000; i++ { |
| 192 | fmt.Fprintf(&created, "create %s/beneath-%d %s\n", req, i, h) |
| 193 | fmt.Fprintf(&deleted, "delete %s/beneath-%d %s\n", req, i, h) |
| 194 | } |
| 195 | r.git(created.String(), "update-ref", "--stdin") |
| 196 | if oid, ok, err := (gitRepository{}).ref(req); ok || err != nil { |
| 197 | t.Fatalf("the request read as %q, %v, %v with only refs beneath its name", oid, ok, err) |
| 198 | } |
| 199 | r.expect("an approval beside refs beneath the request's name", "operator", approval.Ref("main", changeID), zeroID, |
| 200 | r.blob(approvalNoteAt(t, 1, strings.Repeat("2", 40))), "") |
| 201 | r.git(deleted.String(), "update-ref", "--stdin") |
| 202 | r.git("", "update-ref", req, h) |
| 203 | if oid, ok, err := (gitRepository{}).ref(req); !ok || err != nil || oid != h { |
| 204 | t.Fatalf("the request read as %q, %v, %v, not %s", oid, ok, err, h) |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | // An approval is published beside the change's integration request in one |
| 209 | // atomic push, each ref leased: a create against no ref, a replacement or a |
| 210 | // delete against the value read. The push goes through the real hook, run |
| 211 | // by receive-pack. A stale lease on either ref, or an approval the hook |
| 212 | // refuses, leaves both refs as they were. So does an approval of another |
| 213 | // head pushed alone beside a request another approver replaced, though |
| 214 | // its lease on the approval ref holds. |
| 215 | func TestAnApprovalIsPublishedWithItsRequestAtomicallyAndLeased(t *testing.T) { |
| 216 | hook, err := os.Executable() |
| 217 | if err != nil { |
| 218 | t.Fatal(err) |
| 219 | } |
| 220 | dir := t.TempDir() |
| 221 | origin, client := filepath.Join(dir, "origin.git"), filepath.Join(dir, "client") |
| 222 | gitIn(t, dir, "", "init", "--quiet", "--bare", origin) |
| 223 | if err := os.Symlink(hook, filepath.Join(origin, "hooks", "pre-receive")); err != nil { |
| 224 | t.Fatal(err) |
| 225 | } |
| 226 | policyFile, grantsFile := filepath.Join(dir, "policy.json"), filepath.Join(dir, "grants") |
| 227 | if err := os.WriteFile(policyFile, []byte(`{"refs": [], "writers": [], "grants": {}}`), 0o644); err != nil { |
| 228 | t.Fatal(err) |
| 229 | } |
| 230 | if err := os.WriteFile(grantsFile, []byte("approve operator\n"), 0o644); err != nil { |
| 231 | t.Fatal(err) |
| 232 | } |
| 233 | gitIn(t, dir, "", "init", "--quiet", client) |
| 234 | commit := func(subject string) string { |
| 235 | tree := gitIn(t, client, "", "mktree") |
| 236 | return gitIn(t, client, "", "-c", "user.name=t", "-c", "user.email=t@localhost", "commit-tree", tree, "-m", subject) |
| 237 | } |
| 238 | blob := func(content string) string { return gitIn(t, client, content, "hash-object", "-w", "--stdin") } |
| 239 | push := func(args ...string) (bool, string) { |
| 240 | cmd := exec.Command("git", append([]string{"push", "--atomic", "--porcelain", origin}, args...)...) |
| 241 | cmd.Dir = client |
| 242 | cmd.Env = append(os.Environ(), "VALLEYHOOK_TEST_HOOK="+strings.Join([]string{ |
| 243 | "--project", "project", "--policy", policyFile, "--grants", grantsFile, "--principal", "operator", |
| 244 | }, "\n")) |
| 245 | out, err := cmd.CombinedOutput() |
| 246 | return err == nil, string(out) |
| 247 | } |
| 248 | at := func(ref string) string { |
| 249 | cmd := exec.Command("git", "for-each-ref", "--format=%(objectname)", ref) |
| 250 | cmd.Dir = origin |
| 251 | out, err := cmd.Output() |
| 252 | if err != nil { |
| 253 | t.Fatal(err) |
| 254 | } |
| 255 | return strings.TrimSpace(string(out)) |
| 256 | } |
| 257 | |
| 258 | req := requestPrefix + "main/" + change.RequestName(changeID) |
| 259 | ref := approval.Ref("main", changeID) |
| 260 | h1, h2 := commit("one"), commit("two") |
| 261 | a1, a2 := blob(approvalNoteAt(t, 1, h1)), blob(approvalNoteAt(t, 2, h2)) |
| 262 | elsewhere := blob(approvalNote(t, strings.Repeat("k", 32), "main", "operator", 2)) |
| 263 | // The change's record, giving v1 the head h1 and v2 the head h2, |
| 264 | // written into origin as the hook's record rules have admitted it. |
| 265 | rec, err := change.Encode(&change.Record{Schema: change.Schema, ChangeID: changeID, Target: "main", Owner: "alice", |
| 266 | State: change.Ready, Seq: 2, Active: 2, Versions: []change.Version{ |
| 267 | {N: 1, Head: change.HeadPrefix + h1, Title: "one", Branch: "topic", Uploader: "alice"}, |
| 268 | {N: 2, Head: change.HeadPrefix + h2, Title: "two", Branch: "topic", Uploader: "alice"}}}) |
| 269 | if err != nil { |
| 270 | t.Fatal(err) |
| 271 | } |
| 272 | recBlob := gitIn(t, origin, string(rec), "hash-object", "-w", "--stdin") |
| 273 | recTree := gitIn(t, origin, "100644 blob "+recBlob+"\trecord.json\n", "mktree") |
| 274 | gitIn(t, origin, "", "update-ref", change.Ref("main", changeID), gitIn(t, origin, "", "-c", "user.name=t", "-c", "user.email=t@localhost", "commit-tree", recTree, "-m", "record")) |
| 275 | |
| 276 | if ok, out := push("--force-with-lease="+req+":", "--force-with-lease="+ref+":", h1+":"+req, a1+":"+ref); !ok { |
| 277 | t.Fatalf("filing the request and its approval: %s", out) |
| 278 | } |
| 279 | if at(req) != h1 || at(ref) != a1 { |
| 280 | t.Fatalf("after filing: the request is at %q and the approval at %q", at(req), at(ref)) |
| 281 | } |
| 282 | |
| 283 | for _, c := range []struct { |
| 284 | what string |
| 285 | args []string |
| 286 | }{ |
| 287 | {"an approval leased against no ref", []string{"--force-with-lease=" + req + ":" + h1, "--force-with-lease=" + ref + ":", h2 + ":" + req, a2 + ":" + ref}}, |
| 288 | {"an approval leased against another value", []string{"--force-with-lease=" + req + ":" + h1, "--force-with-lease=" + ref + ":" + a2, h2 + ":" + req, a2 + ":" + ref}}, |
| 289 | {"a request leased against another value", []string{"--force-with-lease=" + req + ":" + h2, "--force-with-lease=" + ref + ":" + a1, h2 + ":" + req, a2 + ":" + ref}}, |
| 290 | {"a delete leased against another value", []string{"--force-with-lease=" + req + ":" + h1, "--force-with-lease=" + ref + ":" + a2, ":" + req, ":" + ref}}, |
| 291 | {"an approval the hook refuses", []string{"--force-with-lease=" + req + ":" + h1, "--force-with-lease=" + ref + ":" + a1, h2 + ":" + req, elsewhere + ":" + ref}}, |
| 292 | } { |
| 293 | if ok, out := push(c.args...); ok { |
| 294 | t.Errorf("%s was pushed: %s", c.what, out) |
| 295 | } |
| 296 | if at(req) != h1 || at(ref) != a1 { |
| 297 | t.Errorf("after %s: the request is at %q and the approval at %q", c.what, at(req), at(ref)) |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | // Another approver replaces the request and its approval at h2. An |
| 302 | // approver who read the request at h1 and the approval at a2 pushes |
| 303 | // its approval of h1 alone, leased on a2. |
| 304 | if ok, out := push("--force-with-lease="+req+":"+h1, "--force-with-lease="+ref+":"+a1, h2+":"+req, a2+":"+ref); !ok { |
| 305 | t.Fatalf("replacing the request and its approval: %s", out) |
| 306 | } |
| 307 | if at(req) != h2 || at(ref) != a2 { |
| 308 | t.Fatalf("after replacing: the request is at %q and the approval at %q", at(req), at(ref)) |
| 309 | } |
| 310 | if ok, out := push("--force-with-lease="+ref+":"+a2, a1+":"+ref); ok || !strings.Contains(out, "the integration request beside it files "+h2) { |
| 311 | t.Errorf("an approval of h1 beside the request at h2 was not refused for it: %s", out) |
| 312 | } |
| 313 | if at(req) != h2 || at(ref) != a2 { |
| 314 | t.Fatalf("after the refused approval: the request is at %q and the approval at %q", at(req), at(ref)) |
| 315 | } |
| 316 | if ok, out := push("--force-with-lease="+req+":"+h2, "--force-with-lease="+ref+":"+a2, ":"+req, ":"+ref); !ok { |
| 317 | t.Fatalf("withdrawing the request and its approval: %s", out) |
| 318 | } |
| 319 | if at(req) != "" || at(ref) != "" { |
| 320 | t.Fatalf("after withdrawing: the request is at %q and the approval at %q", at(req), at(ref)) |
| 321 | } |
| 322 | } |