Files
dibs/internal/plugin/amazon_session_test.go
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

390 lines
16 KiB
Go

package plugin
import (
"bytes"
"context"
"errors"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"testing"
"github.com/PuerkitoBio/goquery"
"git.security-command.org/Overlord/dibs/internal/fetch"
)
// fakeAmazon imitates the sign-in, product page and cart of amazon.de, as
// far as the plugin uses them. The product page is a saved real one.
type fakeAmazon struct {
t *testing.T
// product is the saved page as a signed-in customer sees it, guest as
// it was saved, signed out.
product, guest string
mu sync.Mutex
// captcha makes the password step ask for a captcha.
captcha bool
// expireOnProduct ends the session when the product page loads.
expireOnProduct bool
// skipped is set once the request for a phone number was skipped.
skipped bool
// session is the signed-in session's cookie value.
session string
inCart bool
// adds counts the additions to the account's cart.
adds int
}
const fakeASIN = "B0DK51S84Z"
func newFakeAmazon(t *testing.T) *fakeAmazon {
page := savedPage(t, "fulfilled-de")
return &fakeAmazon{t: t, product: signedIn(page), guest: string(page)}
}
// savedPage reads testdata/amazon/pages/<name>.html. Saved pages are not
// tracked, so tests without them are skipped.
func savedPage(t *testing.T, name string) []byte {
t.Helper()
page, err := os.ReadFile(filepath.Join(testdata, "amazon", "pages", name+".html"))
if errors.Is(err, os.ErrNotExist) { t.Skip("no saved page " + name + ": run `dibs fixtures` to fetch the product pages") }
if err != nil { t.Fatal(err) }
return page
}
// signedIn turns a saved page, which is a guest's, into what a signed-in
// customer sees.
func signedIn(page []byte) string {
html := regexp.MustCompile(`https://www\.amazon\.de/ap/signin\?[^"]*`).ReplaceAllString(string(page), "https://www.amazon.de/gp/css/homepage.html")
return strings.ReplaceAll(html, "nav_ya_signin", "nav_youraccount_btn")
}
// state returns whether the item is in the cart, how often it was added and
// the session.
func (f *fakeAmazon) state() (bool, int, string) {
f.mu.Lock()
defer f.mu.Unlock()
return f.inCart, f.adds, f.session
}
func (f *fakeAmazon) setExpireOnProduct(on bool) {
f.mu.Lock()
defer f.mu.Unlock()
f.expireOnProduct = on
}
const signedOutNav = `<div id="nav-link-accountList"><a href="https://www.amazon.de/ap/signin?openid.assoc_handle=deflex" data-csa-c-content-id="nav_ya_signin">Hallo, anmelden</a></div>`
func signInPage(fields string) string {
return `<form name="signIn" method="post" action="https://www.amazon.de/ap/signin">` + fields + `<input type="submit" id="signInSubmit"></form>`
}
func (f *fakeAmazon) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
_ = r.ParseForm()
cookie, _ := r.Cookie("at-acbde")
signedIn := cookie != nil && f.session != "" && cookie.Value == f.session
write := func(body string) { _, _ = w.Write([]byte("<html><body>" + body + "</body></html>")) }
switch {
case r.URL.Path == "/ap/signin" && r.Method == "GET" && r.URL.Query().Get("skip") == "fixup":
f.skipped = true
write(`<form id="auth-mfa-form" method="post" action="/ap/signin"><input type="hidden" name="mfaToken" value="mfa"><input name="otpCode"><input type="checkbox" name="rememberDevice"></form>`)
case r.URL.Path == "/ap/signin" && r.Method == "GET":
if r.URL.Query().Get("openid.assoc_handle") != "deflex" { f.t.Errorf("sign-in URL %s", r.URL) }
http.SetCookie(w, &http.Cookie{Name: "session-id", Value: "guest", Path: "/"})
write(signInPage(`<input type="hidden" name="appActionToken" value="tok1"><input type="email" name="email">`))
case r.URL.Path == "/ap/accountfixup":
f.t.Error("dibs submitted the phone number form")
case r.URL.Path == "/ap/signin" && r.Form.Has("otpCode"):
if r.Form.Get("otpCode") != "123456" || r.Form.Get("mfaToken") != "mfa" {
write(`<form id="auth-mfa-form" method="post" action="/ap/signin"><div id="auth-error-message-box">Wrong code</div></form>`)
return
}
f.session = "signed-in"
http.SetCookie(w, &http.Cookie{Name: "at-acbde", Value: f.session, Path: "/"})
http.Redirect(w, r, "/?ref_=signin", http.StatusFound)
case r.URL.Path == "/ap/signin" && r.Form.Has("password"):
switch {
case r.Form.Get("appActionToken") != "tok2" || r.Form.Get("email") != "me@example.com":
f.t.Errorf("password step got %v", r.Form)
case r.Form.Get("password") != "hunter2":
write(`<div id="auth-error-message-box">Ihr Passwort ist falsch</div>` + signInPage(`<input type="hidden" name="appActionToken" value="tok2"><input type="password" name="password">`))
case f.captcha:
write(`<img id="auth-captcha-image" src="/captcha.jpg">` + signInPage(`<input type="password" name="password">`))
default:
// As on amazon.de: a request for a phone number, with a link
// to skip it.
write(`<form id="auth-account-fixup-phone-form" name="accountFixup" method="post" action="https://www.amazon.de/ap/accountfixup">` +
`<input type="tel" name="mobilePhoneNumber"><input type="submit"></form>` +
`<a id="ap-account-fixup-phone-skip-link" href="https://www.amazon.de/ap/signin?skip=fixup">Nicht jetzt</a>`)
}
case r.URL.Path == "/ap/signin":
if r.Form.Get("appActionToken") != "tok1" || r.Form.Get("email") != "me@example.com" { f.t.Errorf("email step got %v", r.Form) }
write(signInPage(`<input type="hidden" name="appActionToken" value="tok2"><input type="hidden" name="email" value="me@example.com"><input type="password" name="password"><input type="checkbox" name="rememberMe" value="true">`))
case r.URL.Path == "/" && signedIn:
write(`<div id="nav-link-accountList"><a href="/gp/css/homepage.html" data-csa-c-content-id="nav_youraccount_btn">Hallo, Me</a></div>`)
case r.URL.Path == "/gp/cart/view.html" && !signedIn:
write(signedOutNav + `<div id="sc-active-cart"></div>`)
case r.URL.Path == "/gp/cart/view.html":
items := ""
if f.inCart { items = `<div class="sc-list-item" data-asin="` + fakeASIN + `"></div>` }
write(`<div id="sc-active-cart">` + items + `</div><div id="sc-saved-cart"><div data-asin="` + fakeASIN + `"></div></div>`)
case r.URL.Path == "/dp/"+fakeASIN:
if f.expireOnProduct { f.session = "expired" }
_, _ = w.Write([]byte(f.product))
case strings.HasPrefix(r.URL.Path, "/cart/add-to-cart/") && r.Method == "POST":
for name, want := range map[string]string{
"anti-csrftoken-a2z": "hOgocjo+1KjiCPsF4LU3lHBSy+VeMLo/5zSecGDC+HnZAAAAAGrOvcg1Y2U5ZjJiZC0zZGNiLTRjYzctYWNhNC05YjE0ZTkzMjk0ZTA=",
"items[0.base][quantity]": "1",
"items[0.base][asin]": fakeASIN,
"submit.add-to-cart": "In den Einkaufswagen",
} {
if got := r.Form.Get(name); got != want { f.t.Errorf("add to cart: %s = %q, want %q", name, got, want) }
}
if r.Form.Has("submit.buy-now") { f.t.Error("add to cart pressed buy now") }
if signedIn { f.inCart, f.adds = true, f.adds+1 }
http.Redirect(w, r, "/cart/smart-wagon?newItems="+fakeASIN, http.StatusFound)
case r.URL.Path == "/cart/smart-wagon":
// A guest's item goes into a guest cart, under Amazon's real
// signed-out header.
header := ""
if !signedIn { header = f.guest }
write(header + `<div id="NATC_SMART_WAGON_CONF_MSG_SUCCESS">In den Einkaufswagen gelegt</div>`)
default:
f.t.Errorf("unexpected %s %s", r.Method, r.URL)
http.NotFound(w, r)
}
}
// amazonSession sends the plugin's requests to the fake instead of
// www.amazon.de.
type amazonSession struct {
client *fetch.Client
srv string
codes int
}
const amazonOrigin = "https://www.amazon.de"
func (s *amazonSession) local(u string) string { return strings.Replace(u, amazonOrigin, s.srv, 1) }
func (s *amazonSession) remote(u string) string { return strings.Replace(u, s.srv, amazonOrigin, 1) }
func (s *amazonSession) Do(ctx context.Context, r fetch.Request) (*fetch.Response, error) {
if !strings.HasPrefix(r.URL, amazonOrigin+"/") { return nil, errors.New("request outside amazon.de: " + r.URL) }
r.URL = s.local(r.URL)
if r.Referer != "" { r.Referer = s.local(r.Referer) }
resp, err := s.client.Do(ctx, r)
if err != nil { return nil, err }
resp.URL, resp.FinalURL = s.remote(resp.URL), s.remote(resp.FinalURL)
return resp, nil
}
// Click submits the button's form as Chrome does: every field, the button's
// own name and value, to the button's formaction if it has one.
func (s *amazonSession) Click(ctx context.Context, rawURL, sel string) (*fetch.Response, error) {
page, err := s.Do(ctx, fetch.Request{Method: "GET", URL: rawURL})
if err != nil { return nil, err }
doc, err := goquery.NewDocumentFromReader(bytes.NewReader(page.Body))
if err != nil { return nil, err }
button := doc.Find(sel).First()
if button.Length() == 0 { return nil, errors.New("no " + sel) }
f := button.Closest("form")
form := url.Values{}
f.Find("input[name]").Each(func(_ int, in *goquery.Selection) {
kind := in.AttrOr("type", "text")
if kind == "submit" || (kind == "checkbox" && in.AttrOr("checked", "-") == "-") { return }
form.Add(in.AttrOr("name", ""), in.AttrOr("value", ""))
})
f.Find("select[name]").Each(func(_ int, sl *goquery.Selection) { form.Add(sl.AttrOr("name", ""), sl.Find("option").First().AttrOr("value", "")) })
form.Add(button.AttrOr("name", ""), button.AttrOr("value", ""))
return s.Do(ctx, fetch.Request{Method: "POST", URL: amazonOrigin + button.AttrOr("formaction", f.AttrOr("action", "")), Form: form, Referer: rawURL})
}
func (s *amazonSession) Prompt(_ context.Context, label string, secret bool) (string, error) {
s.codes++
return "123456", nil
}
func (s *amazonSession) Cookies(u string) map[string]string {
parsed, _ := url.Parse(s.local(u))
out := map[string]string{}
for _, c := range s.client.Jar().Cookies(parsed) { out[c.Name] = c.Value }
return out
}
type noWait struct{}
func (noWait) WaitCheck(context.Context, string) error { return nil }
func (noWait) Wait(context.Context, string) error { return nil }
func newAmazonSession(t *testing.T) (*fakeAmazon, *amazonSession) {
fake := newFakeAmazon(t)
srv := httptest.NewServer(fake)
t.Cleanup(srv.Close)
client, err := fetch.New(fetch.Options{Limiter: noWait{}})
if err != nil { t.Fatal(err) }
return fake, &amazonSession{client: client, srv: srv.URL}
}
var amazonAccount = Account{Username: "me@example.com", Password: "hunter2", TwoFA: true, Site: "https://www.amazon.de/"}
func TestAmazonSession(t *testing.T) {
p := builtin(t, "amazon")
fake, s := newAmazonSession(t)
ctx := context.Background()
product := "https://www.amazon.de/dp/" + fakeASIN
// Without a session, the cart shows a guest.
if _, err := p.AddToCart(ctx, s, amazonAccount, product); !errors.Is(err, ErrSignedOut) { t.Fatalf("before signing in: got %v, want ErrSignedOut", err) }
if err := p.Login(ctx, s, amazonAccount); err != nil { t.Fatal(err) }
if s.codes != 1 { t.Errorf("asked for %d codes, want 1", s.codes) }
if !fake.skipped { t.Error("the request for a phone number was not skipped") }
// The session runs out between the cart and the click. The page the
// click leads to has Amazon's real signed-out header.
fake.setExpireOnProduct(true)
if _, err := p.AddToCart(ctx, s, amazonAccount, product); !errors.Is(err, ErrSignedOut) { t.Errorf("session ran out before the click: got %v, want ErrSignedOut", err) }
if inCart, _, _ := fake.state(); inCart { t.Error("added to the account's cart while signed out") }
fake.setExpireOnProduct(false)
if err := p.Login(ctx, s, amazonAccount); err != nil { t.Fatal(err) }
// The item saved for later is not in the cart.
cart, err := p.AddToCart(ctx, s, amazonAccount, product)
if err != nil { t.Fatal(err) }
if cart != "https://www.amazon.de/gp/cart/view.html" { t.Errorf("cart page %q", cart) }
if inCart, adds, _ := fake.state(); !inCart || adds != 1 { t.Errorf("in cart %v after %d adds", inCart, adds) }
// Already in the cart: nothing is added again.
if _, err := p.AddToCart(ctx, s, amazonAccount, product); err != nil { t.Fatal(err) }
if _, adds, _ := fake.state(); adds != 1 { t.Errorf("%d adds, want 1: the item went in twice", adds) }
// The session runs out.
fake.mu.Lock()
fake.session, fake.inCart = "expired", false
fake.mu.Unlock()
if _, err := p.AddToCart(ctx, s, amazonAccount, product); !errors.Is(err, ErrSignedOut) { t.Errorf("after the session ran out: got %v, want ErrSignedOut", err) }
}
func TestAmazonLoginFailures(t *testing.T) {
p := builtin(t, "amazon")
for name, tc := range map[string]struct {
account Account
captcha bool
want string
}{
"wrong password": {Account{Username: "me@example.com", Password: "wrong", TwoFA: true, Site: amazonAccount.Site}, false, "Ihr Passwort ist falsch"},
"captcha": {amazonAccount, true, "dibs login amazon --browser"},
"twofa off": {Account{Username: "me@example.com", Password: "hunter2", Site: amazonAccount.Site}, false, "twofa is off"},
"no password": {Account{Username: "me@example.com", Site: amazonAccount.Site}, false, "no password"},
} {
fake, s := newAmazonSession(t)
fake.captcha = tc.captcha
err := p.Login(context.Background(), s, tc.account)
if err == nil || !strings.Contains(err.Error(), tc.want) { t.Errorf("%s: got %v, want an error containing %q", name, err, tc.want) }
if _, _, session := fake.state(); session != "" { t.Errorf("%s: signed in", name) }
}
}
// pageSession serves saved real pages by path and refuses to send forms,
// recording them instead.
type pageSession struct {
pages map[string][]byte
posted []fetch.Request
}
func (s *pageSession) Do(_ context.Context, r fetch.Request) (*fetch.Response, error) {
if r.Method == "POST" {
s.posted = append(s.posted, r)
return nil, errors.New("stopped before posting")
}
u, _ := url.Parse(r.URL)
page, ok := s.pages[u.Path]
if !ok { return nil, errors.New("no saved page for " + u.Path) }
return fetch.NewResponse(r.URL, r.URL, 200, nil, page), nil
}
func (s *pageSession) Click(context.Context, string, string) (*fetch.Response, error) {
return nil, errors.New("no clicks on saved pages")
}
func (s *pageSession) Prompt(context.Context, string, bool) (string, error) { return "", errors.New("no prompts") }
func (s *pageSession) Cookies(string) map[string]string { return nil }
// TestAmazonSavedSessionPages runs the plugin on pages saved from a guest
// session on amazon.de: the sign-in page, an empty cart and a cart holding
// fakeASIN.
func TestAmazonSavedSessionPages(t *testing.T) {
p := builtin(t, "amazon")
ctx := context.Background()
signin := savedPage(t, "session-signin-de")
empty := savedPage(t, "session-cart-guest-de")
full := savedPage(t, "session-cart-item-de")
product := "https://www.amazon.de/dp/" + fakeASIN
if _, err := p.AddToCart(ctx, &pageSession{pages: map[string][]byte{"/gp/cart/view.html": empty}}, amazonAccount, product); !errors.Is(err, ErrSignedOut) { t.Errorf("guest cart: got %v, want ErrSignedOut", err) }
cart, err := p.AddToCart(ctx, &pageSession{pages: map[string][]byte{"/gp/cart/view.html": []byte(signedIn(full))}}, amazonAccount, product)
if err != nil || cart == "" { t.Errorf("cart holding the item: %q, %v, want it found without adding", cart, err) }
// The first step of signing in asks for the email only. Its password
// input is a hidden one for autofill.
s := &pageSession{pages: map[string][]byte{"/ap/signin": signin}}
if err := p.Login(ctx, s, amazonAccount); err == nil { t.Fatal("login went past the saved page") }
if len(s.posted) != 1 { t.Fatalf("%d forms posted, want 1", len(s.posted)) }
r := s.posted[0]
if !strings.HasPrefix(r.URL, "https://www.amazon.de/ax/claim?") { t.Errorf("posted to %s", r.URL) }
if r.Form.Get("email") != amazonAccount.Username { t.Errorf("email = %q", r.Form.Get("email")) }
if r.Form.Get("password") != "" { t.Error("the password went out with the email") }
if r.Form.Get("anti-csrftoken-a2z") == "" || r.Form.Get("appAction") != "SIGNIN_CLAIM_COLLECT" { t.Errorf("hidden fields missing: %v", r.Form) }
}