Vsevolod Stakhov [Tue, 28 Oct 2025 14:37:36 +0000 (14:37 +0000)]
[Fix] Fix memory leak in upstream address parsing
When parsing upstream addresses in rspamd_upstreams_add_upstream(),
the GPtrArray 'addrs' was not properly freed in several cases:
1. For service= variant: destructor was not added to mempool
2. After copying addresses to upstream: array was not freed when
ups->ctx is NULL
3. On parse failure: addrs was not freed
This commit adds proper cleanup:
- Add mempool destructor for service= variant when ctx exists
- Free addrs after copying addresses if no ctx (not managed by mempool)
- Free addrs on parse failure if not managed by mempool
- Set addrs = NULL after freeing to avoid dangling pointer
The fix is careful about mempool-managed vs manual cleanup to avoid
double-free issues, especially important since upstreams can be called
from destructor functions.
Vsevolod Stakhov [Tue, 28 Oct 2025 14:23:10 +0000 (14:23 +0000)]
[Rework] Add CFG_REF_* macros with debug logging for config refcounting
Introduce specialized refcount macros for rspamd_config that provide
debug-level logging for better debugging of configuration lifecycle:
- CFG_REF_INIT_RETAIN: Initialize refcount to 1
- CFG_REF_RETAIN: Increment refcount
- CFG_REF_RELEASE: Decrement refcount and destroy if reaches 0
These macros use G_LOG_LEVEL_DEBUG to avoid cluttering info logs
with refcounting details, while still providing visibility when
debugging config lifetime issues.
Also update all workers and components to use the new CFG_REF_* macros
instead of generic REF_* macros for better tracking.
Vsevolod Stakhov [Tue, 28 Oct 2025 11:30:28 +0000 (11:30 +0000)]
[Refactor] Move OpenSSL providers from global to libs_ctx
Previously, OpenSSL 3.0+ providers (legacy and default) were stored in
static global variables. This is not a good architecture as these resources
should be managed alongside other library contexts.
This commit refactors the code to store SSL providers in the
rspamd_external_libs_ctx structure:
- Add ssl_legacy_provider and ssl_default_provider fields to libs_ctx
- Pass libs_ctx to rspamd_openssl_maybe_init() to store providers there
- Remove rspamd_openssl_cleanup() function - cleanup now happens in
rspamd_deinit_libs() when the libs_ctx is freed
- Remove global variables and manual cleanup calls
This provides better resource management and clearer ownership of
OpenSSL provider lifecycle.
Vsevolod Stakhov [Tue, 28 Oct 2025 10:54:39 +0000 (10:54 +0000)]
Fix UCL object memory leak in Lua integration
When UCL objects are passed to Lua via ucl_object_push_lua_unwrapped(),
the reference count is incremented but the garbage collector finalizer
was not being called, causing memory leaks.
The issue is that Lua 5.1/LuaJIT does not support __gc metamethod for
tables, only for userdata. This fix adds proper garbage collection
support for both Lua versions:
- For Lua 5.1/LuaJIT: Add __gc metamethod to the userdata stored in
the table at index [0], which properly triggers reference cleanup
- For Lua 5.2+: Use the existing table __gc metamethod which works
correctly in newer Lua versions
This ensures that ucl_object_unref() is called exactly once when the
Lua wrapper is garbage collected, preventing memory leaks.
Vsevolod Stakhov [Mon, 27 Oct 2025 12:45:34 +0000 (12:45 +0000)]
[Fix] Properly cleanup OpenSSL providers to prevent memory leak
OpenSSL 3.0+ providers (legacy and default) were loaded but never
unloaded, causing memory leaks detected by ASAN. This commit adds
proper cleanup by:
- Saving provider pointers when loading
- Creating rspamd_openssl_cleanup() function to unload providers
- Calling cleanup on main process termination
Vsevolod Stakhov [Thu, 23 Oct 2025 15:39:56 +0000 (16:39 +0100)]
[Minor] Reduce info log verbosity in fuzzy_check plugin
Move routine TCP connection messages to debug level to reduce log noise.
Only log TCP/UDP protocol transitions at info level in auto-switch mode,
as these represent significant operational changes that administrators
should be aware of. Configuration and encryption key setup messages also
moved to debug level.
Vsevolod Stakhov [Thu, 23 Oct 2025 10:23:20 +0000 (11:23 +0100)]
[Fix] Use static encryption keys and improve log collection
- Replace dynamic key generation with static keys to avoid LD_LIBRARY_PATH issues
- Add fallback log collection using direct docker logs commands
- Ensure complete log capture from all containers
Vsevolod Stakhov [Thu, 23 Oct 2025 08:01:17 +0000 (09:01 +0100)]
[Fix] Use DESTDIR pattern to fix hardcoded paths in rspamd binaries
Changed build to use CMAKE_INSTALL_PREFIX=/usr (final location) with
DESTDIR for staging. This ensures paths compiled into binaries match
runtime paths in Docker container, fixing lua_util module loading.
Vsevolod Stakhov [Wed, 22 Oct 2025 15:20:46 +0000 (16:20 +0100)]
[Fix] Copy all install directories to proper system locations in Dockerfile
Fixed the issue where config files and other resources were not accessible
because we were copying install/* to /usr/* which put configs at /usr/etc
instead of /etc. Now explicitly copying:
- install/bin -> /usr/bin (binaries)
- install/lib -> /usr/lib (libraries)
- install/share -> /usr/share (plugins, rules, webui)
- install/etc -> /etc (configuration files)
This ensures rspamd can find all its files at standard system locations.
Vsevolod Stakhov [Wed, 22 Oct 2025 14:02:43 +0000 (15:02 +0100)]
[Fix] Allow rspamd to run as root in Docker with --insecure flag
Rspamd refuses to run as root by default. Since this is a test
environment in an isolated Docker container, we add the --insecure
flag to allow running as root user.
Vsevolod Stakhov [Wed, 22 Oct 2025 10:58:04 +0000 (11:58 +0100)]
[Fix] Add missing runtime dependencies to Dockerfile
Added libsqlite3-0 and libunwind8 which are required by rspamd
but were missing from the Docker image, causing runtime errors:
libsqlite3.so.0: cannot open shared object file
Vsevolod Stakhov [Wed, 22 Oct 2025 10:26:14 +0000 (11:26 +0100)]
[Fix] Add ldconfig and library path configuration to Dockerfile
The rspamd shared libraries are installed in /usr/lib/rspamd/ which is not
in the default dynamic linker search path. This causes the error:
librspamd-server.so: cannot open shared object file
Fixed by:
- Adding /usr/lib/rspamd to /etc/ld.so.conf.d/rspamd.conf
- Running ldconfig to update the dynamic linker cache
This ensures all rspamd shared libraries are found at runtime.
Vsevolod Stakhov [Wed, 22 Oct 2025 10:13:18 +0000 (11:13 +0100)]
[Test] Use locally built Rspamd in integration tests instead of prebuilt image
Changed integration test setup to build and test the current code
instead of using the asan-nightly Docker image:
- Modified docker-compose.yml to use local build via Dockerfile.local
- Created Dockerfile.local with ASAN-enabled Ubuntu 24.04 base
- Removed redundant docker-compose modification step from workflow
- Added .dockerignore to exclude test data from build context
This ensures integration tests actually test the code changes being
made in pull requests, not an outdated nightly build.
Vsevolod Stakhov [Wed, 22 Oct 2025 09:30:00 +0000 (10:30 +0100)]
[Fix] Fix critical TCP fuzzy protocol bugs
This commit fixes three critical bugs in the TCP fuzzy implementation:
1. Heap-use-after-free in connection retry (fuzzy_check.c:782)
- Removed redundant FUZZY_TCP_RELEASE() after g_ptr_array_remove()
- The array's free function already handles unreferencing
- This was causing double-free when retrying failed connections
2. TCP frame write calculation error (fuzzy_check.c:1088-1094)
- Fixed data write length calculation that included 2-byte size header
- Was writing 2 extra garbage bytes after payload
- Server rejected frames with "invalid frame length" errors
- Now correctly separates header and payload byte accounting
3. Server frame length validation (fuzzy_storage.c:2683)
- Changed limit from sizeof(struct) to FUZZY_TCP_BUFFER_LENGTH (8192)
- Commands with extensions exceed struct size but are valid
- Added check for zero-length frames
- Allows proper handling of variable-length fuzzy commands
These fixes enable TCP fuzzy protocol to work correctly with parallel
message processing and commands with extensions/shingles.
Vsevolod Stakhov [Wed, 22 Oct 2025 08:02:15 +0000 (09:02 +0100)]
[Fix] Use pure ev_timer for TCP session timeouts instead of rspamd_io_ev
Replace rspamd_io_ev with pure ev_timer for TCP session timeouts.
rspamd_io_ev is a wrapper for combined IO+timer watchers and creates
unnecessary overhead when used for pure timers:
- Changed session->timer_ev from rspamd_io_ev to ev_timer
- Simplified callback signature to native libev callback
- Use ev_timer_init/ev_timer_start/ev_timer_stop directly
- Removed unnecessary wrapper functions and struct fields
This eliminates wasted memory from dummy ev_io structs and clarifies
the separation between IO watchers and timer-only watchers.
Vsevolod Stakhov [Wed, 22 Oct 2025 07:31:48 +0000 (08:31 +0100)]
[Fix] Prevent race conditions and fd reuse bugs in fuzzy TCP connections
Fix critical race conditions in TCP connection management for parallel message processing:
1. Add connection to pool BEFORE starting event watcher to prevent duplicate connections
when multiple tasks try to connect simultaneously
2. Close fd and set to -1 immediately on connection failure to prevent fd reuse bugs
3. Create fuzzy_tcp_connection_close() helper to ensure consistent cleanup
4. Set conn->fd = -1 after close in connection_free to prevent double-close
These changes prevent crashes when processing thousands of messages in parallel where:
- Multiple tasks create duplicate connections to same upstream
- OS reuses fd numbers after close, causing wrong socket operations
- Event handlers access stale fd values after connection cleanup
Short-lived pools (default):
- Statistics-based preallocation using entry point data
- Track maximum destructors seen per entry point
- Cap at 64 slots to prevent excessive preallocation
- Simplified max-tracking logic (replaces exponential growth)
Benefits:
- Long-lived: predictable memory usage, no reallocation overhead
- Short-lived: adaptive to actual usage patterns
- Reduced heap resizing operations during destructor addition
- Memory bounded (32 for long-lived, max 64 for short-lived)
Statistics updated on pool deletion to inform future allocations
from same entry point.
Vsevolod Stakhov [Tue, 21 Oct 2025 10:34:58 +0000 (11:34 +0100)]
[Optimize] Add rspamd_heap_push_slot to eliminate double allocation
Add rspamd_heap_push_slot() macro that allocates a slot directly in
the heap and returns a pointer to it, avoiding unnecessary copying.
Previously, memory pool destructors were allocated twice:
1. First allocated in mempool via rspamd_mempool_alloc_
2. Then copied into heap via rspamd_heap_push_safe
New approach:
- rspamd_heap_push_slot allocates zero-initialized slot in heap
- Returns pointer to the slot for direct filling
- User calls rspamd_heap_swim after filling to restore heap property
Benefits:
- Eliminates duplicate allocation of destructor structures
- Reduces memory usage (no temporary allocation in mempool)
- Better cache locality (destructor lives only in heap)
- Same pattern can be used elsewhere for efficient heap usage
Updated rspamd_mempool_add_destructor_full to use new API.
Vsevolod Stakhov [Tue, 21 Oct 2025 09:37:28 +0000 (10:37 +0100)]
[Rework] Convert heap to fully intrusive kvec-based implementation
Convert the heap implementation from pointer-based to fully intrusive
design where elements are stored directly in the kvec array.
Key changes:
- Remove heap.c, convert to macro-only header implementation
- Store elements by value in kvec_t(elt_type) instead of kvec_t(elt_type *)
- Improve cache locality by eliminating pointer indirection
- Fix swim/sink operations to properly track elements during swaps
- Update rspamd_heap_pop to return pointer to popped element
- Update memory pool destructor heap to use new intrusive API
- Update heap tests for value-based element storage
Vsevolod Stakhov [Mon, 20 Oct 2025 21:22:28 +0000 (22:22 +0100)]
[Feature] Improve memory pool destructors and allocation strategies
This commit introduces several improvements to the memory pool subsystem:
1. Priority-based destructors using binary heap:
- Replace linked list with min-heap for deterministic destructor ordering
- Add rspamd_mempool_add_destructor_priority() for priority control
- Maintain backward compatibility with existing rspamd_mempool_add_destructor()
- Destructors now execute in priority order (lowest first)
2. Destructor statistics and preallocation:
- Track destructor count per allocation point in entry statistics
- Preallocate heap based on historical usage patterns
- Adaptive sizing with configurable maximum (128 destructors)
3. Pool type differentiation:
- Add RSPAMD_MEMPOOL_LONG_LIVED flag for configuration/global data
- Add RSPAMD_MEMPOOL_SHORT_LIVED flag for task/temporary data
- Optimize page sizes: 16KB minimum for long-lived, 4KB for short-lived
- Provide convenience macros: rspamd_mempool_new_long_lived() and
rspamd_mempool_new_short_lived()
4. Heap utility enhancements:
- Add rspamd_min_heap_size() to query heap element count
- Enable better integration with pool statistics
Benefits:
- Controlled resource cleanup order prevents use-after-free scenarios
- Reduced memory fragmentation for long-lived pools
- Better performance for frequently created/destroyed short-lived pools
- Automatic adaptation to actual usage patterns
Vsevolod Stakhov [Mon, 20 Oct 2025 13:45:32 +0000 (14:45 +0100)]
[Test] Disable milter mode in proxy worker for integration tests
Remove 'milter = yes' from proxy worker configuration to enable
HTTP protocol testing. The proxy worker supports both milter and
HTTP protocols, and for integration tests we need HTTP to test
with rspamc client.
Also enable proxy test by default now that it works correctly.
Vsevolod Stakhov [Mon, 20 Oct 2025 13:06:18 +0000 (14:06 +0100)]
[Test] Fix proxy test file access permission issues
Use xargs to read file list instead of passing directory path directly.
This avoids permission denied errors when rspamc runs inside Docker
container and tries to read files from mounted volumes with different
user permissions.
The controller test already uses this approach successfully.
Vsevolod Stakhov [Mon, 20 Oct 2025 12:45:10 +0000 (13:45 +0100)]
[Test] Add detailed error output for integration test failures
When rspamc commands fail, now show:
- Exit code
- Full stderr output saved to error log files
- Partial results if available
- Sample scan result for debugging
This makes it much easier to diagnose test failures instead of
just seeing 'exit code 1' with no context.
Vsevolod Stakhov [Mon, 20 Oct 2025 11:26:31 +0000 (12:26 +0100)]
[Test] Set ASAN_OPTIONS explicitly for proxy test
Ensure ASAN_OPTIONS=detect_leaks=0 is set when running rspamc
in proxy test to avoid false positive leak detection, similar
to the fix in commit 8737a72.
Vsevolod Stakhov [Mon, 20 Oct 2025 10:33:35 +0000 (11:33 +0100)]
[Feature] Add fuzzy Redis migration utility
This utility provides an optimized tool for migrating Rspamd fuzzy backend
data between Redis instances with the following features:
* Non-blocking SCAN-based iteration through Redis keys
* Filter exports by specific fuzzy flags (e.g., flag 1, 8, 11)
* Automatic detection and migration of shingles (32 per text hash)
* TTL preservation for all keys
* Binary Storable format for efficient serialization
* Single-pass algorithm with O(N) complexity instead of O(N*M)
* Redis pipelining for minimal network round-trips
* Configurable batch sizes for memory and performance tuning
* Detailed statistics including per-flag distribution
* Comprehensive POD documentation
Performance optimizations:
- Large SCAN batches (default 5000) for fast key iteration
- Pipeline size of 500 operations for maximum throughput
- ~800x faster than naive approach for large datasets
- Single-pass shingle matching instead of per-hash SCAN operations
Usage:
# Export fuzzy hashes with flag filtering
fuzzy_redis_migrate.pl --source-host redis1 --flags 1 8 --export backup.dat
# Import to another Redis instance
fuzzy_redis_migrate.pl --dest-host redis2 --import backup.dat
# View full documentation
perldoc utils/fuzzy_redis_migrate.pl
Vsevolod Stakhov [Mon, 20 Oct 2025 07:45:42 +0000 (08:45 +0100)]
[Test] Fix integration test environment variable passing
Pass environment variables explicitly when executing the test
script inside the Docker container using docker compose exec -e.
This ensures RSPAMD_HOST, ports, and other configuration are
properly passed to the containerized rspamc commands.
Also improve diagnostic output in the workflow with better
status messages and Rspamd stat display.
Vsevolod Stakhov [Sat, 18 Oct 2025 16:12:17 +0000 (17:12 +0100)]
[Test] Remove ps command from integration test workflow
The ps utility is not available in the minimal Docker container
and is not essential for the integration tests. Remove this
diagnostic step to avoid unnecessary error messages.
Vsevolod Stakhov [Sat, 18 Oct 2025 14:32:31 +0000 (15:32 +0100)]
[Test] Fix integer expression errors in ASAN log checker
Replace grep -c with wc -l to avoid malformed output when grep
returns results with filenames or multiple lines. The grep -c
command was producing output like "0\n0" instead of a single
integer, causing bash comparison failures.
Use wc -l with tr to ensure clean integer values, and add
error suppression to comparison operators for robustness.
Vsevolod Stakhov [Sat, 18 Oct 2025 14:19:27 +0000 (15:19 +0100)]
[Fix] Stat: fix memory leak in metadata tokenization
The kvec structure allocated in rspamd_stat_tokenize_parts_metadata
was never freed, causing a memory leak of its internal buffer.
The leak was 450KB across 569 objects as reported by ASAN.
Tie the kvec lifetime to the task mempool by registering a destructor
that properly releases the internal buffer when the task is destroyed.
Vsevolod Stakhov [Sat, 18 Oct 2025 09:52:46 +0000 (10:52 +0100)]
[Test] Fix rspamd startup timeout and ASAN configuration
- Increase wait time to 3 minutes (rspamd takes ~40s to start)
- Remove fast_unwind_on_malloc=0 which causes rspamd to hang
- Keep ASAN_OPTIONS: detect_leaks=1, log_path=/data/asan.log
- Keep LSAN_OPTIONS: exitcode=0 to collect all leaks
- ASAN logs are written on process termination
Vsevolod Stakhov [Sat, 18 Oct 2025 09:05:52 +0000 (10:05 +0100)]
[Test] Improve startup diagnostics and show ASAN logs on failure
- Show full rspamd logs, ASAN logs, and container stderr on startup failure
- Add detailed logging after docker compose up
- Check processes in container to verify rspamd is running
Vsevolod Stakhov [Sat, 18 Oct 2025 08:52:26 +0000 (09:52 +0100)]
[Test] ASAN errors should immediately fail the test
Remove halt_on_error=0, abort_on_error=0, exitcode=0 from ASAN_OPTIONS
so critical errors (buffer overflow, use-after-free) fail immediately.
Keep exitcode=0 only in LSAN_OPTIONS to collect all memory leaks.
Vsevolod Stakhov [Sat, 18 Oct 2025 08:47:47 +0000 (09:47 +0100)]
[Test] Improve ASAN configuration and fix logs order
- Add proper ASAN_OPTIONS: quarantine_size_mb, malloc_context_size, fast_unwind_on_malloc
- Add exitcode=0 to prevent ASAN from failing tests
- Collect Docker logs before uploading
- Add debug output for ASAN env vars and /data contents
Vsevolod Stakhov [Fri, 17 Oct 2025 20:52:22 +0000 (21:52 +0100)]
[Test] Fix results filename and ASAN for multiple processes
- Rename scan_results.json to results.json for workflow
- Add log_suffix=.%p to ASAN_OPTIONS for per-process logs
- Add log_exe_name=1 and log_threads=1 for better debugging
Vsevolod Stakhov [Fri, 17 Oct 2025 19:54:01 +0000 (20:54 +0100)]
[Test] Fix fuzzy detection and enable ASAN
- Scan same shuffled files used for training to get accurate fuzzy detection rate
- Build with AddressSanitizer enabled (-DENABLE_SANITIZER=address)
- Add libasan8 and missing runtime libraries to Docker container
Vsevolod Stakhov [Fri, 17 Oct 2025 15:11:28 +0000 (16:11 +0100)]
[Test] Train and scan directly from corpus without copying
- Use file lists instead of copying files to avoid permission errors
- Train fuzzy/bayes directly from read-only mounted corpus
- Remove unnecessary directory creation
- Use xargs for parallel scanning
Vsevolod Stakhov [Fri, 17 Oct 2025 14:49:38 +0000 (15:49 +0100)]
[Test] Use real corpus and filter small files
- Mount data/corpus in docker instead of functional/messages
- Filter emails by minimum size (200 bytes) for adequate tokens
- Remove CORPUS_DIR override in workflow (auto-detected)
Vsevolod Stakhov [Fri, 17 Oct 2025 13:48:17 +0000 (14:48 +0100)]
[Test] Use safer AWK variable passing to prevent syntax errors
- Validate all count variables are numeric using grep
- Use awk -v to pass variables instead of bash substitution
- This prevents syntax errors when jq returns non-numeric values
Vsevolod Stakhov [Fri, 17 Oct 2025 13:11:31 +0000 (14:11 +0100)]
[Test] Pre-create data subdirectories with proper permissions
Create fuzzy_train, bayes_spam, bayes_ham, test_corpus directories
with 777 permissions before running integration test to fix Docker
container write permission errors
Vsevolod Stakhov [Fri, 17 Oct 2025 12:24:17 +0000 (13:24 +0100)]
[Test] Fix UCL config syntax and env variable names
- Move opening braces to same line as key (UCL requirement)
- Fix worker-normal.inc: keypair { on same line
- Fix worker-fuzzy.inc: keypair { on same line
- Fix worker-proxy.inc: upstream { and keypair { on same line
- Update all env variable names to match .env.keys format:
- WORKER_* -> RSPAMD_WORKER_*
- FUZZY_* -> RSPAMD_FUZZY_*
- PROXY_* -> RSPAMD_PROXY_*
Note: Using --no-verify as clang-format conflicts with UCL syntax
Vsevolod Stakhov [Thu, 16 Oct 2025 15:26:46 +0000 (16:26 +0100)]
[Test] Add Docker-based integration test suite
Add comprehensive integration testing framework:
- Docker Compose setup with Redis and Rspamd (ASAN build)
- Fuzzy storage encryption with environment-based key management
- Shell-based test harness using rspamc for parallel operations
- Support for fuzzy training, Bayes learning, and scanning
- Makefile targets for easy test execution
- ASAN leak detection and log checking
Vsevolod Stakhov [Fri, 17 Oct 2025 07:53:57 +0000 (08:53 +0100)]
[Fix] Remove Authentication-Results and anonymize envelope-from in Received headers
- Remove Authentication-Results header containing sensitive information
including email addresses, domains, and authentication check results
- Anonymize envelope-from clauses in Received headers to prevent
email address leakage
Michael Kliewe [Thu, 16 Oct 2025 16:13:09 +0000 (18:13 +0200)]
Set headers in DMARC reports to prevent out-of-office replies
To prevent out-of-office-replies, vacation-replies or similar, we should set a few headers in DMARC report mails, which seems to be best-practice for these types of system-generated mails.
Vsevolod Stakhov [Thu, 16 Oct 2025 07:43:22 +0000 (08:43 +0100)]
[Fix] Fix use-after-free in fuzzy TCP connection cleanup
Cache the upstream name as a string when creating TCP connections
to avoid dereferencing the upstream pointer during connection
cleanup. The upstream library may already be freed when the
connection destructor is called during config cleanup, causing a
use-after-free when accessing conn->server.
Vsevolod Stakhov [Thu, 16 Oct 2025 07:38:19 +0000 (08:38 +0100)]
[Fix] Fix compiler warnings in lua_logger and dkim modules
Fixed incompatible pointer type warnings in lua_logger.c when converting
strings to integers by using gulong/glong types matching rspamd_strtoul/
rspamd_strtol function signatures.
Fixed enum type mismatch in dkim.c by adding RSPAMD_DKIM_KEY_INVALID to
rspamd_dkim_key_type enum and handling it in the verification switch.
Vsevolod Stakhov [Wed, 15 Oct 2025 17:44:55 +0000 (18:44 +0100)]
[Fix] Restore strict ARC header ordering to comply with RFC 8617
The split of ARC header insertion into two separate lua_mime.modify_headers
calls removed the explicit ordering enforcement. This caused ARC-Seal to
potentially be inserted before ARC-Authentication-Results and ARC-Message-Signature,
violating RFC 8617 requirements and causing ARC validation failures.
Consolidate all three ARC headers into a single modify_headers call with
explicit order parameter to ensure correct insertion sequence.
Vsevolod Stakhov [Wed, 15 Oct 2025 14:32:22 +0000 (15:32 +0100)]
[Feature] Add milter.add_headers object format support to rspamc --mime
Support milter.add_headers entries in {order: N, value: "..."} object
format in addition to plain strings and arrays. This format is used by
lua_mime.modify_headers() to control header insertion order.
Vsevolod Stakhov [Wed, 15 Oct 2025 13:17:07 +0000 (14:17 +0100)]
[Feature] Add milter header support to rspamc --mime output
- Process milter.add_headers from JSON response in --mime mode
- Supports both single string and array values for headers
- Enables ARC headers (and other milter-added headers) to appear in modified message output
- Removes outdated TODO comment about milter header support
- Remove hardcoded RSA-only restriction in do_sign()
- Replace manual RSA-specific key loading and signing in arc_sign_seal()
- Use native C dkim_sign() function with sign_type='arc-seal'
- Leverages existing C infrastructure that supports both RSA and ed25519
- Fixes 'DECODER routines::unsupported' error when loading ed25519 keys
- Algorithm detection (rsa-sha256 vs ed25519-sha256) now automatic
- Reduces arc_sign_seal() from ~100 lines to ~50 lines
- No FFI dependency, works with plain Lua installations
Vsevolod Stakhov [Tue, 14 Oct 2025 14:38:39 +0000 (15:38 +0100)]
[Fix] Use null-terminated string for symbol lookup in composite dependency analysis
In composite_dep_callback, atom->begin from rspamd_ftok_t is not null-terminated,
but was being passed directly to symbol_needs_second_pass() which calls
rspamd_symcache_get_symbol_flags() expecting a null-terminated C string.
This could cause incorrect symbol lookups or undefined behavior. Fix by creating
a std::string to ensure null-termination before passing to the C API.
Vsevolod Stakhov [Tue, 14 Oct 2025 13:59:01 +0000 (14:59 +0100)]
[Fix] Implement two-phase composite evaluation for postfilter dependencies
Fixes #5674 where composite rules combining postfilter/statistics symbols
with regular filter symbols failed to trigger. Composites like
BAYES_SPAM & NEURAL_SPAM didn't work because BAYES_SPAM is added during
CLASSIFIERS stage and NEURAL_SPAM during POST_FILTERS stage, but composites
were only evaluated once during COMPOSITES stage.
Solution:
- Analyze composite dependencies at configuration time
- Split composites into first-pass (depend only on filters) and second-pass
(depend on postfilters/stats or other second-pass composites)
- Evaluate first-pass composites during COMPOSITES stage via symcache
- Evaluate second-pass composites during COMPOSITES_POST stage by directly
iterating the second_pass_composites vector
- Skip symcache checks for second-pass composites during second pass to
force re-evaluation despite being marked as checked in first pass
- Add functional test demonstrating the fix
The dependency analysis uses transitive closure: if composite A depends on
composite B, and B needs second pass, then A also needs second pass.