Skip to content

fix(core): add resource limits and harden production WASM safety#26

Merged
aepfli merged 4 commits intomainfrom
fix/prod-hardening
Mar 30, 2026
Merged

fix(core): add resource limits and harden production WASM safety#26
aepfli merged 4 commits intomainfrom
fix/prod-hardening

Conversation

@aepfli
Copy link
Copy Markdown
Member

@aepfli aepfli commented Mar 14, 2026

Summary

Implements production hardening for the Rust core and WASM runtime as described in #23.

Changes

New: src/limits.rs

Defines resource limit constants with real-world quantification:

Constant Value Meaning
MAX_CONFIG_BYTES 100 MB ~125,000 complex flags — safe for local-file loading
MAX_CONTEXT_BYTES 1 MB ~26,000 context fields — far exceeds real use
MAX_REF_DEPTH 64 $ref hop limit (counts hops only, not JSON traversal)
MAX_JSON_DEPTH 128 Pre-parse nesting depth scan

src/lib.rs

  • Config size check in update_state_internal: fires before string_from_memory — oversized config_len rejected without touching memory
  • Context size check in evaluate_internal / evaluate_by_index_internal
  • Mutex poisoning fix: mutex.lock().unwrap()unwrap_or_else(|e| e.into_inner())
  • Eliminated production .unwrap(): double get_state() in evaluate_internal replaced with single binding

src/evaluator.rs

  • JSON depth pre-scan in FlagEvaluator::update_state: check_json_depth() before serde_json recursion; covers JSON and YAML (post-conversion) inputs

src/model/feature_flag.rs

  • $ref depth counter in resolve_refs: counts $ref hops only; rejects chains longer than 64 hops

Tests

  • New tests/adversarial_tests.rs: deeply nested JSON, exact-limit JSON, deep/exact $ref chains, circular $ref regression
  • New adversarial_wasm_tests module in src/lib.rs: oversized config/context

ARCHITECTURE.md

New Resource Limits section documenting all constants, enforcement points, and error behavior.

Closes #23

- Add src/limits.rs with MAX_CONFIG_BYTES (100MB), MAX_CONTEXT_BYTES (1MB),
  MAX_REF_DEPTH (64), MAX_JSON_DEPTH (128) and check_json_depth() validator
- Enforce config and context size limits at the WASM FFI boundary in
  update_state_internal and evaluate_internal before any memory reads
- Add JSON nesting depth pre-parse scan in FlagEvaluator::update_state to
  prevent stack overflows; applied to both JSON and YAML (post-conversion) paths
- Add $ref hop-depth counter to resolve_refs (depth counts only $ref hops,
  not structural JSON traversal)
- Fix mutex.lock().unwrap() -> unwrap_or_else(|e| e.into_inner()) in the
  native non-WASM evaluator module to survive mutex poisoning gracefully
- Eliminate double get_state() call and production .unwrap() in
  evaluate_internal by binding state once
- Add adversarial tests: oversized config/context, deeply nested JSON,
  deep $ref chains, and circular $ref regression
- Document all limits and enforcement points in ARCHITECTURE.md

Closes #23

Signed-off-by: Simon Schrottner <simon.schrottner@dynatrace.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the robustness and security of the Rust core and WASM runtime by introducing comprehensive resource limits. These limits are designed to protect the evaluator from adversarial or accidentally oversized inputs, preventing potential memory exhaustion, stack overflows, and other stability issues. The changes ensure that the system fails gracefully and deterministically when limits are exceeded, providing a more resilient and predictable evaluation environment.

Highlights

  • Resource Limits: Introduced strict resource limits for configuration size (100 MB), context size (1 MB), JSON nesting depth (128 levels), and $ref resolution depth (64 hops) to prevent resource exhaustion and denial-of-service attacks.
  • WASM Hardening: Implemented safety measures at the WASM boundary, including pre-memory access checks for oversized payloads, graceful mutex poisoning recovery, and elimination of production .unwrap() calls.
  • JSON Depth Validation: Added a pre-parse JSON depth scan to prevent stack overflows from maliciously crafted deeply nested JSON configurations before serde_json processing.
  • $ref Resolution Depth Limit: Enforced a maximum depth for $ref resolution to guard against excessively long or circular evaluator chains.
  • Adversarial Testing: Added comprehensive adversarial tests to validate the new resource limits and ensure deterministic error handling for oversized or deeply nested inputs.
  • Documentation: Updated ARCHITECTURE.md with a new section detailing the resource limits, their enforcement points, and expected error behaviors.
