mirror of
https://github.com/J3vb/OwnCord.git
synced 2026-09-03 03:50:00 +03:00
* fix(identity): 1 defect(s) (OC-0151)
* fix(ws): 1 defect(s) (OC-0152)
* fix(admin): 1 defect(s) (OC-0153)
* fix(admin): 1 defect(s) (OC-0154)
* fix(voice): 2 defect(s) (OC-0155, OC-0167)
Replace distributeRoomKey's per-call offer counter with an instance-level
sliding-window budget shared by every voice_e2ee_offer send path.
- OC-0155: back-to-back rotations (the second run immediately by
drainPendingRotationOrArmTimer) each got a fresh pacing budget, so their
combined sends could exceed the server's single per-second cap.
- OC-0167: handleAnnounceInner's drain-time offer send bypassed pacing
entirely, letting a key holder joining a large ongoing call burst every
queued announce's offer unpaced.
The shared budget is reset in clearState() since the server's limit is
scoped per (sender, channel).
* fix(client): 1 defect(s) (OC-0156)
createPresenceSender dropped a queued custom_status when a later plain
status change superseded the pending retry. The retry now carries the
last committed custom_status forward.
* fix(client): 2 defect(s) (OC-0160, OC-0163)
OC-0160: exempt the handshake frames (ready, auth_ok) from the ws message
size limit and run the guard after parsing. A 'ready' frame grows unbounded
with member/channel/DM counts and carries no seq, so dropping it left the
client on empty stores with no error and no recovery path.
OC-0163: bracket a bare IPv6 host when building the wss:// URL so the
authority parses, and collapse bracketed/bare IPv6 literals to the same
cert_store_key so one server is not pinned (and user-confirmed) twice.
* fix(voice): 1 defect(s) (OC-0162)
updatePttKey armed the Rust poller when a PTT key was bound mid-call but
never applied the gate. The poller only emits 'ptt-state' on a press/release
transition, so an idle key produced no event and the already-published mic
stayed hot until the user's first physical press+release. Mirror the join-time
gate computation in updatePttKey, guarded on being in a call, polling actually
being live, and the mic not already being gated.
* fix(client): 1 defect(s) (OC-0164)
* fix(plugin): 1 defect(s) (OC-0165)
scanPluginDirectory now skips a malformed plugin subdirectory and joins its
error instead of aborting the whole scan, and LoadAll logs-and-continues so
one bad plugin directory cannot disable every other plugin.
* fix(ws): 1 defect(s) (OC-0166)
Route PresenceSelfEvent onto the owner's normal-priority queue instead of
letting it fall through to the UserTargetedEvent high-priority case, so a
user's own presence frames all share one FIFO and cannot be delivered out
of order relative to the visible presence_update path.
* fix(db): 1 defect(s) (OC-0168)
* fix(client): 1 defect(s) (OC-0169)
* fix(client): 1 defect(s) (OC-0171)
addMessage appended a broadcast at the tail even when trailing optimistic
rows were still unreconciled, so a message that committed while our own
send was in flight ended up ordered behind the row confirmSend later
stamped with a higher server id/timestamp. Insert before the trailing
unreconciled run instead.
* fix(voice): 1 defect(s) (OC-0172)
* fix(client): 1 defect(s) (OC-0174)
* fix(ws): 1 defect(s) (OC-0175)
* fix(client): 1 defect(s) (OC-0177)
* fix(client): 1 defect(s) (OC-0178)
* fix(voice): 1 defect(s) (OC-0179)
Undeafening no longer sends a voice_mute{muted:false} the server will
refuse while a moderator-imposed mute stands, matching the localServerMuted
guard already present in onMuteToggle.
* fix(client): 1 defect(s) (OC-0182)
* fix(plugin): 1 defect(s) (OC-0183)
* fix(client): 1 defect(s) (OC-0184)
Treat a trailing underscore as an emphasis delimiter, not part of the URL,
when scanning for the end of an autolinked URL.
* fix(client): 1 defect(s) (OC-0185)
Reveal .msg-actions-bar on .message:focus-within, not only on hover, so
keyboard users can see the per-message action buttons they Tab into
instead of activating them at opacity: 0.
Claude-Session: https://claude.ai/code/session_01M6gVN2JM5wrduhkNaFCxdK
* fix(client): 1 defect(s) (OC-0186)
* fix(client): 1 defect(s) (OC-0187)
The Add Server modal validated addresses with its own narrower regex that
never gained IPv6 support when api.ts's validator did, so an IPv6 server
could be logged into but never saved as a profile. Extract the validator
into src/lib/hostValidation.ts and use it from both call sites.
* fix(client): 1 defect(s) (OC-0189)
DM sidebar rows dropped mention counts entirely and the header total
excluded muted conversations outright, so a direct mention in a muted DM
was invisible. Render a mention badge that outranks the plain unread
badge, and count a muted channel's mentionCount toward the header total.
* fix(client): 1 defect(s) (OC-0190)
* fix(client): 1 defect(s) (OC-0191)
* fix(client): 2 defect(s) (OC-0157, OC-0176)
* fix(client): 1 defect(s) (OC-0161)
confirmTotp answers 401 for a wrong enrollment code while the session is still valid; firing the global onUnauthorized sink signed the user out and deleted their stored credential. Opt that one call out via a skipUnauthorized flag on doFetch.
* fix(admin): 1 defect(s) (OC-0173)
* fix(identity): 1 defect(s) (OC-0180)
* fix(admin): archived channel PATCH skips voice eviction and fan-out (OC-0158)
handlePatchChannel commits the AdminUpdateChannel write, then re-reads the
channel to drive voice eviction and the visibility fan-out. When that
post-commit re-read failed, the handler returned early: the archive was
durable but connected clients were never told and voice members were never
evicted, leaving users talking in a channel that no longer exists for them.
Drive the post-commit work off the values already in hand rather than
abandoning it when the re-read fails.
Adds SetPatchChannelPostCommitHook so the test can land a cancellation in
that exact window deterministically instead of racing wall-clock timing.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M6gVN2JM5wrduhkNaFCxdK
* fix(admin): role changes commit with no client ever notified (OC-0170)
broadcastRoles derived its context from the inbound *http.Request, so the
roles_update fan-out was tied to the request lifetime. A role create,
update, or delete could commit to the database and then broadcast nothing
once that request context was done, leaving every connected client on a
stale role list until the next full resync.
Decouple the fan-out from the request context so the broadcast follows the
commit rather than the caller.
Adds BroadcastRolesForTest to reach broadcastRoles from the external test
package.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M6gVN2JM5wrduhkNaFCxdK
* fix(client): username rename stomps the profile card header (OC-0188)
The account profile card's header is a resolveDisplayName() slot, but the
username-rename save path wrote the raw username straight into it. A user
with a display name set would see the header switch from their display
name to their new username after a rename, disagreeing with every other
surface that renders the same identity.
Resolve the header through the same display-name path the initial render
uses, so a rename updates the username field without touching the header.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M6gVN2JM5wrduhkNaFCxdK
* fix(client): settings overlay never focuses when mounted already-open (OC-0181)
mount() synced initial state — including the show() that calls
focusDialog() — before appending root to the container. .focus() on a
still-detached subtree is a silent no-op, so a caller that mounts while
uiStore.settingsOpen is already true (ConnectPage's lazy first-open path)
got a visible overlay whose focus trap never captured focus: keyboard
users landed outside the dialog with Tab escaping to the page behind it.
Attach root before syncing initial state so focusDialog() runs against a
connected subtree.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M6gVN2JM5wrduhkNaFCxdK
* chore: satisfy the CI gates for this fix batch
The fix batch's own commits left three CI gates red. Nothing here changes
behaviour; every edit is a lint, type, or formatting correction to code
this batch introduced.
golangci-lint:
- OC-0153 and OC-0173 replaced the last two uses of admin's setupSanitizer,
and OC-0151 the last use of api's sanitizer, leaving both package-level
bluemonday vars unused. Remove them along with the now-unused imports,
and reword the comments that named them so they still explain why the
fixpoint sanitizer is the right one without pointing at deleted symbols.
- Modernize the new handshake-deadline test's loop to range-over-int.
tsc --noEmit:
- jsdom ships no types and @types/jsdom is not a dependency, so declare the
surface the new admin-panel test uses, following src/types/jitsi-rnnoise.d.ts.
- Narrow the last-call lookup instead of indexing under
noUncheckedIndexedAccess, with an explicit failure message.
- membersStore.setState replaces whole state, so the presence-sender mocks
must supply typingUsers.
prettier: reformat the five files this batch touched.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M6gVN2JM5wrduhkNaFCxdK
* chore(ledger): record the 2026-08-19 hunt and its fixes
Adds the 41 findings confirmed by the 2026-08-19 hunt and marks the 40
fixed on this branch, each with its commit, the test that pins it, and
revertProof "pass".
"pass" means an independent check, not the fixing agent's self-report:
every commit had its source diff reverted against the working tree, its
own test re-run and required to FAIL, then the source restored and the
test required to PASS. Commits whose tests live inline in Rust
#[cfg(test)] blocks were proven the same way at hunk level, splicing the
pre-fix source onto the post-fix test module.
OC-0159 is recorded as a duplicate of OC-0152: the flow-reconnect and
flow-message lenses independently found the same unbounded handshake
write and proposed the same helper over the same call sites.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M6gVN2JM5wrduhkNaFCxdK
* test(e2e): make the voice-roster join fixture self-consistent
The voice-widget join test emitted a voice_state for user_id 4 claiming
username "newvoiceuser", but id 4 is "member2" in MOCK_MEMBERS_MULTI_ROLE.
A real server never sends a voice_state whose username disagrees with the
member record for that id, and the same file's VOICE_STATE_EVENT already
pairs id 1 with "testuser" correctly — this one event was the outlier.
The contradiction was invisible while the roster rendered the payload's
raw username. OC-0177 makes it resolve identity through membersStore so a
nickname shows the same in voice as everywhere else, at which point the
fixture's own inconsistency surfaced as a failure.
Send id 4's real username and assert on it. The test still covers what it
did before — a genuine join by a user not previously in voice, asserted by
name and by roster count.
Verified against the app unchanged: with the old fixture the spec fails
1/5 (matching CI), with this one it passes 5/5.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01M6gVN2JM5wrduhkNaFCxdK
---------
Co-authored-by: Claude <noreply@anthropic.com>
541 lines
19 KiB
Go
541 lines
19 KiB
Go
//go:build wazero
|
|
|
|
// Phase C Step 9 — Wazero runtime integration tests. Only compiled with
|
|
// `-tags wazero`, alongside sandbox_wazero.go. These tests exercise the
|
|
// behaviours the default build cannot:
|
|
//
|
|
// - NewRegistry stands up a real wazero.Runtime
|
|
// - activateWithRuntime compiles a real .wasm module and tracks the
|
|
// resulting instance on the Instance struct
|
|
// - EnablePlugin takes a manifest from a PluginStore row through
|
|
// activation end-to-end
|
|
// - invokeCommand gracefully returns a user-facing error when the plugin
|
|
// does not export command_dispatch
|
|
// - Close tears the runtime down without panicking
|
|
//
|
|
// Test fixture: the 41-byte `add.wasm` module from the wazero examples, a
|
|
// trivial module that exports `add(i32,i32) -> i32`. It does NOT export
|
|
// `command_dispatch`, which is intentional — the command path must handle
|
|
// that case.
|
|
package plugin
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
"github.com/tetratelabs/wazero"
|
|
)
|
|
|
|
// addWASM is the bytes of a minimal (module (func (export "add") ... )).
|
|
// Verified against the wazero examples fixture; 41 bytes. Using a literal
|
|
// here avoids dragging a binary asset into the repo.
|
|
var addWASM = []byte{
|
|
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
|
|
0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01,
|
|
0x7f, 0x03, 0x02, 0x01, 0x00, 0x07, 0x07, 0x01,
|
|
0x03, 0x61, 0x64, 0x64, 0x00, 0x00, 0x0a, 0x09,
|
|
0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6a,
|
|
0x0b,
|
|
}
|
|
|
|
func writeTestPlugin(t *testing.T, root, name string, manifest string, wasmBytes []byte) {
|
|
t.Helper()
|
|
pluginDir := filepath.Join(root, name)
|
|
if err := os.MkdirAll(pluginDir, 0o755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(pluginDir, "plugin.json"), []byte(manifest), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(pluginDir, "hello.wasm"), wasmBytes, 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func newWazeroTestRegistry(t *testing.T, dir string) (*Registry, PluginStore) {
|
|
t.Helper()
|
|
mem := openPluginTestDB(t)
|
|
reg, err := NewRegistry(Config{
|
|
Directory: dir,
|
|
MaxMemoryMB: 16,
|
|
CPUBudgetMs: 100,
|
|
Store: mem,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("NewRegistry: %v", err)
|
|
}
|
|
t.Cleanup(func() { _ = reg.Close(context.Background()) })
|
|
return reg, mem
|
|
}
|
|
|
|
func TestWazeroRegistryCreatesRuntime(t *testing.T) {
|
|
reg, _ := newWazeroTestRegistry(t, t.TempDir())
|
|
if reg.runtimePlatform == nil {
|
|
t.Fatal("expected wazero runtime to be wired in tagged build")
|
|
}
|
|
if reg.platformClose == nil {
|
|
t.Fatal("expected platformClose to be set")
|
|
}
|
|
}
|
|
|
|
func TestWazeroActivateCompilesModule(t *testing.T) {
|
|
dir := t.TempDir()
|
|
manifest := `{"name":"hello","version":"0.1.0","entrypoint":"hello.wasm","permissions":["commands"],"commands":[{"name":"hello"}]}`
|
|
writeTestPlugin(t, dir, "hello", manifest, addWASM)
|
|
|
|
reg, mem := newWazeroTestRegistry(t, dir)
|
|
ctx := context.Background()
|
|
if err := reg.LoadAll(ctx); err != nil {
|
|
t.Fatalf("LoadAll: %v", err)
|
|
}
|
|
|
|
rows, err := mem.ListPlugins(ctx)
|
|
if err != nil || len(rows) != 1 {
|
|
t.Fatalf("ListPlugins: rows=%+v err=%v", rows, err)
|
|
}
|
|
|
|
// The plugin starts disabled; enable it and confirm the module compiles.
|
|
if err := reg.EnablePlugin(ctx, rows[0].ID); err != nil {
|
|
t.Fatalf("EnablePlugin: %v", err)
|
|
}
|
|
|
|
reg.mu.RLock()
|
|
inst := reg.plugins[rows[0].ID]
|
|
reg.mu.RUnlock()
|
|
if inst == nil {
|
|
t.Fatal("instance not registered after enable")
|
|
}
|
|
if !inst.Enabled {
|
|
t.Fatal("instance should be enabled after EnablePlugin")
|
|
}
|
|
if inst.module == nil {
|
|
t.Fatal("expected inst.module to be populated after activation")
|
|
}
|
|
}
|
|
|
|
func TestWazeroDispatchCommandMissingExport(t *testing.T) {
|
|
dir := t.TempDir()
|
|
manifest := `{"name":"hello","version":"0.1.0","entrypoint":"hello.wasm","permissions":["commands"],"commands":[{"name":"hello"}]}`
|
|
writeTestPlugin(t, dir, "hello", manifest, addWASM)
|
|
|
|
reg, mem := newWazeroTestRegistry(t, dir)
|
|
ctx := context.Background()
|
|
if err := reg.LoadAll(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rows, _ := mem.ListPlugins(ctx)
|
|
if err := reg.EnablePlugin(ctx, rows[0].ID); err != nil {
|
|
t.Fatalf("EnablePlugin: %v", err)
|
|
}
|
|
|
|
reg.mu.RLock()
|
|
inst := reg.plugins[rows[0].ID]
|
|
reg.mu.RUnlock()
|
|
if err := reg.RegisterCommand("hello", inst); err != nil {
|
|
t.Fatalf("RegisterCommand: %v", err)
|
|
}
|
|
|
|
result, ok := reg.DispatchCommand(ctx, 1, 2, "hello", nil)
|
|
if !ok {
|
|
t.Fatal("expected DispatchCommand to return a result")
|
|
}
|
|
if result == nil || result.Reply == "" {
|
|
t.Fatal("expected a non-empty reply when export is missing")
|
|
}
|
|
}
|
|
|
|
func TestWazeroCloseTearsDownRuntime(t *testing.T) {
|
|
dir := t.TempDir()
|
|
manifest := `{"name":"hello","version":"0.1.0","entrypoint":"hello.wasm","permissions":["commands"],"commands":[{"name":"hello"}]}`
|
|
writeTestPlugin(t, dir, "hello", manifest, addWASM)
|
|
|
|
reg, mem := newWazeroTestRegistry(t, dir)
|
|
ctx := context.Background()
|
|
if err := reg.LoadAll(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rows, _ := mem.ListPlugins(ctx)
|
|
if err := reg.EnablePlugin(ctx, rows[0].ID); err != nil {
|
|
t.Fatalf("EnablePlugin: %v", err)
|
|
}
|
|
|
|
if err := reg.Close(ctx); err != nil {
|
|
t.Fatalf("Close: %v", err)
|
|
}
|
|
if reg.runtimePlatform != nil || reg.platformClose != nil {
|
|
t.Fatal("Close should clear platform fields")
|
|
}
|
|
// Calling Close twice must not panic.
|
|
if err := reg.Close(ctx); err != nil {
|
|
t.Fatalf("Close (second): %v", err)
|
|
}
|
|
}
|
|
|
|
func TestWazeroDisablePluginFreesModule(t *testing.T) {
|
|
dir := t.TempDir()
|
|
manifest := `{"name":"hello","version":"0.1.0","entrypoint":"hello.wasm","permissions":["commands"],"commands":[{"name":"hello"}]}`
|
|
writeTestPlugin(t, dir, "hello", manifest, addWASM)
|
|
|
|
reg, mem := newWazeroTestRegistry(t, dir)
|
|
ctx := context.Background()
|
|
if err := reg.LoadAll(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rows, _ := mem.ListPlugins(ctx)
|
|
if err := reg.EnablePlugin(ctx, rows[0].ID); err != nil {
|
|
t.Fatalf("EnablePlugin: %v", err)
|
|
}
|
|
reg.mu.RLock()
|
|
inst := reg.plugins[rows[0].ID]
|
|
reg.mu.RUnlock()
|
|
if inst.module == nil {
|
|
t.Fatal("pre-condition: module should be populated after EnablePlugin")
|
|
}
|
|
if err := reg.DisablePlugin(ctx, rows[0].ID); err != nil {
|
|
t.Fatalf("DisablePlugin: %v", err)
|
|
}
|
|
if inst.module != nil {
|
|
t.Fatal("DisablePlugin must release the wazero module (inst.module != nil)")
|
|
}
|
|
if inst.Enabled {
|
|
t.Fatal("DisablePlugin must clear inst.Enabled")
|
|
}
|
|
// Re-enabling must rebuild a new module.
|
|
if err := reg.EnablePlugin(ctx, rows[0].ID); err != nil {
|
|
t.Fatalf("re-EnablePlugin: %v", err)
|
|
}
|
|
if inst.module == nil {
|
|
t.Fatal("re-Enable should repopulate inst.module")
|
|
}
|
|
}
|
|
|
|
// spinWASM implements the command-dispatch ABI with input-dependent runtime:
|
|
//
|
|
// (module
|
|
// (memory (export "memory") 1)
|
|
// (func (export "allocate") (param i32) (result i32) i32.const 8)
|
|
// (func (export "deallocate") (param i32 i32))
|
|
// (func (export "command_dispatch") (param i32 i32) (result i32 i32)
|
|
// local.get 1 ;; payload length
|
|
// i32.const 100
|
|
// i32.gt_u
|
|
// if (loop br 0 end) end ;; payloads over 100 bytes spin forever
|
|
// i32.const 0 i32.const 0))
|
|
//
|
|
// A dispatch with no args stays under 100 payload bytes and returns
|
|
// immediately; long args push the JSON payload over 100 bytes and trigger an
|
|
// infinite loop, which the CPU budget must interrupt.
|
|
var spinWASM = []byte{
|
|
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, // \0asm v1
|
|
// type section: (i32)->i32, (i32,i32)->(), (i32,i32)->(i32,i32)
|
|
0x01, 0x12, 0x03,
|
|
0x60, 0x01, 0x7f, 0x01, 0x7f,
|
|
0x60, 0x02, 0x7f, 0x7f, 0x00,
|
|
0x60, 0x02, 0x7f, 0x7f, 0x02, 0x7f, 0x7f,
|
|
// function section: 3 funcs using types 0,1,2
|
|
0x03, 0x04, 0x03, 0x00, 0x01, 0x02,
|
|
// memory section: 1 page, no max
|
|
0x05, 0x03, 0x01, 0x00, 0x01,
|
|
// export section: memory, allocate, deallocate, command_dispatch
|
|
0x07, 0x35, 0x04,
|
|
0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00,
|
|
0x08, 0x61, 0x6c, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x65, 0x00, 0x00,
|
|
0x0a, 0x64, 0x65, 0x61, 0x6c, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x65, 0x00, 0x01,
|
|
0x10, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x5f, 0x64, 0x69, 0x73, 0x70, 0x61, 0x74, 0x63, 0x68, 0x00, 0x02,
|
|
// code section
|
|
0x0a, 0x1e, 0x03,
|
|
// allocate: return 8
|
|
0x04, 0x00, 0x41, 0x08, 0x0b,
|
|
// deallocate: nop
|
|
0x02, 0x00, 0x0b,
|
|
// command_dispatch: spin if len>100 else return (0,0)
|
|
0x14, 0x00,
|
|
0x20, 0x01, // local.get 1
|
|
0x41, 0xe4, 0x00, // i32.const 100
|
|
0x4b, // i32.gt_u
|
|
0x04, 0x40, // if
|
|
0x03, 0x40, // loop
|
|
0x0c, 0x00, // br 0
|
|
0x0b, // end loop
|
|
0x0b, // end if
|
|
0x41, 0x00, // i32.const 0
|
|
0x41, 0x00, // i32.const 0
|
|
0x0b, // end
|
|
}
|
|
|
|
// TestWazeroCPUBudgetOverrunDoesNotBrickPlugin locks in the W1-1 fix: an
|
|
// over-budget command must return the budget error, and the SAME plugin must
|
|
// serve the next command via lazy re-instantiation — not stay dead until an
|
|
// admin disable/enable cycle or server restart.
|
|
func TestWazeroCPUBudgetOverrunDoesNotBrickPlugin(t *testing.T) {
|
|
dir := t.TempDir()
|
|
manifest := `{"name":"spinner","version":"0.1.0","entrypoint":"hello.wasm","permissions":["commands"],"commands":[{"name":"spin"}]}`
|
|
writeTestPlugin(t, dir, "spinner", manifest, spinWASM)
|
|
|
|
reg, mem := newWazeroTestRegistry(t, dir)
|
|
ctx := context.Background()
|
|
if err := reg.LoadAll(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rows, _ := mem.ListPlugins(ctx)
|
|
if err := reg.EnablePlugin(ctx, rows[0].ID); err != nil {
|
|
t.Fatalf("EnablePlugin: %v", err)
|
|
}
|
|
reg.mu.RLock()
|
|
inst := reg.plugins[rows[0].ID]
|
|
reg.mu.RUnlock()
|
|
if err := reg.RegisterCommand("spin", inst); err != nil {
|
|
t.Fatalf("RegisterCommand: %v", err)
|
|
}
|
|
|
|
// Baseline: a small payload dispatches fine.
|
|
result, ok := reg.DispatchCommand(ctx, 1, 2, "spin", nil)
|
|
if !ok || result == nil {
|
|
t.Fatalf("baseline dispatch failed: ok=%v result=%+v", ok, result)
|
|
}
|
|
if strings.Contains(result.Reply, "CPU budget") {
|
|
t.Fatalf("baseline dispatch should not hit the budget: %q", result.Reply)
|
|
}
|
|
|
|
// Overrun: a long arg pushes the payload over the spin threshold; the
|
|
// 100ms budget must interrupt it and surface the budget error.
|
|
result, ok = reg.DispatchCommand(ctx, 1, 2, "spin", []string{strings.Repeat("x", 200)})
|
|
if !ok || result == nil {
|
|
t.Fatalf("overrun dispatch returned no result: ok=%v", ok)
|
|
}
|
|
if !strings.Contains(result.Reply, "CPU budget") {
|
|
t.Fatalf("expected CPU budget error, got %q", result.Reply)
|
|
}
|
|
|
|
// The plugin must still work: the next small dispatch re-instantiates the
|
|
// module lazily instead of dispatching into the closed one forever.
|
|
result, ok = reg.DispatchCommand(ctx, 1, 2, "spin", nil)
|
|
if !ok || result == nil {
|
|
t.Fatalf("post-overrun dispatch failed: ok=%v result=%+v", ok, result)
|
|
}
|
|
if strings.Contains(result.Reply, "CPU budget") || strings.Contains(result.Reply, "module closed") {
|
|
t.Fatalf("plugin still bricked after overrun: %q", result.Reply)
|
|
}
|
|
if !inst.Enabled {
|
|
t.Fatal("overrun must not disable the plugin")
|
|
}
|
|
}
|
|
|
|
// TestWazeroConcurrentDispatchRace locks F2: concurrent invocations of the same
|
|
// plugin command must be serialized per Instance. Without a per-Instance lock,
|
|
// two goroutines drive one shared wazero module (allocate / mem.Write /
|
|
// command_dispatch / mem.Read) with no synchronization, racing on its linear
|
|
// memory. Run under -race: without the fix the detector reports a data race;
|
|
// with it the run is clean.
|
|
func TestWazeroConcurrentDispatchRace(t *testing.T) {
|
|
dir := t.TempDir()
|
|
manifest := `{"name":"spinner","version":"0.1.0","entrypoint":"hello.wasm","permissions":["commands"],"commands":[{"name":"spin"}]}`
|
|
writeTestPlugin(t, dir, "spinner", manifest, spinWASM)
|
|
|
|
reg, mem := newWazeroTestRegistry(t, dir)
|
|
ctx := context.Background()
|
|
if err := reg.LoadAll(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rows, _ := mem.ListPlugins(ctx)
|
|
if err := reg.EnablePlugin(ctx, rows[0].ID); err != nil {
|
|
t.Fatalf("EnablePlugin: %v", err)
|
|
}
|
|
reg.mu.RLock()
|
|
inst := reg.plugins[rows[0].ID]
|
|
reg.mu.RUnlock()
|
|
if err := reg.RegisterCommand("spin", inst); err != nil {
|
|
t.Fatalf("RegisterCommand: %v", err)
|
|
}
|
|
|
|
const goroutines = 8
|
|
var wg sync.WaitGroup
|
|
start := make(chan struct{})
|
|
for i := 0; i < goroutines; i++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
<-start
|
|
for j := 0; j < 20; j++ {
|
|
reg.DispatchCommand(ctx, 1, 2, "spin", nil)
|
|
}
|
|
}()
|
|
}
|
|
close(start)
|
|
wg.Wait()
|
|
}
|
|
|
|
// noMemWASM exports the command ABI but declares NO memory section, so
|
|
// api.Module.Memory() returns nil for it:
|
|
//
|
|
// (module
|
|
// (func (export "list_commands") (result i32 i32) i32.const 0 i32.const 0)
|
|
// (func (export "allocate") (param i32) (result i32) i32.const 0)
|
|
// (func (export "command_dispatch") (param i32 i32) (result i32 i32)
|
|
// i32.const 0 i32.const 0))
|
|
var noMemWASM = []byte{
|
|
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, // \0asm v1
|
|
// type section: ()->(i32,i32), (i32)->i32, (i32,i32)->(i32,i32)
|
|
0x01, 0x12, 0x03,
|
|
0x60, 0x00, 0x02, 0x7f, 0x7f,
|
|
0x60, 0x01, 0x7f, 0x01, 0x7f,
|
|
0x60, 0x02, 0x7f, 0x7f, 0x02, 0x7f, 0x7f,
|
|
// function section: 3 funcs using types 0,1,2
|
|
0x03, 0x04, 0x03, 0x00, 0x01, 0x02,
|
|
// (no memory section — this is the point of the fixture)
|
|
// export section: list_commands, allocate, command_dispatch
|
|
0x07, 0x2f, 0x03,
|
|
0x0d, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x73, 0x00, 0x00,
|
|
0x08, 0x61, 0x6c, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x65, 0x00, 0x01,
|
|
0x10, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x5f, 0x64, 0x69, 0x73, 0x70, 0x61, 0x74, 0x63, 0x68, 0x00, 0x02,
|
|
// code section
|
|
0x0a, 0x14, 0x03,
|
|
0x06, 0x00, 0x41, 0x00, 0x41, 0x00, 0x0b, // list_commands: (0,0)
|
|
0x04, 0x00, 0x41, 0x00, 0x0b, // allocate: 0
|
|
0x06, 0x00, 0x41, 0x00, 0x41, 0x00, 0x0b, // command_dispatch: (0,0)
|
|
}
|
|
|
|
// TestWazeroMemorylessModuleDoesNotPanic locks the nil-memory guard: a guest
|
|
// that exports the command ABI but declares no memory section must be handled
|
|
// as a bad plugin, not dereferenced. Both host paths that touch guest memory
|
|
// are covered — activation (list_commands) and dispatch (command_dispatch) —
|
|
// because a panic on the activation path aborts server startup for every
|
|
// subsequent restart while the plugin row stays enabled.
|
|
func TestWazeroMemorylessModuleDoesNotPanic(t *testing.T) {
|
|
dir := t.TempDir()
|
|
manifest := `{"name":"nomem","version":"0.1.0","entrypoint":"hello.wasm","permissions":["commands"],"commands":[{"name":"noop"}]}`
|
|
writeTestPlugin(t, dir, "nomem", manifest, noMemWASM)
|
|
|
|
reg, mem := newWazeroTestRegistry(t, dir)
|
|
ctx := context.Background()
|
|
if err := reg.LoadAll(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rows, _ := mem.ListPlugins(ctx)
|
|
// Activation calls list_commands, which used to nil-deref the guest memory.
|
|
if err := reg.EnablePlugin(ctx, rows[0].ID); err != nil {
|
|
t.Fatalf("EnablePlugin: %v", err)
|
|
}
|
|
reg.mu.RLock()
|
|
inst := reg.plugins[rows[0].ID]
|
|
reg.mu.RUnlock()
|
|
if inst == nil || inst.module == nil {
|
|
t.Fatal("expected the module to activate")
|
|
}
|
|
// No command may bind: the name list is unreadable without memory.
|
|
reg.mu.RLock()
|
|
_, bound := reg.commands["noop"]
|
|
reg.mu.RUnlock()
|
|
if bound {
|
|
t.Fatal("memoryless module must not auto-bind commands")
|
|
}
|
|
|
|
// The dispatch path must report a diagnostic instead of writing into nil.
|
|
if err := reg.RegisterCommand("noop", inst); err != nil {
|
|
t.Fatalf("RegisterCommand: %v", err)
|
|
}
|
|
result, ok := reg.DispatchCommand(ctx, 1, 2, "noop", nil)
|
|
if !ok || result == nil {
|
|
t.Fatalf("expected a dispatch result: ok=%v result=%+v", ok, result)
|
|
}
|
|
if !strings.Contains(result.Reply, "no exported memory") {
|
|
t.Fatalf("expected a missing-memory diagnostic, got %q", result.Reply)
|
|
}
|
|
}
|
|
|
|
func TestWazeroInvalidWASMFailsActivation(t *testing.T) {
|
|
dir := t.TempDir()
|
|
manifest := `{"name":"brokey","version":"0.1.0","entrypoint":"hello.wasm","permissions":["commands"]}`
|
|
writeTestPlugin(t, dir, "brokey", manifest, []byte("not a wasm"))
|
|
|
|
reg, mem := newWazeroTestRegistry(t, dir)
|
|
ctx := context.Background()
|
|
if err := reg.LoadAll(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rows, _ := mem.ListPlugins(ctx)
|
|
if err := reg.EnablePlugin(ctx, rows[0].ID); err == nil {
|
|
t.Fatal("expected EnablePlugin to fail on invalid WASM")
|
|
}
|
|
}
|
|
|
|
// Every re-activation compiles the module again; without closing the previous
|
|
// CompiledModule the shared runtime retains each copy until process exit.
|
|
func TestWazeroDeactivateClosesCompiledModule(t *testing.T) {
|
|
dir := t.TempDir()
|
|
manifest := `{"name":"hello","version":"0.1.0","entrypoint":"hello.wasm","permissions":["commands"],"commands":[{"name":"hello"}]}`
|
|
writeTestPlugin(t, dir, "hello", manifest, addWASM)
|
|
|
|
reg, mem := newWazeroTestRegistry(t, dir)
|
|
ctx := context.Background()
|
|
if err := reg.LoadAll(ctx); err != nil {
|
|
t.Fatalf("LoadAll: %v", err)
|
|
}
|
|
rows, err := mem.ListPlugins(ctx)
|
|
if err != nil || len(rows) != 1 {
|
|
t.Fatalf("ListPlugins: rows=%+v err=%v", rows, err)
|
|
}
|
|
if err := reg.EnablePlugin(ctx, rows[0].ID); err != nil {
|
|
t.Fatalf("EnablePlugin: %v", err)
|
|
}
|
|
|
|
reg.mu.RLock()
|
|
inst := reg.plugins[rows[0].ID]
|
|
reg.mu.RUnlock()
|
|
if inst == nil || inst.module == nil {
|
|
t.Fatal("instance not activated")
|
|
}
|
|
if inst.compiled == nil {
|
|
t.Fatal("activation must retain the CompiledModule handle for teardown")
|
|
}
|
|
|
|
reg.platformDeactivate(ctx, inst)
|
|
if inst.module != nil {
|
|
t.Error("deactivate left inst.module set")
|
|
}
|
|
if inst.compiled != nil {
|
|
t.Error("deactivate leaked the CompiledModule — re-activation cycles retain every compile")
|
|
}
|
|
}
|
|
|
|
// memoryWASM is a minimal module containing only a memory section declaring
|
|
// `(memory 1)` — a single required page, no export needed. wazero validates
|
|
// a module's declared memory against the runtime's configured page limit at
|
|
// CompileModule time (internal/wasm.Memory.Validate), so this is enough to
|
|
// observe the effective page limit platformInit installed.
|
|
var memoryWASM = []byte{
|
|
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, // magic, version
|
|
0x05, 0x03, 0x01, 0x00, 0x01, // memory section: 1 memory, min-only, min=1 page
|
|
}
|
|
|
|
// TestPlatformInitPageCountDoesNotOverflowUint32 pins OC-0183:
|
|
// `uint32(memMB) * 1024 * 1024 / wazeroPageBytes` computed the byte count in
|
|
// uint32 before dividing, so it wraps at 4 GiB. A MaxMemoryMB of exactly 4096
|
|
// (4 GiB) wraps the byte count to 0, so WithMemoryLimitPages(0) is installed
|
|
// and every plugin whose WASM declares a memory section fails to compile —
|
|
// even though 4096 MiB is a legitimate, in-range request (wazero's own
|
|
// ceiling is 65536 pages = 4 GiB, i.e. exactly this value is allowed).
|
|
func TestPlatformInitPageCountDoesNotOverflowUint32(t *testing.T) {
|
|
platform, closeFn, err := platformInit(Config{MaxMemoryMB: 4096})
|
|
if err != nil {
|
|
t.Fatalf("platformInit: %v", err)
|
|
}
|
|
t.Cleanup(func() { _ = closeFn(context.Background()) })
|
|
|
|
rt, ok := platform.(wazero.Runtime)
|
|
if !ok || rt == nil {
|
|
t.Fatal("platformInit did not return a usable wazero.Runtime")
|
|
}
|
|
|
|
ctx := context.Background()
|
|
if _, err := rt.CompileModule(ctx, memoryWASM); err != nil {
|
|
t.Fatalf("CompileModule with MaxMemoryMB=4096 should succeed (4096 MiB = 65536 pages, "+
|
|
"wazero's own ceiling) but got: %v — the byte-count math overflowed uint32 and wrapped "+
|
|
"the effective memory limit to (near) zero pages", err)
|
|
}
|
|
}
|