Skip to content

Filter body plugin - #1

Closed
bryancall wants to merge 21 commits into
masterfrom
filter_body_plugin
Closed

bryancall wants to merge 21 commits into
masterfrom
filter_body_plugin

Conversation

@bryancall

@bryancall bryancall commented Dec 5, 2025 •

Copy link
Copy Markdown
Owner

Note

Adds an experimental filter_body remap plugin for streaming request/response body inspection with YAML rules and actions, plus docs, tests, and build/test harness updates.

  • Plugin (experimental):
    • Adds plugins/experimental/filter_body remap plugin providing zero-copy streaming body inspection with YAML-configured rules (headers/methods/status, body_patterns) and actions (log, block, add_header), with per-rule metrics.
    • Integrates build via BUILD_FILTER_BODY option and add_subdirectory(filter_body).
  • Documentation:
    • New admin guide page doc/admin-guide/plugins/filter_body.en.rst and index entry; plugin README.md.
  • Tests:
    • Adds AuTests under tests/gold_tests/pluginTest/filter_body/ with replay scenarios (log, block, add header for request/response) and YAML configs.
    • Extends test harness (autest-site): support return_code for client/server, configurable log validation, and disable_log_checks in MakeATSProcess.
  • Build/CMake:
    • Enables plugin option in cmake/ExperimentalPlugins.cmake and wires into plugins/experimental/CMakeLists.txt.

Written by Cursor Bugbot for commit 3160a54. This will update automatically on new commits. Configure here.

bryancall and others added 3 commits December 5, 2025 10:44
This plugin provides streaming body content inspection with configurable
pattern matching and actions. It can be used to detect and mitigate CVE
exploits and other malicious content patterns.

Features:
- YAML-based configuration with rule definitions
- Header-based filtering (AND logic between headers, OR within patterns)
- Case-insensitive header matching, case-sensitive body patterns
- Configurable actions per rule: log, block, add_header
- Support for both request and response body inspection
- Streaming transform with lookback buffer for cross-boundary patterns
- Optional max_content_length to skip large bodies
- Configurable HTTP methods to match (GET, POST, etc.)

Actions:
- log: Log pattern matches to traffic.out (via debug tags)
- block: Set 403 Forbidden status and close connection
- add_header: Add custom header to request/response

