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:
1 parent
e2cbc1a55c
commit
15a34e1f84
39 files changed
+3529
-163
No files matched your search
@@ -0,0 +1,335 @@
|
||||
// Package session runs a shop's session mode: signing in to the user's
|
||||
// account and adding an item to its cart, through the plugin's login and
|
||||
// add_to_cart. The account's cookies are kept apart from the watcher's, so
|
||||
// checks of product pages never carry the account.
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"maps"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/chrome"
|
||||
"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"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrNoPrompt means nobody can answer a question, such as when dibs
|
||||
// runs headless without a terminal.
|
||||
ErrNoPrompt = errors.New("no terminal to ask in")
|
||||
// ErrDeclined means the user turned down the plugin's session warning.
|
||||
ErrDeclined = errors.New("session mode declined")
|
||||
)
|
||||
|
||||
// Prompter asks the user. The TUI shows a modal; on the command line, the
|
||||
// question goes to the terminal.
|
||||
type Prompter interface {
|
||||
// Prompt asks for text, such as a one-time code. title names the shop
|
||||
// and site that ask.
|
||||
Prompt(ctx context.Context, title, label string, secret bool) (string, error)
|
||||
// Confirm asks the user to accept message before going on.
|
||||
Confirm(ctx context.Context, title, message string) (bool, error)
|
||||
}
|
||||
|
||||
// Record is what the state file remembers of a shop's session mode.
|
||||
type Record struct {
|
||||
// Warned is when the user accepted the plugin's session warning.
|
||||
Warned time.Time `json:"warned,omitzero"`
|
||||
// Logins has the time of the last sign-in to each host.
|
||||
Logins map[string]time.Time `json:"logins,omitempty"`
|
||||
}
|
||||
|
||||
// Store shares the records with other dibs processes.
|
||||
type Store interface {
|
||||
Lock() func()
|
||||
LoadSession(shop string) (Record, bool)
|
||||
StoreSession(shop string, r Record)
|
||||
}
|
||||
|
||||
// Manager is one shop's session. It is safe for concurrent use; logins and
|
||||
// additions to the cart run one at a time.
|
||||
type Manager struct {
|
||||
shop string
|
||||
vault *Vault
|
||||
jar *fetch.Jar
|
||||
pipeline *chrome.Pipeline
|
||||
chrome *chrome.Chrome
|
||||
limiter *ratelimit.Limiter
|
||||
store Store
|
||||
logger *slog.Logger
|
||||
|
||||
calls sync.Mutex
|
||||
|
||||
mu sync.Mutex
|
||||
account config.Account
|
||||
prompter Prompter
|
||||
}
|
||||
|
||||
// New returns shop's session with the cookies saved in vault. Requests wait
|
||||
// for limiter like every other request to the shop.
|
||||
func New(shop string, vault *Vault, limiter *ratelimit.Limiter, store Store, logger *slog.Logger) (*Manager, error) {
|
||||
jar := fetch.NewJar()
|
||||
|
||||
if err := vault.Load(shop, jar); err != nil {
|
||||
logger.Warn("signed-in cookies unreadable, signing in again", "shop", shop, "err", err)
|
||||
if err := vault.Forget(shop); err != nil { return nil, err }
|
||||
|
||||
jar = fetch.NewJar()
|
||||
}
|
||||
|
||||
client, err := fetch.New(fetch.Options{Limiter: limiter, Jar: jar})
|
||||
if err != nil { return nil, err }
|
||||
|
||||
browser := chrome.New(fetch.DefaultBrowser(), jar, logger)
|
||||
|
||||
return &Manager{
|
||||
shop: shop,
|
||||
vault: vault,
|
||||
jar: jar,
|
||||
pipeline: &chrome.Pipeline{Client: client, Chrome: browser, Limiter: limiter, Logger: logger},
|
||||
chrome: browser,
|
||||
limiter: limiter,
|
||||
store: store,
|
||||
logger: logger,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Update switches to new account settings and to the way to reach the
|
||||
// user, after a reload.
|
||||
func (m *Manager) Update(account config.Account, prompter Prompter) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
m.account, m.prompter = account, prompter
|
||||
}
|
||||
|
||||
func (m *Manager) settings() (config.Account, Prompter) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
return m.account, m.prompter
|
||||
}
|
||||
|
||||
// HasPassword reports whether the account can sign in without the user.
|
||||
func (m *Manager) HasPassword() bool {
|
||||
acc, _ := m.settings()
|
||||
return acc.PasswordEnv != "" && os.Getenv(acc.PasswordEnv) != ""
|
||||
}
|
||||
|
||||
// SignedIn reports whether dibs, in this or another process, signed in to
|
||||
// host and has not found the session signed out since.
|
||||
func (m *Manager) SignedIn(host string) bool {
|
||||
r, _ := m.store.LoadSession(m.shop)
|
||||
_, ok := r.Logins[strings.ToLower(host)]
|
||||
|
||||
return ok
|
||||
}
|
||||
|
||||
// Accept shows p's session warning, unless the user accepted it before. It
|
||||
// returns ErrDeclined if the user turns it down now. Without anyone to ask,
|
||||
// the warning is logged and counts as accepted.
|
||||
func (m *Manager) Accept(ctx context.Context, p *plugin.Plugin) error {
|
||||
if p.SessionWarning == "" { return nil }
|
||||
|
||||
if r, _ := m.store.LoadSession(m.shop); !r.Warned.IsZero() { return nil }
|
||||
|
||||
_, prompter := m.settings()
|
||||
|
||||
ok, err := prompter.Confirm(ctx, "Session mode for "+m.shop, p.SessionWarning)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, ErrNoPrompt):
|
||||
m.logger.Warn(p.SessionWarning, "shop", m.shop)
|
||||
case err != nil:
|
||||
return err
|
||||
case !ok:
|
||||
return ErrDeclined
|
||||
}
|
||||
|
||||
m.update(func(r *Record) { r.Warned = time.Now() })
|
||||
return nil
|
||||
}
|
||||
|
||||
// Login signs in to site, such as https://www.amazon.de/, with the plugin's
|
||||
// login and the account's password.
|
||||
func (m *Manager) Login(ctx context.Context, p *plugin.Plugin, site string) error {
|
||||
host, err := hostOf(site)
|
||||
if err != nil { return err }
|
||||
|
||||
if err := m.Accept(ctx, p); err != nil { return err }
|
||||
|
||||
acc, prompter := m.settings()
|
||||
if acc.PasswordEnv == "" { return fmt.Errorf("accounts.%s has no password_env; sign in with: dibs login %s --browser", m.shop, m.shop) }
|
||||
|
||||
m.calls.Lock()
|
||||
defer m.calls.Unlock()
|
||||
|
||||
m.sync()
|
||||
defer m.sync()
|
||||
|
||||
account := m.pluginAccount(acc, site)
|
||||
account.Password = os.Getenv(acc.PasswordEnv)
|
||||
|
||||
m.logger.Info("signing in", "shop", m.shop, "host", host, "user", acc.Username)
|
||||
|
||||
if err := p.Login(ctx, m.session(prompter, host), account); err != nil { return err }
|
||||
|
||||
m.update(func(r *Record) { r.Logins[host] = time.Now() })
|
||||
m.logger.Info("signed in", "shop", m.shop, "host", host)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// BrowserLogin opens loginURL, or site if it is empty, in a visible Chrome
|
||||
// window for the user to sign in themselves, and keeps the cookies once the
|
||||
// window is closed. The window does not count against the rate limits.
|
||||
func (m *Manager) BrowserLogin(ctx context.Context, site, loginURL string) error {
|
||||
host, err := hostOf(site)
|
||||
if err != nil { return err }
|
||||
|
||||
if loginURL == "" { loginURL = site }
|
||||
|
||||
m.calls.Lock()
|
||||
defer m.calls.Unlock()
|
||||
|
||||
m.sync()
|
||||
defer m.sync()
|
||||
|
||||
n, err := m.chrome.SignIn(ctx, loginURL)
|
||||
if err != nil { return err }
|
||||
if n == 0 { return fmt.Errorf("Chrome had no cookies for %s", host) }
|
||||
|
||||
m.update(func(r *Record) { r.Logins[host] = time.Now() })
|
||||
m.limiter.Success(host)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddToCart puts the item on productURL in the cart, unless it is there
|
||||
// already, and returns the cart page. It returns plugin.ErrSignedOut when
|
||||
// the session has run out; the next Login signs in again.
|
||||
func (m *Manager) AddToCart(ctx context.Context, p *plugin.Plugin, productURL string) (string, error) {
|
||||
host, err := hostOf(productURL)
|
||||
if err != nil { return "", err }
|
||||
|
||||
acc, prompter := m.settings()
|
||||
|
||||
m.calls.Lock()
|
||||
defer m.calls.Unlock()
|
||||
|
||||
m.sync()
|
||||
defer m.sync()
|
||||
|
||||
u, _ := url.Parse(productURL)
|
||||
|
||||
cart, err := p.AddToCart(ctx, m.session(prompter, host), m.pluginAccount(acc, u.Scheme+"://"+u.Host+"/"), productURL)
|
||||
if errors.Is(err, plugin.ErrSignedOut) { m.update(func(r *Record) { delete(r.Logins, host) }) }
|
||||
|
||||
return cart, err
|
||||
}
|
||||
|
||||
// Logout deletes the session's cookies, in every dibs process.
|
||||
func (m *Manager) Logout() error {
|
||||
m.calls.Lock()
|
||||
defer m.calls.Unlock()
|
||||
|
||||
m.jar.Clear()
|
||||
m.update(func(r *Record) { r.Logins = nil })
|
||||
|
||||
return m.vault.Save(m.shop, m.jar)
|
||||
}
|
||||
|
||||
func (m *Manager) pluginAccount(acc config.Account, site string) plugin.Account {
|
||||
return plugin.Account{Username: acc.Username, TwoFA: acc.TwoFA, LoginURL: acc.LoginURL, CartURL: acc.CartURL, Site: site}
|
||||
}
|
||||
|
||||
// sync saves the cookies, which also takes in what other processes saved,
|
||||
// such as a `dibs login` next to a running watcher.
|
||||
func (m *Manager) sync() {
|
||||
if err := m.vault.Save(m.shop, m.jar); err != nil { m.logger.Warn("saving signed-in cookies failed", "shop", m.shop, "err", err) }
|
||||
}
|
||||
|
||||
func (m *Manager) update(change func(r *Record)) {
|
||||
unlock := m.store.Lock()
|
||||
defer unlock()
|
||||
|
||||
r, _ := m.store.LoadSession(m.shop)
|
||||
|
||||
logins := maps.Clone(r.Logins)
|
||||
if logins == nil { logins = map[string]time.Time{} }
|
||||
r.Logins = logins
|
||||
|
||||
change(&r)
|
||||
m.store.StoreSession(m.shop, r)
|
||||
}
|
||||
|
||||
func (m *Manager) session(prompter Prompter, host string) *pluginSession {
|
||||
return &pluginSession{m: m, prompter: prompter, title: m.shop + " · " + host}
|
||||
}
|
||||
|
||||
// pluginSession is the plugin.Session of one call.
|
||||
type pluginSession struct {
|
||||
m *Manager
|
||||
prompter Prompter
|
||||
title string
|
||||
}
|
||||
|
||||
// Do sends a request with the account's cookies. Its outcome backs the
|
||||
// host off or clears its backoff like a check's.
|
||||
func (s *pluginSession) Do(ctx context.Context, r fetch.Request) (*fetch.Response, error) {
|
||||
resp, err := s.m.pipeline.Do(ctx, r)
|
||||
|
||||
if u, perr := url.Parse(r.URL); perr == nil && ctx.Err() == nil { fetch.RecordOutcome(s.m.limiter, u.Hostname(), resp, err) }
|
||||
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// Click presses a button in headless Chrome. Loading the page and clicking
|
||||
// each wait for the host floor.
|
||||
func (s *pluginSession) Click(ctx context.Context, rawURL, sel string) (*fetch.Response, error) {
|
||||
host, err := hostOf(rawURL)
|
||||
if err != nil { return nil, err }
|
||||
|
||||
wait := func() error { return s.m.limiter.Wait(ctx, host) }
|
||||
if err := wait(); err != nil { return nil, err }
|
||||
|
||||
resp, err := s.m.chrome.Click(ctx, rawURL, sel, wait)
|
||||
|
||||
// A missing button or a failed Chrome is no sign of the host's mood.
|
||||
if err == nil { fetch.RecordOutcome(s.m.limiter, host, resp, nil) }
|
||||
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (s *pluginSession) Prompt(ctx context.Context, label string, secret bool) (string, error) {
|
||||
return s.prompter.Prompt(ctx, s.title, label, secret)
|
||||
}
|
||||
|
||||
func (s *pluginSession) Cookies(rawURL string) map[string]string {
|
||||
out := map[string]string{}
|
||||
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil { return out }
|
||||
|
||||
for _, c := range s.m.jar.Cookies(u) { out[c.Name] = c.Value }
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func hostOf(rawURL string) (string, error) {
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil { return "", err }
|
||||
if u.Hostname() == "" { return "", fmt.Errorf("no host in %q", rawURL) }
|
||||
|
||||
return strings.ToLower(u.Hostname()), nil
|
||||
}
|
||||
@@ -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") }
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/zalando/go-keyring"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||
"git.security-command.org/Overlord/dibs/internal/fsutil"
|
||||
)
|
||||
|
||||
const (
|
||||
keyringService = "dibs"
|
||||
keyringUser = "session-key"
|
||||
)
|
||||
|
||||
// Vault keeps each shop's signed-in cookies in a file of their own. The
|
||||
// files are encrypted with a key kept in the OS keyring. Without a keyring,
|
||||
// they are plain files only the user can read.
|
||||
//
|
||||
// The keyring holds only the key: Windows limits a keyring entry to 2560
|
||||
// bytes, which a shop's cookies can exceed.
|
||||
type Vault struct {
|
||||
dir string
|
||||
codec fetch.Codec // nil without a keyring
|
||||
}
|
||||
|
||||
// OpenVault returns the vault in dir/sessions. When the keyring cannot be
|
||||
// used, it also returns an error saying so, and the vault stores plain
|
||||
// files.
|
||||
func OpenVault(dir string) (*Vault, error) {
|
||||
v := &Vault{dir: filepath.Join(dir, "sessions")}
|
||||
|
||||
key, err := v.key()
|
||||
if err != nil { return v, fmt.Errorf("no usable OS keyring, so signed-in cookies are stored unencrypted in %s: %w", v.dir, err) }
|
||||
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil { return v, err }
|
||||
|
||||
aead, err := cipher.NewGCM(block)
|
||||
if err != nil { return v, err }
|
||||
|
||||
v.codec = sealer{aead}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// Encrypted reports whether the files are encrypted.
|
||||
func (v *Vault) Encrypted() bool { return v.codec != nil }
|
||||
|
||||
// key returns the vault's key from the keyring, creating it on first use.
|
||||
func (v *Vault) key() ([]byte, error) {
|
||||
// Two processes creating a key at once would each encrypt with their
|
||||
// own.
|
||||
unlock, err := fsutil.Lock(filepath.Join(v.dir, "key.lock"))
|
||||
if err != nil { return nil, err }
|
||||
defer unlock()
|
||||
|
||||
s, err := keyring.Get(keyringService, keyringUser)
|
||||
|
||||
switch {
|
||||
case err == nil:
|
||||
key, err := base64.StdEncoding.DecodeString(s)
|
||||
if err != nil || len(key) != 32 { return nil, errors.New("the session key in the keyring is not a 256-bit key") }
|
||||
|
||||
return key, nil
|
||||
case errors.Is(err, keyring.ErrNotFound):
|
||||
key := make([]byte, 32)
|
||||
_, _ = rand.Read(key)
|
||||
|
||||
if err := keyring.Set(keyringService, keyringUser, base64.StdEncoding.EncodeToString(key)); err != nil { return nil, err }
|
||||
|
||||
return key, nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func (v *Vault) path(shop string) string {
|
||||
if v.codec != nil { return filepath.Join(v.dir, shop+".cookies") }
|
||||
|
||||
return v.plainPath(shop)
|
||||
}
|
||||
|
||||
func (v *Vault) plainPath(shop string) string { return filepath.Join(v.dir, shop+".json") }
|
||||
|
||||
// Load reads shop's cookies into jar. Cookies stored unencrypted before a
|
||||
// keyring was available are encrypted now.
|
||||
func (v *Vault) Load(shop string, jar *fetch.Jar) error {
|
||||
if err := jar.LoadWith(v.path(shop), v.codec); err != nil { return fmt.Errorf("reading %s: %w", v.path(shop), err) }
|
||||
|
||||
if v.codec == nil { return nil }
|
||||
|
||||
plain := v.plainPath(shop)
|
||||
if _, err := os.Stat(plain); errors.Is(err, fs.ErrNotExist) { return nil }
|
||||
|
||||
if err := jar.Load(plain); err != nil { return fmt.Errorf("reading %s: %w", plain, err) }
|
||||
if err := v.Save(shop, jar); err != nil { return err }
|
||||
|
||||
return os.Remove(plain)
|
||||
}
|
||||
|
||||
// Save writes jar as shop's cookies, after taking in newer cookies other
|
||||
// dibs processes saved.
|
||||
func (v *Vault) Save(shop string, jar *fetch.Jar) error {
|
||||
return jar.SaveWith(v.path(shop), v.codec)
|
||||
}
|
||||
|
||||
// Forget removes shop's file, such as one that cannot be decrypted.
|
||||
func (v *Vault) Forget(shop string) error {
|
||||
for _, p := range []string{v.path(shop), v.plainPath(shop)} {
|
||||
if err := os.Remove(p); err != nil && !errors.Is(err, fs.ErrNotExist) { return err }
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// sealer encrypts with AES-GCM, with the nonce in front of the ciphertext.
|
||||
type sealer struct{ aead cipher.AEAD }
|
||||
|
||||
var additionalData = []byte("dibs session cookies v1")
|
||||
|
||||
func (s sealer) Encode(data []byte) ([]byte, error) {
|
||||
nonce := make([]byte, s.aead.NonceSize())
|
||||
_, _ = rand.Read(nonce)
|
||||
|
||||
return s.aead.Seal(nonce, nonce, data, additionalData), nil
|
||||
}
|
||||
|
||||
func (s sealer) Decode(data []byte) ([]byte, error) {
|
||||
n := s.aead.NonceSize()
|
||||
if len(data) < n { return nil, errors.New("the file is too short to be encrypted cookies") }
|
||||
|
||||
out, err := s.aead.Open(nil, data[:n], data[n:], additionalData)
|
||||
if err != nil { return nil, errors.New("the file cannot be decrypted with the key in the keyring") }
|
||||
|
||||
return out, nil
|
||||
}
|
||||
Reference in new issue
Block a user