Skip to content

Harden wire/zlib parsing, fix delivery/storage bugs, and share DB pool - #54

Merged
markmnl merged 5 commits into
mainfrom
review/perf-and-reliability
Nov 25, 2026
Merged

markmnl merged 5 commits into
mainfrom
review/perf-and-reliability

Conversation

@markmnl

@markmnl markmnl commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Summary

High-impact security, correctness, performance, and maintainability improvements from a Go code review (strictly preserving SPEC.md wire conformance and existing dd.sql schema):

Security & Protocol Correctness

  • Bound zlib decompression & fix integer overflows (pkg/fmsg/fmsg.go, pkg/fmsg/deflate.go, cmd/fmsgd/host.go): Wrap zlib.Reader in io.LimitReader(zr, int64(expandedSize)+1), remove uint32 truncation on written byte counts, check zr.Close(), accumulate attachment sizes in uint64 to prevent uint32 wrap bypassing MAX_SIZE/MAX_EXPANDED_SIZE, and use int64 in deflate.go's compression ratio check.
  • Fix wire read panics, silent truncation, and socket leaks (cmd/fmsgd/host.go, pkg/fmsg/prepare.go): Use io.ReadFull into exact-sized buffers in handleChallenge, ReadUInt8Slice, readHeader pid, and challenge; close connections on recovered panics in handleConn; send RejectCodeInvalid on duplicate to and add-to attachment count mismatch; add cycle/depth bounds to isMessageRetrievable; deep-copy AddToFrom and StoredWire in Header.Clone().
  • Fix delivery and storage bugs (cmd/fmsgd/sender.go, cmd/fmsgd/store.go, cmd/fmsgd/host.go):
    • Filter msg_add_to updates by batch_id (preventing sibling batches from overwriting each other) and propagate tx.Exec errors.
    • Only mark isLocked for recipient entries matching the unit's table (msg_to vs msg_add_to) so addresses in both To and AddTo aren't double-updated.
    • Pass localOutcome into attachAddToRecipients and use strings.EqualFold for local domain matching.
    • Defer mutating h.Attachments[i].Filepath until all copies succeed, skip persistAttachmentPayloads on skipData, deduplicate accepted local addresses before file copies and quota recording, and replace TOCTOU os.Stat+os.Create loops with atomic O_CREATE|O_EXCL.
  • Timeouts, connection leaks, DNSSEC, and shutdown (cmd/fmsgd/host.go, id.go, dns.go, sender.go): Add dial/IO deadlines and defer conn2.Close() in challenge; unwrap *tls.Conn in abortConn; include attachment sizes in upload/download deadlines and set header write deadlines; use a dedicated pooled http.Client with timeout, non-200 rejection, and body draining in id.go; add resolver timeouts, reuse *dns.Client, and verify DNSSEC AD records directly in dns.go; add SIGINT/SIGTERM graceful shutdown and accept-error backoff in main.

Performance

  • Shared *sql.DB pool (cmd/fmsgd/store.go, sender.go, indicators.go): Replace per-query sql.Open/defer db.Close() with a single shared connection pool.
  • Eliminate redundant disk hashing & dispatch storms (pkg/fmsg/prepare.go, pkg/message/store.go, cmd/fmsgd/sender.go, store.go, indicators.go): Export fmsg.UnmarshalPreparedHeader for header-only reads, skip unused queries & double hashing in FinalizeBatch, track in-flight pendingTarget keys in processPendingMessages, defer UnmarshalPrepared in deliverUnit until pending rows are locked, compress directly to a temp file in destination dir in preparePart, and pool zlib.Writer via sync.Pool in pkg/fmsg/deflate.go.
  • Indicators & hot-path allocations (cmd/fmsgd/indicators.go, pkg/fmsg/fmsg.go, cmd/fmsgd/host.go): Gate sourceLimiter and ipCache full-map pruning at >= 1s, compute ipCache TTL after lookup, remove redundant 3rd DB query in subjectsOf, optimize Header.Encode()/Address.ToString()/GetCommonMediaTypeID/GetMessageHash, batch N+1 duplicate hash lookups, replace time.After in select loops with reusable timers, and deduplicate readMediaType / addrEqualFold.