Includes ATSReplayTest autests covering:
- Log-only mode (pattern detection without blocking)
- Header addition on pattern match
- Header mismatch (no inspection when headers don't match)

Co-authored-by: Brian Neradt <[email protected]>
Adds comprehensive RST documentation covering:
- Plugin description and features
- Installation instructions
- YAML configuration file format
- All rule options and their usage
- Header and body pattern matching logic
- Available actions (log, block, add_header)
- Example configurations for common use cases:
  - XXE attack detection
  - SQL injection detection
  - Sensitive data leak detection
- Debugging tips
- Known limitations

Also updates the plugin index to include filter_body in the
experimental plugins section.

Co-authored-by: Brian Neradt <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This PR is being reviewed by Cursor Bugbot

Details

You are on the Bugbot Free tier. On this plan, Bugbot will review limited PRs each billing cycle.

To receive Bugbot reviews on all of your PRs, visit the Cursor dashboard to activate Pro and start your 14-day free trial.

Comment on lines +41 to +48
- YAML-based configuration with flexible rule definitions
- Header-based filtering with AND/OR logic
- Case-insensitive header matching, case-sensitive body patterns
- Configurable actions per rule: ``log``, ``block``, ``add_header``
- Support for both request and response body inspection
- Streaming transform with lookback buffer for cross-boundary pattern matching
- Optional ``max_content_length`` to skip inspection of large bodies
- Configurable HTTP methods to match (GET, POST, PUT, etc.)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nit: lets end these with periods.

Comment on lines +53 to +56
The ``filter_body`` plugin is an experimental plugin. To build it, pass
``-DENABLE_FILTER_BODY=ON`` to ``cmake`` when configuring the build::

cmake -DENABLE_FILTER_BODY=ON ...

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Isn't there a generic ENABLE_EXPERIMENTAL_PLUGINS switch too? Maybe mention that.

- log
- block
add_header_name: X-Security-Match
add_header_value: "rule_name"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Maybe organize these various rules under filter and action, two keep the two conecepts distinct.

Thus:

      - name: rule_name
        filter:
          direction: request|response
          methods:
            - POST
            - PUT
          max_content_length: 1048576
          headers:
            - name: Content-Type
              patterns:
                - "application/xml"
                - "text/xml"
          body_patterns:
            - "<!ENTITY"
            - "<!DOCTYPE"
        action:
          - log
          - block
        add_header_name: X-Security-Match
        add_header_value: "rule_name"

Also, tuck the add header manipulations under action as well:

  action
    - log
    - block
    - add_headers:
      - X-Security-Match: <rule_name>
      - X-Some-Header: "some value"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Still needs to be done.

Comment on lines +100 to +106
``direction`` (required)
Specifies whether to inspect request or response bodies.
Valid values: ``request``, ``response``

``methods`` (optional)
List of HTTP methods to match. If not specified, all methods are matched.
Example: ``[GET, POST, PUT]``

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

If response is a supported direction, then in addition to filtering on methods we should filter on status as well. An error should come if status is used with request or method is used with response.

Comment on lines +133 to +137
``add_header_name`` (optional)
Name of the header to add when ``add_header`` action is configured.

``add_header_value`` (optional)
Value of the header to add. Defaults to the rule name if not specified.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Indicate that <rule_name> is a directive indicating that the rules:name node value should be used for the http header field value.

Comment on lines +147 to +150
1. All configured headers must match (AND logic between headers)
2. Within each header, any pattern can match (OR logic between patterns)
3. Header name matching is case-insensitive
4. Header value matching is case-insensitive

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

End with periods.

Comment on lines +184 to +192
When the ``log`` action is configured, pattern matches are logged to the
Traffic Server debug log. To see these messages, enable debug logging with
the ``filter_body`` tag::

records:
proxy.config.diags.debug.enabled: 1
proxy.config.diags.debug.tags: filter_body

Log messages include the rule name and matched pattern.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Given that this is used to find security issues, maybe this should actually do error logging.

Maybe support both error_log and debug_log?

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actually, nevermind: debug logging should always just happen. Just keep it log and make it do error logging if the log action is used.

Comment on lines +199 to +206
- For request transforms: The connection is closed without forwarding to origin
- The HTTP status is set to 403 Forbidden

.. note::

For request body transforms, blocking occurs after body inspection begins.
The connection is closed rather than returning a clean HTTP 403 response
to the client.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

We have to be clear that since the plugin streams the body, this means that the origin may have received the problematic body by the time we send the 403 response.

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.

the plugin should make sure we are not sending invalid bodies to the origin, add a test for this too

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Yeah, you're right. It should be able to stop the request. That's good.

``name`` (required)
A unique name for the rule. Used in log messages when the rule matches.

``direction`` (required)

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.

default this to request, so it can be an optional config

@bneradt bneradt left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Adding a metric counter for each of these based on rule name would be helpful.

Comment on lines +95 to +138
// Case-insensitive string search
const char *
strcasestr_local(const char *haystack, size_t haystack_len, const char *needle, size_t needle_len)
{
if (needle_len == 0) {
return haystack;
}
if (haystack_len < needle_len) {
return nullptr;
}

for (size_t i = 0; i <= haystack_len - needle_len; ++i) {
bool match = true;
for (size_t j = 0; j < needle_len; ++j) {
if (std::tolower(static_cast<unsigned char>(haystack[i + j])) != std::tolower(static_cast<unsigned char>(needle[j]))) {
match = false;
break;
}
}
if (match) {
return haystack + i;
}
}
return nullptr;
}

// Case-sensitive string search
const char *
strstr_local(const char *haystack, size_t haystack_len, const char *needle, size_t needle_len)
{
if (needle_len == 0) {
return haystack;
}
if (haystack_len < needle_len) {
return nullptr;
}

for (size_t i = 0; i <= haystack_len - needle_len; ++i) {
if (memcmp(haystack + i, needle, needle_len) == 0) {
return haystack + i;
}
}
return nullptr;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Please re-implement using TextView.h. I believe that supports both case and case insenstive searches.

Comment on lines +148 to +159
int method_len = 0;
const char *method = TSHttpHdrMethodGet(bufp, hdr_loc, &method_len);
if (method == nullptr) {
return false;
}

std::string method_str(method, method_len);
for (const auto &m : rule.methods) {
if (strcasecmp(method_str.c_str(), m.c_str()) == 0) {
return true;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Switch these out for TextView.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Importantly, don't use std::string because that could do an unecessary copy.

Comment on lines +194 to +207
for (int i = 0; i < num_values && !matched; ++i) {
int value_len = 0;
const char *value = TSMimeHdrFieldValueStringGet(bufp, hdr_loc, field_loc, i, &value_len);
if (value == nullptr) {
continue;
}

// Check if any pattern matches (OR logic within header)
for (const auto &pattern : cond.patterns) {
if (strcasestr_local(value, value_len, pattern.c_str(), pattern.length()) != nullptr) {
matched = true;
break;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Again, TextView

return 0;
}

for (const auto &rule : config->response_rules) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Can you change all the const identifiers to right side const? Thus auto const &rule instead of cosnt auto &rule.

@bneradt bneradt left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

For the tests, please put the configs under a config directory like the replay files are under a replay directory.

const std::string *
search_body_patterns(const Rule &rule, const char *data, size_t data_len)
{
for (const auto &pattern : rule.body_patterns) {

@bryancall bryancall Dec 5, 2025 •

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.

would it be faster to search for all patterns at once instead of doing them one at a time? I am thinking about CPU cache. Maybe the complexity is not worth it.

TSMBuffer bufp;
TSMLoc hdr_loc;

// Add header to server request (proxy request going to origin)

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.

take a look at the direction to see if it is a request or a response and then add the header

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Yes. And probably best to always add our headers either to the TSHttpTxnServerReqGet (for requests) or TSHttpTxnClientRspGet (for responses).

Comment on lines +765 to +767
TSCont contp = TSContCreate(hook_handler, nullptr);
TSContDataSet(contp, config);
TSHttpTxnHookAdd(txnp, TS_HTTP_READ_RESPONSE_HDR_HOOK, contp);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

For clarity, let's rename hook_handler to response_handler

bool headers_added = false;
};

// Case-insensitive string search

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Add doxygen comments to all of these. Please use the [in], [out], and [in,out] decorators too.

Add Header Action
-----------------

When the ``add_header`` action is configured, a custom header is added:

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.

state that the new header won't be transferred to the origin or the client, because they might have already been sent because we examine the body most likely after the header were sent. Verity this in the ATS code base on how it works.

For request the added the header to the server request and for the response direction add the header to the client response. Make note of that in the docs. Maybe give a logging example or link to the docs on how to long headers for the server request and and the client response can be loggged.

// Search for patterns in lookback + current block
std::string search_window;
if (!data->lookback.empty()) {
search_window = data->lookback + std::string(block_data, block_avail);

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.

doesn't this copy all the data into a string? this isn't zero copy

}

TSRemapStatus
TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri ATS_UNUSED)

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.

maybe a better var name than ih?

TSVIOReenable(data->output_vio);

// Consume all remaining input
int64_t remaining = TSIOBufferReaderAvail(reader);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Make the type int64_t const

Comment on lines +184 to +192
When the ``log`` action is configured, pattern matches are logged to the
Traffic Server debug log. To see these messages, enable debug logging with
the ``filter_body`` tag::

records:
proxy.config.diags.debug.enabled: 1
proxy.config.diags.debug.tags: filter_body

Log messages include the rule name and matched pattern.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actually, nevermind: debug logging should always just happen. Just keep it log and make it do error logging if the log action is used.

bryancall and others added 3 commits December 5, 2025 12:38
Code improvements:
- Add doxygen comments with [in], [out], [in,out] decorators to all functions
- Rename 'ih' parameter to 'instance' for clarity in remap functions
- Make 'remaining' variable const as suggested
- Add detailed comment explaining the search_window copy for cross-boundary
  pattern matching (not truly zero-copy for this case)
- Add more inline comments throughout the code

Logging changes:
- Change log action from Dbg to TSNote so logging occurs without debug tags
- Log format is now: NOTE: [filter_body] Matched rule: <name>, pattern: <pat>

Documentation updates:
- Update log action section to reflect TSNote logging (no debug config needed)
- Add note about logging headers for debugging add_header action
- Expand add_header documentation to explain when headers are added
  (server request for request rules, client response for response rules)
- Add limitation about cross-boundary pattern search memory copy
- Update log format example to show NOTE: prefix

Test updates:
- Update log_only test to check diags_log instead of traffic_out

Co-authored-by: Brian Neradt <[email protected]>
Replace single-pass search that copied the entire block with a two-phase
approach:

Phase 1 (boundary search): Create a small buffer containing only the
lookback data plus the first (max_pattern_len - 1) bytes of the current
block. This catches patterns that span block boundaries. The copy is
limited to at most (2 * max_lookback) bytes.

Phase 2 (block search): Search the entire current block in-place without
any memory copying (zero-copy). This catches patterns entirely within
the block.

This significantly reduces memory copying - instead of copying the entire
block (which could be many KB), we now only copy a small boundary region
(typically < 100 bytes depending on pattern length).

Co-authored-by: Brian Neradt <[email protected]>
Changes:
- Add metrics counter for each rule that increments on pattern match
  - Metric name format: plugin.filter_body.rule.<rule_name>.matches
  - Plugin fails to load if stat creation fails (required for monitoring)
- Move test config files to config/ subdirectory per reviewer request
- Update replay files to reference new config paths
- Update documentation with Metrics section explaining how to query stats

Co-authored-by: Brian Neradt <[email protected]>
}
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: Pattern detection duplicates stats and logging

The two-phase pattern search can detect the same pattern occurrence twice. Phase 1 searches lookback + first boundary_extent bytes of block, while Phase 2 searches the entire block. When a pattern exists entirely within the first boundary_extent bytes of the current block (not spanning the boundary), both phases will find it. This causes execute_actions to be called twice for the same occurrence, resulting in double stat increments and duplicate log entries, skewing metrics and log analysis.

Fix in Cursor Fix in Web

…rules

Documentation changes:
- Add periods to end all feature list items and action list items.
- Mention ENABLE_EXPERIMENTAL_PLUGINS as alternative build option.
- Make 'direction' optional with default value of 'request'.
- Add 'status' option documentation for filtering response rules by HTTP status code.
- Document '<rule_name>' directive for dynamic header value substitution.
- Add warning about streaming limitation: origin may receive data before block.
- Update YAML examples to show optional direction and status filter.

Code changes:
- Add status_codes field to Rule struct for response rule status filtering.
- Add status_matches() function to check response status against rule filter.
- Parse 'status' configuration option in YAML.
- Apply status filter in response rule evaluation.

Co-authored-by: Brian Neradt <[email protected]>
if (rule_node["add_header"]["value"]) {
rule.add_header_value = rule_node["add_header"]["value"].as<std::string>();
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: Documented header value substitution feature not implemented

The documentation states that add_header_value "defaults to the rule name if not specified" and that users can "use the special value <rule_name> to substitute the rule's name dynamically." Neither feature is implemented. The config parsing doesn't set a default value when value is omitted (leaving it as empty string), and execute_actions passes rule->add_header_value directly to add_header_to_message without any substitution. Users following the documentation would get empty or literal <rule_name> header values instead of the expected rule name.

Additional Locations (1)

Fix in Cursor Fix in Web

Comment on lines +60 to +62
Or enable all experimental plugins with ``-DENABLE_EXPERIMENTAL_PLUGINS=ON``::

cmake -DENABLE_EXPERIMENTAL_PLUGINS=ON ...

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

It's actually BUILD_EXPERIMENTAL_PLUGINS not ENABLE_EXPERIMENTAL_PLUGINS.

Code changes:
- Fix memory leak: Add TS_HTTP_TXN_CLOSE_HOOK to destroy response handler
  continuation when transaction closes
- Fix response add_header: Use TSHttpTxnClientRespGet for response rules
  to add headers to client response instead of server request
- Rename hook_handler to response_handler for clarity
- Change to right-side const style throughout the code
- Validate method/status config: Error if 'status' used with request rules
  or 'methods' used with response rules
- Add direction field to TransformData to track request vs response

Test changes:
- Fix filter_body_response.yaml: Remove invalid 'methods' field, use 'status'
- Add response_filter test that verifies response rule matching
- Add test configs for response_add_header and status_filter (currently
  disabled due to timing issues with multi-transaction tests)

Co-authored-by: Brian Neradt <[email protected]>
if (rule_node["add_header"]["value"]) {
rule.add_header_value = rule_node["add_header"]["value"].as<std::string>();
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: Flat add_header_name config format not parsed

The configuration parser only handles the nested format (add_header.name and add_header.value) but does not parse the flat format (add_header_name and add_header_value). The test configuration file filter_body_response_header.yaml uses the flat format with add_header_name: "X-Data-Classification" and add_header_value: "sensitive", but this will not be parsed. The rule.add_header_name and rule.add_header_value fields will remain empty strings, causing the add_header action to silently add an empty header name.

Additional Locations (1)

Fix in Cursor Fix in Web

break;
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: Duplicate pattern detection causes double-counting metrics

The two-phase pattern search can detect the same pattern twice. Phase 1 searches the boundary buffer (lookback + first max_lookback bytes of current block), and Phase 2 searches the entire current block. A pattern within the first max_lookback bytes of the block can match in both phases, causing duplicate calls to execute_actions. This results in double-incrementing the metrics counter and duplicate log messages for the same pattern occurrence.

Fix in Cursor Fix in Web

rule.max_pattern_len = pattern.length();
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: Missing validation for required body_patterns field

The documentation specifies that body_patterns is required for each rule, but the configuration parser doesn't validate this requirement. If a rule is defined without body_patterns, it will be silently accepted, a transform will be created when header conditions match, and body inspection will run, but no patterns will ever match. This wastes resources and could lead to confusion when rules appear to never trigger despite correct header matching. The code should reject rules with empty or missing body_patterns.

Fix in Cursor Fix in Web

@bryancall

Copy link
Copy Markdown
Owner Author

Summary of Unaddressed PR Comments

Here are the PR comments that haven't been fully addressed and the reasons:

Code Refactoring (Deferred)

  1. Use TextView.h instead of std::string (lines 138, 190, 285)

    • Why not addressed: This requires a more extensive refactoring to replace std::string with swoc::TextView throughout the string comparison functions. The current implementation works correctly; this is an optimization/style change that could be done in a follow-up.
  2. Remove project() from CMakeLists.txt (line 18)

    • Why not addressed: After checking, many other experimental plugins (block_errors, access_control, rate_limit, etc.) also have project() in their CMakeLists.txt, so this appears to be an acceptable pattern.
  3. Search all patterns at once for CPU cache (line 328)

    • Why not addressed: This is an optimization suggestion. The current sequential pattern search works correctly. A multi-pattern algorithm (like Aho-Corasick) would add complexity and is better suited for a future optimization PR.

Documentation (Deferred by User Request)

  1. Support both error_log and debug_log (line 192)

    • Why not addressed: Deferred - currently using TSNote which always logs to diags.log.
  2. Reorganize YAML schema with filter and action sections (line 92)

    • Why not addressed: This is a significant schema change that would require code changes to the YAML parser and would break backward compatibility with existing configs. Better suited for a v2 design discussion.

Known Limitations (Documented)

  1. Response blocking doesn't return clean 403

    • Why not fully fixed: Response transforms process data after the response has started streaming. The block action sets the status but the response may already be partially sent. This is documented as a limitation in the docs.
  2. Response add_header timing issues

    • Why not fully working: TSHttpTxnClientRespGet may not be available during response body transforms. The code attempts to add headers but it may fail silently in some cases. This needs further investigation of the correct hook/timing for response header modification.

Summary: The core functionality is complete and tested. The remaining items are either optimizations, style preferences, or require more extensive architectural changes that would be better addressed in follow-up PRs.

Refactors the add_header action to use a cleaner YAML schema that
supports multiple headers in a single action:

  action:
    - log
    - add_header:
        X-Security-Match: "<rule_name>"
        X-Another-Header: "some-value"

Changes:
- Add AddHeader struct to store header name/value pairs
- Replace single add_header_name/add_header_value with vector of AddHeader
- Update YAML parser to parse nested add_header map format
- Add substitute_rule_name() function for <rule_name> placeholder
- Update execute_actions() to iterate and add all configured headers
- Update documentation with new schema and examples
- Update test configs and replay files for new format

Co-authored-by: Brian Neradt <[email protected]>
}
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: Patterns in block start cause duplicate match and logging

The two-phase pattern search causes duplicate matches when a pattern exists within the first boundary_extent bytes of a block. Phase 1 constructs boundary_buffer as lookback + first boundary_extent bytes of current block and searches it entirely. Phase 2 then searches the entire current block. A pattern starting at position >= lookback.length() in boundary_buffer will be found by both phases, causing execute_actions to be called twice. This results in the stats counter being incremented twice and duplicate log messages for each single pattern occurrence. The intent per the comments is for Phase 1 to only catch patterns that span block boundaries (starting in lookback), but the implementation also catches patterns entirely within the overlapping region.

Fix in Cursor Fix in Web

data->lookback.reserve(config->max_lookback);
}

TSContDataSet(connp, data);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: Missing error check causes memory leak on transform creation failure

The create_transform function allocates a TransformData object on line 674 after calling TSTransformCreate on line 672, but never checks if TSTransformCreate succeeded. If TSTransformCreate returns an invalid connection (e.g., during resource exhaustion), the allocated TransformData would be leaked because TSContDataSet would be called on an invalid handle, and the data pointer would never be cleaned up by the transform handler's cleanup logic.

Fix in Cursor Fix in Web

- Convert to proper markdown format with tables and code blocks
- Update add_header examples to use new nested schema
- Add metrics section
- Add link to official documentation
- Modernize to match other experimental plugins

Co-authored-by: Brian Neradt <[email protected]>
Comment on lines +81 to +93
direction: request # optional, defaults to request
methods: # for request rules only
- POST
- PUT
max_content_length: 1048576
headers:
- name: Content-Type
patterns:
- "application/xml"
- "text/xml"
body_patterns:
- "<!ENTITY"
- "<!DOCTYPE"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

To create a clear distinction between nodes that are actions and filters, make a filter node like we have an action node. filter should contain methods, max_content_length, headers, and body_patterns and status. All the nodes related to filtering which requests the action will apply to.

bneradt and others added 3 commits December 8, 2025 08:59
Add a 'filter' node to contain all filtering criteria (direction, methods,
status, max_content_length, headers, body_patterns), creating a clear
distinction between what triggers a rule and what action is taken.

Changes:
- Update YAML parser to require and parse the filter node
- Update all test configuration files to use new schema
- Update documentation (RST and README.md) with new examples
- End documentation items with periods for consistency

This change improves configuration clarity by grouping all filtering
criteria together, separate from the action configuration.

New schema format:
  rules:
    - name: rule_name
      filter:
        direction: request
        methods: [POST]
        headers:
          - name: Content-Type
            patterns: ["application/xml"]
        body_patterns:
          - "<!ENTITY"
      action:
        - log
        - block

Co-authored-by: Bryan Call <[email protected]>
Add TSHttpTxnReenable call when handling TS_EVENT_HTTP_TXN_CLOSE in
response_handler. Without this, the transaction may not complete
properly when the close event fires.

Co-authored-by: Bryan Call <[email protected]>
The two-phase search was detecting patterns twice when they existed
entirely within the first boundary_extent bytes of a block:
- Phase 1: Found in boundary_buffer (lookback + start of block)
- Phase 2: Found again when searching entire block

Fix by tracking search_offset and having Phase 2 skip the bytes
already covered by Phase 1's boundary search. This prevents duplicate
logging, stats increments, and action execution for the same pattern.

Co-authored-by: Bryan Call <[email protected]>
bneradt and others added 3 commits December 8, 2025 09:41
The previous duplicate-detection fix could miss patterns that start within
the first max_lookback bytes of a block but extend past the boundary_extent.

Example: For an 8-byte pattern (max_lookback=7), a pattern starting at block
position 0 would occupy indices 7-14 in boundary_buffer, but boundary_buffer
was only 14 bytes (indices 0-13), so the pattern wasn't fully contained.

Fix:
- Increase boundary_extent to 2*max_lookback to ensure patterns starting
  anywhere in the first max_lookback bytes are fully contained
- Set search_offset to max_lookback (not boundary_extent) so Phase 2 still
  avoids duplicates while Phase 1 now covers more patterns

Co-authored-by: Bryan Call <[email protected]>
Once a pattern is found and actions are executed, there's no need to
continue searching for more patterns in the current or subsequent blocks.
This improves performance and avoids duplicate action execution.

Changes:
- Use matched_rule pointer to track if a match has been found
- Stop block iteration when matched_rule is set
- Skip Phase 1/Phase 2 searches if already matched
- Skip lookback buffer updates if already matched (no more searching needed)

Co-authored-by: Bryan Call <[email protected]>
}
TSContDestroy(contp);
return 0;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: Missing TSIOBufferReaderFree causes memory leak

The output_reader allocated at line 513 via TSIOBufferReaderAlloc is never freed. When cleaning up in the TSVConnClosedGet branch, only TSIOBufferDestroy(data->output_buffer) is called, but TSIOBufferReaderFree(data->output_reader) is missing. Other Traffic Server plugins (like esi, background_fetch, authproxy) consistently free the reader before destroying the buffer to avoid memory leaks.

Fix in Cursor Fix in Web

The output_reader allocated with TSIOBufferReaderAlloc was not being
freed before destroying the output_buffer. Add TSIOBufferReaderFree
call in the cleanup code when the transform connection closes.

Co-authored-by: Bryan Call <[email protected]>
- [Content-Length, 30]
- [uuid, xxe-header-test]
content:
data: '<?xml?><!ENTITY xxe "test">'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: Test file Content-Length mismatches actual body size

The Content-Length header value doesn't match the actual body content length in multiple test replay files. In add_header.replay.yaml and log_only.replay.yaml, Content-Length is 30 but the body '<?xml?><!ENTITY xxe "test">' is 27 characters. In response_add_header.replay.yaml, Content-Length is 25 but the body '{"data": "secret_data"}' is 23 characters. These mismatches could cause HTTP protocol errors or test failures during replay testing.

Additional Locations (2)

Fix in Cursor Fix in Web

- [Content-Type, "text/plain"]
- [Content-Length, 35]
content:
data: 'Not found: test_pattern in error'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: Test file Content-Length mismatches actual body size

The status_filter.replay.yaml test file has two Content-Length mismatches. The first server response specifies Content-Length: 35 but 'Not found: test_pattern in error' is 32 characters. The second server response specifies Content-Length: 20 but 'Found: test_pattern' is 19 characters. These HTTP protocol violations could cause test failures or unexpected behavior during replay testing.

Additional Locations (1)

Fix in Cursor Fix in Web

- add block tests
- full request and response coverage
- consolidate under one replay file
rule.max_pattern_len = pattern.length();
}
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: Missing validation for required body_patterns configuration field

The documentation states that body_patterns is a required field, but the configuration parser doesn't validate its presence or ensure it's non-empty. If a rule is configured without body_patterns, the rule will be loaded successfully, a transform will be set up to inspect request/response bodies, but no patterns will ever match. This wastes processing resources and could indicate a user misconfiguration that goes undetected. The code at lines 900-908 conditionally parses body_patterns but doesn't report an error when it's missing.

Fix in Cursor Fix in Web

}
rule.headers.push_back(cond);
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: Header conditions with missing fields silently fail

When parsing header conditions, the code doesn't validate that the name and patterns sub-fields are present. A HeaderCondition is added to the rule even if name is empty or patterns is missing. In header_condition_matches, an empty name causes TSMimeHdrFieldFind to fail, and empty patterns causes the matching loop to never execute. Either case returns false, causing the rule to silently never match any request or response. This wastes resources setting up transforms for rules that can never trigger actions.

Fix in Cursor Fix in Web

@bryancall bryancall closed this Dec 9, 2025
bryancall pushed a commit that referenced this pull request Jan 21, 2026
…2803)

Fix a race condition between NetAcceptAction::cancel() and
NetAccept::acceptEvent() where the server pointer could be dereferenced
after the NetAccept object was deleted.

The race occurred as follows:
1. Thread T4 calls NetAcceptAction::cancel(), sets cancelled=true
2. Thread T3 running acceptEvent() sees cancelled==true
3. Thread T3 deletes the NetAccept (including embedded Server)
4. Thread T4 tries to call server->close() on freed memory

The fix uses std::atomic<Server*> with atomic exchange to ensure only
one thread can successfully obtain and use the server pointer. Both
cancel() and the cleanup paths before delete this atomically exchange
the pointer with nullptr - whichever succeeds first closes the server,
the other becomes a no-op.

This addresses the TODO comment that was in the code:
"// TODO fix race between cancel accept and call back"

ASAN report this fixes (seen intermittently on rocky CI builds):

==8850==ERROR: AddressSanitizer: heap-use-after-free on address 0x616000028cb4 at pc 0x000001346739 bp 0x7fa40fd2f580 sp 0x7fa40fd2f570
WRITE of size 4 at 0x616000028cb4 thread T4 ([ET_NET 2])
    #0 0x1346738 in UnixSocket::close() ../src/iocore/eventsystem/UnixSocket.cc:138
    #1 0x12b44ed in Server::close() ../src/iocore/net/Server.cc:88
    #2 0x121fb95 in NetAcceptAction::cancel(Continuation*) ../src/iocore/net/P_NetAccept.h:71
    apache#3 0x7fa41686d082 in TSActionCancel(tsapi_action*) ../src/api/InkAPI.cc:5828
    ...

0x616000028cb4 is located 308 bytes inside of 576-byte region [0x616000028b80,0x616000028dc0)
freed by thread T3 ([ET_NET 1]) here:
    #0 0x7fa416d2036f in operator delete(void*, unsigned long)
    #1 0x12593c4 in NetAccept::~NetAccept() ../src/iocore/net/P_NetAccept.h:128
    #2 0x12bebf0 in NetAccept::acceptEvent(int, void*) ../src/iocore/net/UnixNetAccept.cc:484
    ...
bryancall pushed a commit that referenced this pull request Mar 16, 2026
…2803)