Changelog
  • ARCHITECTURE.md
    • Added a new 'Resource Limits' section detailing constants, enforcement points, and error behavior.
  • src/evaluator.rs
    • Imported check_json_depth from crate::limits.
    • Implemented pre-parse JSON depth validation in update_state to prevent stack overflows.
  • src/lib.rs
    • Updated mutex locking to use unwrap_or_else(|e| e.into_inner()) for graceful recovery from poisoning.
    • Imported limits module and MAX_CONFIG_BYTES, MAX_CONTEXT_BYTES constants.
    • Added a config size check in update_state_internal to reject oversized payloads before memory access.
    • Added context size checks in evaluate_by_index_internal and evaluate_internal.
    • Refactored evaluate_internal to remove redundant get_state() calls and improve error handling for uninitialized state.
    • Added a new adversarial_wasm_tests module for WASM-boundary specific tests.
  • src/limits.rs
    • Created a new file defining MAX_CONFIG_BYTES, MAX_CONTEXT_BYTES, MAX_REF_DEPTH, and MAX_JSON_DEPTH constants.
    • Implemented check_json_depth function for pre-parsing JSON depth validation.
    • Added unit tests for the check_json_depth function.
  • src/model/feature_flag.rs
    • Imported MAX_REF_DEPTH from crate::limits.
    • Modified resolve_refs to include a depth parameter and enforce MAX_REF_DEPTH for $ref resolution.
    • Updated calls to resolve_refs to pass the new depth parameter, ensuring only $ref hops increment depth.
  • tests/adversarial_tests.rs
    • Added new tests to verify rejection of deeply nested JSON configurations.
    • Added tests to confirm acceptance of JSON configurations at the maximum allowed depth.
    • Added tests to verify rejection of deep $ref chains.
    • Added tests to confirm acceptance of $ref chains at the maximum allowed depth.
    • Verified that existing circular $ref detection still functions correctly.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces important hardening measures by adding resource limits for configuration and context sizes, as well as nesting depth for JSON and $ref resolution. The changes are well-implemented and include comprehensive tests for the new limits. The handling of mutex poisoning and the removal of an .unwrap() call further improve the robustness of the evaluator. I've identified one area for improvement regarding code duplication.

src/lib.rs Outdated
Comment on lines +538 to +546
if context_len as usize > MAX_CONTEXT_BYTES {
return EvaluationResult::error(
ErrorCode::ParseError,
format!(
"Context size ({} bytes) exceeds the maximum allowed size of {} bytes (1 MB)",
context_len, MAX_CONTEXT_BYTES
),
);
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The logic for parsing the context from memory, including this new size check, is duplicated in evaluate_internal (lines 628-636). This duplication extends to the surrounding memory reading and JSON parsing logic.

To improve maintainability and reduce the risk of future inconsistencies, consider extracting this shared logic into a private helper function. For example, a function with a signature like fn parse_context_from_memory(context_ptr: *const u8, context_len: u32) -> Result<Value, EvaluationResult> could encapsulate this behavior. Both evaluate_by_index_internal and evaluate_internal could then call this helper.

aepfli added a commit that referenced this pull request Mar 30, 2026
…plication

Resolve the review comment on PR #26: the context-parsing logic
(size check → UTF-8 read → JSON parse) was duplicated verbatim in both
evaluate_by_index_internal and evaluate_internal.

Extract it into a single private helper
  fn parse_context_from_memory(ptr, len) -> Result<Value, EvaluationResult>

Both callers now delegate to this helper.  evaluate_internal retains its
extra short-circuit (flag has no targeting rules → skip parsing) as a
plain if/else around the helper call.

Signed-off-by: Simon Schrottner <simon.schrottner@aepfli.at>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…plication

Resolve the review comment on PR #26: the context-parsing logic
(size check → UTF-8 read → JSON parse) was duplicated verbatim in both
evaluate_by_index_internal and evaluate_internal.

Extract it into a single private helper
  fn parse_context_from_memory(ptr, len) -> Result<Value, EvaluationResult>

Both callers now delegate to this helper.  evaluate_internal retains its
extra short-circuit (flag has no targeting rules → skip parsing) as a
plain if/else around the helper call.

Signed-off-by: Simon Schrottner <simon.schrottner@aepfli.at>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: Simon Schrottner <simon.schrottner@dynatrace.com>
@aepfli aepfli force-pushed the fix/prod-hardening branch from fdb515b to 4b6412a Compare March 30, 2026 15:32
aepfli and others added 2 commits March 30, 2026 17:34
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: Simon Schrottner <simon.schrottner@dynatrace.com>
EvaluationResult's size (136 bytes) is inherent to the type; boxing it
would complicate all call-sites for no real benefit.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: Simon Schrottner <simon.schrottner@dynatrace.com>
@aepfli aepfli merged commit b141bd1 into main Mar 30, 2026
18 checks passed
@github-actions github-actions bot mentioned this pull request Mar 30, 2026
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.

Production readiness: harden Rust core and WASM runtime

1 participant