Testing

  • Added unit tests covering zlib bombs, uint32 attachment size overflow, truncated challenge/slice reads, duplicate to/add-to attachment mismatch codes, cycle detection, atomic uniqueFilepath, id.go 5xx handling, Header.Clone(), UnmarshalPreparedHeader, sourceLimiter/ipCache behavior, deliverUnit To ∩ AddTo locking, and DNSSEC validation.
  • Verified with go vet ./..., go build ./..., and go test -race -count=1 ./....

@markmnl

markmnl commented Nov 25, 2026

Copy link
Copy Markdown
Owner Author

Review findings to remediate

Reviewed at cf64c0c against main. Three regressions introduced by this PR and two nits. Each was checked against the code on both branches. Line numbers refer to cf64c0c.

1. Shared DB pool can be starved by the sender (regression)

Where: cmd/fmsgd/store.go:33 (db.SetMaxOpenConns(48)), cmd/fmsgd/sender.go:586 (deliverUnit)

Problem: The new process-wide pool is capped at 48 connections. The sender runs up to MaxConcurrentSend (default 1024) deliverUnit goroutines, and each one opens a transaction with db.Begin() and holds it, with rows locked FOR UPDATE SKIP LOCKED, through the DNS lookup, TLS dial, header write, the 30s initial-response read, the data upload and the per-recipient code reads.

Failure scenario: 48 or more pending (msg, domain) targets in flight at once, for example a backlog after an outage or a slow or unreachable peer. Those goroutines take every connection in the pool. Every inbound handleConn DB call (lookupMsgIdByHash, getMsgByID, receivedAddrsForMsgHash, storeMsgDetail) and every indicator query (cmd/fmsgd/indicators.go:919) then blocks waiting for a connection, so remote senders hit their read deadlines and incoming messages are not accepted. Two fmsgd peers delivering to each other can stall each other until the 30s deadlines expire.

On main: every call opened its own uncapped pool with sql.Open, and indicators had a dedicated pool sized indicatorRecvWorkers + 2, so receive paths were never queued behind the sender.

Fix: inbound and indicator DB access must not be starved by long sender transactions. Either:

  • give the sender its own pool, separate from the one used by inbound and indicators, or bound in-flight deliveries below the pool size so connections are always left over; or
  • stop holding a transaction across network I/O in deliverUnit (claim the rows, commit, deliver, then record outcomes in a second short transaction). This is the more complete fix but a larger change, since the SKIP LOCKED row locks currently provide the mutual exclusion between senders.

Please add a test that fails if inbound store calls block while the sender has more deliveries in flight than the pool has connections.

2. DNS lookup timeout defeats resolver failover (regression)

Where: cmd/fmsgd/dns.go:124-126, dnsLookupTimeout at cmd/fmsgd/dns.go:18

Problem: The non-DNSSEC path now wraps net.DefaultResolver.LookupIP in a 5s context. That equals the Go resolver's default per-attempt timeout (timeout:5 in resolv.conf terms). The first exchange uses the whole budget, so every later attempt or nameserver fails immediately on the expired context.

Failure scenario: the first nameserver in /etc/resolv.conf is down or slow, or a single UDP query or reply is lost. Effects:

  • at startup, verifyDomainIP calls lookupAuthorisedIPs and log.Panicfs on error (cmd/fmsgd/dns.go:181-183), so the daemon crash-loops where it used to start after one failover;
  • every inbound connection fails verifySenderIP and is terminated;
  • every outbound deliverUnit records a retryable failure and backs off;
  • the indicator IP cache negative-caches the failure, so indicators to that domain are dropped.

On main: net.LookupIP(fmsgDomain) with no overall deadline, so the resolver's own attempts and server failover applied.

Fix: make the overall deadline for this path larger than per-attempt timeout × attempts × servers (a separate constant of 15-20s is reasonable), or drop the overall cap and rely on the resolver's own bounds. Keep the 5s value for the DNSSEC dns.Clients at lines 21-22, where it is per server and the loop already fails over.

3. FinalizeBatch no longer verifies the stored payload hash (regression)

Where: pkg/message/store.go:239 and pkg/message/store.go:246

Problem: Both branches now call fmsg.UnmarshalPreparedHeader(...). On main they were fmsg.UnmarshalPrepared(s.prepared, s.hash) and fmsg.UnmarshalPrepared(snapshot, batchHash), which check that the on-disk payload still hashes to the stored sha256. That check is now skipped just before a new, permanent batch identity is derived from the same files via h.GetMessageHash().

