package chrome import ( "context" "fmt" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "strings" "testing" "time" fhttp "github.com/bogdanfinn/fhttp" "github.com/go-rod/rod/lib/launcher" "git.security-command.org/Overlord/dibs/internal/fetch" ) // challengeServer answers /item with a JavaScript challenge until the // browser has run it, which sets a clearance cookie, and /stuck with one // that never clears. Past the challenge it shows what the browser sent. func challengeServer() *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if _, err := r.Cookie("clearance"); err != nil || r.URL.Path == "/stuck" { w.WriteHeader(http.StatusServiceUnavailable) _, _ = io.WriteString(w, `
%s
%s
%s
", r.UserAgent(), r.Header.Get("Sec-Ch-Ua"), session) })) } func newChrome(t *testing.T) (*Chrome, *fetch.Jar) { t.Helper() if testing.Short() { t.Skip("starts Chrome") } if _, ok := launcher.LookPath(); !ok { t.Skip("no Chrome, Chromium or Edge installed") } jar := fetch.NewJar() c := New(fetch.DefaultBrowser(), jar, slog.New(slog.NewTextHandler(io.Discard, nil))) c.challengeTimeout = 5 * time.Second return c, jar } func TestFetchClearsChallenge(t *testing.T) { c, jar := newChrome(t) srv := challengeServer() defer srv.Close() u, _ := url.Parse(srv.URL + "/item") jar.SetCookies(u, []*fhttp.Cookie{{Name: "session", Value: "from-the-jar", Path: "/"}}) resp, err := c.Fetch(context.Background(), u.String()) if err != nil { t.Fatal(err) } body := string(resp.Body) browser := fetch.DefaultBrowser() if resp.Verdict != fetch.OK { t.Fatalf("verdict %s, want ok: %s", resp.Verdict, body) } if !strings.Contains(body, browser.UserAgent) { t.Errorf("Chrome did not claim the user agent of tls-client: %s", body) } if !strings.Contains(body, fmt.Sprintf(`"Chromium";v="%d"`, browser.Major)) { t.Errorf("Chrome did not claim the client hints of tls-client: %s", body) } if !strings.Contains(body, "from-the-jar") { t.Errorf("Chrome did not send the jar's cookies: %s", body) } got := "" for _, ck := range jar.Cookies(u) { got += ck.Name + "=" + ck.Value + " " } if !strings.Contains(got, "clearance=ok") { t.Errorf("the clearance cookie did not reach the jar: %s", got) } } func TestFetchGivesUp(t *testing.T) { c, _ := newChrome(t) srv := challengeServer() defer srv.Close() start := time.Now() resp, err := c.Fetch(context.Background(), srv.URL+"/stuck") if err != nil { t.Fatal(err) } if resp.Verdict != fetch.Challenge { t.Errorf("verdict %s, want challenge", resp.Verdict) } if d := time.Since(start); d > 20*time.Second { t.Errorf("gave up after %s", d) } } type noLimit struct{} func (noLimit) WaitCheck(context.Context, string) error { return nil } func (noLimit) Wait(context.Context, string) error { return nil } func TestPipelineEscalates(t *testing.T) { c, jar := newChrome(t) srv := challengeServer() defer srv.Close() client, err := fetch.New(fetch.Options{Limiter: noLimit{}, Jar: jar}) if err != nil { t.Fatal(err) } p := &Pipeline{Client: client, Chrome: c, Limiter: noLimit{}, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))} for path, want := range map[string]fetch.Verdict{"/item": fetch.OK, "/stuck": fetch.NeedsHuman} { resp, err := p.Get(context.Background(), srv.URL+path) if err != nil { t.Fatal(err) } if resp.Verdict != want { t.Errorf("%s: verdict %s, want %s", path, resp.Verdict, want) } } // Chrome's clearance cookie lets tls-client through on its own now. resp, err := client.Get(context.Background(), srv.URL+"/item") if err != nil { t.Fatal(err) } if resp.Verdict != fetch.OK { t.Errorf("tls-client after Chrome: verdict %s", resp.Verdict) } } // TestSignIn has the page sign in the way a user would, by script here, and // checks that the cookies reach the jar when the window's time is up. func TestSignIn(t *testing.T) { c, jar := newChrome(t) c.humanTimeout = 3 * time.Second srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if _, err := r.Cookie("guest"); err != nil { t.Error("the jar's cookie did not reach Chrome") } http.SetCookie(w, &http.Cookie{Name: "account", Value: "signed-in", Path: "/", HttpOnly: true, Expires: time.Now().Add(time.Hour)}) _, _ = io.WriteString(w, `Signed in`) })) defer srv.Close() u, _ := url.Parse(srv.URL + "/") jar.SetCookies(u, []*fhttp.Cookie{{Name: "guest", Value: "1", Path: "/"}}) n, err := c.signIn(context.Background(), u.String(), true) if err != nil { t.Fatal(err) } if n != 3 { t.Errorf("kept %d cookies, want 3", n) } got := map[string]string{} for _, ck := range jar.Cookies(u) { got[ck.Name] = ck.Value } if got["account"] != "signed-in" || got["later"] != "1" { t.Errorf("jar after signing in: %v", got) } } func TestClick(t *testing.T) { c, _ := newChrome(t) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/item": _, _ = io.WriteString(w, ``) case "/cart": _ = r.ParseForm() _, _ = fmt.Fprintf(w, "%s %s
", r.PostForm.Get("id"), r.PostForm.Get("submit.add")) default: http.NotFound(w, r) } })) defer srv.Close() waited := 0 wait := func() error { waited++ return nil } resp, err := c.Click(context.Background(), srv.URL+"/item", "#add", wait) if err != nil { t.Fatal(err) } if !strings.Contains(string(resp.Body), "X Add") || resp.FinalURL != srv.URL+"/cart" { t.Errorf("after the click: %s %s", resp.FinalURL, resp.Body) } if waited != 1 { t.Errorf("waited %d times before clicking, want 1", waited) } }