Repository navigation
fix(tsx): count sandbox memory where built-ins allocate by size - #802
Conversation
|
Not merging yet: the approach needs a design decision before it can meet #760's acceptance ("a bundle that allocates past The watcher in
Smaller points: A heap sample of the shared Go heap cannot attribute memory to one sandbox, so I think the bound needs to be counted rather than sampled: charge the sandbox's own budget at the places goja allocates by size ( Repro test (tsx/zz_repro_test.go)package tsx_test
import (
"runtime"
"testing"
"testing/fstest"
"github.com/nsgo-dev/nsgo/core"
"github.com/nsgo-dev/nsgo/nsgotest"
"github.com/nsgo-dev/nsgo/tsx"
"github.com/nsgo-dev/nsgo/tsx/bundler"
)
func reproApp(t *testing.T, body string, limit int, host func()) (*nsgotest.App, *error) {
code, err := bundler.Compile(fstest.MapFS{"App.tsx": {Data: []byte(`import { mount, Text } from "nsgo";
const kept = [];
mount(() => <Text testID="go" onPress={() => { ` + body + ` }}>ok</Text>);`)}}, "App.tsx")
if err != nil {
t.Fatal(err)
}
limits := tsx.DefaultLimits
limits.Memory = limit
var failed error
app := nsgotest.Start(t, func(cx *core.Scope) core.Node {
return core.Catch{Try: tsx.Sandboxed("App.tsx", code, tsx.Sandbox{Limits: &limits}), Fallback: func(cx *core.Scope, err error, _ func()) core.Node {
failed = err
return core.Text{Content: "cut"}
}}
})
return app, &failed
}
// Retained memory across calls is never bounded: each call's base is reset.
func TestReproRetainedAcrossCalls(t *testing.T) {
app, failed := reproApp(t, `kept.push(new Array(200_000).fill(1));`, 32<<20, nil)
var before runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&before)
for range 60 {
app.Press("id:go")
}
var after runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&after)
t.Logf("retained growth %d MiB with a 32 MiB limit, failed=%v", (after.HeapAlloc-before.HeapAlloc)>>20, *failed)
}
// One allocation completes before the watcher can sample.
func TestReproSingleAllocation(t *testing.T) {
app, failed := reproApp(t, `kept.push(new ArrayBuffer(512 * 1024 * 1024));`, 1<<20, nil)
app.Press("id:go")
var after runtime.MemStats
runtime.ReadMemStats(&after)
t.Logf("heap after %d MiB with a 1 MiB limit, failed=%v", after.HeapAlloc>>20, *failed)
}
// Host allocations on another goroutine stop an innocent plugin.
var sink [][]byte
func TestReproHostAllocation(t *testing.T) {
app, failed := reproApp(t, `const end = Date.now() + 300; while (Date.now() < end) {}`, 64<<20, nil)
go func() {
for range 100 {
sink = append(sink, make([]byte, 1<<20))
}
}()
app.Press("id:go")
t.Logf("plugin allocating nothing, host 100 MiB, limit 64 MiB: failed=%v", *failed)
} |
185e9cd to
177faa9
Compare
177faa9 to
4194ef0
Compare
Add tsx.Limits.Memory, off by default, and memory= in -limits. A sandbox with one replaces, before hardening, the goja built-ins that allocate by a size the bundle gives them (ArrayBuffer and the typed arrays with their copying, transfer and join methods, String repeat/padStart/padEnd/raw, Array.from, Array join/toLocaleString/fill/sort/toSorted/toReversed/toSpliced/with, the argument lists of apply, Reflect.apply and Reflect.construct, and JSON.stringify) with wrappers that check the sandbox's budget before calling the original and charge what it made, by a weak pointer to its memory, until a cleanup sees the collector free it. Past the budget the runtime stops with ERR_NSH_QUOTA_EXCEEDED, as past its node quota. This replaces sampling the process heap during each call, which missed a single large allocation, reset across calls, and stopped bundles for the host's allocations. Refs #760
…at JSON.stringify and String.raw write A getter, a proxy or a valueOf on a length could read 0 for the wrapper's check and then a huge length for the original (typed array constructors, Array.from, sort, fill, toSorted, toReversed, toSpliced, with, apply, Reflect.apply, Reflect.construct, String.raw and JSON.stringify's property list), letting one call allocate gigabytes under a 1 MiB budget. The wrappers now read the size once and hand the original a value, a copy or a proxy that answers it. JSON.stringify now counts the indentation of deep output, escapes, numbers and raw JSON, and counts a property list too, through a proxy per object with just the listed keys. String.raw counts the strings it joins. Strings JSON.stringify returns as imported strings are held like the others. The docs say plainly that copies, concatenations, spreads and replace are not counted, and that they allocate at the speed of memory.
4194ef0 to
7b86bfb
Compare
|
Reviewed. Adversarial pass found that the wrappers checked a size and the original read it again: a length getter, a proxy or a valueOf reading 0 then 2^24 let |
Part of #760.
Reworked after review: instead of sampling the process heap every millisecond during a call, the sandbox now counts bytes where goja allocates by a size the bundle gives it, without changing goja and without new dependencies.
What is bounded
tsx.Limits.Memory(bytes,memory=in-limits) stays off by default. When set,Sandbox.startreplaces these built-ins before hardening (tsx/memory_goja.go):ArrayBufferand the eleven typed array constructors (number, array-like, iterable and typed-array sources; a view of a buffer allocates nothing),ArrayBuffer.prototype.slice,transfer,transferToFixedLength, and%TypedArray%.prototypeslice,map,filter,toReversed,toSorted,with,join,toLocaleStringString.prototype.repeat,padStart,padEnd,String.rawArray.from,Array.prototype.join,toLocaleString,fill,sort,toSorted,toReversed,toSpliced,withFunction.prototype.apply,Reflect.apply,Reflect.construct(goja preallocates them from an array-like'slength)JSON.stringify, which checks the strings and keys it writes as it reaches them through a replacer of its own around the bundle'sEach wrapper converts size arguments once (so a
valueOfcannot report one size to the check and another to the original), checks the remaining budget before calling the original, so what would not fit is never allocated, then charges what the original made. The charge is tied to the allocation's own memory by a weak pointer and released by aruntime.AddCleanuponce the collector frees it, so the budget is what the bundle holds across calls, not what one call adds.joinandtoLocaleStringstringify each element first and then let the original join the strings, so the total is checked before the result is built. Past the budget the runtime stops withERR_NSH_QUOTA_EXCEEDED(resourcememory), as past the node quota: JS cannot catch it and the host keeps running. Constructors are wrapped in a tiny JS shim, since goja's Go constructors cannot tellnewfrom a call; the shim takes the original's statics, prototype and prototype chain soinstanceof, subclasses, species andUint8Array.fromkeep working.Host allocations and other sandboxes' allocations are never counted, and the 1 ms polling and the timer locking it needed are gone.
What is not bounded
What the bundle's JS makes as it runs: objects, closures, arrays filled element by element or spread, strings concatenated with
+or template literals (goja keeps them as ropes, and reading one flattens it at once), keys listed withObject.keys/for…in, whatreplace/splitmake, and the web APIs' copies (Blob,TextEncoder). Nothing on the web target, whose page's engine keeps its own heap. Allocations under 1 KiB are not charged. The architecture doc keeps the line that a package's root is still trusted not to exhaust memory, now "past" what is bounded, and the roadmap row says what is left.Tests
TestSandboxMemoryStopsOneLargeAllocation,TestSandboxMemoryCountsWhatCallsKeep,TestSandboxMemoryIgnoresTheHostsAllocations: the three cases from the review, end to end throughtsx.Sandboxed, the first including the issue'snew ArrayBuffer(2 ** 32). All three fail on the previous head (177faa9) and pass now.TestMemoryStopsWhatWouldNotFit: one case or more per wrapped built-in, each allocating past a 1 MiB budget at once (up to exabytes), insidetry/catch; each must stop with the quota and hold at most the budget.TestMemoryKeepsTheBuiltinsBehavior: scripts run with and without the wrappers must agree (constructor identity, subclasses, species, errors for bad sizes and missingnew, cycles injoin, replacers, frozen built-ins, names and lengths).TestMemoryKeepsWhatFits,TestMemoryReleasesWhatIsCollected: kept allocations stay charged; 40 calls allocating 12 MiB each under a 32 MiB budget never stop once collected.Checks:
go test ./tsx/... ./internal/moduletest/(also-raceon the sandbox and memory tests),go tool nsgo check -target linux,web,android,windows.Screenshots
None.