Failure scenario: a stored .fmsg-wire-* payload or attachment file changes in place without changing length (bit-rot, an operator or tool editing it, a partial restore). Previously FinalizeBatch failed with "prepared message hash mismatch" and no batch was sealed. Now the altered bytes are hashed and persisted as the batch's sha256, with pid still set to the original's untouched hash. deliverUnit's later UnmarshalPrepared(b.Prepared, b.Hash) passes because the batch hash matches the altered data. Hosts that do not hold the original accept altered content under a batch claiming the original as its parent. Hosts that do hold the original compute a different batch hash, terminate, and those deliveries retry until RetryMaxAge without ever succeeding.

Fix: restore the hash-checked decode in both branches: fmsg.UnmarshalPrepared(prepared, msgHash) for the original, and fmsg.UnmarshalPrepared(snapshot, <that batch's sha256>) for a received batch. The snapshot query at line 245 currently selects only wire_message, so it needs to select that row's sha256 as well. Add a test that corrupts a stored payload file in place and asserts FinalizeBatch returns an error and seals nothing.

4. Reject-code precedence in readAttachmentHeaders (nit)

Where: cmd/fmsgd/host.go:1048-1059

Problem: The new per-attachment size checks inside the loop send RejectCodeTooBig (4) before later attachment headers have gone through the SPEC §10.3 step 3 validation (reserved flag bits, common type ID, filename). The SPEC has those failures answered with code 1 (invalid) and the size check coming later (step 5).

Failure scenario: attachment 1 pushes the running total past MAX_SIZE and attachment 2 has an unmapped common type ID or a reserved flag bit. The receiver now answers 4 where main answered 1, and the sender records the wrong reject reason.

Fix: remove the two in-loop checks. totalSize and totalExpandedSize are now uint64 and cannot overflow, so the post-loop checks at lines 1071-1083 already enforce the limits.

5. Duplicated SQL in updateRecipient (nit)

Where: cmd/fmsgd/sender.go:193-226

Problem: Four near-identical UPDATE statements (msg_add_to/msg_to × delivered/failed). Within each delivered/failed pair the SET clause is the same; only the table and the WHERE key differ (batch_id = $3 with batchID versus msg_id = $3 with msgID). A later change to the delivered or retry columns has to be made twice, and missing one lets msg_to and msg_add_to retry bookkeeping drift apart silently.

Fix: choose the table, scope column and key once, then keep two statements (delivered and failed). Behaviour must stay the same, including msg_add_to being scoped by batch_id.

Acceptance

  • go build ./..., go vet ./... and go test ./... pass.
  • Findings 1-3 each have a regression test.
  • No behaviour changes beyond the five items above.

…ut, verify FinalizeBatch hash, fix attachment reject precedence, deduplicate updateRecipient
@markmnl

markmnl commented Nov 25, 2026

Copy link
Copy Markdown
Owner Author

Addressed all 5 review findings in 9e1956f:

  1. Isolated sender DB pool (cmd/fmsgd/store.go, sender.go, host.go): Added a dedicated getSenderDB()/closeSenderDB() pool (MaxOpenConns(32)) for outbound sender transactions, completely separate from getDB() (MaxOpenConns(48)) used by inbound handlers and indicators. Added TestSenderPoolSaturationDoesNotStarveInboundPool.
  2. Non-DNSSEC resolver failover timeout (cmd/fmsgd/dns.go): Kept dnsLookupTimeout = 5s for per-server DNSSEC clients and added resolverLookupTimeout = 20s for the non-DNSSEC net.DefaultResolver.LookupIP path so resolver retries and server failover work. Added TestLookupAuthorisedIPsResolverTimeoutAllowsFailover.
  3. FinalizeBatch payload hash verification (pkg/message/store.go): Restored fmsg.UnmarshalPrepared(prepared, msgHash) for the original branch and SELECT wire_message, sha256 + fmsg.UnmarshalPrepared(snapshot, batchHash) for received batches. Added regression tests TestFinalizeBatchVerifiesOriginalPayloadHash, TestFinalizeBatchVerifiesReceivedBatchPayloadHash, and TestFinalizeBatchRejectsCorruptedPayload.
  4. Reject-code precedence (cmd/fmsgd/host.go): Removed the two in-loop size checks in readAttachmentHeaders so SPEC §10.3 step 3 validation runs on all attachment headers before step 5 uint64 size checks (RejectCodeTooBig). Added TestReadAttachmentHeadersInvalidPrecedesTooBig.
  5. updateRecipient SQL deduplication (cmd/fmsgd/sender.go): Selected table/scope column once and collapsed to two UPDATE statements (delivered vs failed), covered by TestUpdateRecipientSQL.

@markmnl markmnl left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked 9e1956f against the five findings above and read the rest of the diff independently; 0dc188f on top of it only changes a test. All five are fixed and I found nothing blocking. One note inline on the sender pool size.

The five findings

  1. Sender pool: findPendingTargets, deliverMessage and markLocalDelivered use getSenderDB(); inbound handlers and indicators stay on getDB(). A stalled peer can no longer take connections from the receive path.
  2. Resolver timeout: the non-DNSSEC path has 20s overall; the 5s value stays per server on the DNSSEC clients.
  3. FinalizeBatch: both branches are back to the hash-checked UnmarshalPrepared, and the snapshot query selects sha256 again. The logic now matches main line for line.
  4. Reject precedence: the in-loop size checks are gone; the uint64 totals are checked after all attachment headers are validated.
  5. updateRecipient: two statements, with msg_add_to still scoped by batch_id.

Checked beyond that

  • Wire encoding: the rewritten Header.Encode produces byte-identical output to main's across 200,000 random headers (all flag combinations, pid, add-to, attachments). I did this as a throwaway differential test because the fmsg-docker suite runs this branch on both hosts and would not catch an encoding change that is self-consistent.
  • Indicators: subjectsOf reusing the first batch header is equivalent to the dropped originalFromBatch query (same filter and order).
  • preparePart: the rename into place cannot overwrite anything, since dst is inside a directory created for that message.
  • go vet passes and go test -race ./... at 0dc188f passes with the DB-backed tests enabled against a throwaway PostgreSQL 17 (172 pass, 0 skipped), including the new regression tests for findings 1 to 5.
  • The fmsg-docker suite passes 16/16 with 9e1956f on both hosts, together with the other three review/perf-and-reliability branches.

Minor, no change needed

  • Shutdown stops accepting and returns; in-flight exchanges and deliveries are cut when the process exits, as on main where the signal simply killed it. Deliveries are retried after restart. A bounded wait for in-flight handlers would make it a drain.

Comment thread cmd/fmsgd/store.go
const (
dbMaxOpenConns = 48
dbMaxIdleConns = 16
senderDBMaxOpenConns = 32

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is now the real ceiling on outbound concurrency. deliverUnit holds one connection from this pool for the whole exchange, so at most 32 deliveries run at once whatever FMSG_MAX_CONCURRENT_SEND says (default 1024, and the README still describes it as the limit). The remaining goroutines queue in db.Begin() while holding their semaphore slot.

Where it shows: a backlog for an unreachable domain. Each attempt holds a connection for the 10s dial per IP, so 1,000 pending messages for a dead peer occupy the pool for about five minutes, and deliveries to healthy domains wait behind them. findPendingTargets shares the pool, so the poll waits too.

main was not better in principle (one uncapped pool per delivery, bounded only by PostgreSQL's max_connections), so I would not block on this. Options:

  • Size the pool from configuration, e.g. min(MaxConcurrentSend, FMSG_SENDER_DB_MAX_CONNS), and document that this is the effective limit.
  • Note in the README that fmsgd can now open up to 80 connections (48 + 32) against a default max_connections of 100 shared with fmsg-webapi.
  • Longer term, the second option from finding 1: claim the rows and commit, deliver without a transaction open, then record outcomes. That removes the coupling between network time and DB connections.

markmnl and others added 2 commits November 25, 2026 21:27
Each outbound delivery holds one connection from the 32-connection sender
pool for the whole exchange, so FMSG_MAX_CONCURRENT_SEND has no effect
above 32.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@markmnl

markmnl commented Nov 25, 2026

Copy link
Copy Markdown
Owner Author

Pushed a README-only change (3cff8f6 plus df748b4): the FMSG_MAX_CONCURRENT_SEND row now says that each delivery holds one connection from the 32-connection sender pool, so at most 32 run at once.

3cff8f6 also converted the file's CRLF line endings by mistake; df748b4 restores them, so the net change against 0dc188f is that one table row. The pool size itself is unchanged and tracked as a follow-up.

@markmnl
markmnl merged commit 9289b61 into main Nov 25, 2026
2 checks passed
@markmnl
markmnl deleted the review/perf-and-reliability branch November 25, 2026 15:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant