| 1 | //go:build browser |
| 2 | |
| 3 | package equipo |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "encoding/json" |
| 8 | "fmt" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "net/url" |
| 12 | "strings" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/rastrillo/rastrillo/harness" |
| 17 | "github.com/chromedp/chromedp" |
| 18 | ) |
| 19 | |
| 20 | // Real POST, CSRF, one-use exchange, 303, browser cookie jar, wrapper CSP and |
| 21 | // child-frame request. No browser authentication bypass or injected grant. |
| 22 | func TestBrowserPreviewPassExchange(t *testing.T) { |
| 23 | rig := newPreviewPassRig(t) |
| 24 | childRequests := make(chan *http.Request, 10) |
| 25 | child := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 26 | select { |
| 27 | case childRequests <- r.Clone(context.Background()): |
| 28 | default: |
| 29 | } |
| 30 | if r.URL.Path == "/frames-result" { |
| 31 | w.WriteHeader(204) |
| 32 | return |
| 33 | } |
| 34 | w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 35 | fmt.Fprint(w, previewFramesFixture) |
| 36 | })) |
| 37 | defer child.Close() |
| 38 | // Cookies do not distinguish ports. Different hosts are essential here. |
| 39 | childURL := strings.Replace(child.URL, "127.0.0.1", "localhost", 1) |
| 40 | var stored map[string]any |
| 41 | var preview string |
| 42 | if err := rig.s.db.Reader().QueryRow("SELECT preview FROM chat_steps WHERE id = ?", "preview_step").Scan(&preview); err != nil { |
| 43 | t.Fatal(err) |
| 44 | } |
| 45 | if err := json.Unmarshal([]byte(preview), &stored); err != nil { |
| 46 | t.Fatal(err) |
| 47 | } |
| 48 | stored["url"] = childURL + "/" |
| 49 | data, _ := json.Marshal(stored) |
| 50 | if _, err := rig.s.db.Writer().Exec("UPDATE chat_steps SET preview = ? WHERE id = ?", string(data), "preview_step"); err != nil { |
| 51 | t.Fatal(err) |
| 52 | } |
| 53 | exchangeCodes := make(chan int, 8) |
| 54 | var handler http.Handler |
| 55 | parent := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 56 | if r.URL.Path == "/native/preview/exchange" { |
| 57 | recorder := httptest.NewRecorder() |
| 58 | handler.ServeHTTP(recorder, r) |
| 59 | for k, values := range recorder.Header() { |
| 60 | for _, v := range values { |
| 61 | w.Header().Add(k, v) |
| 62 | } |
| 63 | } |
| 64 | w.WriteHeader(recorder.Code) |
| 65 | _, _ = w.Write(recorder.Body.Bytes()) |
| 66 | exchangeCodes <- recorder.Code |
| 67 | } else { |
| 68 | handler.ServeHTTP(w, r) |
| 69 | } |
| 70 | })) |
| 71 | defer parent.Close() |
| 72 | parentURL := strings.Replace(parent.URL, "127.0.0.1", "equipo.example", 1) |
| 73 | rig.s.personOrigin = parentURL |
| 74 | handler = Mux(previewPassRouter(t, rig)) |
| 75 | pass := rig.mint(t) |
| 76 | form := url.Values{"pass": {pass.Pass}, "task": {"tk_preview"}, "candidate": {strings.Repeat("1", 40)}}.Encode() |
| 77 | opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.NoSandbox, chromedp.Flag("host-resolver-rules", "MAP equipo.example 127.0.0.1"), chromedp.Flag("no-proxy-server", true), chromedp.Flag("ignore-certificate-errors", true), chromedp.UserDataDir(t.TempDir())) |
| 78 | alloc, stop := chromedp.NewExecAllocator(context.Background(), opts...) |
| 79 | defer stop() |
| 80 | ctx, cancel := chromedp.NewContext(alloc) |
| 81 | defer cancel() |
| 82 | ctx, timeout := context.WithTimeout(ctx, 30*time.Second) |
| 83 | defer timeout() |
| 84 | // Load a same-origin public page, then submit a body-only form as WebKit does. |
| 85 | if _, err := chromedp.Run(ctx, chromedp.Navigate(parentURL+"/")); err != nil { |
| 86 | t.Fatal(err) |
| 87 | } |
| 88 | script := fmt.Sprintf(`(()=>{const f=document.createElement('form');f.method='POST';f.action='/native/preview/exchange';for(const [name,value] of new URLSearchParams(%q)){const i=document.createElement('input');i.name=name;i.value=value;f.append(i)}document.body.append(f);f.submit()})()`, form) |
| 89 | if _, err := chromedp.Run(ctx, chromedp.Evaluate[any](script)); err != nil { |
| 90 | t.Fatal(err) |
| 91 | } |
| 92 | select { |
| 93 | case r := <-childRequests: |
| 94 | if r.Header.Get("Cookie") != "" || r.Header.Get("Authorization") != "" || r.Header.Get("Referer") != "" { |
| 95 | t.Fatalf("preview received Equipo authority: %v", r.Header) |
| 96 | } |
| 97 | case <-ctx.Done(): |
| 98 | t.Fatal("wrapper iframe never loaded") |
| 99 | } |
| 100 | verified := false |
| 101 | for !verified { |
| 102 | select { |
| 103 | case request := <-childRequests: |
| 104 | if request.URL.Path == "/frames-result" { |
| 105 | if request.URL.Query().Get("ok") != "true" { |
| 106 | t.Fatal("srcdoc/blob fixture failed") |
| 107 | } |
| 108 | verified = true |
| 109 | } |
| 110 | case <-ctx.Done(): |
| 111 | t.Fatal("srcdoc/blob frame results missing") |
| 112 | } |
| 113 | } |
| 114 | location, err := chromedp.Run(ctx, chromedp.Evaluate[string](`location.href`)) |
| 115 | if err != nil || location != parentURL+"/tasks/tk_preview/preview" { |
| 116 | t.Fatalf("location=%q err=%v", location, err) |
| 117 | } |
| 118 | sandbox, err := chromedp.Run(ctx, chromedp.Evaluate[string](`document.querySelector('iframe').getAttribute('sandbox')`)) |
| 119 | if err != nil || sandbox != "allow-scripts allow-same-origin" { |
| 120 | t.Fatalf("sandbox=%q err=%v", sandbox, err) |
| 121 | } |
| 122 | if code := <-exchangeCodes; code != 303 { |
| 123 | t.Fatalf("exchange status %d", code) |
| 124 | } |
| 125 | // Reuse is refused by the actual browser route. Start from a public |
| 126 | // page, since the wrapper deliberately prohibits injected scripts. |
| 127 | if _, err = chromedp.Run(ctx, chromedp.Navigate(parentURL+"/")); err != nil { |
| 128 | t.Fatal(err) |
| 129 | } |
| 130 | if _, err = chromedp.Run(ctx, chromedp.Evaluate[any](script)); err != nil { |
| 131 | t.Fatal(err) |
| 132 | } |
| 133 | select { |
| 134 | case code := <-exchangeCodes: |
| 135 | if code != 404 { |
| 136 | t.Fatalf("replay status %d", code) |
| 137 | } |
| 138 | case <-ctx.Done(): |
| 139 | t.Fatal("replay did not reach exchange") |
| 140 | } |
| 141 | } |
| 142 | |