Fix a race condition between NetAcceptAction::cancel() and
NetAccept::acceptEvent() where the server pointer could be dereferenced
after the NetAccept object was deleted.

The race occurred as follows:
1. Thread T4 calls NetAcceptAction::cancel(), sets cancelled=true
2. Thread T3 running acceptEvent() sees cancelled==true
3. Thread T3 deletes the NetAccept (including embedded Server)
4. Thread T4 tries to call server->close() on freed memory

The fix uses std::atomic<Server*> with atomic exchange to ensure only
one thread can successfully obtain and use the server pointer. Both
cancel() and the cleanup paths before delete this atomically exchange
the pointer with nullptr - whichever succeeds first closes the server,
the other becomes a no-op.

This addresses the TODO comment that was in the code:
"// TODO fix race between cancel accept and call back"

ASAN report this fixes (seen intermittently on rocky CI builds):

==8850==ERROR: AddressSanitizer: heap-use-after-free on address 0x616000028cb4 at pc 0x000001346739 bp 0x7fa40fd2f580 sp 0x7fa40fd2f570
WRITE of size 4 at 0x616000028cb4 thread T4 ([ET_NET 2])
    #0 0x1346738 in UnixSocket::close() ../src/iocore/eventsystem/UnixSocket.cc:138
    #1 0x12b44ed in Server::close() ../src/iocore/net/Server.cc:88
    #2 0x121fb95 in NetAcceptAction::cancel(Continuation*) ../src/iocore/net/P_NetAccept.h:71
    apache#3 0x7fa41686d082 in TSActionCancel(tsapi_action*) ../src/api/InkAPI.cc:5828
    ...

0x616000028cb4 is located 308 bytes inside of 576-byte region [0x616000028b80,0x616000028dc0)
freed by thread T3 ([ET_NET 1]) here:
    #0 0x7fa416d2036f in operator delete(void*, unsigned long)
    #1 0x12593c4 in NetAccept::~NetAccept() ../src/iocore/net/P_NetAccept.h:128
    #2 0x12bebf0 in NetAccept::acceptEvent(int, void*) ../src/iocore/net/UnixNetAccept.cc:484
    ...
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.

2 participants