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 <noreply@anthropic.com>
This commit is contained in:
1 parent
f90ef18f90
commit
bb010356a0
28 files changed
+2096
-26
No files matched your search
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user