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>
This commit is contained in:
OverlordandClaude Bot committed 2026-10-14 17:26:26 +02:00
1 parent e2cbc1a55c
commit 15a34e1f84
39 files changed
+3529 -163

No files matched your search

+197
View File
@@ -0,0 +1,197 @@
package session_test
import (
"bytes"
"context"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"sync"
"sync/atomic"
"testing"
"time"
fhttp "github.com/bogdanfinn/fhttp"
"github.com/zalando/go-keyring"
"git.security-command.org/Overlord/dibs/internal/config"
"git.security-command.org/Overlord/dibs/internal/fetch"
"git.security-command.org/Overlord/dibs/internal/plugin"
"git.security-command.org/Overlord/dibs/internal/ratelimit"
"git.security-command.org/Overlord/dibs/internal/session"
"git.security-command.org/Overlord/dibs/internal/state"
)
func discard() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
func TestVault(t *testing.T) {
dir := t.TempDir()
u := &url.URL{Scheme: "https", Host: "www.amazon.de", Path: "/"}
jar := fetch.NewJar()
jar.SetCookies(u, []*fhttp.Cookie{{Name: "at-acbde", Value: "secret-session", Path: "/", Expires: time.Now().Add(time.Hour)}})
// Without a keyring, the cookies are stored, but in plain text.
keyring.MockInitWithError(errors.New("no secret service"))
plain, err := session.OpenVault(dir)
if err == nil || plain.Encrypted() { t.Fatalf("without a keyring: err %v, encrypted %v", err, plain.Encrypted()) }
if err := plain.Save("amazon", jar); err != nil { t.Fatal(err) }
data, err := os.ReadFile(filepath.Join(dir, "sessions", "amazon.json"))
if err != nil || !bytes.Contains(data, []byte("secret-session")) { t.Fatalf("plain file: %v, %s", err, data) }
// With a keyring, the plain file is encrypted on first use.
keyring.MockInit()
vault, err := session.OpenVault(dir)
if err != nil || !vault.Encrypted() { t.Fatalf("with a keyring: err %v, encrypted %v", err, vault.Encrypted()) }
loaded := fetch.NewJar()
if err := vault.Load("amazon", loaded); err != nil { t.Fatal(err) }
if got := loaded.Cookies(u); len(got) != 1 || got[0].Value != "secret-session" { t.Errorf("loaded %v", got) }
if _, err := os.Stat(filepath.Join(dir, "sessions", "amazon.json")); !errors.Is(err, os.ErrNotExist) { t.Errorf("plain file still there: %v", err) }
data, err = os.ReadFile(filepath.Join(dir, "sessions", "amazon.cookies"))
if err != nil || bytes.Contains(data, []byte("secret-session")) || bytes.Contains(data, []byte("at-acbde")) { t.Errorf("encrypted file: %v, %q", err, data) }
// Another process opening the vault uses the same key.
again, err := session.OpenVault(dir)
if err != nil { t.Fatal(err) }
other := fetch.NewJar()
if err := again.Load("amazon", other); err != nil { t.Fatal(err) }
if got := other.Cookies(u); len(got) != 1 { t.Errorf("second process loaded %v", got) }
}
// instantClock lets the limiter's waits pass at once.
type instantClock struct {
mu sync.Mutex
now time.Time
}
func (c *instantClock) Now() time.Time {
c.mu.Lock()
defer c.mu.Unlock()
return c.now
}
func (c *instantClock) After(d time.Duration) <-chan time.Time {
c.mu.Lock()
c.now = c.now.Add(d)
c.mu.Unlock()
ch := make(chan time.Time, 1)
ch <- c.Now()
return ch
}
type fakePrompter struct {
accept bool
confirms int
}
func (f *fakePrompter) Prompt(context.Context, string, string, bool) (string, error) { return "123456", nil }
func (f *fakePrompter) Confirm(context.Context, string, string) (bool, error) {
f.confirms++
return f.accept, nil
}
// shop serves testdata/session/shop.lua's sign-in and cart.
func shop(t *testing.T) (*httptest.Server, *atomic.Int32) {
requests := &atomic.Int32{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
_ = r.ParseForm()
c, _ := r.Cookie("session")
switch {
case r.URL.Path == "/signin" && r.Method == "POST" && r.Form.Get("password") == "hunter2":
http.SetCookie(w, &http.Cookie{Name: "session", Value: "yes", Path: "/"})
_, _ = w.Write([]byte(`<p id="result">welcome</p>`))
case r.URL.Path == "/cart" && c != nil && r.Header.Get("X-Test") == "yes":
w.Header().Set("X-Cart", "1")
}
}))
t.Cleanup(srv.Close)
return srv, requests
}
func newManager(t *testing.T, dir string, prompter session.Prompter) (*session.Manager, *plugin.Plugin) {
t.Helper()
code, err := os.ReadFile(filepath.Join("..", "..", "testdata", "session", "shop.lua"))
if err != nil { t.Fatal(err) }
p, err := plugin.Load("shop", "shop.lua", code, plugin.DefaultLimits(), discard())
if err != nil { t.Fatal(err) }
t.Cleanup(p.Close)
vault, err := session.OpenVault(dir)
if err != nil { t.Fatal(err) }
limiter := ratelimit.New(nil, ratelimit.WithClock(&instantClock{now: time.Now()}))
m, err := session.New("shop", vault, limiter, state.Open(dir), discard())
if err != nil { t.Fatal(err) }
t.Setenv("DIBS_TEST_SHOP_PASS", "hunter2")
m.Update(config.Account{Username: "me@example.com", PasswordEnv: "DIBS_TEST_SHOP_PASS", CartMode: config.CartModeSession, TwoFA: true}, prompter)
return m, p
}
func TestManager(t *testing.T) {
keyring.MockInit()
dir := t.TempDir()
srv, requests := shop(t)
site := srv.URL + "/"
host := "127.0.0.1"
ctx := context.Background()
// Turning down the session warning stops the login before any request.
declining := &fakePrompter{}
m, p := newManager(t, dir, declining)
if err := m.Login(ctx, p, site); !errors.Is(err, session.ErrDeclined) { t.Fatalf("declined: got %v", err) }
if n := requests.Load(); n != 0 { t.Errorf("%d requests after declining", n) }
accepting := &fakePrompter{accept: true}
m.Update(config.Account{Username: "me@example.com", PasswordEnv: "DIBS_TEST_SHOP_PASS", TwoFA: true}, accepting)
if err := m.Login(ctx, p, site); err != nil { t.Fatal(err) }
if !m.SignedIn(host) { t.Error("not signed in after Login") }
// The warning is shown once.
if err := m.Login(ctx, p, site); err != nil { t.Fatal(err) }
if accepting.confirms != 1 { t.Errorf("warning shown %d times", accepting.confirms) }
// Another process picks up the session from the vault and the state
// file.
other, p2 := newManager(t, dir, accepting)
if !other.SignedIn(host) { t.Error("other process: not signed in") }
cart, err := other.AddToCart(ctx, p2, site+"item/ok")
if err != nil || cart != site+"cart" { t.Errorf("other process: %q, %v", cart, err) }
// A session found signed out needs a new login.
if _, err := other.AddToCart(ctx, p2, site+"item/signedout"); !errors.Is(err, plugin.ErrSignedOut) { t.Errorf("signed out: got %v", err) }
if m.SignedIn(host) { t.Error("still signed in after the session ran out") }
// Logging out clears the cookies of the other process too.
if err := m.Login(ctx, p, site); err != nil { t.Fatal(err) }
if err := m.Logout(); err != nil { t.Fatal(err) }
if _, err := other.AddToCart(ctx, p2, site+"item/ok"); err == nil { t.Error("added to the cart after logging out") }
}