Repository navigation
Fix: bound moca-egress cap refusals and stop audit from stalling the proxy - #614
Conversation
moca-egress is one shared host process serving every microVM, so two unbounded paths in it let a single guest degrade other tenants. Every connection over MaxConnsPerVM started an unbounded refusal goroutine, each holding a socket across two drainTimeout windows (~2s) and emitting one conn_cap line. A guest connecting in a tight loop therefore multiplied live fds against the process's shared LimitNOFILE, and flooded journald, whose rate limit then dropped *other* VMs' audit events. Refusals in flight are now bounded per VM by maxCapRefusalsPerVM; past it the connection is closed at once without spending a goroutine or a drain. conn_cap events are coalesced per VM per capEventEvery interval, driven by the Proxy.now clock seam rather than a new timer, with the suppressed count carried on the next event so nothing vanishes from the audit trail. Coalescing is per VM, not global, so a noisy guest cannot silence a quiet one. jsonSink.Emit encoded synchronously under a mutex, directly beneath a comment claiming auditing must not stall the proxy. It is called from proxyConn.emit while holding pc.mu and from abort() via Unregister, so a stalled journald blocked Unregister, Close, and the control socket behind them. Production now wraps stdout in NewAsyncSink: Emit does a non-blocking send and takes no lock, a single goroutine forwards to the inner sink, and a full queue drops rather than blocks. Drops are counted and reported as an audit_dropped event so a gap is visible instead of silent. The sink is a wrapper, so every existing test's synchronous sink stays deterministic; main closes it after proxy.Close() returns, keeping Unregister's late aborted events. Event gains two omitempty fields, dropped and coalesced, leaving the existing audit shape unchanged for anything already parsing it. Both defects were found in the rossoctl#583 review and deferred by agreement. The tests pin in-process behaviour: the journald rate limit and host fd exhaustion are not reproduced, and the fd bound holds by construction rather than by measurement. Fixes rossoctl#586 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
TestCapRefusalPastTheBoundClosesWithoutDraining asserted the guest's read ends in EOF. Past the bound the proxy closes a socket whose request is still unread in the receive buffer, and how the kernel answers that is its choice, not this code's: Linux sends an RST, so the guest reads ECONNRESET, while macOS gives EOF. CI is Linux, so the test failed there and passed locally. Either ending is a shed fd. The properties that matter are that no refusal was written and that the read did not block for drainTimeout, so assert exactly those and let the error be whatever the platform returns. Reintroducing the unbounded refusal path still fails this test on the written 429. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Bounds per-VM cap refusals (at most 8 in flight, the rest closed without draining), coalesces conn_cap audit events to one per second per VM with a coalesced count, and puts the stdout audit sink behind a non-blocking asyncSink. That sink drops events when full, reports the count as audit_dropped, and is flushed after proxy.Close() on every exit path. The accounting holds up: capRefusals and wg.Add/Done stay paired under p.mu, Emit after Close cannot panic because the channel is never closed, and the shutdown ordering in main is correct.
No must-fix. Five suggestions, inline: coalesced refusals are lost when a VM goes quiet or unregisters; the Close doc overclaims the Emit/Close race; the concurrent Emit/Close test does not overlap them; the past-the-bound test depends on timing; and the lossy/coalesced audit semantics are undocumented. Two nits.
Author: cwiklik (MEMBER — maintainer)
Areas reviewed: Go (remote-worker egress proxy, audit sink, config, main), tests, docs
Agent/IDE config (.claude/.vscode): none
Commits: 2, all signed-off: yes
CI status: passing (15/15)
| // event to emit, if any. The first refusal in an interval is reported, and | ||
| // carries however many were suppressed since the last report; the rest are | ||
| // only counted. Caller holds Proxy.mu. | ||
| func (b *vmBinding) chargeCapRefusal(now time.Time) (Event, bool) { |
There was a problem hiding this comment.
suggestion — refusals coalesced in the last interval are never reported if no later refusal arrives. chargeCapRefusal only flushes capSuppressed on the next refusal at least capEventEvery later. So a guest that floods 1000 refusals and stops, or whose VM is unregistered, leaves one conn_cap with coalesced: 0 and 999 refusals stuck in b.capSuppressed until the binding is deleted. The capCharged test helper has to add the pending b.capSuppressed to balance its totals, which shows this. Consider emitting a final conn_cap with any non-zero capSuppressed in Unregister (the b.closed = true block). Also note that Coalesced counts refusals from an earlier, possibly much older, interval than the event's timestamp.
| s.inner.Emit(Event{Time: s.now().UTC(), Decision: DecisionAuditDropped, Dropped: n}) | ||
| } | ||
|
|
||
| // Close stops the sink after flushing the queue. It is idempotent, and safe to |
There was a problem hiding this comment.
suggestion — the doc comment overstates the guarantee. After run reaches the default: arm (reportDrops(), return), a later Emit can still land in the buffered channel. It is then neither written nor counted. A drop counted after the final dropped.Swap(0) is never reported either. Production is safe because main calls CloseAudit only after proxy.Close() has waited on p.wg. Either reword this to "close only after all emitters have stopped; an Emit after Close may be lost", or have Emit check done and count a drop.
| } | ||
| } | ||
|
|
||
| func TestAsyncSinkConcurrentEmitAndClose(t *testing.T) { |
There was a problem hiding this comment.
suggestion — this test never overlaps Emit with Close. All 50 emitters finish (wg.Wait()) before s.Close() runs, so it only covers concurrent Emits. That leaves the race the name (and the Close doc comment) promise untested. Start Close while emitters are still running and assert accounting only for emits that finished before it, or rename the test.
| // answers the close with an RST (ECONNRESET) where macOS gives EOF. Either | ||
| // is a shed fd; what must hold is that no refusal was written and the read | ||
| // did not block for drainTimeout. | ||
| over := dial(t, path) |
There was a problem hiding this comment.
suggestion — this test is timing-sensitive. Each held refusal frees its slot about drainTimeout (1 s) after it was admitted, once writeAndClose's read deadline fires. The wait loop above can take up to 2 s to see all 8 in flight, so on a slow or -race runner the first slot may already be free when over is dialed. over then drains, gets a 429, and fails len(b) != 0. Record when the first held conn was dialed, and skip or fail clearly if about 1 s has passed before dialing over.
| DecisionAborted = "aborted" | ||
| // DecisionAuditDropped reports events an async sink could not queue. It | ||
| // carries no VM: the drops may span VMs, and Dropped says how many. | ||
| DecisionAuditDropped = "audit_dropped" |
There was a problem hiding this comment.
suggestion — the audit stream is now lossy under backpressure and conn_cap is rate-limited, but no docs changed. deploy/microvm/P4-ON-P6.md (~line 597) still says "one JSON line per request". The audit contract in remote-worker/egress/conformance/doc.go (lines 36-38) does not list audit_dropped or the dropped/coalesced fields, and should note that audit_dropped carries no vm_id/sid, so per-VM filters will not see it. One paragraph would tell operators that a gap is announced and that one conn_cap line can stand for many refusals.
| // flushed) or is counted as a drop (and reported). | ||
| func (s *asyncSink) Close() error { | ||
| s.closeOne.Do(func() { close(s.done) }) | ||
| <-s.stopped |
There was a problem hiding this comment.
nit — if journald stays stalled, run blocks forever in inner.Emit, so Close blocks forever on <-s.stopped, and SIGTERM only finishes when systemd SIGKILLs the process. That was also true before this PR, so it is not a regression. A bounded wait here (select on stopped with a timer of a few seconds that logs the queued count) would let shutdown complete.
| // Async, because this sink is stdout: a stalled journald must not block the | ||
| // proxy's hot path, nor Unregister and the control socket behind it. The | ||
| // caller flushes it on shutdown via CloseAudit. | ||
| cfg.Audit = NewAsyncSink(NewJSONSink(os.Stdout), 0) |
There was a problem hiding this comment.
nit — ConfigFromEnv now starts a goroutine as a side effect. It leaks on the later error return (a bad MOCA_EGRESS_CONTROL_UIDS) and in every config_test.go case, since none of them call CloseAudit. Wrapping the sink in main instead would keep config parsing pure.
Summary
moca-egressis one shared host process serving every microVM's egress. Two unbounded paths in it let a single guest degrade other tenants. Both were found in the #583 review, deferred out of that PR by agreement, and filed as #586.Defect 1 — cap refusals were unbounded
Every connection over
MaxConnsPerVMdidp.wg.Add(1)+go writeAndClose(...)with no bound on concurrent refusals. Each holds a socket across twodrainTimeoutwindows (1s write + 1s drain ≈ 2s), and emits oneconn_capline. A guest connecting in a tight loop therefore multiplied live fds against the shared process'sLimitNOFILE, and flooded journald — whose default per-service rate limit (10000/30s) then drops other VMs' audit events.Now:
maxCapRefusalsPerVM(8). Below the bound, the existing contract holds: a pipelined guest still reads a named 429 rather than an RST. At or past it the connection is closed immediately — no goroutine, no drain. Shedding the fd matters more than the guest reading its refusal.conn_capevents are coalesced per VM percapEventEvery(1s). The first refusal in an interval reports and carries however many were suppressed since the last report; the rest are only counted. This reuses theProxy.nowclock seam (already used bycountRequest's lazy sweep) rather than adding a timer goroutine, so tests drive it without sleeping.Defect 2 — audit could stall the proxy
jsonSink.Emittook a mutex and encoded straight to the writer, directly under a comment claiming the opposite: "auditing must not stall the proxy". It is called fromproxyConn.emitwhile holdingpc.mu, and fromabort(), whichUnregistercalls per connection. So a stalled journald blockedUnregister→Close→ the control socket, and with it every VM's registration.Now production wraps stdout in
NewAsyncSink:Emitdoes a non-blocking channel send and takes no lock, so it is safe to call while holding one. One goroutine forwards to the inner sink.audit_droppedevent, on a ticker and once more onClose, so a gap is visible rather than silent.jsonSink, so every existing test's synchronous sink stays deterministic; only the production wiring opts in.maincloses it afterproxy.Close()returns, soUnregister's lateabortedevents are still written.Audit shape
Eventgainsdroppedandcoalesced, bothomitempty, leaving the existing shape byte-identical for anything already parsing it.audit_droppeddeliberately carries novm_id: the drops may span VMs.Decisions
P4-ON-P6.mdunchanged. It is a safety bound, not a policy.Verification
go build ./...(module)go vet ./internal/egress/...go test ./...(whole module)go test -race -count=2egress + cmdgofmt -lEach defect was reintroduced to prove the tests catch it — 7 mutations, all caught. Removing the per-VM scoping of coalescing fails with exactly #586's symptom: "vm-quiet's refusal was never recorded while vm-noisy flooded".
conformance_test.goinjectsNewJSONSinkdirectly and is untouched, so the audit stream still decodes unchanged.Honest limitation
These tests pin in-process behaviour. The real journald rate limit and host fd exhaustion are not reproduced in a unit test; the fd claim is bounded by construction (a per-VM constant) rather than measured. No load test ran.
Out of scope
#585 (idle deadlines on tunnels / forward path) and #587 (control client dropping the shared connection) — the other two deferred #583 follow-ups. Adjacent files, separate issues.
Fixes #586
Assisted-By: Claude Code