Files
dibs/internal/chrome/chrome_test.go
T
OverlordandClaude Bot 15a34e1f84 Add session mode: signing in and adding to the cart.
With cart_mode = "session", dibs signs in to the shop's account and puts
an item in the cart when it fires. The account's cookies are kept apart
from the watcher's and stored encrypted, with the key in the OS keyring.
Without a keyring, they're stored in a file only you can read.

An alert now goes out right away, without a cart link, and a second one
follows once the item is in the cart. If adding fails, the second alert
carries the cart link instead.

Amazon only accepts additions its page scripts have seen, so plugins can
now press a button in headless Chrome with ctx:click.

The TUI asks for one-time codes and shows the plugin's warning about
account locks in a modal. 'dibs login' signs in from a terminal, or
with --browser in a Chrome window, and 'dibs logout' deletes the cookies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 17:26:26 +02:00

174 lines
6.3 KiB
Go

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, `<html><head><title>Just a moment...</title><script>window._cf_chl_opt = {};
if (location.pathname === "/item") { document.cookie = "clearance=ok; path=/"; setTimeout(() => location.reload(), 300) }
</script></head><body>Checking your browser</body></html>`)
return
}
session := ""
if ck, err := r.Cookie("session"); err == nil { session = ck.Value }
_, _ = fmt.Fprintf(w, "<html><body><p id=ua>%s</p><p id=ch>%s</p><p id=session>%s</p></body></html>",
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, `<html><body><script>document.cookie = "later=1; path=/"</script>Signed in</body></html>`)
}))
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, `<html><body><form method="post" action="/wrong"><input type="hidden" name="id" value="X">
<input type="submit" id="add" name="submit.add" value="Add" formaction="/cart"></form></body></html>`)
case "/cart":
_ = r.ParseForm()
_, _ = fmt.Fprintf(w, "<html><body><p id=added>%s %s</p></body></html>", 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) }
}