| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/base64" |
| 8 | "encoding/hex" |
| 9 | "encoding/json" |
| 10 | "errors" |
| 11 | "fmt" |
| 12 | "os" |
| 13 | "path/filepath" |
| 14 | "regexp" |
| 15 | "slices" |
| 16 | "strings" |
| 17 | "sync" |
| 18 | "syscall" |
| 19 | "testing" |
| 20 | "time" |
| 21 | |
| 22 | "the-valley/web/export" |
| 23 | ) |
| 24 | |
| 25 | const goodLink = `{"id": "lk-0123456789abcdef", "principal": "alice", "note": "laptop", "verifier": "` + |
| 26 | "3a6eb0790f39ac87c94f3856b2dd2c5d110e6811602261a9a923d3bb23adc8b7" + `", "issued": "2026-10-29T12:00:00Z", "changed": 3` |
| 27 | |
| 28 | // The credential file is read strictly: a missing or empty file holds no |
| 29 | // links, and any key, ID or field the format does not allow is refused, |
| 30 | // never skipped. |
| 31 | func TestTheCredentialFileIsReadStrictly(t *testing.T) { |
| 32 | dir := t.TempDir() |
| 33 | path := filepath.Join(dir, "links") |
| 34 | if f, err := readLinks(path); err != nil || len(f.Links) != 0 { |
| 35 | t.Fatalf("a missing file read as %+v, %v", f, err) |
| 36 | } |
| 37 | read := func(body string) (linksFile, error) { |
| 38 | t.Helper() |
| 39 | if err := os.WriteFile(path, []byte(body), 0o600); err != nil { |
| 40 | t.Fatal(err) |
| 41 | } |
| 42 | return readLinks(path) |
| 43 | } |
| 44 | if f, err := read(""); err != nil || len(f.Links) != 0 { |
| 45 | t.Fatalf("an empty file read as %+v, %v", f, err) |
| 46 | } |
| 47 | if f, err := read(`{"revision": 3, "links": [` + goodLink + `}]}`); err != nil || f.Revision != 3 || len(f.active()) != 1 { |
| 48 | t.Fatalf("a valid file read as %+v, %v", f, err) |
| 49 | } |
| 50 | for _, bad := range []string{ |
| 51 | `{"revision": 3, "links": [` + goodLink + `, "secret": "x"}]}`, |
| 52 | `{"revision": 3, "links": [` + strings.Replace(goodLink, `"principal"`, `"Principal"`, 1) + `}]}`, |
| 53 | `{"revision": 3, "links": [` + goodLink + `}, ` + goodLink + `, "revoked": "2026-10-29T13:00:00Z"}]}`, |
| 54 | `{"revision": 3, "links": [` + strings.Replace(goodLink, "lk-0123456789abcdef", "lk-0123456789ABCDEF", 1) + `}]}`, |
| 55 | `{"revision": 3, "links": [` + strings.Replace(goodLink, `"alice"`, `"anyone"`, 1) + `}]}`, |
| 56 | `{"revision": 3, "links": [` + strings.Replace(goodLink, "3a6e", "zz6e", 1) + `}]}`, |
| 57 | `{"revision": 3, "links": [` + strings.Replace(goodLink, "12:00:00Z", "12:00:00+01:00", 1) + `}]}`, |
| 58 | `{"revision": 3, "links": [` + strings.Replace(goodLink, "laptop", `lap\ttop`, 1) + `}]}`, |
| 59 | `{"revision": -1, "links": []}`, |
| 60 | `{"revision": 2, "links": [` + goodLink + `}]}`, |
| 61 | `{"revision": 3, "links": [` + strings.Replace(goodLink, `"changed": 3`, `"changed": 0`, 1) + `}]}`, |
| 62 | `{"revision": 3, "revision": 4, "links": []}`, |
| 63 | } { |
| 64 | if f, err := read(bad); err == nil { |
| 65 | t.Errorf("%s read as %+v", bad, f) |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | // link runs the link command over the test valley, with the flags the |
| 71 | // verb reads after the arguments given. |
| 72 | func (v *testValley) link(links string, args ...string) (string, string, int) { |
| 73 | var stdout, stderr bytes.Buffer |
| 74 | args = append(args, "--links", links, "--state", v.state) |
| 75 | if args[0] == "issue" { |
| 76 | args = append(args, "--instance-repo", filepath.Join(v.srv, "valley.git"), "--destination", destination, "--host", v.host, |
| 77 | "--read-schema", filepath.Join(v.schemas, "read.cue"), |
| 78 | "--identity-schema", filepath.Join(v.schemas, "identity.cue")) |
| 79 | } |
| 80 | code := runLink(context.Background(), args, &stdout, &stderr) |
| 81 | return stdout.String(), stderr.String(), code |
| 82 | } |
| 83 | |
| 84 | // issue issues a link for the principal and returns its ID. A failure |
| 85 | // reports the link's shape, never the link. |
| 86 | func (v *testValley) issue(links, principal string) string { |
| 87 | v.t.Helper() |
| 88 | stdout, stderr, code := v.link(links, "issue", "--principal", principal) |
| 89 | m := linkPattern.FindStringSubmatch(stdout) |
| 90 | if code != 0 || m == nil { |
| 91 | v.t.Fatalf("issue exited %d and printed %d bytes, not one link: %s", code, len(stdout), stderr) |
| 92 | } |
| 93 | return m[1] |
| 94 | } |
| 95 | |
| 96 | var linkPattern = regexp.MustCompile(`^https://` + regexp.QuoteMeta(destination) + `/-/redeem#(lk-[0-9a-f]{16})\.([A-Za-z0-9_-]{43})\n$`) |
| 97 | |
| 98 | // A link is issued only to a principal who may read a project at the |
| 99 | // destination: one the registry does not name is refused, and so is one |
| 100 | // with a grant no project's policy/read consents to. An issued link is |
| 101 | // printed once; the file keeps its verifier, never its secret, and every |
| 102 | // link has an ID of its own. |
| 103 | func TestIssueNeedsEffectiveReadAccess(t *testing.T) { |
| 104 | v := newValley(t) |
| 105 | links := filepath.Join(v.root, "links", "links") |
| 106 | if _, stderr, code := v.link(links, "issue", "--principal", "bob"); code != 1 || !strings.Contains(stderr, "grants bob no edge read") { |
| 107 | t.Errorf("issuing to bob exited %d: %s", code, stderr) |
| 108 | } |
| 109 | seen := map[string]bool{} |
| 110 | for i := range 3 { |
| 111 | stdout, stderr, code := v.link(links, "issue", "--principal", "operator", "--note", "laptop") |
| 112 | m := linkPattern.FindStringSubmatch(stdout) |
| 113 | if code != 0 || m == nil { |
| 114 | t.Fatalf("issue %d exited %d and printed %d bytes, not one link: %s", i, code, len(stdout), stderr) |
| 115 | } |
| 116 | secret, err := base64.RawURLEncoding.DecodeString(m[2]) |
| 117 | if err != nil || len(secret) != 32 { |
| 118 | t.Fatalf("the secret of %s decodes to %d bytes, not 32: %v", m[1], len(secret), err) |
| 119 | } |
| 120 | f, err := readLinks(links) |
| 121 | if err != nil || f.Revision != int64(i+1) || len(f.Links) != i+1 { |
| 122 | t.Fatalf("after issue %d the file reads as %+v, %v", i, f, err) |
| 123 | } |
| 124 | l := f.Links[i] |
| 125 | sum := sha256.Sum256(secret) |
| 126 | if l.ID != m[1] || l.Principal != "operator" || l.Note != "laptop" || l.Changed != int64(i+1) { |
| 127 | t.Errorf("issue %d recorded %+v", i, l) |
| 128 | } |
| 129 | if l.Verifier != hex.EncodeToString(sum[:]) { |
| 130 | t.Errorf("issue %d recorded a verifier for %s that is not the SHA-256 of its secret", i, l.ID) |
| 131 | } |
| 132 | data, _ := os.ReadFile(links) |
| 133 | if bytes.Contains(data, []byte(m[2])) { |
| 134 | t.Errorf("the credential file holds the secret of %s", l.ID) |
| 135 | } |
| 136 | seen[l.ID] = true |
| 137 | } |
| 138 | if len(seen) != 3 { |
| 139 | t.Errorf("three issues made %d IDs", len(seen)) |
| 140 | } |
| 141 | if info, err := os.Stat(links); err != nil || info.Mode().Perm() != 0o640 { |
| 142 | t.Errorf("the credential file's mode is %v, %v", info.Mode(), err) |
| 143 | } |
| 144 | |
| 145 | v.declare("app", policy("app", "anyone")) |
| 146 | v.declare("site", policy("site", "anyone")) |
| 147 | if _, stderr, code := v.link(links, "issue", "--principal", "operator"); code != 1 || !strings.Contains(stderr, "operator may read no project") { |
| 148 | t.Errorf("issuing to operator, whom no policy names, exited %d: %s", code, stderr) |
| 149 | } |
| 150 | if f, _ := readLinks(links); len(f.Links) != 3 { |
| 151 | t.Errorf("a refused issue changed the file: %+v", f) |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | // Each pass carries the active links to the receiver, and a revoked link |
| 156 | // is absent from the next. A credential file that cannot be read fails |
| 157 | // the pass closed: the receiver stores an authorization with no binding, |
| 158 | // never one from an older file. |
| 159 | func TestBindingsFollowTheCredentialFile(t *testing.T) { |
| 160 | v := newValley(t) |
| 161 | rv := newReceiver(t, v) |
| 162 | links := filepath.Join(v.root, "links", "links") |
| 163 | ids := []string{v.issue(links, "operator"), v.issue(links, "operator")} |
| 164 | v.publish(append(rv.flags(), "--links", links, "--policy-only")...) |
| 165 | if first := rv.stored(); len(first.Bindings) != 2 { |
| 166 | t.Fatalf("the first authorization carries %d bindings, not 2", len(first.Bindings)) |
| 167 | } |
| 168 | if stdout, _, code := v.link(links, "revoke", ids[0]); code != 0 || !strings.Contains(stdout, "revoked "+ids[0]) { |
| 169 | t.Fatalf("revoke exited %d: %s", code, stdout) |
| 170 | } |
| 171 | if stdout, stderr, code := v.link(links, "list", "--check"); code != 1 || !strings.Contains(stderr, ids[0]+": revoked here; the edge may accept it") || |
| 172 | !regexp.MustCompile(ids[1]+` +operator +active +enforced`).MatchString(stdout) { |
| 173 | t.Errorf("list before delivery exited %d:\n%s%s", code, stdout, stderr) |
| 174 | } |
| 175 | v.publish(append(rv.flags(), "--links", links, "--policy-only")...) |
| 176 | second := rv.stored() |
| 177 | if len(second.Bindings) != 1 || second.Bindings[0].ID != ids[1] { |
| 178 | t.Errorf("after the revocation the authorization carries %+v", second.Bindings) |
| 179 | } |
| 180 | if stdout, stderr, code := v.link(links, "list", "--check", ids[0]); code != 0 || !regexp.MustCompile(ids[0]+` +operator +revoked +enforced`).MatchString(stdout) { |
| 181 | t.Errorf("list after delivery exited %d:\n%s%s", code, stdout, stderr) |
| 182 | } |
| 183 | |
| 184 | if err := os.WriteFile(links, []byte("{"), 0o600); err != nil { |
| 185 | t.Fatal(err) |
| 186 | } |
| 187 | if _, _, err := v.tryPublish(nil, append(rv.flags(), "--links", links)...); err == nil { |
| 188 | t.Error("a pass with a corrupt credential file succeeded") |
| 189 | } |
| 190 | if third := rv.stored(); third.Sequence <= second.Sequence || len(third.Bindings) != 0 { |
| 191 | t.Errorf("a corrupt credential file sent authorization %d with %+v", third.Sequence, third.Bindings) |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | // stored is the authorization the receiver stored. |
| 196 | func (rv *testReceiver) stored() *export.Authorization { |
| 197 | rv.t.Helper() |
| 198 | a, _, err := rv.store.Authorization() |
| 199 | if err != nil { |
| 200 | rv.t.Fatal(err) |
| 201 | } |
| 202 | return a |
| 203 | } |
| 204 | |
| 205 | // The revision and enforcement rules. A link is enforced only once the |
| 206 | // receiver acknowledged an authorization carrying the links of the |
| 207 | // revision that set its state: a revocation made after an acknowledgement |
| 208 | // was lost is pending, though the record shows no authorization carrying |
| 209 | // the link. A credential file restored from an older copy is signed as it |
| 210 | // is, the links it holds active again, and the next change to it writes |
| 211 | // past every revision a pass signed from. |
| 212 | func TestRevisionsOnlyMoveForward(t *testing.T) { |
| 213 | v := newValley(t) |
| 214 | rv := newReceiver(t, v) |
| 215 | links := filepath.Join(v.root, "links", "links") |
| 216 | pass := func() error { |
| 217 | t.Helper() |
| 218 | _, _, err := v.tryPublish(nil, append(rv.flags(), "--links", links, "--policy-only")...) |
| 219 | return err |
| 220 | } |
| 221 | if err := pass(); err != nil { |
| 222 | t.Fatal(err) |
| 223 | } |
| 224 | record := filepath.Join(v.state, linkDeliveryFile) |
| 225 | before, err := os.ReadFile(record) |
| 226 | if err != nil { |
| 227 | t.Fatal(err) |
| 228 | } |
| 229 | lost := v.issue(links, "operator") |
| 230 | if err := pass(); err != nil { |
| 231 | t.Fatal(err) |
| 232 | } |
| 233 | if len(rv.stored().Bindings) != 1 { |
| 234 | t.Fatalf("the receiver holds %d bindings, not 1", len(rv.stored().Bindings)) |
| 235 | } |
| 236 | // The receiver stored it, and the acknowledgement was lost. |
| 237 | if err := os.WriteFile(record, before, 0o600); err != nil { |
| 238 | t.Fatal(err) |
| 239 | } |
| 240 | v.link(links, "revoke", lost) |
| 241 | if stdout, _, code := v.link(links, "list", "--check", lost); code != 1 || !regexp.MustCompile(lost+` +operator +revoked +pending`).MatchString(stdout) { |
| 242 | t.Errorf("a revocation after a lost acknowledgement is not pending (exit %d):\n%s", code, stdout) |
| 243 | } |
| 244 | if err := pass(); err != nil { |
| 245 | t.Fatal(err) |
| 246 | } |
| 247 | if stdout, _, code := v.link(links, "list", "--check", lost); code != 0 || !regexp.MustCompile(lost+` +operator +revoked +enforced`).MatchString(stdout) { |
| 248 | t.Errorf("a delivered revocation is not enforced (exit %d):\n%s", code, stdout) |
| 249 | } |
| 250 | |
| 251 | restored := v.issue(links, "operator") |
| 252 | older, err := os.ReadFile(links) |
| 253 | if err != nil { |
| 254 | t.Fatal(err) |
| 255 | } |
| 256 | v.link(links, "revoke", restored) |
| 257 | if err := pass(); err != nil { |
| 258 | t.Fatal(err) |
| 259 | } |
| 260 | f, _ := readLinks(links) |
| 261 | published := f.Revision |
| 262 | if err := os.WriteFile(links, older, 0o640); err != nil { |
| 263 | t.Fatal(err) |
| 264 | } |
| 265 | if err := pass(); err != nil { |
| 266 | t.Fatalf("a pass from an older credential file failed: %v", err) |
| 267 | } |
| 268 | if b := rv.stored().Bindings; len(b) != 1 || b[0].ID != restored { |
| 269 | t.Errorf("an older credential file sent %+v, not the one link it holds active", b) |
| 270 | } |
| 271 | if stdout, _, code := v.link(links, "list", "--check", restored); code != 0 || !regexp.MustCompile(restored+` +operator +active +enforced`).MatchString(stdout) { |
| 272 | t.Errorf("a link active in the restored file is not enforced (exit %d):\n%s", code, stdout) |
| 273 | } |
| 274 | if _, stderr, code := v.link(links, "revoke", "--all"); code != 0 { |
| 275 | t.Fatalf("revoke --all on an older credential file exited %d: %s", code, stderr) |
| 276 | } |
| 277 | if f, _ := readLinks(links); f.Revision != published+1 { |
| 278 | t.Errorf("revoke --all on an older credential file wrote revision %d, not %d", f.Revision, published+1) |
| 279 | } |
| 280 | if stdout, _, code := v.link(links, "list", "--check", restored); code != 1 || !regexp.MustCompile(restored+` +operator +revoked +pending`).MatchString(stdout) { |
| 281 | t.Errorf("a revocation past the restored file's revision is not pending (exit %d):\n%s", code, stdout) |
| 282 | } |
| 283 | if err := pass(); err != nil { |
| 284 | t.Fatalf("a pass after revoke --all failed: %v", err) |
| 285 | } |
| 286 | if n := len(rv.stored().Bindings); n != 0 { |
| 287 | t.Errorf("after revoke --all the authorization carries %d bindings", n) |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | // sizedLinks is a credential file at revision 1 that writes to exactly |
| 292 | // size bytes: active links, then revoked ones, their notes padded to fit. |
| 293 | func sizedLinks(t *testing.T, size, active int) linksFile { |
| 294 | t.Helper() |
| 295 | written := func(f linksFile) int { |
| 296 | data, err := json.MarshalIndent(f, "", " ") |
| 297 | if err != nil { |
| 298 | t.Fatal(err) |
| 299 | } |
| 300 | return len(data) + 1 |
| 301 | } |
| 302 | record := func(i int, revoked bool) linkRecord { |
| 303 | l := linkRecord{ID: fmt.Sprintf("lk-%016x", i), Principal: "operator", |
| 304 | Verifier: strings.Repeat("3a", 32), Issued: "2026-10-29T12:00:00Z", Changed: 1} |
| 305 | if revoked { |
| 306 | l.Revoked = "2026-10-29T13:00:00Z" |
| 307 | } |
| 308 | return l |
| 309 | } |
| 310 | f := linksFile{Revision: 1, Links: []linkRecord{}} |
| 311 | for i := range active { |
| 312 | f.Links = append(f.Links, record(i, false)) |
| 313 | } |
| 314 | f.Links = append(f.Links, record(active, true)) |
| 315 | one := written(f) |
| 316 | f.Links = append(f.Links, record(active+1, true)) |
| 317 | each := written(f) - one |
| 318 | for i := active + 2; i <= active+(size-one)/each; i++ { |
| 319 | f.Links = append(f.Links, record(i, true)) |
| 320 | } |
| 321 | for i := len(f.Links) - 1; written(f) < size && i >= 0; i-- { |
| 322 | f.Links[i].Note = strings.Repeat("x", min(maxNote, size-written(f))) |
| 323 | } |
| 324 | if got := written(f); got != size { |
| 325 | t.Fatalf("made a credential file of %d bytes, not %d", got, size) |
| 326 | } |
| 327 | return f |
| 328 | } |
| 329 | |
| 330 | // writeRaw writes f as writeLinks would, with no limit. |
| 331 | func writeRaw(t *testing.T, path string, f linksFile) { |
| 332 | t.Helper() |
| 333 | data, err := json.MarshalIndent(f, "", " ") |
| 334 | if err != nil { |
| 335 | t.Fatal(err) |
| 336 | } |
| 337 | if err := os.WriteFile(path, append(data, '\n'), 0o640); err != nil { |
| 338 | t.Fatal(err) |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | // Reads and writes hold the credential file to one limit, so a file the |
| 343 | // link command writes is one a pass can read. |
| 344 | func TestTheCredentialFileHasOneLimit(t *testing.T) { |
| 345 | path := filepath.Join(t.TempDir(), "links") |
| 346 | at, over := sizedLinks(t, maxLinksFile, 0), sizedLinks(t, maxLinksFile+1, 0) |
| 347 | writeRaw(t, path, at) |
| 348 | if _, err := readLinks(path); err != nil { |
| 349 | t.Errorf("a file of %d bytes did not read: %v", maxLinksFile, err) |
| 350 | } |
| 351 | if err := writeLinks(path, at); err != nil { |
| 352 | t.Errorf("a file of %d bytes was not written: %v", maxLinksFile, err) |
| 353 | } |
| 354 | writeRaw(t, path, over) |
| 355 | if _, err := readLinks(path); err == nil || !strings.Contains(err.Error(), "larger than") { |
| 356 | t.Errorf("a file of %d bytes read with %v", maxLinksFile+1, err) |
| 357 | } |
| 358 | if err := writeLinks(path, over); err == nil || !strings.Contains(err.Error(), "valley-web-link prune") { |
| 359 | t.Errorf("a file of %d bytes was written with %v", maxLinksFile+1, err) |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | // Issue keeps 64 KiB of the file's limit for revocations: it writes a |
| 364 | // file up to the headroom and refuses one byte past it, saying to prune. |
| 365 | // A revocation of every link is accepted at the headroom, with the most |
| 366 | // active links an authorization carries. |
| 367 | func TestIssueKeepsHeadroomForRevocations(t *testing.T) { |
| 368 | v := newValley(t) |
| 369 | links := filepath.Join(v.root, "links", "links") |
| 370 | if err := os.MkdirAll(filepath.Dir(links), 0o750); err != nil { |
| 371 | t.Fatal(err) |
| 372 | } |
| 373 | headroom := maxLinksFile - linksHeadroom |
| 374 | // What an issue adds to a file of revoked links at revision 1. |
| 375 | base := sizedLinks(t, 100_000, 0) |
| 376 | issued := base |
| 377 | issued.Revision = 2 |
| 378 | issued.Links = append(slices.Clone(base.Links), linkRecord{ID: "lk-ffffffffffffffff", Principal: "operator", |
| 379 | Verifier: strings.Repeat("3a", 32), Issued: "2026-10-29T12:00:00Z", Changed: 2}) |
| 380 | a, _ := json.MarshalIndent(base, "", " ") |
| 381 | b, _ := json.MarshalIndent(issued, "", " ") |
| 382 | adds := len(b) - len(a) |
| 383 | |
| 384 | writeRaw(t, links, sizedLinks(t, headroom-adds+1, 0)) |
| 385 | before, _ := os.ReadFile(links) |
| 386 | if _, stderr, code := v.link(links, "issue", "--principal", "operator"); code != 1 || !strings.Contains(stderr, "run valley-web-link prune") { |
| 387 | t.Errorf("an issue past the headroom exited %d: %s", code, stderr) |
| 388 | } |
| 389 | if after, _ := os.ReadFile(links); !bytes.Equal(after, before) { |
| 390 | t.Error("a refused issue changed the credential file") |
| 391 | } |
| 392 | writeRaw(t, links, sizedLinks(t, headroom-adds, 0)) |
| 393 | v.issue(links, "operator") |
| 394 | if info, err := os.Stat(links); err != nil || info.Size() != int64(headroom) { |
| 395 | t.Errorf("an issue to the headroom wrote %v bytes, not %d: %v", info.Size(), headroom, err) |
| 396 | } |
| 397 | |
| 398 | writeRaw(t, links, sizedLinks(t, headroom, export.MaxBindings)) |
| 399 | if stdout, stderr, code := v.link(links, "revoke", "--all"); code != 0 || strings.Count(stdout, "revoked lk-") != export.MaxBindings { |
| 400 | t.Fatalf("revoke --all at the headroom exited %d: %s", code, stderr) |
| 401 | } |
| 402 | f, err := readLinks(links) |
| 403 | if err != nil || len(f.active()) != 0 { |
| 404 | t.Errorf("after revoke --all at the headroom the file reads as %d active links, %v", len(f.active()), err) |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | // Prune removes the revocations a pass delivered and keeps those still |
| 409 | // pending. |
| 410 | func TestPruneRemovesOnlyEnforcedRevocations(t *testing.T) { |
| 411 | v := newValley(t) |
| 412 | rv := newReceiver(t, v) |
| 413 | links := filepath.Join(v.root, "links", "links") |
| 414 | pass := func() error { |
| 415 | t.Helper() |
| 416 | _, _, err := v.tryPublish(nil, append(rv.flags(), "--links", links, "--policy-only")...) |
| 417 | return err |
| 418 | } |
| 419 | ids := []string{v.issue(links, "operator"), v.issue(links, "operator"), v.issue(links, "operator")} |
| 420 | if err := pass(); err != nil { |
| 421 | t.Fatal(err) |
| 422 | } |
| 423 | v.link(links, "revoke", ids[0]) |
| 424 | if err := pass(); err != nil { |
| 425 | t.Fatal(err) |
| 426 | } |
| 427 | v.link(links, "revoke", ids[1]) |
| 428 | stdout, stderr, code := v.link(links, "prune") |
| 429 | if code != 0 || !strings.Contains(stdout, "pruned "+ids[0]) || strings.Contains(stdout, ids[1]) || !strings.Contains(stdout, "kept 1 revoked links") { |
| 430 | t.Fatalf("prune exited %d:\n%s%s", code, stdout, stderr) |
| 431 | } |
| 432 | f, err := readLinks(links) |
| 433 | if err != nil || len(f.Links) != 2 || f.Links[0].ID != ids[1] || f.Links[1].ID != ids[2] { |
| 434 | t.Fatalf("after prune the file holds %+v, %v", f.Links, err) |
| 435 | } |
| 436 | if stdout, _, code := v.link(links, "list", "--check"); code != 1 || !regexp.MustCompile(ids[1]+` +operator +revoked +pending`).MatchString(stdout) || |
| 437 | !regexp.MustCompile(ids[2]+` +operator +active +enforced`).MatchString(stdout) { |
| 438 | t.Errorf("list after prune exited %d:\n%s", code, stdout) |
| 439 | } |
| 440 | if err := pass(); err != nil { |
| 441 | t.Fatal(err) |
| 442 | } |
| 443 | if b := rv.stored().Bindings; len(b) != 1 || b[0].ID != ids[2] { |
| 444 | t.Errorf("after prune the receiver binds %+v", b) |
| 445 | } |
| 446 | if stdout, _, code := v.link(links, "prune"); code != 0 || !strings.Contains(stdout, "pruned "+ids[1]) { |
| 447 | t.Errorf("a second prune exited %d: %s", code, stdout) |
| 448 | } |
| 449 | if stdout, _, code := v.link(links, "prune"); code != 0 || !strings.Contains(stdout, "no enforced revocation to prune") { |
| 450 | t.Errorf("a prune with nothing to prune exited %d: %s", code, stdout) |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | // Every change to the credential file holds the links lock, and so does a |
| 455 | // pass from its read of the file until it has signed. A change takes no |
| 456 | // lock in the publisher's state: one goes through while a pass holds the |
| 457 | // authorization lock. A change that cannot take the links lock says it is |
| 458 | // waiting, and after linksWait fails having changed nothing. A pass that |
| 459 | // cannot take it says so too, then signs no binding and fails. Once the |
| 460 | // lock is free, a change goes through. |
| 461 | func TestTheLinksLockSerializesChangesAndPasses(t *testing.T) { |
| 462 | v := newValley(t) |
| 463 | rv := newReceiver(t, v) |
| 464 | links := filepath.Join(v.root, "links", "links") |
| 465 | id := v.issue(links, "operator") |
| 466 | v.publish(append(rv.flags(), "--links", links, "--policy-only")...) |
| 467 | |
| 468 | unlockAuthorization, err := lockFile(filepath.Join(v.state, authorizationLockFile)) |
| 469 | if err != nil { |
| 470 | t.Fatal(err) |
| 471 | } |
| 472 | if _, stderr, code := v.link(links, "issue", "--principal", "operator"); code != 0 || strings.Contains(stderr, "waiting") { |
| 473 | t.Errorf("issue while a pass holds the authorization lock exited %d: %s", code, stderr) |
| 474 | } |
| 475 | unlockAuthorization() |
| 476 | |
| 477 | before, err := os.ReadFile(links) |
| 478 | if err != nil { |
| 479 | t.Fatal(err) |
| 480 | } |
| 481 | was := linksWait |
| 482 | linksWait = 300 * time.Millisecond |
| 483 | t.Cleanup(func() { linksWait = was }) |
| 484 | unlock, err := lockLinks(links, func(string) { t.Error("the test waited for the links lock") }) |
| 485 | if err != nil { |
| 486 | t.Fatal(err) |
| 487 | } |
| 488 | for _, args := range [][]string{{"issue", "--principal", "operator"}, {"revoke", id}, {"revoke", "--all"}, {"prune"}} { |
| 489 | stdout, stderr, code := v.link(links, args...) |
| 490 | if code != 1 || stdout != "" || !strings.Contains(stderr, "waiting up to 300ms for the policy pass or the change that holds the links lock") || |
| 491 | !strings.Contains(stderr, "the credential file is unchanged") { |
| 492 | t.Errorf("%s with the links lock held exited %d:\n%s%s", args[0], code, stdout, stderr) |
| 493 | } |
| 494 | } |
| 495 | if after, err := os.ReadFile(links); err != nil || !bytes.Equal(after, before) { |
| 496 | t.Errorf("a change that could not take the links lock wrote the credential file: %v", err) |
| 497 | } |
| 498 | _, stderr, err := v.tryPublish(nil, append(rv.flags(), "--links", links, "--policy-only")...) |
| 499 | if err == nil || !strings.Contains(stderr, "waiting up to 300ms for the change to the credential file") || |
| 500 | !strings.Contains(stderr, "was held for longer than 300ms; the authorization carries no read links") { |
| 501 | t.Errorf("a pass with the links lock held ended with %v:\n%s", err, stderr) |
| 502 | } |
| 503 | if b := rv.stored().Bindings; len(b) != 0 { |
| 504 | t.Errorf("a pass that could not take the links lock sent %+v", b) |
| 505 | } |
| 506 | unlock() |
| 507 | if stdout, stderr, code := v.link(links, "revoke", id); code != 0 || !strings.Contains(stdout, "revoked "+id) || strings.Contains(stderr, "waiting") { |
| 508 | t.Errorf("revoke with the links lock free exited %d:\n%s%s", code, stdout, stderr) |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | // The links lock is opened without following a symbolic link or waiting |
| 513 | // on a FIFO. A lock replaced by either is refused at once: by a change, |
| 514 | // which writes nothing and makes nothing where the link points, and by a |
| 515 | // pass, which signs no binding and fails. The delivery record, in the |
| 516 | // publisher's own state, which a change reads as root, is refused the same |
| 517 | // way. |
| 518 | func TestAHostileLinksLockIsRefused(t *testing.T) { |
| 519 | v := newValley(t) |
| 520 | rv := newReceiver(t, v) |
| 521 | dir := filepath.Join(v.root, "links") |
| 522 | links := filepath.Join(dir, "links") |
| 523 | id := v.issue(links, "operator") |
| 524 | v.publish(append(rv.flags(), "--links", links, "--policy-only")...) |
| 525 | before, err := os.ReadFile(links) |
| 526 | if err != nil { |
| 527 | t.Fatal(err) |
| 528 | } |
| 529 | unchanged := func(what string) { |
| 530 | t.Helper() |
| 531 | if after, err := os.ReadFile(links); err != nil || !bytes.Equal(after, before) { |
| 532 | t.Errorf("%s: the credential file changed: %v", what, err) |
| 533 | } |
| 534 | } |
| 535 | target := filepath.Join(v.root, "elsewhere") |
| 536 | hostile := []struct { |
| 537 | name, refused string |
| 538 | make func(path string) error |
| 539 | }{ |
| 540 | {"a symbolic link", "is a symbolic link", func(path string) error { return os.Symlink(target, path) }}, |
| 541 | {"a FIFO", "is a FIFO, not", func(path string) error { return syscall.Mkfifo(path, 0o640) }}, |
| 542 | } |
| 543 | lock := filepath.Join(dir, linksLockFile) |
| 544 | for _, h := range hostile { |
| 545 | if err := os.Remove(lock); err != nil { |
| 546 | t.Fatal(err) |
| 547 | } |
| 548 | if err := h.make(lock); err != nil { |
| 549 | t.Fatal(err) |
| 550 | } |
| 551 | var stdout, stderr string |
| 552 | var code int |
| 553 | promptly(t, "a revoke with a lock that is "+h.name, func() { stdout, stderr, code = v.link(links, "revoke", id) }) |
| 554 | if code != 1 || stdout != "" || !strings.Contains(stderr, "the links lock "+lock+" "+h.refused) { |
| 555 | t.Errorf("a revoke with a lock that is %s exited %d:\n%s%s", h.name, code, stdout, stderr) |
| 556 | } |
| 557 | unchanged("a revoke with a lock that is " + h.name) |
| 558 | var err error |
| 559 | promptly(t, "a pass with a lock that is "+h.name, func() { |
| 560 | _, stderr, err = v.tryPublish(nil, append(rv.flags(), "--links", links, "--policy-only")...) |
| 561 | }) |
| 562 | if err == nil || !strings.Contains(stderr, "the links lock "+lock+" "+h.refused) { |
| 563 | t.Errorf("a pass with a lock that is %s ended with %v:\n%s", h.name, err, stderr) |
| 564 | } |
| 565 | if b := rv.stored().Bindings; len(b) != 0 { |
| 566 | t.Errorf("a pass with a lock that is %s sent %+v", h.name, b) |
| 567 | } |
| 568 | if _, err := os.Lstat(target); err == nil { |
| 569 | t.Errorf("a lock that is %s made %s", h.name, target) |
| 570 | } |
| 571 | } |
| 572 | if err := os.Remove(lock); err != nil { |
| 573 | t.Fatal(err) |
| 574 | } |
| 575 | |
| 576 | delivery := filepath.Join(v.state, linkDeliveryFile) |
| 577 | for _, h := range hostile { |
| 578 | if err := os.Remove(delivery); err != nil { |
| 579 | t.Fatal(err) |
| 580 | } |
| 581 | if err := h.make(delivery); err != nil { |
| 582 | t.Fatal(err) |
| 583 | } |
| 584 | var stdout, stderr string |
| 585 | var code int |
| 586 | promptly(t, "a revoke with a delivery record that is "+h.name, func() { stdout, stderr, code = v.link(links, "revoke", id) }) |
| 587 | if code != 1 || stdout != "" || !strings.Contains(stderr, delivery+" "+h.refused) { |
| 588 | t.Errorf("a revoke with a delivery record that is %s exited %d:\n%s%s", h.name, code, stdout, stderr) |
| 589 | } |
| 590 | unchanged("a revoke with a delivery record that is " + h.name) |
| 591 | } |
| 592 | } |
| 593 | |
| 594 | // A change on a fresh host, before the publisher has a state directory, |
| 595 | // takes the links lock all the same, so it serializes with a pass that |
| 596 | // starts beside it. Here a revoke pauses holding the lock, as it reads a |
| 597 | // credential file that is a FIFO. A pass started meanwhile makes the state |
| 598 | // directory, checks the policy, and waits for the lock. Once the revoke |
| 599 | // has written the file, the pass signs it: the revoked link has no |
| 600 | // binding. |
| 601 | func TestAChangeOnAFreshHostSerializesWithAPass(t *testing.T) { |
| 602 | v := newValley(t) |
| 603 | rv := newReceiver(t, v) |
| 604 | dir := filepath.Join(v.root, "links") |
| 605 | links := filepath.Join(dir, "links") |
| 606 | revoked, kept := v.issue(links, "operator"), v.issue(links, "operator") |
| 607 | if _, err := os.Stat(v.state); !errors.Is(err, os.ErrNotExist) { |
| 608 | t.Fatalf("the state directory exists before the first pass: %v", err) |
| 609 | } |
| 610 | data, err := os.ReadFile(links) |
| 611 | if err != nil { |
| 612 | t.Fatal(err) |
| 613 | } |
| 614 | // The credential file becomes a FIFO, whose reader waits for a writer. |
| 615 | fifo := filepath.Join(dir, "fifo") |
| 616 | if err := syscall.Mkfifo(fifo, 0o640); err != nil { |
| 617 | t.Fatal(err) |
| 618 | } |
| 619 | if err := os.Remove(links); err != nil { |
| 620 | t.Fatal(err) |
| 621 | } |
| 622 | if err := os.Link(fifo, links); err != nil { |
| 623 | t.Fatal(err) |
| 624 | } |
| 625 | type result struct { |
| 626 | stdout, stderr string |
| 627 | code int |
| 628 | } |
| 629 | revoking := make(chan result, 1) |
| 630 | go func() { |
| 631 | stdout, stderr, code := v.link(links, "revoke", revoked) |
| 632 | revoking <- result{stdout, stderr, code} |
| 633 | }() |
| 634 | eventually(t, "the revoke taking the links lock", func() bool { return linksLocked(t, dir) }) |
| 635 | |
| 636 | var passed lockedBuffer |
| 637 | passing := make(chan error, 1) |
| 638 | go func() { |
| 639 | _, _, err := v.tryPublish(func(p *publisher) { p.stderr = &passed }, append(rv.flags(), "--links", links, "--policy-only")...) |
| 640 | passing <- err |
| 641 | }() |
| 642 | eventually(t, "the pass waiting for the links lock", func() bool { |
| 643 | return strings.Contains(passed.String(), "waiting up to 1m0s for the change to the credential file") |
| 644 | }) |
| 645 | if _, err := os.Stat(v.state); err != nil { |
| 646 | t.Errorf("the waiting pass has no state directory: %v", err) |
| 647 | } |
| 648 | |
| 649 | // Once the revoke has opened the FIFO, a regular file takes its place |
| 650 | // for the revoke's write, and the revoke reads the file through the |
| 651 | // FIFO. |
| 652 | w, err := os.OpenFile(fifo, os.O_WRONLY, 0) |
| 653 | if err != nil { |
| 654 | t.Fatal(err) |
| 655 | } |
| 656 | if err := os.WriteFile(filepath.Join(dir, "regular"), data, 0o640); err != nil { |
| 657 | t.Fatal(err) |
| 658 | } |
| 659 | if err := os.Rename(filepath.Join(dir, "regular"), links); err != nil { |
| 660 | t.Fatal(err) |
| 661 | } |
| 662 | if _, err := w.Write(data); err != nil { |
| 663 | t.Fatal(err) |
| 664 | } |
| 665 | w.Close() |
| 666 | if r := <-revoking; r.code != 0 || !strings.Contains(r.stdout, "revoked "+revoked) { |
| 667 | t.Fatalf("the revoke exited %d:\n%s%s", r.code, r.stdout, r.stderr) |
| 668 | } |
| 669 | if err := <-passing; err != nil { |
| 670 | t.Fatalf("the pass failed: %v\n%s", err, passed.String()) |
| 671 | } |
| 672 | if b := rv.stored().Bindings; len(b) != 1 || b[0].ID != kept { |
| 673 | t.Errorf("the pass that waited for the revoke sent %+v, not %s alone", b, kept) |
| 674 | } |
| 675 | if stdout, stderr, code := v.link(links, "list", "--check"); code != 0 { |
| 676 | t.Errorf("list after the pass exited %d:\n%s%s", code, stdout, stderr) |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | // promptly runs f, and fails the test unless f returns within thirty |
| 681 | // seconds. |
| 682 | func promptly(t *testing.T, what string, f func()) { |
| 683 | t.Helper() |
| 684 | done := make(chan struct{}) |
| 685 | go func() { |
| 686 | defer close(done) |
| 687 | f() |
| 688 | }() |
| 689 | select { |
| 690 | case <-done: |
| 691 | case <-time.After(30 * time.Second): |
| 692 | t.Fatalf("%s blocked", what) |
| 693 | } |
| 694 | } |
| 695 | |
| 696 | // eventually waits up to a minute for cond, and fails the test if it |
| 697 | // never holds. |
| 698 | func eventually(t *testing.T, what string, cond func() bool) { |
| 699 | t.Helper() |
| 700 | for deadline := time.Now().Add(time.Minute); !cond(); time.Sleep(20 * time.Millisecond) { |
| 701 | if time.Now().After(deadline) { |
| 702 | t.Fatalf("%s did not happen within a minute", what) |
| 703 | } |
| 704 | } |
| 705 | } |
| 706 | |
| 707 | // linksLocked is whether something holds the links lock in dir. |
| 708 | func linksLocked(t *testing.T, dir string) bool { |
| 709 | t.Helper() |
| 710 | f, err := os.Open(filepath.Join(dir, linksLockFile)) |
| 711 | if errors.Is(err, os.ErrNotExist) { |
| 712 | return false |
| 713 | } |
| 714 | if err != nil { |
| 715 | t.Fatal(err) |
| 716 | } |
| 717 | defer f.Close() |
| 718 | err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) |
| 719 | if err != nil && !errors.Is(err, syscall.EWOULDBLOCK) { |
| 720 | t.Fatal(err) |
| 721 | } |
| 722 | return err != nil |
| 723 | } |
| 724 | |
| 725 | // lockedBuffer is a buffer that a pass running beside the test writes. |
| 726 | type lockedBuffer struct { |
| 727 | mu sync.Mutex |
| 728 | b bytes.Buffer |
| 729 | } |
| 730 | |
| 731 | func (l *lockedBuffer) Write(p []byte) (int, error) { |
| 732 | l.mu.Lock() |
| 733 | defer l.mu.Unlock() |
| 734 | return l.b.Write(p) |
| 735 | } |
| 736 | |
| 737 | func (l *lockedBuffer) String() string { |
| 738 | l.mu.Lock() |
| 739 | defer l.mu.Unlock() |
| 740 | return l.b.String() |
| 741 | } |