gunk-dev/the-valley

crash_test.go

source86596a33fae0main's published tip history
19.6 KiB
1package main
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "crypto/sha256"
8 "encoding/base64"
9 "encoding/hex"
10 "errors"
11 "fmt"
12 "io"
13 "net/http"
14 "os"
15 "os/exec"
16 "path/filepath"
17 "regexp"
18 "strings"
19 "sync"
20 "syscall"
21 "testing"
22 "time"
23
24 "the-valley/web/export"
25 "the-valley/web/export/exporttest"
26 "the-valley/web/readerstate"
27)
28
29// These tests are the web-reader-state-crash check: valley-web run as a
30// process of its own, killed or failed at each step of a browser-state
31// transaction, and run again over what it left. web-server-unit skips
32// them.
33
34// faultOf is the fault hook for VALLEY_WEB_TEST_FAULT, "<op>:<step>:<how>":
35// at that step of every transaction of that kind, the process kills
36// itself with SIGKILL when how is kill, and the step fails when it is
37// fail. "" is no hook.
38func faultOf(spec string) func(readerstate.Op, readerstate.Step) error {
39 if spec == "" {
40 return nil
41 }
42 parts := strings.Split(spec, ":")
43 return func(op readerstate.Op, step readerstate.Step) error {
44 if op.String() != parts[0] || step.String() != parts[1] {
45 return nil
46 }
47 if parts[2] == "kill" {
48 syscall.Kill(os.Getpid(), syscall.SIGKILL)
49 select {}
50 }
51 return errors.New("a fault the test injected")
52 }
53}
54
55const testOrigin = "https://example.org"
56
57// readerEdge is a store the fixture's export was uploaded to, with an
58// empty browser-state directory beside its descriptor, and the links its
59// authorization may bind.
60type readerEdge struct {
61 t *testing.T
62 state string
63 store *export.Store
64 links []testLink
65}
66
67type testLink struct {
68 credential string
69 binding export.Binding
70}
71
72func newReaderEdge(t *testing.T) *readerEdge {
73 t.Helper()
74 _, state := uploaded(t)
75 if err := os.Mkdir(filepath.Join(filepath.Dir(state), "browser"), 0o700); err != nil {
76 t.Fatal(err)
77 }
78 store, err := export.OpenStore(state, nil)
79 if err != nil {
80 t.Fatal(err)
81 }
82 e := &readerEdge{t: t, state: state, store: store}
83 for n := 1; n <= 3; n++ {
84 secret := bytes.Repeat([]byte{byte(n), 0x5a}, 16)
85 sum := sha256.Sum256(secret)
86 id := fmt.Sprintf("lk-%016x", n)
87 e.links = append(e.links, testLink{id + "." + base64.RawURLEncoding.EncodeToString(secret),
88 export.Binding{ID: id, Principal: "alice", Verifier: hex.EncodeToString(sum[:])}})
89 }
90 return e
91}
92
93// bind stores, as the receiver does, an authorization one past the
94// stored one that binds the edge's links when bound is set, and none when
95// it is not.
96func (e *readerEdge) bind(bound bool) {
97 e.t.Helper()
98 a, _, err := e.store.Authorization()
99 if err != nil {
100 e.t.Fatal(err)
101 }
102 next := *a
103 next.Sequence, next.Bindings = a.Sequence+1, nil
104 if bound {
105 for _, l := range e.links {
106 next.Bindings = append(next.Bindings, l.binding)
107 }
108 }
109 if err := e.store.Authorize(context.Background(), &next, exporttest.SignAuthorization(e.t, &next)); err != nil {
110 e.t.Fatal(err)
111 }
112}
113
114func (e *readerEdge) browser(name string) string {
115 return filepath.Join(filepath.Dir(e.state), "browser", name)
116}
117
118// served is one valley-web process, with what it logged.
119type served struct {
120 cmd *exec.Cmd
121 addr string
122 mu sync.Mutex
123 log bytes.Buffer
124 done chan struct{}
125}
126
127func (s *served) logged() string {
128 s.mu.Lock()
129 defer s.mu.Unlock()
130 return s.log.String()
131}
132
133// serve starts valley-web over the edge with --origin, meeting fault, and
134// waits for it to listen.
135func (e *readerEdge) serve(fault string) *served {
136 e.t.Helper()
137 cmd := valleyWeb("--state", e.state, "--listen", "127.0.0.1:0", "--origin", testOrigin)
138 cmd.Env = append(cmd.Env, "VALLEY_WEB_TEST_FAULT="+fault)
139 return e.start(cmd)
140}
141
142// start starts cmd, a valley-web over the edge, keeps what it logs, and
143// waits for it to listen.
144func (e *readerEdge) start(cmd *exec.Cmd) *served {
145 e.t.Helper()
146 stderr, err := cmd.StderrPipe()
147 if err != nil {
148 e.t.Fatal(err)
149 }
150 if _, err := exporttest.Start(e.t, cmd); err != nil {
151 e.t.Fatal(err)
152 }
153 s := &served{cmd: cmd, done: make(chan struct{})}
154 lines := make(chan string, 1)
155 go func() {
156 r := bufio.NewReader(stderr)
157 for {
158 line, err := r.ReadString('\n')
159 s.mu.Lock()
160 s.log.WriteString(line)
161 s.mu.Unlock()
162 if addr, ok := strings.CutPrefix(strings.TrimSpace(line), "valley-web: listening on "); ok {
163 lines <- addr
164 }
165 if err != nil {
166 close(lines)
167 break
168 }
169 }
170 cmd.Wait()
171 close(s.done)
172 }()
173 e.t.Cleanup(func() { s.kill() })
174 select {
175 case addr, ok := <-lines:
176 if !ok {
177 e.t.Fatalf("valley-web exited before it listened:\n%s", redacted(s.logged()))
178 }
179 s.addr = addr
180 case <-time.After(30 * time.Second):
181 e.t.Fatal("valley-web did not say where it listens")
182 }
183 return s
184}
185
186// secretPart is a link's credential or a session token: a credential ID,
187// then 32 bytes of unpadded base64url, the secret or the token's random
188// part.
189var secretPart = regexp.MustCompile(`\b(lk-[0-9a-f]{16})\.[A-Za-z0-9_-]{43}`)
190
191// redacted is s, for a failure's message, with each credential and
192// session token in it cut to its credential ID.
193func redacted(s string) string { return secretPart.ReplaceAllString(s, "$1.<redacted>") }
194
195func (s *served) kill() {
196 s.cmd.Process.Kill()
197 <-s.done
198}
199
200// exited waits for the process to end, as a fault that kills it ends it.
201func (s *served) exited(t *testing.T) {
202 t.Helper()
203 select {
204 case <-s.done:
205 case <-time.After(30 * time.Second):
206 t.Fatal("valley-web did not exit")
207 }
208}
209
210var client = &http.Client{Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
211
212// redeem posts a redemption of credential as a reader page's script does,
213// and returns its status and the token it sets. A request the process
214// never answered is status 0.
215func (s *served) redeem(t *testing.T, credential string) (int, string) {
216 t.Helper()
217 return s.post(t, "/-/redeem", `{"credential":"`+credential+`"}`, "")
218}
219
220// logout posts a logout as a reader page's script does, carrying token's
221// session cookie, and returns its status, 0 when the process never
222// answered.
223func (s *served) logout(t *testing.T, token string) int {
224 t.Helper()
225 status, _ := s.post(t, "/-/logout", `{}`, token)
226 return status
227}
228
229// post posts body to a reader page with the headers its script sends,
230// and token's session cookie when token is not "". It returns the status,
231// 0 when the process never answered, and the session token the response
232// sets.
233func (s *served) post(t *testing.T, path, body, token string) (int, string) {
234 t.Helper()
235 r, _ := http.NewRequest("POST", "http://"+s.addr+path, strings.NewReader(body))
236 r.Header.Set("Origin", testOrigin)
237 r.Header.Set("Content-Type", "application/json")
238 r.Header.Set("X-Valley-Reader", "1")
239 if token != "" {
240 r.Header.Set("Cookie", "__Host-valley-reader="+token)
241 }
242 res, err := client.Do(r)
243 if err != nil {
244 return 0, ""
245 }
246 io.Copy(io.Discard, res.Body)
247 res.Body.Close()
248 set := ""
249 for _, c := range res.Cookies() {
250 if c.Name == "__Host-valley-reader" {
251 set = c.Value
252 }
253 }
254 return res.StatusCode, set
255}
256
257// get is the status of a GET of target carrying token's session cookie,
258// when token is not "", and whether the response renewed it.
259func (s *served) get(t *testing.T, target, token string) (int, bool) {
260 t.Helper()
261 r, _ := http.NewRequest("GET", "http://"+s.addr+target, nil)
262 if token != "" {
263 r.Header.Set("Cookie", "__Host-valley-reader="+token)
264 }
265 res, err := client.Do(r)
266 if err != nil {
267 t.Fatal(err)
268 }
269 io.Copy(io.Discard, res.Body)
270 res.Body.Close()
271 renewed := token != "" && strings.HasPrefix(res.Header.Get("Set-Cookie"), "__Host-valley-reader="+token+";")
272 return res.StatusCode, renewed
273}
274
275// created waits for the edge's browser state to be made.
276func (e *readerEdge) created() {
277 e.t.Helper()
278 for range 300 {
279 if data, err := os.ReadFile(e.browser("state")); err == nil && string(data) == readerstate.Type+"\n" {
280 return
281 }
282 time.Sleep(10 * time.Millisecond)
283 }
284 e.t.Fatal("valley-web did not make the browser state")
285}
286
287// A redemption killed at each step of its transaction is retried once the
288// process restarts: before the rename the link redeems once, and from the
289// rename on it is consumed. A redemption failed at each step leaves the
290// state unavailable until the restart, with anyone served meanwhile. In
291// no case does a link redeem twice.
292func TestCrashARedemption(t *testing.T) {
293 for _, how := range []string{"kill", "fail"} {
294 for _, step := range readerstate.Steps {
295 t.Run(how+"-"+step.String(), func(t *testing.T) {
296 e := newReaderEdge(t)
297 first := e.serve("")
298 e.created()
299 first.kill()
300 e.bind(true)
301 s := e.serve("redeem:" + step.String() + ":" + how)
302 status, _ := s.redeem(t, e.links[0].credential)
303 switch how {
304 case "kill":
305 if status != 0 {
306 t.Fatalf("a redemption killed at %s answered %d", step, status)
307 }
308 s.exited(t)
309 case "fail":
310 if status != http.StatusServiceUnavailable {
311 t.Fatalf("a redemption failed at %s answered %d", step, status)
312 }
313 if status, _ := s.redeem(t, e.links[1].credential); status != http.StatusServiceUnavailable {
314 t.Errorf("another redemption after the failure answered %d", status)
315 }
316 if status, _ := s.get(t, "/-/knots", e.links[1].credential); status != http.StatusServiceUnavailable {
317 t.Errorf("a request with a cookie after the failure answered %d", status)
318 }
319 if status, _ := s.get(t, "/-/knots", ""); status != http.StatusOK {
320 t.Errorf("a request with no cookie after the failure answered %d", status)
321 }
322 s.kill()
323 }
324 if _, err := os.Lstat(e.browser("state.new")); step < readerstate.Renamed && how == "fail" && err == nil {
325 t.Error("a failed redemption left state.new")
326 }
327 again := e.serve("")
328 status, token := again.redeem(t, e.links[0].credential)
329 want := http.StatusNoContent
330 if step >= readerstate.Renamed {
331 want = http.StatusForbidden
332 }
333 if status != want {
334 t.Errorf("after a restart, the link answered %d, want %d", status, want)
335 }
336 if status, _ := again.redeem(t, e.links[0].credential); status != http.StatusForbidden {
337 t.Errorf("the link redeemed twice: %d", status)
338 }
339 if token != "" {
340 if _, renewed := again.get(t, "/-/knots", token); !renewed {
341 t.Error("the retried redemption's session is not valid")
342 }
343 }
344 if status, _ := again.redeem(t, e.links[1].credential); status != http.StatusNoContent {
345 t.Errorf("another link after the restart answered %d", status)
346 }
347 })
348 }
349 }
350}
351
352// A redemption whose answer reached the reader survives a crash right
353// after it, and its session with it. Neither the link nor the token is
354// ever logged.
355func TestCrashAfterAnAcknowledgedRedemption(t *testing.T) {
356 e := newReaderEdge(t)
357 first := e.serve("")
358 e.created()
359 first.kill()
360 e.bind(true)
361 s := e.serve("")
362 status, token := s.redeem(t, e.links[0].credential)
363 if status != http.StatusNoContent || token == "" {
364 t.Fatalf("the redemption answered %d", status)
365 }
366 s.cmd.Process.Signal(syscall.SIGKILL)
367 s.exited(t)
368 again := e.serve("")
369 if status, renewed := again.get(t, "/-/knots", token); status != http.StatusOK || !renewed {
370 t.Errorf("after the crash the session answered %d, renewed %v", status, renewed)
371 }
372 if status, _ := again.redeem(t, e.links[0].credential); status != http.StatusForbidden {
373 t.Errorf("after the crash the link answered %d", status)
374 }
375 secret := strings.SplitN(e.links[0].credential, ".", 2)[1]
376 random := strings.SplitN(token, ".", 2)[1]
377 for _, p := range []*served{first, s, again} {
378 if log := p.logged(); strings.Contains(log, secret) || strings.Contains(log, random) {
379 t.Errorf("valley-web logged a secret or a token:\n%s", strings.NewReplacer(secret, "<secret>", random, "<token>").Replace(log))
380 }
381 }
382 data, _ := os.ReadFile(e.browser("state"))
383 if bytes.Contains(data, []byte(secret)) || bytes.Contains(data, []byte(random)) {
384 t.Error("the browser state holds the link's secret or the session's token")
385 }
386}
387
388// A logout killed or failed at each step of its transaction is never
389// acknowledged. Before the rename, the session holds after the restart,
390// and the reader, told nothing, signs out again; from the rename on, the
391// token works no more. A failed logout leaves the state unavailable until
392// the restart, with anyone served meanwhile.
393func TestCrashALogout(t *testing.T) {
394 for _, how := range []string{"kill", "fail"} {
395 for _, step := range readerstate.Steps {
396 t.Run(how+"-"+step.String(), func(t *testing.T) {
397 e := newReaderEdge(t)
398 first := e.serve("")
399 e.created()
400 first.kill()
401 e.bind(true)
402 s := e.serve("logout:" + step.String() + ":" + how)
403 status, token := s.redeem(t, e.links[0].credential)
404 if status != http.StatusNoContent {
405 t.Fatalf("the redemption answered %d", status)
406 }
407 status = s.logout(t, token)
408 switch how {
409 case "kill":
410 if status != 0 {
411 t.Fatalf("a logout killed at %s answered %d", step, status)
412 }
413 s.exited(t)
414 case "fail":
415 if status != http.StatusServiceUnavailable {
416 t.Fatalf("a logout failed at %s answered %d", step, status)
417 }
418 if status, renewed := s.get(t, "/-/knots", token); status != http.StatusServiceUnavailable || renewed {
419 t.Errorf("the session after the failure answered %d, renewed %v", status, renewed)
420 }
421 if status, _ := s.get(t, "/-/knots", ""); status != http.StatusOK {
422 t.Errorf("a request with no cookie after the failure answered %d", status)
423 }
424 s.kill()
425 }
426 again := e.serve("")
427 if step < readerstate.Renamed {
428 if status, renewed := again.get(t, "/-/knots", token); status != http.StatusOK || !renewed {
429 t.Errorf("after a restart, the session the logout did not end answered %d, renewed %v", status, renewed)
430 }
431 if status := again.logout(t, token); status != http.StatusNoContent {
432 t.Errorf("signing out again answered %d", status)
433 }
434 }
435 if status, renewed := again.get(t, "/-/knots", token); status != http.StatusOK || renewed {
436 t.Errorf("after the logout, the token answered %d, renewed %v", status, renewed)
437 }
438 if status, _ := again.redeem(t, e.links[0].credential); status != http.StatusForbidden {
439 t.Errorf("the signed-out link redeemed again: %d", status)
440 }
441 })
442 }
443 }
444}
445
446// A logout whose 204 reached the reader holds through a crash right after
447// it: a copy of the token it ended never works again.
448func TestCrashAfterAnAcknowledgedLogout(t *testing.T) {
449 e := newReaderEdge(t)
450 first := e.serve("")
451 e.created()
452 first.kill()
453 e.bind(true)
454 s := e.serve("")
455 status, token := s.redeem(t, e.links[0].credential)
456 if status != http.StatusNoContent {
457 t.Fatalf("the redemption answered %d", status)
458 }
459 if status := s.logout(t, token); status != http.StatusNoContent {
460 t.Fatalf("the logout answered %d", status)
461 }
462 s.cmd.Process.Signal(syscall.SIGKILL)
463 s.exited(t)
464 again := e.serve("")
465 if status, renewed := again.get(t, "/-/knots", token); status != http.StatusOK || renewed {
466 t.Errorf("after the crash, the signed-out token answered %d, renewed %v", status, renewed)
467 }
468}
469
470// crashMaking makes valley-web make the edge's state, killed or failed at
471// step, and leaves no valley-web running. A failed one answers a cookie
472// 503 before it stops.
473func (e *readerEdge) crashMaking(step readerstate.Step, how string) {
474 t := e.t
475 t.Helper()
476 fault := "initialize:" + step.String() + ":" + how
477 if how == "kill" {
478 cmd := valleyWeb("--state", e.state, "--listen", "127.0.0.1:0", "--origin", testOrigin)
479 cmd.Env = append(cmd.Env, "VALLEY_WEB_TEST_FAULT="+fault)
480 if _, err := output(t, cmd); err == nil {
481 t.Fatal("valley-web killed while it made the state exited 0")
482 }
483 return
484 }
485 s := e.serve(fault)
486 if status, _ := s.get(t, "/-/knots", e.links[0].credential); status != http.StatusServiceUnavailable {
487 t.Errorf("a request with a cookie after the failure answered %d", status)
488 }
489 s.kill()
490}
491
492// Making the state, killed or failed at each step, leaves no state or an
493// empty one, and the next process makes it or uses it, under the same
494// authorization with no binding.
495func TestCrashMakingTheState(t *testing.T) {
496 for _, how := range []string{"kill", "fail"} {
497 for _, step := range readerstate.Steps {
498 t.Run(how+"-"+step.String(), func(t *testing.T) {
499 e := newReaderEdge(t)
500 e.crashMaking(step, how)
501 data, err := os.ReadFile(e.browser("state"))
502 switch {
503 case step < readerstate.Renamed && err == nil:
504 t.Errorf("a state was left by a crash before its rename: %q", data)
505 case step >= readerstate.Renamed && string(data) != readerstate.Type+"\n":
506 t.Errorf("the state left after its rename holds %q, %v", data, err)
507 }
508 s := e.serve("")
509 e.created()
510 e.bind(true)
511 if status, _ := s.redeem(t, e.links[0].credential); status != http.StatusNoContent {
512 t.Errorf("a link after the restart answered %d", status)
513 }
514 })
515 }
516 }
517}
518
519// Making the state, killed or failed before its rename, leaves none. An
520// authorization that binds links, stored before the restart, keeps the
521// restart from making one: redemption stays closed, a cookie answers 503,
522// and anyone is served. From the rename on, the empty state was made
523// before the binding was stored, and the link redeems.
524func TestCrashMakingTheStateThenABinding(t *testing.T) {
525 for _, how := range []string{"kill", "fail"} {
526 for _, step := range readerstate.Steps {
527 t.Run(how+"-"+step.String(), func(t *testing.T) {
528 e := newReaderEdge(t)
529 e.crashMaking(step, how)
530 e.bind(true)
531 s := e.serve("")
532 status, _ := s.redeem(t, e.links[0].credential)
533 if step >= readerstate.Renamed {
534 if status != http.StatusNoContent {
535 t.Errorf("a link bound after the state was made answered %d", status)
536 }
537 return
538 }
539 if status != http.StatusServiceUnavailable {
540 t.Errorf("a link bound while no state was made answered %d", status)
541 }
542 if status, _ := s.get(t, "/-/knots", e.links[1].credential); status != http.StatusServiceUnavailable {
543 t.Errorf("a request with a cookie answered %d", status)
544 }
545 if status, _ := s.get(t, "/-/knots", ""); status != http.StatusOK {
546 t.Errorf("a request with no cookie answered %d", status)
547 }
548 if data, err := os.ReadFile(e.browser("state")); err == nil {
549 t.Errorf("the restart made a state under an authorization that binds links: %q", data)
550 }
551 })
552 }
553 }
554}
555
556// One process owns a browser state: a second valley-web over it refuses
557// to start, and so does one whose browser directory is missing or open to
558// other users, or whose origin is not an HTTPS origin.
559func TestCrashOneOwner(t *testing.T) {
560 e := newReaderEdge(t)
561 e.serve("")
562 out, err := output(t, valleyWeb("--state", e.state, "--listen", "127.0.0.1:0", "--origin", testOrigin))
563 if err == nil || !strings.Contains(string(out), "another process owns the browser state") {
564 t.Errorf("a second valley-web gave %v:\n%s", err, out)
565 }
566 _, other := uploaded(t)
567 out, err = output(t, valleyWeb("--state", other, "--listen", "127.0.0.1:0", "--origin", testOrigin))
568 if err == nil || !strings.Contains(string(out), "opening the browser state") {
569 t.Errorf("valley-web with no browser directory gave %v:\n%s", err, out)
570 }
571 os.Mkdir(filepath.Join(filepath.Dir(other), "browser"), 0o755)
572 os.Chmod(filepath.Join(filepath.Dir(other), "browser"), 0o755)
573 out, err = output(t, valleyWeb("--state", other, "--listen", "127.0.0.1:0", "--origin", testOrigin))
574 if err == nil || !strings.Contains(string(out), "mode 0755") {
575 t.Errorf("valley-web with an open browser directory gave %v:\n%s", err, out)
576 }
577 for _, o := range []string{"http://example.org", "https://example.org/", "https://Example.org", "https://example.org:443", "https://example.org?x", "https://u@example.org", "example.org"} {
578 out, err := output(t, valleyWeb("--state", e.state, "--listen", "127.0.0.1:0", "--origin", o))
579 if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 2 || !strings.Contains(string(out), "is not an HTTPS origin") {
580 t.Errorf("--origin %s gave %v:\n%s", o, err, out)
581 }
582 }
583}