From bb010356a0ef7b59a818b49d32bfd4b4c3601ed5 Mon Sep 17 00:00:00 2001 From: Overlord Date: Wed, 14 Oct 2026 01:46:03 +0200 Subject: [PATCH] Add Lua plugin host, built-in amazon plugin and dibs check. Sandboxed gopher-lua with time, memory and call-stack limits from [sandbox], a goquery-backed doc API, price parsing, and the 'check', 'plugin test' and 'fixtures' commands. Sellers are first_party, fulfilled (shipped by the shop) or third_party, and items accept fulfilled by default; used-only offers are not available. Plugin tests run on real pages that 'dibs fixtures' fetches into an untracked directory. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 + cmd/dibs/check.go | 148 ++++++++++++ cmd/dibs/fixtures.go | 126 ++++++++++ cmd/dibs/main.go | 46 +++- go.mod | 3 + go.sum | 6 + internal/config/config.go | 33 +++ internal/config/config_test.go | 27 ++- internal/config/validate.go | 6 +- internal/fetch/client.go | 28 ++- internal/fixtures/fixtures.go | 104 +++++++++ internal/plugin/builtin/amazon.lua | 208 +++++++++++++++++ internal/plugin/doc.go | 168 +++++++++++++ internal/plugin/helpers.go | 107 +++++++++ internal/plugin/host.go | 165 +++++++++++++ internal/plugin/pages_test.go | 100 ++++++++ internal/plugin/plugin.go | 363 +++++++++++++++++++++++++++++ internal/plugin/sandbox.go | 183 +++++++++++++++ internal/plugin/sandbox_test.go | 80 +++++++ internal/price/price.go | 82 +++++++ internal/price/price_test.go | 42 ++++ testdata/amazon/cases.toml | 36 +++ testdata/amazon/urls.toml | 20 ++ testdata/sandbox/call_stack.lua | 8 + testdata/sandbox/globals.lua | 9 + testdata/sandbox/memory.lua | 7 + testdata/sandbox/string_rep.lua | 6 + testdata/sandbox/timeout.lua | 8 + 28 files changed, 2096 insertions(+), 26 deletions(-) create mode 100644 cmd/dibs/check.go create mode 100644 cmd/dibs/fixtures.go create mode 100644 internal/fixtures/fixtures.go create mode 100644 internal/plugin/builtin/amazon.lua create mode 100644 internal/plugin/doc.go create mode 100644 internal/plugin/helpers.go create mode 100644 internal/plugin/host.go create mode 100644 internal/plugin/pages_test.go create mode 100644 internal/plugin/plugin.go create mode 100644 internal/plugin/sandbox.go create mode 100644 internal/plugin/sandbox_test.go create mode 100644 internal/price/price.go create mode 100644 internal/price/price_test.go create mode 100644 testdata/amazon/cases.toml create mode 100644 testdata/amazon/urls.toml create mode 100644 testdata/sandbox/call_stack.lua create mode 100644 testdata/sandbox/globals.lua create mode 100644 testdata/sandbox/memory.lua create mode 100644 testdata/sandbox/string_rep.lua create mode 100644 testdata/sandbox/timeout.lua diff --git a/.gitignore b/.gitignore index 1dd4b20..178c441 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,6 @@ go.work.sum .env + +# Real shop pages fetched by 'dibs fixtures'. +testdata/*/pages/ diff --git a/cmd/dibs/check.go b/cmd/dibs/check.go new file mode 100644 index 0000000..c7946db --- /dev/null +++ b/cmd/dibs/check.go @@ -0,0 +1,148 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "os" + "os/signal" + + "git.security-command.org/Overlord/dibs/internal/config" + "git.security-command.org/Overlord/dibs/internal/fetch" + "git.security-command.org/Overlord/dibs/internal/plugin" +) + +// runCheck implements `dibs check [--shop NAME] `: one fetch and parse, +// printed as JSON. +func runCheck(args []string, stdout, stderr io.Writer) int { + flags, configPath := newFlagSet("dibs check", stderr) + shop := flags.String("shop", "", "plugin to use (default: the first whose matches() accepts the URL)") + + pos, ok := parseArgs(flags, args) + if !ok { return 2 } + if len(pos) != 1 { + _, _ = fmt.Fprintf(stderr, "dibs check: expected one URL\n\n%s", usage) + return 2 + } + + cfg, ok := loadOptionalConfig(*configPath, stderr) + if !ok { return 1 } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + + logger := slog.New(slog.NewTextHandler(stderr, nil)) + + host, err := newHost(cfg, logger) + if err != nil { return fail(stderr, "check", err) } + defer host.Close() + + url := pos[0] + + p, err := pickPlugin(ctx, host, *shop, url) + if err != nil { return fail(stderr, "check", err) } + + fetchURL, err := p.Normalize(ctx, url) + if err != nil { return fail(stderr, "check", err) } + + client, err := fetch.New(fetch.Options{}) + if err != nil { return fail(stderr, "check", err) } + + resp, err := client.Get(ctx, fetchURL) + if err != nil { return fail(stderr, "check", err) } + + report, err := plugin.Evaluate(ctx, p, url, resp) + printJSON(stdout, report) + if err != nil { return fail(stderr, "check", err) } + + return 0 +} + +// runPlugin implements `dibs plugin test [--status CODE] +// [url]`: run a plugin on a saved page. +func runPlugin(args []string, stdout, stderr io.Writer) int { + if len(args) == 0 || args[0] != "test" { + _, _ = fmt.Fprintf(stderr, "dibs plugin: expected \"test\"\n\n%s", usage) + return 2 + } + + flags, configPath := newFlagSet("dibs plugin test", stderr) + status := flags.Int("status", 200, "HTTP status the page was served with") + + pos, ok := parseArgs(flags, args[1:]) + if !ok { return 2 } + if len(pos) < 2 || len(pos) > 3 { + _, _ = fmt.Fprintf(stderr, "dibs plugin test: expected [url]\n\n%s", usage) + return 2 + } + + cfg, ok := loadOptionalConfig(*configPath, stderr) + if !ok { return 1 } + + code, err := os.ReadFile(pos[0]) + if err != nil { return fail(stderr, "plugin test", err) } + + page, err := os.ReadFile(pos[1]) + if err != nil { return fail(stderr, "plugin test", err) } + + url := "https://example.invalid/" + if len(pos) == 3 { url = pos[2] } + + ctx := context.Background() + logger := slog.New(slog.NewTextHandler(stderr, nil)) + + p, err := plugin.Load("", pos[0], code, limits(cfg), logger) + if err != nil { return fail(stderr, "plugin test", err) } + defer p.Close() + + fetchURL, err := p.Normalize(ctx, url) + if err != nil { return fail(stderr, "plugin test", err) } + + report, err := plugin.Evaluate(ctx, p, url, fetch.NewResponse(fetchURL, fetchURL, *status, nil, page)) + printJSON(stdout, report) + if err != nil { return fail(stderr, "plugin test", err) } + + return 0 +} + +func newHost(cfg *config.Config, logger *slog.Logger) (*plugin.Host, error) { + var user map[string]string + if cfg != nil { user = cfg.Plugins } + + return plugin.NewHost(user, limits(cfg), logger) +} + +func limits(cfg *config.Config) plugin.Limits { + if cfg == nil { return plugin.DefaultLimits() } + + return plugin.LimitsFrom(cfg.Sandbox) +} + +func pickPlugin(ctx context.Context, host *plugin.Host, shop, url string) (*plugin.Plugin, error) { + if shop == "" { + p, err := host.ForURL(ctx, url) + if errors.Is(err, plugin.ErrNoPlugin) { return nil, fmt.Errorf("%w; pick one with --shop", err) } + + return p, err + } + + p, ok := host.Plugin(shop) + if !ok { return nil, fmt.Errorf("no plugin named %q (built-in: %v)", shop, plugin.Builtins()) } + + return p, nil +} + +func printJSON(w io.Writer, v any) { + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + enc.SetEscapeHTML(false) + _ = enc.Encode(v) +} + +func fail(stderr io.Writer, cmd string, err error) int { + _, _ = fmt.Fprintf(stderr, "dibs %s: %v\n", cmd, err) + return 1 +} diff --git a/cmd/dibs/fixtures.go b/cmd/dibs/fixtures.go new file mode 100644 index 0000000..3ac0251 --- /dev/null +++ b/cmd/dibs/fixtures.go @@ -0,0 +1,126 @@ +package main + +import ( + "context" + "fmt" + "io" + "log/slog" + "net/url" + "os" + "os/signal" + "time" + + "git.security-command.org/Overlord/dibs/internal/fetch" + "git.security-command.org/Overlord/dibs/internal/fixtures" + "git.security-command.org/Overlord/dibs/internal/plugin" +) + +// fixtureSpacing is the pause between two requests to the same host. +const fixtureSpacing = 12 * time.Second + +// runFixtures implements `dibs fixtures [--dir DIR] [--only NAME]`: fetch the +// pages listed in DIR//cases.toml for the plugin tests. +func runFixtures(args []string, stdout, stderr io.Writer) int { + flags, configPath := newFlagSet("dibs fixtures", stderr) + dir := flags.String("dir", "testdata", "directory with /cases.toml files") + only := flags.String("only", "", "fetch only the case with this name") + + pos, ok := parseArgs(flags, args) + if !ok { return 2 } + if len(pos) > 0 { + _, _ = fmt.Fprintf(stderr, "dibs fixtures: unexpected argument %q\n\n%s", pos[0], usage) + return 2 + } + + suites, err := fixtures.Load(*dir) + if err != nil { return fail(stderr, "fixtures", err) } + if len(suites) == 0 { return fail(stderr, "fixtures", fmt.Errorf("no */cases.toml in %s", *dir)) } + + cfg, ok := loadOptionalConfig(*configPath, stderr) + if !ok { return 1 } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + + host, err := newHost(cfg, slog.New(slog.NewTextHandler(stderr, nil))) + if err != nil { return fail(stderr, "fixtures", err) } + defer host.Close() + + client, err := fetch.New(fetch.Options{}) + if err != nil { return fail(stderr, "fixtures", err) } + + lastRequest := map[string]time.Time{} + failed := 0 + + for _, suite := range suites { + p, ok := host.Plugin(suite.Shop) + if !ok { + _, _ = fmt.Fprintf(stderr, "dibs fixtures: %s: no plugin named %q, skipping\n", suite.Dir, suite.Shop) + continue + } + + for _, c := range suite.Cases { + if *only != "" && c.Name != *only { continue } + + if err := fetchFixture(ctx, client, p, suite, c, lastRequest, stdout); err != nil { + if ctx.Err() != nil { return fail(stderr, "fixtures", ctx.Err()) } + + _, _ = fmt.Fprintf(stderr, "dibs fixtures: %s: %v\n", c.Name, err) + failed++ + } + } + } + + if failed > 0 { return 1 } + + return 0 +} + +func fetchFixture(ctx context.Context, client *fetch.Client, p *plugin.Plugin, suite fixtures.Suite, c fixtures.Case, lastRequest map[string]time.Time, stdout io.Writer) error { + fetchURL, err := p.Normalize(ctx, c.URL) + if err != nil { return err } + + u, err := url.Parse(fetchURL) + if err != nil { return err } + + if wait := time.Until(lastRequest[u.Host].Add(fixtureSpacing)); wait > 0 { + select { + case <-time.After(wait): + case <-ctx.Done(): + return ctx.Err() + } + } + lastRequest[u.Host] = time.Now() + + resp, err := client.Get(ctx, fetchURL) + if err != nil { return err } + + report, err := plugin.Evaluate(ctx, p, c.URL, resp) + if err != nil { return err } + + // Saved reports must not depend on how fast the shop answered. + report.ElapsedMS = 0 + + if err := suite.Save(c, resp.Body, report); err != nil { return err } + + _, _ = fmt.Fprintf(stdout, "%-20s %s\n", c.Name, summary(report)) + _, _ = fmt.Fprintf(stdout, "%-20s %s\n\n", "", c.Note) + + return nil +} + +func summary(r *plugin.Report) string { + s := r.Verdict + if r.Challenge != "" { s += " (" + r.Challenge + ")" } + if r.Result == nil { return s } + + res := r.Result + + avail := "unavailable" + if res.Available { avail = "AVAILABLE" } + + price := "no price" + if res.Price != nil { price = fmt.Sprintf("%.2f %s", *res.Price, res.Currency) } + + return fmt.Sprintf("%s, %s, %s, seller %s", s, avail, price, res.Seller) +} diff --git a/cmd/dibs/main.go b/cmd/dibs/main.go index 8bcb09d..1f54094 100644 --- a/cmd/dibs/main.go +++ b/cmd/dibs/main.go @@ -12,19 +12,18 @@ import ( "runtime/debug" "git.security-command.org/Overlord/dibs/internal/config" + "git.security-command.org/Overlord/dibs/internal/plugin" ) // version is set at build time with -ldflags "-X main.version=...". var version = "dev" -// builtinPlugins are the plugins embedded in the binary. -var builtinPlugins = []string{"amazon"} - const usage = `Usage: dibs [--config FILE] [--headless] watch items (TUI unless --headless) - dibs check fetch and parse one URL, print JSON - dibs plugin test [url] + dibs check [--shop NAME] fetch and parse one URL, print JSON + dibs plugin test [--status CODE] [url] dibs config validate [--config FILE] + dibs fixtures [--dir testdata] [--only NAME] fetch real pages for the plugin tests dibs version ` @@ -40,9 +39,12 @@ func run(args []string, stdout, stderr io.Writer) int { case "version": printVersion(stdout) return 0 - case "check", "plugin": - _, _ = fmt.Fprintf(stderr, "dibs %s: not implemented yet\n", args[0]) - return 1 + case "check": + return runCheck(args[1:], stdout, stderr) + case "plugin": + return runPlugin(args[1:], stdout, stderr) + case "fixtures": + return runFixtures(args[1:], stdout, stderr) case "help", "-h", "--help": _, _ = fmt.Fprint(stdout, usage) return 0 @@ -112,7 +114,7 @@ func loadConfig(path string, stderr io.Writer) (*config.Config, bool) { } } - cfg, err := config.Load(path, config.Options{Builtins: builtinPlugins}) + cfg, err := config.Load(path, config.Options{Builtins: plugin.Builtins()}) if err != nil { var errs config.Errors switch { @@ -131,6 +133,32 @@ func loadConfig(path string, stderr io.Writer) (*config.Config, bool) { return cfg, true } +// loadOptionalConfig is loadConfig for commands that also work without a +// config: with no --config and no file at the default path it returns nil. +func loadOptionalConfig(path string, stderr io.Writer) (*config.Config, bool) { + if path == "" { + def, err := config.DefaultPath() + if err != nil { return nil, true } + if _, err := os.Stat(def); errors.Is(err, fs.ErrNotExist) { return nil, true } + } + + return loadConfig(path, stderr) +} + +// parseArgs parses flags anywhere among the arguments, so that +// "dibs check URL --shop amazon" works too, and returns the positional ones. +func parseArgs(flags *flag.FlagSet, args []string) ([]string, bool) { + var pos []string + + for { + if err := flags.Parse(args); err != nil { return nil, false } + if flags.NArg() == 0 { return pos, true } + + pos = append(pos, flags.Arg(0)) + args = flags.Args()[1:] + } +} + func printVersion(w io.Writer) { v, rev := version, "" if info, ok := debug.ReadBuildInfo(); ok { diff --git a/go.mod b/go.mod index f52d780..5b279f6 100644 --- a/go.mod +++ b/go.mod @@ -3,9 +3,12 @@ module git.security-command.org/Overlord/dibs go 1.26.0 require ( + github.com/PuerkitoBio/goquery v1.13.0 + github.com/andybalholm/cascadia v1.3.4 github.com/bogdanfinn/fhttp v0.6.9 github.com/bogdanfinn/tls-client v1.16.0 github.com/pelletier/go-toml/v2 v2.4.3 + github.com/yuin/gopher-lua v1.1.2 golang.org/x/net v0.60.0 ) diff --git a/go.sum b/go.sum index 588e974..00c4246 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,9 @@ +github.com/PuerkitoBio/goquery v1.13.0 h1:mqHbjD7Jmnul4DTR24LKTjo1uUmHUh072kteGV+xpFM= +github.com/PuerkitoBio/goquery v1.13.0/go.mod h1:Hip5mdBL8K2wEGKJdr27sRaNwIdDajmCwB/ExUPwW+g= github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ= github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= +github.com/andybalholm/cascadia v1.3.4 h1:vM2lgh0Vru9Vwyfm4cQqWP2HHMW0u0+2PAW7Q38Qufg= +github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM= github.com/bdandy/go-errors v1.2.2 h1:WdFv/oukjTJCLa79UfkGmwX7ZxONAihKu4V0mLIs11Q= github.com/bdandy/go-errors v1.2.2/go.mod h1:NkYHl4Fey9oRRdbB1CoC6e84tuqQHiqrOcZpqFEkBxM= github.com/bdandy/go-socks4 v1.2.3 h1:Q6Y2heY1GRjCtHbmlKfnwrKVU/k81LS8mRGLRlmDlic= @@ -32,6 +36,8 @@ github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 h1:YqAladjX7xpA6BM04leX github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5/go.mod h1:2JjD2zLQYH5HO74y5+aE3remJQvl6q4Sn6aWA2wD1Ng= github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= +github.com/yuin/gopher-lua v1.1.2 h1:yF/FjE3hD65tBbt0VXLE13HWS9h34fdzJmrWRXwobGA= +github.com/yuin/gopher-lua v1.1.2/go.mod h1:7aRmXIWl37SqRf0koeyylBEzJ+aPt8A+mmkQ4f1ntR8= go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= diff --git a/internal/config/config.go b/internal/config/config.go index e33e779..402e46c 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -16,7 +16,10 @@ import ( const MinInterval = 60 * time.Second const ( + // Seller policies for an item: sold by the shop itself; sold or at least + // shipped by it (e.g. Fulfilled by Amazon); or anyone. SellerFirstParty = "first_party" + SellerFulfilled = "fulfilled" SellerAny = "any" CartModeDeeplink = "deeplink" @@ -35,6 +38,10 @@ const ( DefaultSessionTimeout = 5 * time.Minute DefaultMemoryMB = 64 DefaultCallStack = 200 + + // DefaultSeller also accepts marketplace offers the shop ships (such as + // Fulfilled by Amazon), which is how many listings are sold. + DefaultSeller = SellerFulfilled ) type Config struct { @@ -119,6 +126,32 @@ func (d Duration) MarshalText() ([]byte, error) { // IsSet reports whether the value came from the config file. func (d Duration) IsSet() bool { return d.set } +// sellerRanks orders the sellers a plugin reports, from most to least +// trusted. The values match plugin.Seller*. +var sellerRanks = map[string]int{ + "first_party": 0, + "fulfilled": 1, + "third_party": 2, + "unknown": 3, +} + +// policyRanks is the least trusted seller each policy still accepts. +var policyRanks = map[string]int{ + SellerFirstParty: 0, + SellerFulfilled: 1, + SellerAny: 3, +} + +// AcceptsSeller reports whether an offer from seller, as a plugin reports it, +// passes the item's seller policy. The policies are ordered: "fulfilled" +// accepts everything "first_party" does, and "any" accepts every seller. +func (it Item) AcceptsSeller(seller string) bool { + rank, ok := sellerRanks[seller] + if !ok { return false } + + return rank <= policyRanks[it.Seller] +} + // Options control validation that depends on the environment. type Options struct { // Builtins are the names of the embedded plugins. diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 98c2d67..c779fd0 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -21,9 +21,10 @@ seller = "any" interval = "5m" [[item]] -name = "Console" -shop = "mediamarkt" -urls = ["https://www.mediamarkt.de/de/product/_console-123.html"] +name = "Console" +shop = "mediamarkt" +seller = "fulfilled" +urls = ["https://www.mediamarkt.de/de/product/_console-123.html"] [accounts.amazon] username = "me@example.com" @@ -104,6 +105,8 @@ func TestLoadFull(t *testing.T) { if len(cfg.Items) != 2 { t.Fatalf("items: got %d, want 2", len(cfg.Items)) } + + if s := cfg.Items[1].Seller; s != SellerFulfilled { t.Errorf("item[1].seller: got %q, want fulfilled", s) } it := cfg.Items[0] if it.Currency != "EUR" { t.Errorf("currency: got %q, want it uppercased to EUR", it.Currency) @@ -145,7 +148,7 @@ urls = ["https://www.amazon.de/dp/B0HMX2FSTF"] t.Fatal(err) } it := cfg.Items[0] - if it.Seller != SellerFirstParty || it.Interval.Duration != DefaultInterval || it.MaxPrice != nil { + if it.Seller != SellerFulfilled || it.Interval.Duration != DefaultInterval || it.MaxPrice != nil { t.Errorf("item defaults: got %+v", it) } if cfg.Accounts["amazon"].CartMode != CartModeDeeplink { @@ -273,7 +276,7 @@ call_stack = 1 wantErr(t, es, "item[0].urls[0]", 4, "http:// or https://") wantErr(t, es, "item[0].max_price", 5, "positive") wantErr(t, es, "item[0].currency", 6, "ISO 4217") - wantErr(t, es, "item[0].seller", 7, `"first_party" or "any"`) + wantErr(t, es, "item[0].seller", 7, `"first_party", "fulfilled" or "any"`) wantErr(t, es, "item[0].interval", 8, "at least 1m0s") wantErr(t, es, "item[1].urls[0]", 13, "duplicate URL (also item[0].urls[1])") wantErr(t, es, "item[1].fx_margin", 14, "needs both currency and max_price") @@ -334,3 +337,17 @@ func TestErrorFormat(t *testing.T) { t.Errorf("got %q, want %q", got, want) } } + +func TestAcceptsSeller(t *testing.T) { + for policy, want := range map[string]map[string]bool{ + SellerFirstParty: {"first_party": true, "fulfilled": false, "third_party": false, "unknown": false}, + SellerFulfilled: {"first_party": true, "fulfilled": true, "third_party": false, "unknown": false}, + SellerAny: {"first_party": true, "fulfilled": true, "third_party": true, "unknown": true}, + } { + for seller, ok := range want { + if got := (Item{Seller: policy}).AcceptsSeller(seller); got != ok { t.Errorf("policy %s, seller %s: got %v, want %v", policy, seller, got, ok) } + } + + if (Item{Seller: policy}).AcceptsSeller("amazon") { t.Errorf("policy %s accepts an invalid seller", policy) } + } +} diff --git a/internal/config/validate.go b/internal/config/validate.go index 3825042..5a20b9d 100644 --- a/internal/config/validate.go +++ b/internal/config/validate.go @@ -247,10 +247,10 @@ func (v *validator) items(cfg *Config, shops map[string]bool, builtins []string) switch it.Seller { case "": - it.Seller = SellerFirstParty - case SellerFirstParty, SellerAny: + it.Seller = DefaultSeller + case SellerFirstParty, SellerFulfilled, SellerAny: default: - v.errorf(key+".seller", "must be %q or %q (got %q)", SellerFirstParty, SellerAny, it.Seller) + v.errorf(key+".seller", "must be %q, %q or %q (got %q)", SellerFirstParty, SellerFulfilled, SellerAny, it.Seller) } switch { diff --git a/internal/fetch/client.go b/internal/fetch/client.go index 765f08c..f127af8 100644 --- a/internal/fetch/client.go +++ b/internal/fetch/client.go @@ -102,15 +102,25 @@ func (c *Client) Get(ctx context.Context, rawURL string) (*Response, error) { if err != nil { return nil, fmt.Errorf("reading body: %w", err) } if int64(len(data)) > c.maxBody { return nil, fmt.Errorf("%w: more than %d bytes", ErrBodyTooLarge, c.maxBody) } - r := &Response{ - URL: rawURL, - FinalURL: resp.Request.URL.String(), - Status: resp.StatusCode, - Header: stdhttp.Header(resp.Header), - Body: data, - Elapsed: time.Since(start), - } - r.Verdict, r.Challenge = classify(r.Status, r.Header, r.FinalURL, r.Body) + r := NewResponse(rawURL, resp.Request.URL.String(), resp.StatusCode, stdhttp.Header(resp.Header), data) + r.Elapsed = time.Since(start) return r, nil } + +// NewResponse builds and classifies a Response for a page obtained another +// way, such as a saved fixture or the browser fallback. +func NewResponse(rawURL, finalURL string, status int, header stdhttp.Header, body []byte) *Response { + if header == nil { header = stdhttp.Header{} } + + r := &Response{ + URL: rawURL, + FinalURL: finalURL, + Status: status, + Header: header, + Body: body, + } + r.Verdict, r.Challenge = classify(r.Status, r.Header, r.FinalURL, r.Body) + + return r +} diff --git a/internal/fixtures/fixtures.go b/internal/fixtures/fixtures.go new file mode 100644 index 0000000..519e9b1 --- /dev/null +++ b/internal/fixtures/fixtures.go @@ -0,0 +1,104 @@ +// Package fixtures manages the real product pages the plugin tests run on. +// +// Which pages to use is tracked, in testdata//cases.toml. The pages +// themselves change over time and may contain personal data, so they are +// not tracked: `dibs fixtures` fetches them into testdata//pages/, +// next to the report dibs produced for each. The tests then check that the +// plugin still reads every saved page the same way. +package fixtures + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "path/filepath" + "regexp" + + "github.com/pelletier/go-toml/v2" +) + +// Case is one page to test with. +type Case struct { + Name string `toml:"name"` + URL string `toml:"url"` + // Note says what the page is for, e.g. "only a used offer". + Note string `toml:"note"` +} + +// Suite is the cases of one shop. +type Suite struct { + // Shop is the plugin to use, named after the directory. + Shop string + Dir string + Cases []Case +} + +var nameRe = regexp.MustCompile(`^[a-z0-9-]+$`) + +// Load reads every dir//cases.toml. +func Load(dir string) ([]Suite, error) { + files, err := filepath.Glob(filepath.Join(dir, "*", "cases.toml")) + if err != nil { return nil, err } + + var suites []Suite + + for _, f := range files { + data, err := os.ReadFile(f) + if err != nil { return nil, err } + + var doc struct { + Cases []Case `toml:"case"` + } + + dec := toml.NewDecoder(bytes.NewReader(data)) + dec.DisallowUnknownFields() + if err := dec.Decode(&doc); err != nil { return nil, fmt.Errorf("%s: %w", f, err) } + + seen := map[string]bool{} + for _, c := range doc.Cases { + switch { + case !nameRe.MatchString(c.Name): + return nil, fmt.Errorf("%s: case name %q must contain only a-z, 0-9 and -", f, c.Name) + case seen[c.Name]: + return nil, fmt.Errorf("%s: duplicate case %q", f, c.Name) + case c.URL == "": + return nil, fmt.Errorf("%s: case %q has no url", f, c.Name) + } + + seen[c.Name] = true + } + + suiteDir := filepath.Dir(f) + suites = append(suites, Suite{Shop: filepath.Base(suiteDir), Dir: suiteDir, Cases: doc.Cases}) + } + + return suites, nil +} + +func (s Suite) PagePath(c Case) string { return filepath.Join(s.Dir, "pages", c.Name+".html") } +func (s Suite) ReportPath(c Case) string { return filepath.Join(s.Dir, "pages", c.Name+".json") } + +// Save writes a fetched page and its report. +func (s Suite) Save(c Case, page []byte, report any) error { + data, err := EncodeReport(report) + if err != nil { return err } + + if err := os.MkdirAll(filepath.Join(s.Dir, "pages"), 0o700); err != nil { return err } + if err := os.WriteFile(s.PagePath(c), page, 0o600); err != nil { return err } + + return os.WriteFile(s.ReportPath(c), data, 0o600) +} + +// EncodeReport is the one way reports are written, so saved and fresh ones +// compare byte for byte. +func EncodeReport(report any) ([]byte, error) { + var b bytes.Buffer + + enc := json.NewEncoder(&b) + enc.SetIndent("", " ") + enc.SetEscapeHTML(false) + if err := enc.Encode(report); err != nil { return nil, err } + + return b.Bytes(), nil +} diff --git a/internal/plugin/builtin/amazon.lua b/internal/plugin/builtin/amazon.lua new file mode 100644 index 0000000..a157cf8 --- /dev/null +++ b/internal/plugin/builtin/amazon.lua @@ -0,0 +1,208 @@ +-- Built-in plugin for Amazon product pages (de, co.uk, fr, it, es, nl, com). +-- +-- It uses only the public plugin API, so it doubles as the reference for +-- writing your own: see "Writing a plugin" in README.md. + +local tlds = { + ["de"] = "EUR", + ["fr"] = "EUR", + ["it"] = "EUR", + ["es"] = "EUR", + ["nl"] = "EUR", + ["co.uk"] = "GBP", + ["com"] = "USD", +} + +-- Amazon's own merchant IDs. A page sold by Amazon carries one of them in +-- the buybox form. +local amazon_merchants = { + A3JWKAKR8XB7XF = true, -- amazon.de + A3P5ROKL5A1OLE = true, -- amazon.co.uk + A1X6FK5RDHNB96 = true, -- amazon.fr + A11IL2PNWYJU7H = true, -- amazon.it + A1AT7YVPFBWXBL = true, -- amazon.es + A17D2BRD4YMT0X = true, -- amazon.nl + ATVPDKIKX0DER = true, -- amazon.com +} + +-- Any of these buttons means a new item can go into the cart. The preorder +-- selectors are a best guess until we have a real preorder page. +-- "#add-to-cart-button-ubb" is deliberately missing: it belongs to the used +-- buybox, which Amazon shows when only used copies are left. +local buy_buttons = table.concat({ + "#add-to-cart-button", + "#buy-now-button", + "input[name='submit.add-to-cart']", + "input[name='submit.buy-now']", + "input[name='submit.preorder']", + "#preorder-button", +}, ", ") + +-- Where Amazon says an item can't be bought. +local availability_area = { "#availability", "#outOfStock", "#buybox" } + +local unavailable_phrases = { + "currently unavailable", + "derzeit nicht verfügbar", + "actuellement indisponible", + "non disponibile", + "no disponible", + "momenteel niet verkrijgbaar", +} + +-- Older layouts say who sells and ships the item in one sentence, such as +-- "Versand und Verkauf durch Amazon." or "Verkauf durch X und Versand durch +-- Amazon." +local sold_by_amazon_phrases = { + "sold by amazon", + "verkauf durch amazon", + "vendu par amazon", + "venduto da amazon", + "venduto e spedito da amazon", + "vendido por amazon", + "vendido y enviado por amazon", + "verkocht door amazon", +} + +local shipped_by_amazon_phrases = { + "fulfilled by amazon", + "ships from amazon", + "dispatched from amazon", + "versand durch amazon", + "expédié par amazon", + "spedito da amazon", + "enviado por amazon", + "verzonden door amazon", +} + +local price_selectors = { + "#corePrice_feature_div .a-price .a-offscreen", + "#corePriceDisplay_desktop_feature_div .priceToPay .a-offscreen", + "#apex_desktop .priceToPay .a-offscreen", + ".priceToPay .a-offscreen", + "#price_inside_buybox", + "#priceblock_ourprice", + "#priceblock_dealprice", +} + +-- split returns the TLD and ASIN of an Amazon product URL, or nil. +local function split(url) + local host = url:match("^[Hh][Tt][Tt][Pp][Ss]?://([^/?#]+)") + if not host then return nil end + + local tld = host:lower():match("^www%.amazon%.(.+)$") or host:lower():match("^amazon%.(.+)$") + if not tld or not tlds[tld] then return nil end + + local m = regex_match(url, "(?i)/(?:dp|gp/product|gp/aw/d|exec/obidos/asin)/([a-z0-9]{10})(?:[/?#]|$)") + if not m then return nil end + + return tld, m[1]:upper() +end + +-- Amazon itself appears as "Amazon", "Amazon.de", "Amazon EU S.à r.l." and +-- similar. Shops called "Amazonas Games" must not count. +local function is_amazon(name) + if not name then return false end + + local n = name:lower():gsub("^%s+", ""):gsub("[%s%.]+$", "") + return n == "amazon" or n:match("^amazon%.[%a%.]+$") ~= nil or n:match("^amazon eu") ~= nil or n:match("^amazon media eu") ~= nil +end + +local function legacy_merchant_info(doc) + return doc:text("#merchant-info") or doc:text("#merchantInfoFeature_feature_div") +end + +-- sold_by_amazon is true or false when the page says who sells the item, and +-- nil when it doesn't, e.g. when there is no offer at all. +local function sold_by_amazon(doc) + -- The buybox form names the merchant whose offer the buttons buy. + local id = doc:attr("input#merchantID, input[name='merchantID']", "value") + if id and id ~= "" then return amazon_merchants[id] == true end + + -- Newer layout: a "Verkäufer" / "Sold by" row. + local name = doc:text("#merchantInfoFeature_feature_div .offer-display-feature-text-message") + if name then return is_amazon(name) end + + local info = legacy_merchant_info(doc) + if info then return contains_any(info, sold_by_amazon_phrases) end + + if doc:exists("#sellerProfileTriggerId") then return false end + + return nil +end + +local function shipped_by_amazon(doc) + -- Newer layout: a "Versand" / "Ships from" row. + local name = doc:text("#fulfillerInfoFeature_feature_div .offer-display-feature-text-message") + if name then return is_amazon(name) end + + return contains_any(legacy_merchant_info(doc), shipped_by_amazon_phrases) +end + +local function seller(doc) + local sold = sold_by_amazon(doc) + + if sold == nil then return "unknown" end + if sold then return "first_party" end + if shipped_by_amazon(doc) then return "fulfilled" end + + return "third_party" +end + +local function unavailable(doc) + for _, sel in ipairs(availability_area) do + if contains_any(doc:text(sel), unavailable_phrases) then return true end + end + + return false +end + +local function find_price(doc) + for _, sel in ipairs(price_selectors) do + local value, currency = parse_price(doc:text(sel)) + if value then return value, currency end + end + + return nil +end + +return { + name = "amazon", + + matches = function(url) + return split(url) ~= nil + end, + + -- Every variant of a product URL becomes https://www.amazon./dp/, + -- so the same item is never watched twice. + normalize = function(url) + local tld, asin = split(url) + if not tld then return url end + + return "https://www.amazon." .. tld .. "/dp/" .. asin + end, + + parse = function(doc, url) + local tld, asin = split(url) + local title = doc:text("#productTitle") + local value, currency = find_price(doc) + + return { + title = title, + -- A dog page or a search result has no product title, so it is + -- never available. + available = title ~= nil and doc:exists(buy_buttons) and not unavailable(doc), + price = value, + currency = currency or (tld and tlds[tld]), + seller = seller(doc), + id = asin, + } + end, + + cart_link = function(url, id) + local tld, asin = split(url) + if not tld then return nil end + + return "https://www.amazon." .. tld .. "/gp/aws/cart/add.html?ASIN.1=" .. (id or asin) .. "&Quantity.1=1" + end, +} diff --git a/internal/plugin/doc.go b/internal/plugin/doc.go new file mode 100644 index 0000000..da3cb7e --- /dev/null +++ b/internal/plugin/doc.go @@ -0,0 +1,168 @@ +package plugin + +import ( + "strings" + "sync" + + "github.com/PuerkitoBio/goquery" + "github.com/andybalholm/cascadia" + lua "github.com/yuin/gopher-lua" + "golang.org/x/net/html" +) + +const nodeType = "dibs.node" + +// The methods of doc and of the nodes doc:all() returns. Each takes an +// optional CSS selector: without one it works on the node itself, with one +// on the first match inside it. +var nodeMethods = map[string]lua.LGFunction{ + "text": nodeText, + "attr": nodeAttr, + "exists": nodeExists, + "count": nodeCount, + "html": nodeHTML, + "all": nodeAll, +} + +func registerNode(L *lua.LState) { + mt := L.NewTypeMetatable(nodeType) + L.SetField(mt, "__index", L.SetFuncs(L.NewTable(), nodeMethods)) +} + +func pushNode(L *lua.LState, sel *goquery.Selection) lua.LValue { + ud := L.NewUserData() + ud.Value = sel + L.SetMetatable(ud, L.GetTypeMetatable(nodeType)) + + return ud +} + +func checkNode(L *lua.LState) *goquery.Selection { + if ud, ok := L.Get(1).(*lua.LUserData); ok { + if sel, ok := ud.Value.(*goquery.Selection); ok { return sel } + } + + L.ArgError(1, "node expected (call methods with a colon, as in doc:text(...))") + return nil +} + +// target is the node itself, or what the selector in argument arg matches +// inside it. +func target(L *lua.LState, node *goquery.Selection, arg int) *goquery.Selection { + if L.GetTop() < arg || L.Get(arg) == lua.LNil { return node } + + return node.FindMatcher(selector(L, arg)) +} + +var selectors sync.Map // string -> cascadia.Selector + +func selector(L *lua.LState, arg int) cascadia.Selector { + src := L.CheckString(arg) + if s, ok := selectors.Load(src); ok { return s.(cascadia.Selector) } + + s, err := cascadia.Compile(src) + if err != nil { + L.ArgError(arg, "invalid selector "+src+": "+err.Error()) + return nil + } + + selectors.Store(src, s) + return s +} + +// node:text([sel]) is the visible text of the node or its first match, with +// whitespace collapsed. It is nil if nothing matches or the text is empty, +// so `if doc:text(sel) then` means "has text". Use exists to test presence. +func nodeText(L *lua.LState) int { + s := target(L, checkNode(L), 2).First() + + text := "" + if s.Length() > 0 { text = visibleText(s) } + + if text == "" { L.Push(lua.LNil) } else { L.Push(lua.LString(text)) } + return 1 +} + +// node:attr(name) or node:attr(sel, name) is an attribute value, or nil. +func nodeAttr(L *lua.LState) int { + node := checkNode(L) + + s, name := node, L.CheckString(2) + if L.GetTop() >= 3 { s, name = target(L, node, 2), L.CheckString(3) } + + if v, ok := s.First().Attr(name); ok { L.Push(lua.LString(v)) } else { L.Push(lua.LNil) } + return 1 +} + +// node:exists(sel) reports whether sel matches anything. +func nodeExists(L *lua.LState) int { + L.Push(lua.LBool(checkNode(L).FindMatcher(selector(L, 2)).Length() > 0)) + return 1 +} + +// node:count(sel) is the number of matches. +func nodeCount(L *lua.LState) int { + L.Push(lua.LNumber(checkNode(L).FindMatcher(selector(L, 2)).Length())) + return 1 +} + +// node:html([sel]) is the outer HTML of the node or its first match, or nil. +func nodeHTML(L *lua.LState) int { + s := target(L, checkNode(L), 2).First() + if s.Length() == 0 { + L.Push(lua.LNil) + return 1 + } + + out, err := goquery.OuterHtml(s) + if err != nil { L.RaiseError("html: %v", err) } + + L.Push(lua.LString(out)) + return 1 +} + +// node:all(sel) is a list of nodes, one per match. +func nodeAll(L *lua.LState) int { + t := L.NewTable() + checkNode(L).FindMatcher(selector(L, 2)).Each(func(_ int, s *goquery.Selection) { t.Append(pushNode(L, s)) }) + + L.Push(t) + return 1 +} + +// hiddenElements never contribute visible text. Amazon puts large inline +// scripts inside its availability block, for example. +var hiddenElements = map[string]bool{"script": true, "style": true, "noscript": true, "template": true} + +// inlineElements run into the text around them. Other elements are +// separated by a space, so "
  • a
  • b
  • " reads "a b". +var inlineElements = map[string]bool{ + "a": true, "abbr": true, "b": true, "bdi": true, "bdo": true, "cite": true, "code": true, "data": true, + "em": true, "i": true, "kbd": true, "mark": true, "q": true, "s": true, "small": true, "span": true, + "strong": true, "sub": true, "sup": true, "time": true, "u": true, "var": true, +} + +func visibleText(s *goquery.Selection) string { + var b strings.Builder + for _, n := range s.Nodes { writeText(&b, n) } + + return strings.Join(strings.Fields(b.String()), " ") +} + +func writeText(b *strings.Builder, n *html.Node) { + switch n.Type { + case html.TextNode: + b.WriteString(n.Data) + case html.ElementNode: + if hiddenElements[n.Data] { return } + + block := !inlineElements[n.Data] + if block { b.WriteByte(' ') } + for c := n.FirstChild; c != nil; c = c.NextSibling { writeText(b, c) } + if block { b.WriteByte(' ') } + case html.DocumentNode: + for c := n.FirstChild; c != nil; c = c.NextSibling { writeText(b, c) } + default: + // Comments and doctypes have no visible text. + } +} diff --git a/internal/plugin/helpers.go b/internal/plugin/helpers.go new file mode 100644 index 0000000..953557e --- /dev/null +++ b/internal/plugin/helpers.go @@ -0,0 +1,107 @@ +package plugin + +import ( + "log/slog" + "regexp" + "strings" + "sync" + + lua "github.com/yuin/gopher-lua" + + "git.security-command.org/Overlord/dibs/internal/price" +) + +func registerHelpers(L *lua.LState, logger *slog.Logger) { + logFn := L.NewFunction(func(L *lua.LState) int { + parts := make([]string, L.GetTop()) + for i := range parts { parts[i] = L.ToStringMeta(L.Get(i + 1)).String() } + + logger.Info(strings.Join(parts, " ")) + return 0 + }) + + L.SetGlobal("log", logFn) + L.SetGlobal("print", logFn) + L.SetGlobal("contains_any", L.NewFunction(containsAny)) + L.SetGlobal("parse_price", L.NewFunction(parsePrice)) + L.SetGlobal("regex_match", L.NewFunction(regexMatch)) +} + +// contains_any(str, {phrases}) reports whether str contains any of the +// phrases, ignoring case. A nil str contains nothing. +func containsAny(L *lua.LState) int { + phrases := L.CheckTable(2) + if L.Get(1) == lua.LNil { + L.Push(lua.LFalse) + return 1 + } + + s := strings.ToLower(L.CheckString(1)) + found := false + + phrases.ForEach(func(_, v lua.LValue) { + if p, ok := v.(lua.LString); ok && !found && strings.Contains(s, strings.ToLower(string(p))) { found = true } + }) + + L.Push(lua.LBool(found)) + return 1 +} + +// parse_price(str) returns the price in str and its currency code (or nil), +// or nil if str holds no price. +func parsePrice(L *lua.LState) int { + if L.Get(1) == lua.LNil { + L.Push(lua.LNil) + return 1 + } + + v, cur, ok := price.Parse(L.CheckString(1)) + if !ok { + L.Push(lua.LNil) + return 1 + } + + L.Push(lua.LNumber(v)) + if cur != "" { L.Push(lua.LString(cur)) } else { L.Push(lua.LNil) } + return 2 +} + +var regexps sync.Map // string -> *regexp.Regexp + +// regex_match(str, pattern) matches a Go (RE2) regular expression. It +// returns a list of the capture groups, or of the whole match if the +// pattern has no groups, or nil if it does not match. +func regexMatch(L *lua.LState) int { + pattern := L.CheckString(2) + if L.Get(1) == lua.LNil { + L.Push(lua.LNil) + return 1 + } + + s := L.CheckString(1) + + var re *regexp.Regexp + if cached, ok := regexps.Load(pattern); ok { + re = cached.(*regexp.Regexp) + } else { + compiled, err := regexp.Compile(pattern) + if err != nil { L.ArgError(2, "invalid pattern: "+err.Error()) } + + re = compiled + regexps.Store(pattern, re) + } + + m := re.FindStringSubmatch(s) + if m == nil { + L.Push(lua.LNil) + return 1 + } + + if len(m) > 1 { m = m[1:] } + + t := L.NewTable() + for _, g := range m { t.Append(lua.LString(g)) } + + L.Push(t) + return 1 +} diff --git a/internal/plugin/host.go b/internal/plugin/host.go new file mode 100644 index 0000000..127699f --- /dev/null +++ b/internal/plugin/host.go @@ -0,0 +1,165 @@ +package plugin + +import ( + "context" + "embed" + "errors" + "fmt" + "io/fs" + "log/slog" + "maps" + "os" + "slices" + "strings" + + "git.security-command.org/Overlord/dibs/internal/fetch" +) + +//go:embed builtin/*.lua +var builtinFS embed.FS + +// ErrNoPlugin is returned when no plugin matches a URL. +var ErrNoPlugin = errors.New("no plugin matches the URL") + +// Builtins returns the names of the embedded plugins. +func Builtins() []string { + files, _ := fs.Glob(builtinFS, "builtin/*.lua") + + names := make([]string, len(files)) + for i, f := range files { names[i] = strings.TrimSuffix(strings.TrimPrefix(f, "builtin/"), ".lua") } + + return names +} + +// BuiltinSource returns the code of an embedded plugin. +func BuiltinSource(name string) ([]byte, error) { + return builtinFS.ReadFile("builtin/" + name + ".lua") +} + +// Host holds the loaded plugins. +type Host struct { + plugins map[string]*Plugin + // order is the order ForURL tries plugins in: user plugins first, so + // they win over built-ins they don't replace. + order []string +} + +// NewHost loads the built-in plugins and the user's (name -> file). A user +// plugin replaces a built-in one of the same name. +func NewHost(user map[string]string, limits Limits, logger *slog.Logger) (*Host, error) { + h := &Host{plugins: map[string]*Plugin{}} + + var errs []error + + for _, name := range slices.Sorted(maps.Keys(user)) { + code, err := os.ReadFile(user[name]) + if err != nil { + errs = append(errs, fmt.Errorf("plugin %s: %w", name, err)) + continue + } + + p, err := Load(name, user[name], code, limits, logger) + if err != nil { + errs = append(errs, err) + continue + } + + h.plugins[name] = p + h.order = append(h.order, name) + } + + for _, name := range Builtins() { + if _, replaced := user[name]; replaced { continue } + + code, err := BuiltinSource(name) + if err == nil { + var p *Plugin + if p, err = Load(name, "built-in", code, limits, logger); err == nil { + h.plugins[name] = p + h.order = append(h.order, name) + continue + } + } + + errs = append(errs, err) + } + + if len(errs) > 0 { + h.Close() + return nil, errors.Join(errs...) + } + + return h, nil +} + +// Plugin returns the plugin called name. +func (h *Host) Plugin(name string) (*Plugin, bool) { + p, ok := h.plugins[name] + return p, ok +} + +// ForURL returns the first plugin whose matches(url) is true. +func (h *Host) ForURL(ctx context.Context, url string) (*Plugin, error) { + for _, name := range h.order { + p := h.plugins[name] + + ok, err := p.Matches(ctx, url) + if err != nil { return nil, err } + if ok { return p, nil } + } + + return nil, ErrNoPlugin +} + +func (h *Host) Close() { + for _, p := range h.plugins { p.Close() } +} + +// Report is the outcome of checking one URL, as `dibs check` prints it. +type Report struct { + URL string `json:"url"` + FetchURL string `json:"fetch_url"` + FinalURL string `json:"final_url"` + Shop string `json:"shop"` + Status int `json:"status"` + Verdict string `json:"verdict"` + Challenge string `json:"challenge,omitempty"` + Result *Result `json:"result,omitempty"` + CartLink string `json:"cart_link,omitempty"` + ElapsedMS int64 `json:"elapsed_ms"` +} + +// Evaluate turns a fetched page into a Report. Only pages with the OK +// verdict are parsed. A NotFound page is reported as unavailable without +// asking the plugin, and bot checks and errors have no result. +func Evaluate(ctx context.Context, p *Plugin, rawURL string, resp *fetch.Response) (*Report, error) { + r := &Report{ + URL: rawURL, + FetchURL: resp.URL, + FinalURL: resp.FinalURL, + Shop: p.Name, + Status: resp.Status, + Verdict: resp.Verdict.String(), + Challenge: resp.Challenge, + ElapsedMS: resp.Elapsed.Milliseconds(), + } + + switch resp.Verdict { + case fetch.OK: + res, err := p.Parse(ctx, resp.Body, resp.URL) + if err != nil { return r, err } + + r.Result = res + + link, err := p.CartLink(ctx, resp.URL, res.ID) + if err != nil { return r, err } + + r.CartLink = link + case fetch.NotFound: + r.Result = &Result{Seller: SellerUnknown} + default: + // Challenge, Blocked or HTTPError: nothing to read. + } + + return r, nil +} diff --git a/internal/plugin/pages_test.go b/internal/plugin/pages_test.go new file mode 100644 index 0000000..f61ff8e --- /dev/null +++ b/internal/plugin/pages_test.go @@ -0,0 +1,100 @@ +package plugin + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "io/fs" + "log/slog" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/pelletier/go-toml/v2" + + "git.security-command.org/Overlord/dibs/internal/fetch" + "git.security-command.org/Overlord/dibs/internal/fixtures" +) + +// testdata is the repository's top-level testdata directory. +var testdata = filepath.Join("..", "..", "testdata") + +func discardLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } + +func builtin(t *testing.T, name string) *Plugin { + t.Helper() + + code, err := BuiltinSource(name) + if err != nil { t.Fatal(err) } + + p, err := Load(name, "built-in", code, DefaultLimits(), discardLogger()) + if err != nil { t.Fatal(err) } + t.Cleanup(p.Close) + + return p +} + +// TestSavedPages re-reads every page `dibs fixtures` saved and checks the +// plugin still reports what it reported when the page was fetched. +func TestSavedPages(t *testing.T) { + suites, err := fixtures.Load(testdata) + if err != nil { t.Fatal(err) } + + ran := 0 + + for _, suite := range suites { + if !slices.Contains(Builtins(), suite.Shop) { continue } + + p := builtin(t, suite.Shop) + + for _, c := range suite.Cases { + page, err := os.ReadFile(suite.PagePath(c)) + if errors.Is(err, fs.ErrNotExist) { continue } + if err != nil { t.Fatal(err) } + + ran++ + + t.Run(suite.Shop+"/"+c.Name, func(t *testing.T) { + want, err := os.ReadFile(suite.ReportPath(c)) + if err != nil { t.Fatal(err) } + + var saved Report + if err := json.Unmarshal(want, &saved); err != nil { t.Fatal(err) } + + report, err := Evaluate(context.Background(), p, saved.URL, fetch.NewResponse(saved.FetchURL, saved.FinalURL, saved.Status, nil, page)) + if err != nil { t.Fatal(err) } + + got, err := fixtures.EncodeReport(report) + if err != nil { t.Fatal(err) } + + if !bytes.Equal(got, want) { t.Errorf("%s (%s) now reads differently.\ngot:\n%s\nsaved:\n%s", c.Name, c.Note, got, want) } + }) + } + } + + if ran == 0 { t.Skip("no saved pages: run `dibs fixtures` to fetch them") } +} + +func TestAmazonNormalize(t *testing.T) { + data, err := os.ReadFile(filepath.Join(testdata, "amazon", "urls.toml")) + if err != nil { t.Fatal(err) } + + var urls struct { + Normalize []struct { + In string `toml:"in"` + Out string `toml:"out"` + } `toml:"normalize"` + } + if err := toml.Unmarshal(data, &urls); err != nil { t.Fatal(err) } + + p := builtin(t, "amazon") + + for _, u := range urls.Normalize { + got, err := p.Normalize(context.Background(), u.In) + if err != nil { t.Fatal(err) } + if got != u.Out { t.Errorf("normalize(%q) = %q, want %q", u.In, got, u.Out) } + } +} diff --git a/internal/plugin/plugin.go b/internal/plugin/plugin.go new file mode 100644 index 0000000..7e0c470 --- /dev/null +++ b/internal/plugin/plugin.go @@ -0,0 +1,363 @@ +// Package plugin runs shop plugins: sandboxed Lua files that read product +// pages. +package plugin + +import ( + "bytes" + "context" + "errors" + "fmt" + "log/slog" + "math" + "path/filepath" + "regexp" + "slices" + "strings" + "sync" + + "github.com/PuerkitoBio/goquery" + lua "github.com/yuin/gopher-lua" +) + +// Who sells the item, as parse reports it. +const ( + // SellerFirstParty: the shop itself sells it. + SellerFirstParty = "first_party" + // SellerFulfilled: a marketplace seller sells it, but the shop ships it + // (e.g. Fulfilled by Amazon). + SellerFulfilled = "fulfilled" + // SellerThirdParty: a marketplace seller sells and ships it. + SellerThirdParty = "third_party" + SellerUnknown = "unknown" +) + +// Result is what a plugin's parse function read from a page. +type Result struct { + Title string `json:"title,omitempty"` + Available bool `json:"available"` + Price *float64 `json:"price"` + Currency string `json:"currency,omitempty"` + Seller string `json:"seller"` + // ID is the shop's product ID, such as an ASIN. It is passed to + // cart_link. + ID string `json:"id,omitempty"` +} + +// hooks are the functions a plugin table may define. Only parse is required. +var hooks = []string{"matches", "normalize", "parse", "cart_link", "login", "add_to_cart"} + +var currencyRe = regexp.MustCompile(`^[A-Z]{3}$`) + +// Plugin is a loaded plugin. It is safe for concurrent use; calls into one +// plugin run one at a time. +type Plugin struct { + Name string + // Source is the plugin's file, or "built-in". + Source string + + chunk string + code []byte + limits Limits + logger *slog.Logger + nameFixed bool // the name came from the config, not the table + + mu sync.Mutex + state *lua.LState + funcs map[string]*lua.LFunction +} + +// Load runs a plugin's code and checks the table it returns. An empty name +// takes the name from the table, or else from the file name. +func Load(name, source string, code []byte, limits Limits, logger *slog.Logger) (*Plugin, error) { + chunk := filepath.Base(source) + if source == "built-in" { chunk = name + ".lua" } + + p := &Plugin{ + Name: name, + Source: source, + chunk: chunk, + code: code, + limits: limits, + logger: logger, + nameFixed: name != "", + } + if !p.nameFixed { p.Name = strings.TrimSuffix(chunk, ".lua") } + + shortCalls.Lock() + defer shortCalls.Unlock() + + if err := p.reset(); err != nil { return nil, fmt.Errorf("plugin %s (%s): %w", name, source, err) } + + return p, nil +} + +// reset loads the plugin into a fresh Lua state. Callers hold shortCalls. +func (p *Plugin) reset() error { + if p.state != nil { + p.state.Close() + p.state = nil + } + + L := newState(p.limits) + registerNode(L) + registerHelpers(L, p.logger.With("plugin", p.Name)) + + fn, err := L.Load(bytes.NewReader(p.code), p.chunk) + if err != nil { + L.Close() + return luaError(err) + } + + var tbl *lua.LTable + + err = run(L, context.Background(), p.limits.Timeout, p.limits.MemoryBytes, func() error { + if err := L.CallByParam(lua.P{Fn: fn, NRet: 1, Protect: true}); err != nil { return err } + + ret := L.Get(-1) + L.Pop(1) + + t, ok := ret.(*lua.LTable) + if !ok { return fmt.Errorf("must return a table, got %s", ret.Type()) } + + tbl = t + return nil + }) + if err == nil { err = p.readTable(tbl) } + if err != nil { + L.Close() + return err + } + + p.state = L + return nil +} + +// readTable checks the plugin table and picks up its functions. +func (p *Plugin) readTable(tbl *lua.LTable) error { + var problems []string + + funcs := map[string]*lua.LFunction{} + + tbl.ForEach(func(k, v lua.LValue) { + key := k.String() + + switch { + case key == "name": + s, ok := v.(lua.LString) + switch { + case !ok || s == "": + problems = append(problems, fmt.Sprintf("name must be a non-empty string, got %s", v.Type())) + case !p.nameFixed: + p.Name = string(s) + case string(s) != p.Name: + problems = append(problems, fmt.Sprintf("name is %q, but the plugin is configured as %q", s, p.Name)) + } + case slices.Contains(hooks, key): + if fn, ok := v.(*lua.LFunction); ok { funcs[key] = fn } else { problems = append(problems, fmt.Sprintf("%s must be a function, got %s", key, v.Type())) } + default: + problems = append(problems, fmt.Sprintf("unknown key %q (known: name, %s)", key, strings.Join(hooks, ", "))) + } + }) + + if funcs["parse"] == nil && !slices.ContainsFunc(problems, func(s string) bool { return strings.HasPrefix(s, "parse ") }) { + problems = append(problems, "parse function is missing") + } + + if len(problems) > 0 { + slices.Sort(problems) + return errors.New(strings.Join(problems, "; ")) + } + + p.funcs = funcs + return nil +} + +// Has reports whether the plugin defines hook. +func (p *Plugin) Has(hook string) bool { + p.mu.Lock() + defer p.mu.Unlock() + + return p.funcs[hook] != nil +} + +// call runs a short hook, one of matches, normalize, parse and cart_link. +// args builds the arguments in the plugin's Lua state. +func (p *Plugin) call(ctx context.Context, hook string, nret int, args func(L *lua.LState) []lua.LValue) ([]lua.LValue, error) { + p.mu.Lock() + defer p.mu.Unlock() + + shortCalls.Lock() + defer shortCalls.Unlock() + + // An earlier call was killed and reloading failed. + if p.state == nil { + if err := p.reset(); err != nil { return nil, fmt.Errorf("plugin %s: %w", p.Name, err) } + } + + L := p.state + + var out []lua.LValue + + err := run(L, ctx, p.limits.Timeout, p.limits.MemoryBytes, func() error { + if err := L.CallByParam(lua.P{Fn: p.funcs[hook], NRet: nret, Protect: true}, args(L)...); err != nil { return err } + + for i := nret; i > 0; i-- { out = append(out, L.Get(-i)) } + L.Pop(nret) + + return nil + }) + + // A killed call can stop anywhere, so start over with a clean state. + if errors.Is(err, ErrTimeout) || errors.Is(err, ErrMemoryLimit) { + if rerr := p.reset(); rerr != nil { p.logger.Error("reloading plugin failed", "plugin", p.Name, "err", rerr) } + } + + if err != nil { return nil, fmt.Errorf("plugin %s: %s: %w", p.Name, hook, err) } + + return out, nil +} + +// Matches runs matches(url). A plugin without it matches nothing. +func (p *Plugin) Matches(ctx context.Context, url string) (bool, error) { + if !p.Has("matches") { return false, nil } + + out, err := p.call(ctx, "matches", 1, func(*lua.LState) []lua.LValue { return []lua.LValue{lua.LString(url)} }) + if err != nil { return false, err } + + return lua.LVAsBool(out[0]), nil +} + +// Normalize runs normalize(url). Without it, or if it returns nil, the URL +// stays as it is. +func (p *Plugin) Normalize(ctx context.Context, url string) (string, error) { + if !p.Has("normalize") { return url, nil } + + out, err := p.call(ctx, "normalize", 1, func(*lua.LState) []lua.LValue { return []lua.LValue{lua.LString(url)} }) + if err != nil { return "", err } + + switch v := out[0].(type) { + case lua.LString: + return string(v), nil + case *lua.LNilType: + return url, nil + default: + return "", fmt.Errorf("plugin %s: normalize must return a string, got %s", p.Name, v.Type()) + } +} + +// Parse runs parse(doc, url) on a page. +func (p *Plugin) Parse(ctx context.Context, page []byte, url string) (*Result, error) { + // Parse the HTML before the call, so it does not count against the + // call's time and memory. + doc, err := goquery.NewDocumentFromReader(bytes.NewReader(page)) + if err != nil { return nil, fmt.Errorf("parsing HTML: %w", err) } + + out, err := p.call(ctx, "parse", 1, func(L *lua.LState) []lua.LValue { return []lua.LValue{pushNode(L, doc.Selection), lua.LString(url)} }) + if err != nil { return nil, err } + + r, err := toResult(out[0]) + if err != nil { return nil, fmt.Errorf("plugin %s: parse: %w", p.Name, err) } + + return r, nil +} + +// CartLink runs cart_link(url, id). It returns "" if the plugin has no +// cart_link or it returns nil. +func (p *Plugin) CartLink(ctx context.Context, url, id string) (string, error) { + if !p.Has("cart_link") { return "", nil } + + out, err := p.call(ctx, "cart_link", 1, func(*lua.LState) []lua.LValue { + idArg := lua.LValue(lua.LNil) + if id != "" { idArg = lua.LString(id) } + + return []lua.LValue{lua.LString(url), idArg} + }) + if err != nil { return "", err } + + switch v := out[0].(type) { + case lua.LString: + return string(v), nil + case *lua.LNilType: + return "", nil + default: + return "", fmt.Errorf("plugin %s: cart_link must return a string, got %s", p.Name, v.Type()) + } +} + +// Close frees the Lua state. +func (p *Plugin) Close() { + p.mu.Lock() + defer p.mu.Unlock() + + if p.state != nil { + p.state.Close() + p.state = nil + } +} + +// toResult checks parse's return value field by field. +func toResult(v lua.LValue) (*Result, error) { + t, ok := v.(*lua.LTable) + if !ok { return nil, fmt.Errorf("must return a table, got %s", v.Type()) } + + r := &Result{Seller: SellerUnknown} + + var problems []string + + bad := func(format string, args ...any) { problems = append(problems, fmt.Sprintf(format, args...)) } + + hasAvailable := false + + t.ForEach(func(k, val lua.LValue) { + key := k.String() + + switch key { + case "title": + if s, ok := val.(lua.LString); ok { r.Title = strings.TrimSpace(string(s)) } else { bad("title must be a string or nil, got %s", val.Type()) } + case "available": + b, ok := val.(lua.LBool) + if !ok { + bad("available must be true or false, got %s", val.Type()) + return + } + + r.Available, hasAvailable = bool(b), true + case "price": + n, ok := val.(lua.LNumber) + switch f := float64(n); { + case !ok: + bad("price must be a number or nil, got %s", val.Type()) + case f < 0 || math.IsInf(f, 0) || math.IsNaN(f): + bad("price must be a positive number, got %v", f) + default: + r.Price = &f + } + case "currency": + s, ok := val.(lua.LString) + if c := strings.ToUpper(string(s)); ok && currencyRe.MatchString(c) { r.Currency = c } else { bad("currency must be a 3-letter code such as EUR or nil, got %s", val) } + case "seller": + s, ok := val.(lua.LString) + switch string(s) { + case SellerFirstParty, SellerFulfilled, SellerThirdParty, SellerUnknown: + if ok { r.Seller = string(s) } + default: + bad("seller must be %q, %q, %q or %q, got %s", SellerFirstParty, SellerFulfilled, SellerThirdParty, SellerUnknown, val) + } + case "id": + if s, ok := val.(lua.LString); ok { r.ID = string(s) } else { bad("id must be a string or nil, got %s", val.Type()) } + default: + bad("unknown field %q", key) + } + }) + + if !hasAvailable && !slices.ContainsFunc(problems, func(s string) bool { return strings.HasPrefix(s, "available ") }) { + bad("available is missing") + } + + if len(problems) > 0 { + slices.Sort(problems) + return nil, errors.New(strings.Join(problems, "; ")) + } + + return r, nil +} diff --git a/internal/plugin/sandbox.go b/internal/plugin/sandbox.go new file mode 100644 index 0000000..b19fc19 --- /dev/null +++ b/internal/plugin/sandbox.go @@ -0,0 +1,183 @@ +package plugin + +import ( + "context" + "errors" + "fmt" + "runtime/metrics" + "strings" + "sync" + "sync/atomic" + "time" + + lua "github.com/yuin/gopher-lua" + + "git.security-command.org/Overlord/dibs/internal/config" +) + +// Limits cap every Lua call. They come from [sandbox] in dibs.toml. +type Limits struct { + // Timeout applies to loading a plugin and to matches, normalize, parse + // and cart_link. + Timeout time.Duration + // SessionTimeout applies to login and add_to_cart. + SessionTimeout time.Duration + // MemoryBytes is the heap growth one call may cause. It is measured for + // the whole process, so it is approximate. + MemoryBytes int64 + // CallStack is the maximum Lua call depth. + CallStack int +} + +func DefaultLimits() Limits { + return Limits{ + Timeout: config.DefaultSandboxTimeout, + SessionTimeout: config.DefaultSessionTimeout, + MemoryBytes: config.DefaultMemoryMB << 20, + CallStack: config.DefaultCallStack, + } +} + +func LimitsFrom(s config.Sandbox) Limits { + return Limits{ + Timeout: s.Timeout.Duration, + SessionTimeout: s.SessionTimeout.Duration, + MemoryBytes: int64(s.MemoryMB) << 20, + CallStack: s.CallStack, + } +} + +var ( + ErrTimeout = errors.New("timed out") + ErrMemoryLimit = errors.New("exceeded the memory limit") +) + +// removedGlobals could load code, or reach the interpreter's internals. +// The os, io, debug, package and coroutine libraries are never opened. +var removedGlobals = []string{ + "dofile", "loadfile", "load", "loadstring", "require", "module", + "collectgarbage", "getfenv", "setfenv", "newproxy", "_printregs", +} + +// shortCalls lets one parse-type call run at a time, so the heap growth the +// memory watchdog sees is that call's. These calls take milliseconds. +var shortCalls sync.Mutex + +const watchInterval = 2 * time.Millisecond + +func newState(limits Limits) *lua.LState { + L := lua.NewState(lua.Options{ + SkipOpenLibs: true, + CallStackSize: limits.CallStack, + RegistrySize: 16 * 1024, + RegistryMaxSize: 256 * 1024, + MinimizeStackMemory: true, + }) + + for _, lib := range []struct { + name string + open lua.LGFunction + } { + {lua.BaseLibName, lua.OpenBase}, + {lua.TabLibName, lua.OpenTable}, + {lua.StringLibName, lua.OpenString}, + {lua.MathLibName, lua.OpenMath}, + } { + L.Push(L.NewFunction(lib.open)) + L.Push(lua.LString(lib.name)) + L.Call(1, 0) + } + + for _, name := range removedGlobals { L.SetGlobal(name, lua.LNil) } + + // string.rep allocates its whole result at once, faster than the + // watchdog can react. + if str, ok := L.GetGlobal("string").(*lua.LTable); ok { str.RawSetString("rep", L.NewFunction(cappedRep(limits.MemoryBytes))) } + + return L +} + +func cappedRep(limit int64) lua.LGFunction { + return func(L *lua.LState) int { + s := L.CheckString(1) + n := L.CheckInt(2) + if n <= 0 || s == "" { + L.Push(lua.LString("")) + return 1 + } + + if int64(len(s))*int64(n) > limit { L.RaiseError("string.rep: result of %d bytes exceeds the memory limit", int64(len(s))*int64(n)) } + + L.Push(lua.LString(strings.Repeat(s, n))) + return 1 + } +} + +// run calls fn, which must call into L, under a timeout and the memory +// watchdog. +func run(L *lua.LState, parent context.Context, timeout time.Duration, memLimit int64, fn func() error) error { + ctx, cancel := context.WithTimeout(parent, timeout) + defer cancel() + + var overLimit atomic.Bool + + done := make(chan struct{}) + defer close(done) + go watchMemory(ctx, done, memLimit, &overLimit, cancel) + + L.SetContext(ctx) + defer L.RemoveContext() + + err := fn() + + switch { + case err == nil: + return nil + case overLimit.Load(): + return ErrMemoryLimit + case parent.Err() != nil: + return parent.Err() + case errors.Is(ctx.Err(), context.DeadlineExceeded): + return fmt.Errorf("%w after %s", ErrTimeout, timeout) + default: + return luaError(err) + } +} + +// watchMemory cancels the call once the heap has grown by more than limit +// since the call started. +func watchMemory(ctx context.Context, done <-chan struct{}, limit int64, overLimit *atomic.Bool, cancel context.CancelFunc) { + sample := []metrics.Sample{{Name: "/memory/classes/heap/objects:bytes"}} + heap := func() int64 { + metrics.Read(sample) + return int64(sample[0].Value.Uint64()) + } + + base := heap() + ticker := time.NewTicker(watchInterval) + defer ticker.Stop() + + for { + select { + case <-done: + return + case <-ctx.Done(): + return + case <-ticker.C: + if heap()-base > limit { + overLimit.Store(true) + cancel() + return + } + } + } +} + +// luaError turns a Lua error into a one-line error such as +// "amazon.lua:12: attempt to index a nil value". +func luaError(err error) error { + var apiErr *lua.ApiError + if errors.As(err, &apiErr) && apiErr.Object != nil { return errors.New(strings.TrimSpace(apiErr.Object.String())) } + + return err +} diff --git a/internal/plugin/sandbox_test.go b/internal/plugin/sandbox_test.go new file mode 100644 index 0000000..d24526c --- /dev/null +++ b/internal/plugin/sandbox_test.go @@ -0,0 +1,80 @@ +package plugin + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "git.security-command.org/Overlord/dibs/internal/config" +) + +// sandboxed loads testdata/sandbox/.lua. +func sandboxed(t *testing.T, name string, limits Limits) *Plugin { + t.Helper() + + path := filepath.Join(testdata, "sandbox", name+".lua") + + code, err := os.ReadFile(path) + if err != nil { t.Fatal(err) } + + p, err := Load(name, path, code, limits, discardLogger()) + if err != nil { t.Fatal(err) } + t.Cleanup(p.Close) + + return p +} + +func parse(p *Plugin, url string) (*Result, error) { + return p.Parse(context.Background(), []byte(""), url) +} + +func TestSandboxGlobals(t *testing.T) { + r, err := parse(sandboxed(t, "globals", DefaultLimits()), "") + if err != nil { t.Fatal(err) } + if !r.Available { t.Errorf("reachable from the sandbox: %s", r.Title) } +} + +func TestSandboxTimeout(t *testing.T) { + limits := DefaultLimits() + limits.Timeout = 50 * time.Millisecond + + p := sandboxed(t, "timeout", limits) + + for _, url := range []string{"loop", "pcall"} { + start := time.Now() + if _, err := parse(p, url); !errors.Is(err, ErrTimeout) { t.Errorf("%s: got %v, want ErrTimeout", url, err) } + if d := time.Since(start); d > 2*time.Second { t.Errorf("%s: timeout took %s", url, d) } + } + + // The plugin was reloaded and still works. + if r, err := parse(p, "fine"); err != nil || !r.Available { t.Errorf("after a timeout: %v, %+v", err, r) } +} + +func TestSandboxMemoryLimit(t *testing.T) { + limits := DefaultLimits() + limits.Timeout = 20 * time.Second + limits.MemoryBytes = 16 << 20 + + if _, err := parse(sandboxed(t, "memory", limits), ""); !errors.Is(err, ErrMemoryLimit) { t.Errorf("got %v, want ErrMemoryLimit", err) } + if _, err := parse(sandboxed(t, "string_rep", limits), ""); err == nil || !strings.Contains(err.Error(), "memory limit") { t.Errorf("string.rep: got %v, want a memory limit error", err) } +} + +func TestSandboxCallStack(t *testing.T) { + limits := DefaultLimits() + limits.CallStack = 50 + + if _, err := parse(sandboxed(t, "call_stack", limits), ""); err == nil || !strings.Contains(err.Error(), "stack overflow") { t.Errorf("got %v, want a stack overflow", err) } +} + +// The config's seller policies rank these values by name, so a renamed +// constant would silently never pass a policy. +func TestSellersKnownToConfig(t *testing.T) { + anyone := config.Item{Seller: config.SellerAny} + for _, s := range []string{SellerFirstParty, SellerFulfilled, SellerThirdParty, SellerUnknown} { + if !anyone.AcceptsSeller(s) { t.Errorf("config does not know seller %q", s) } + } +} diff --git a/internal/price/price.go b/internal/price/price.go new file mode 100644 index 0000000..17f9060 --- /dev/null +++ b/internal/price/price.go @@ -0,0 +1,82 @@ +// Package price reads prices as shops print them. +package price + +import ( + "regexp" + "strconv" + "strings" +) + +// symbols maps currency signs and local abbreviations to ISO 4217 codes. +// Ambiguous ones such as "kr" are left out on purpose. +var symbols = []struct{ sign, code string }{ + {"€", "EUR"}, + {"£", "GBP"}, + {"US$", "USD"}, + {"$", "USD"}, + {"¥", "JPY"}, + {"zł", "PLN"}, + {"Kč", "CZK"}, + {"Fr.", "CHF"}, +} + +var ( + codeRe = regexp.MustCompile(`\b(EUR|GBP|USD|CHF|PLN|SEK|NOK|DKK|CZK|HUF|JPY|CAD|AUD)\b`) + numberRe = regexp.MustCompile(`\d[\d.,' \x{00a0}\x{202f}]*`) +) + +// Parse reads the first price in s, such as "1.299,99 €", "£1,299.99", +// "1 299,99 €" or "EUR 12.50". It returns the amount, the ISO 4217 +// currency code if `s` names one (or "" if not), and whether a price was +// found. +func Parse(s string) (float64, string, bool) { + num := strings.TrimRight(numberRe.FindString(s), ".,' \u00a0\u202f") + if num == "" { return 0, "", false } + + v, err := strconv.ParseFloat(normalize(num), 64) + if err != nil { return 0, "", false } + + return v, currency(s), true +} + +// normalize turns a localized number into the form ParseFloat accepts. +func normalize(num string) string { + // Spaces and apostrophes only ever group thousands. + num = strings.NewReplacer(" ", "", "\u00a0", "", "\u202f", "", "'", "").Replace(num) + + dot, comma := strings.LastIndex(num, "."), strings.LastIndex(num, ",") + + switch { + case dot >= 0 && comma >= 0: + // Both present: the last one is the decimal separator. + if dot > comma { return strings.ReplaceAll(num, ",", "") } + + return strings.ReplaceAll(strings.ReplaceAll(num, ".", ""), ",", ".") + case comma >= 0: + return decimalOrGrouping(num, ",") + case dot >= 0: + return decimalOrGrouping(num, ".") + default: + return num + } +} + +// decimalOrGrouping handles a number with only one kind of separator. Used +// more than once, or followed by exactly three digits, it groups thousands +// ("1.299", "1,299,000"). Otherwise it is the decimal point ("12,5", "9.99"). +func decimalOrGrouping(num, sep string) string { + last := num[strings.LastIndex(num, sep)+1:] + if strings.Count(num, sep) > 1 || len(last) == 3 { return strings.ReplaceAll(num, sep, "") } + + return strings.Replace(num, sep, ".", 1) +} + +func currency(s string) string { + if m := codeRe.FindString(s); m != "" { return m } + + for _, sym := range symbols { + if strings.Contains(s, sym.sign) { return sym.code } + } + + return "" +} diff --git a/internal/price/price_test.go b/internal/price/price_test.go new file mode 100644 index 0000000..6ac4019 --- /dev/null +++ b/internal/price/price_test.go @@ -0,0 +1,42 @@ +package price + +import "testing" + +func TestParse(t *testing.T) { + for in, want := range map[string]struct { + value float64 + currency string + }{ + "1.299,99 €": {1299.99, "EUR"}, + "£1,299.99": {1299.99, "GBP"}, + "1 299,99 €": {1299.99, "EUR"}, + "1\u00a0299,99\u00a0€": {1299.99, "EUR"}, + "1\u202f299,99 €": {1299.99, "EUR"}, + "129,99 €": {129.99, "EUR"}, + "129,99€": {129.99, "EUR"}, + "€129.99": {129.99, "EUR"}, + "$1,299.99": {1299.99, "USD"}, + "US$ 49.00": {49, "USD"}, + "EUR 12,50": {12.5, "EUR"}, + "12.50 GBP": {12.5, "GBP"}, + "CHF 1'299.90": {1299.9, "CHF"}, + "1.299 €": {1299, "EUR"}, + "1,299": {1299, ""}, + "1.299.000,00 €": {1299000, "EUR"}, + "12,5": {12.5, ""}, + "9.99": {9.99, ""}, + "49": {49, ""}, + "Preis: 59,99 € inkl. MwSt.": {59.99, "EUR"}, + " £7. ": {7, "GBP"}, + "99,00 zł": {99, "PLN"}, + } { + v, c, ok := Parse(in) + if !ok || v != want.value || c != want.currency { t.Errorf("Parse(%q) = %v, %q, %v; want %v, %q", in, v, c, ok, want.value, want.currency) } + } +} + +func TestParseNoPrice(t *testing.T) { + for _, in := range []string{"", "Derzeit nicht verfügbar", "€", "kostenlos"} { + if v, c, ok := Parse(in); ok { t.Errorf("Parse(%q) = %v, %q, true; want no price", in, v, c) } + } +} diff --git a/testdata/amazon/cases.toml b/testdata/amazon/cases.toml new file mode 100644 index 0000000..0cf50d6 --- /dev/null +++ b/testdata/amazon/cases.toml @@ -0,0 +1,36 @@ +# Real Amazon pages the amazon plugin is tested on. `dibs fixtures` fetches +# them into pages/ (not tracked), together with the report dibs made for +# each. Pages change: when a case stops showing what its note says, pick +# another product. +# +# Still wanted: a page sold by Amazon itself, and a preorder. + +[[case]] +name = "out-of-stock-de" +url = "https://www.amazon.de/dp/B0HMX2FSTF" +note = "Metro 2039 CE (Xbox), currently unavailable, no offer at all" + +[[case]] +name = "out-of-stock-uk" +url = "https://www.amazon.co.uk/dp/B0HM497GJJ" +note = "Metro 2039 CE (PC), currently unavailable, prices in GBP" + +[[case]] +name = "fulfilled-de" +url = "https://www.amazon.de/dp/B0DK51S84Z" +note = "Silkland cable, sold by Silkland-DE, shipped by Amazon" + +[[case]] +name = "fulfilled-de-2" +url = "https://www.amazon.de/dp/B076WS2WJ6" +note = "UGREEN enclosure, sold by a marketplace seller, shipped by Amazon" + +[[case]] +name = "used-only-de" +url = "https://www.amazon.de/dp/B0948LPGNG" +note = "Metro Exodus Complete (PS5), only a used copy in the buybox: not available" + +[[case]] +name = "not-found-de" +url = "https://www.amazon.de/dp/B0NOTREAL1" +note = "no such product: Amazon's 404 dog page" diff --git a/testdata/amazon/urls.toml b/testdata/amazon/urls.toml new file mode 100644 index 0000000..db772fd --- /dev/null +++ b/testdata/amazon/urls.toml @@ -0,0 +1,20 @@ +# How the amazon plugin's normalize() rewrites product URLs. Anything that is +# not an Amazon product URL on a supported TLD stays as it is. + +normalize = [ + { in = "https://www.amazon.de/dp/B0HMX2FSTF", out = "https://www.amazon.de/dp/B0HMX2FSTF" }, + { in = "https://www.amazon.de/dp/B0HMX2FSTF?th=1", out = "https://www.amazon.de/dp/B0HMX2FSTF" }, + { in = "https://www.amazon.de/dp/B0HMX2FSTF/ref=sr_1_1?th=1&psc=1", out = "https://www.amazon.de/dp/B0HMX2FSTF" }, + { in = "https://www.amazon.de/Metro-2039-Collectors-Edition/dp/B0HMX2FSTF", out = "https://www.amazon.de/dp/B0HMX2FSTF" }, + { in = "https://www.amazon.co.uk/gp/product/B0HM497GJJ", out = "https://www.amazon.co.uk/dp/B0HM497GJJ" }, + { in = "https://www.amazon.co.uk/gp/product/B0HM497GJJ/ref=ppx_yo_dt_b_asin", out = "https://www.amazon.co.uk/dp/B0HM497GJJ" }, + { in = "https://www.amazon.fr/gp/aw/d/B0HMX2FSTF", out = "https://www.amazon.fr/dp/B0HMX2FSTF" }, + { in = "https://amazon.it/dp/b0hmx2fstf", out = "https://www.amazon.it/dp/B0HMX2FSTF" }, + { in = "HTTPS://WWW.AMAZON.ES/dp/B0HMX2FSTF#reviews", out = "https://www.amazon.es/dp/B0HMX2FSTF" }, + { in = "https://www.amazon.nl/dp/B0HMX2FSTF", out = "https://www.amazon.nl/dp/B0HMX2FSTF" }, + { in = "https://www.amazon.com/exec/obidos/ASIN/B0HMX2FSTF", out = "https://www.amazon.com/dp/B0HMX2FSTF" }, + { in = "https://www.amazon.co.jp/dp/B0HMX2FSTF", out = "https://www.amazon.co.jp/dp/B0HMX2FSTF" }, + { in = "https://www.amazon.de/s?k=metro", out = "https://www.amazon.de/s?k=metro" }, + { in = "https://www.amazon.de/dp/B0HMX2FSTFX", out = "https://www.amazon.de/dp/B0HMX2FSTFX" }, + { in = "https://www.notamazon.de/dp/B0HMX2FSTF", out = "https://www.notamazon.de/dp/B0HMX2FSTF" }, +] diff --git a/testdata/sandbox/call_stack.lua b/testdata/sandbox/call_stack.lua new file mode 100644 index 0000000..63b8b44 --- /dev/null +++ b/testdata/sandbox/call_stack.lua @@ -0,0 +1,8 @@ +-- Recurses until the call stack limit is hit. +local function deep(n) return deep(n + 1) + 1 end + +return { parse = function() + deep(0) + + return { available = true } +end } diff --git a/testdata/sandbox/globals.lua b/testdata/sandbox/globals.lua new file mode 100644 index 0000000..90e224f --- /dev/null +++ b/testdata/sandbox/globals.lua @@ -0,0 +1,9 @@ +-- Nothing that reads files, loads code or reaches the interpreter's +-- internals may be visible to a plugin. +local leaked = {} +for _, name in ipairs({ "os", "io", "debug", "package", "coroutine", "dofile", "loadfile", "load", + "loadstring", "require", "module", "collectgarbage", "getfenv", "setfenv", "newproxy", "_printregs" }) do + if _G[name] ~= nil then leaked[#leaked + 1] = name end +end + +return { parse = function() return { available = #leaked == 0, title = table.concat(leaked, ",") } end } diff --git a/testdata/sandbox/memory.lua b/testdata/sandbox/memory.lua new file mode 100644 index 0000000..9adee8a --- /dev/null +++ b/testdata/sandbox/memory.lua @@ -0,0 +1,7 @@ +-- Grows a table until the memory watchdog stops it. +return { parse = function() + local t = {} + for i = 1, 1e8 do t[i] = "value " .. i end + + return { available = true } +end } diff --git a/testdata/sandbox/string_rep.lua b/testdata/sandbox/string_rep.lua new file mode 100644 index 0000000..1871432 --- /dev/null +++ b/testdata/sandbox/string_rep.lua @@ -0,0 +1,6 @@ +-- string.rep would allocate 10 GB at once, faster than the watchdog reacts. +return { parse = function() + local s = string.rep("x", 1e10) + + return { available = true } +end } diff --git a/testdata/sandbox/timeout.lua b/testdata/sandbox/timeout.lua new file mode 100644 index 0000000..1ca92d4 --- /dev/null +++ b/testdata/sandbox/timeout.lua @@ -0,0 +1,8 @@ +-- Loops forever on "loop" and "pcall"; pcall must not be able to swallow the +-- timeout. Any other URL returns normally. +return { parse = function(doc, url) + if url == "loop" then while true do end end + if url == "pcall" then while true do pcall(function() while true do end end) end end + + return { available = true } +end }