Skip to content

fix: osec audit fixes#1882

Merged
SwenSchaeferjohann merged 7 commits intomainfrom
jorrit/osec-audit-fixes
Jul 23, 2025
Merged

fix: osec audit fixes#1882
SwenSchaeferjohann merged 7 commits intomainfrom
jorrit/osec-audit-fixes

Conversation

@ananas-block
Copy link
Contributor

@ananas-block ananas-block commented Jul 22, 2025

Summary by CodeRabbit

  • New Features

    • Added validation to ensure tree root history capacity is sufficient for input/output queue operations.
    • Introduced a new field for tracking tree capacity in queue metadata and account structures.
    • Enhanced capacity checks before batch insertions to prevent overflow.
    • Added a new error to detect duplicate accounts appearing both as inputs and read-only.
    • Implemented checks to prevent duplicate compressed accounts between inputs and read-only accounts.
    • Enforced mutability requirements on certain accounts during processing.
  • Bug Fixes

    • Improved overflow detection in queue operations by explicitly tracking tree capacity.
    • Enforced mutability checks on specific accounts to ensure proper permissions.
  • Tests

    • Added and updated tests to verify correct handling of tree capacity and validation of root history requirements.
    • Added tests to confirm detection of duplicate accounts in inputs and read-only sets.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 22, 2025

Walkthrough

The changes introduce a tree_capacity parameter to the BatchedQueueMetadata and BatchedQueueAccount structures, updating their initialization methods and propagating this parameter throughout related code and tests. Additional validation logic is added to ensure root_history_capacity is sufficient relative to batch sizes in both address and state tree initialization. The tree_is_full and check_tree_is_full methods are updated to consider batch sizes when checking capacity. Mutability checks are added for optional accounts in system modules, with corresponding usage updates. New and updated tests verify these validations and the correct assignment of tree_capacity.

Changes

File(s) Change Summary
program-libs/batched-merkle-tree/src/queue.rs Added tree_capacity field to BatchedQueueMetadata; updated init methods to accept and store this parameter; modified tree_is_full logic; added/updated tests for capacity logic.
program-libs/batched-merkle-tree/src/initialize_state_tree.rs Enhanced validation to check root_history_capacity covers both input/output queues; passed tree_capacity to queue initialization; restricted supported ZKP batch sizes; added tests for validation.
program-libs/batched-merkle-tree/src/initialize_address_tree.rs Added validation that root_history_capacity is sufficient for input queue batches; restricted supported ZKP batch sizes; added tests for this check.
program-libs/batched-merkle-tree/src/batch.rs Simplified test by passing tree_capacity as an argument instead of manual assignment.
program-libs/batched-merkle-tree/src/merkle_tree.rs Updated tree_is_full and check_tree_is_full methods to accept optional batch size parameter; updated calls accordingly; adjusted tests.
program-libs/batched-merkle-tree/tests/queue.rs Updated test initializations to pass explicit tree_capacity argument.
programs/account-compression/src/instructions/migrate_state.rs Updated test helper to pass tree_capacity during output queue initialization.
programs/system/src/accounts/account_checks.rs Added mutability checks (check_mut) for optional accounts after existing validations; renamed anchor_option_account_info to anchor_option_mut_account_info.
programs/system/src/invoke/instruction.rs Replaced anchor_option_account_info with anchor_option_mut_account_info for decompression_recipient account to require mutability.
programs/system/src/invoke_cpi/instruction.rs Replaced anchor_option_account_info with anchor_option_mut_account_info for decompression_recipient account to require mutability.

Sequence Diagram(s)

sequenceDiagram
    participant Test
    participant BatchedQueueAccount
    participant BatchedQueueMetadata

    Test->>BatchedQueueAccount: init(..., tree_capacity)
    BatchedQueueAccount->>BatchedQueueMetadata: init(..., tree_capacity)
    BatchedQueueMetadata-->>BatchedQueueAccount: stores tree_capacity
    BatchedQueueAccount-->>Test: returns initialized account with tree_capacity
Loading
sequenceDiagram
    participant Validator
    participant Params

    Validator->>Params: validate_batched_tree_params(params)
    Params-->>Validator: checks root_history_capacity >= (output_batches + input_batches)
    Validator->>Params: validate_batched_address_tree_params(params)
    Params-->>Validator: checks root_history_capacity >= input_batches
Loading
sequenceDiagram
    participant MerkleTreeAccount
    participant QueueMetadata

    MerkleTreeAccount->>MerkleTreeAccount: tree_is_full(batch_size)
    MerkleTreeAccount-->>Caller: returns true if next_index + batch_size >= capacity
Loading

Estimated code review effort

3 (~45 minutes)

Possibly related PRs

Suggested reviewers

  • sergeytimoshin
  • SwenSchaeferjohann

Poem

In the warren where Merkle trees grow,
A new field called capacity starts to show.
With roots and queues now checked with care,
Overflow’s no longer a hare’s nightmare!
Tests hop along, validation’s tight—
All is balanced, code feels light.
🐇🌳

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🔭 Outside diff range comments (3)
program-libs/batched-merkle-tree/src/queue.rs (3)

61-78: Validate tree_capacity upfront

tree_capacity is blindly assigned but never sanity-checked.
Consider asserting that:

  • tree_capacity > 0
  • tree_capacity >= batch_size * NUM_BATCHES
  • tree_capacity.is_power_of_two() (if height-based)

This prevents silent overflow/under-allocation later on.


421-423: Potential off-by-one & overflow in tree_is_full

Equality misses the case where next_index has already exceeded capacity, returning false again:

- self.tree_capacity == self.batch_metadata.next_index
+ self.batch_metadata.next_index >= self.tree_capacity

Combine this with an internal guard in insert_into_current_batch to early-abort when full.


215-243: Guard insertions against overflowing the tree

insert_into_current_batch doesn’t call check_tree_is_full; callers might forget and push past capacity.

Add at the very top:

self.check_tree_is_full()?;

Ensures safety at the API boundary.

🧹 Nitpick comments (1)
program-libs/batched-merkle-tree/src/initialize_state_tree.rs (1)

260-273: Enhance test coverage for edge cases.

While the panic test is good, consider adding more comprehensive test cases to cover edge scenarios like non-divisible batch sizes and boundary conditions.

Additional test cases to consider:

#[test]
fn test_validate_root_history_capacity_edge_cases() {
    // Test with non-perfectly divisible batch sizes
    let params = InitStateTreeAccountsInstructionData {
        root_history_capacity: 21, // Should be enough for (101/10) + (101/10) = 20.2 -> 20
        input_queue_batch_size: 101,
        output_queue_batch_size: 101,
        input_queue_zkp_batch_size: 10,
        output_queue_zkp_batch_size: 10,
        ..Default::default()
    };
    validate_batched_tree_params(params);
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aef5ab4 and f94733c.

📒 Files selected for processing (6)
  • program-libs/batched-merkle-tree/src/batch.rs (1 hunks)
  • program-libs/batched-merkle-tree/src/initialize_address_tree.rs (2 hunks)
  • program-libs/batched-merkle-tree/src/initialize_state_tree.rs (2 hunks)
  • program-libs/batched-merkle-tree/src/queue.rs (10 hunks)
  • program-libs/batched-merkle-tree/tests/queue.rs (2 hunks)
  • programs/account-compression/src/instructions/migrate_state.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Forester e2e test
  • GitHub Check: system-programs (system-cpi-test-v2-functional, ["cargo-test-sbf -p system-cpi-v2-test -- functio...
  • GitHub Check: Test batched-merkle-tree-simulate
🔇 Additional comments (5)
program-libs/batched-merkle-tree/src/initialize_state_tree.rs (2)

165-165: LGTM: Tree capacity calculation is correct.

The addition of 2u64.pow(params.height) as the tree capacity parameter is mathematically correct for a binary Merkle tree, where the capacity equals 2^height.


253-258: LGTM: Basic validation test is appropriate.

The test verifies that default parameters pass validation, which is a good baseline check.

program-libs/batched-merkle-tree/src/batch.rs (1)

992-992: LGTM! Clean refactoring removes redundant assignment.

The change eliminates the redundant manual assignment of tree_capacity by passing the value directly to the init function, which is more consistent with the new initialization pattern.

program-libs/batched-merkle-tree/tests/queue.rs (1)

74-74: LGTM! Tests correctly updated for new initialization signature.

The addition of the tree_capacity parameter (1024 = 2^10) to the BatchedQueueAccount::init calls properly aligns with the API changes and uses appropriate test values.

Also applies to: 103-103

programs/account-compression/src/instructions/migrate_state.rs (1)

218-218: LGTM! Test helper correctly uses capacity from metadata.

The change properly passes account.tree_capacity from the BatchedQueueMetadata struct to the initialization function, ensuring consistency between the metadata and the initialized account.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
programs/system/src/errors.rs (1)

115-118: Consider improving error message clarity.

The new error variants follow the correct pattern, but the error messages could be more descriptive:

  1. BorrowingDataFailed - Consider specifying what type of data borrowing failed
  2. DuplicateAccountInInputsAndReadOnly - Consider adding context about why this is invalid
-    #[error("Borrowing data failed")]
+    #[error("Failed to borrow account data")]
     BorrowingDataFailed,
-    #[error("DuplicateAccountInInputsAndReadOnly")]
+    #[error("Account appears in both inputs and read-only accounts")]
     DuplicateAccountInInputsAndReadOnly,
programs/system/src/processor/process.rs (1)

352-368: Verify the efficiency of the nested loop approach.

The implementation correctly prevents duplicate accounts between inputs and read-only accounts. However, the O(n×m) complexity could be optimized for large transactions.

Consider using a HashSet for better performance with large account lists:

+use std::collections::HashSet;

-#[inline(always)]
-fn check_no_duplicate_accounts_in_inputs_and_read_only(
-    input_nullifiers: &ZeroCopySliceMut<'_, u8, InsertNullifierInput, false>,
-    read_only_accounts: &[ZPackedReadOnlyCompressedAccount],
-) -> Result<()> {
-    for read_only_account in read_only_accounts {
-        for input_nullifier in input_nullifiers.iter() {
-            if read_only_account.account_hash == input_nullifier.account_hash {
-                return Err(SystemProgramError::DuplicateAccountInInputsAndReadOnly.into());
-            }
-        }
-    }
-    Ok(())
-}
+#[inline(always)]
+fn check_no_duplicate_accounts_in_inputs_and_read_only(
+    input_nullifiers: &ZeroCopySliceMut<'_, u8, InsertNullifierInput, false>,
+    read_only_accounts: &[ZPackedReadOnlyCompressedAccount],
+) -> Result<()> {
+    let input_hashes: HashSet<[u8; 32]> = input_nullifiers
+        .iter()
+        .map(|input| input.account_hash)
+        .collect();
+    
+    for read_only_account in read_only_accounts {
+        if input_hashes.contains(&read_only_account.account_hash) {
+            return Err(SystemProgramError::DuplicateAccountInInputsAndReadOnly.into());
+        }
+    }
+    Ok(())
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c8a68a2 and eaa5068.

📒 Files selected for processing (5)
  • anchor-programs/system/src/errors.rs (1 hunks)
  • program-tests/system-cpi-v2-test/tests/invoke_cpi_with_read_only.rs (1 hunks)
  • program-tests/utils/src/e2e_test_env.rs (1 hunks)
  • programs/system/src/errors.rs (2 hunks)
  • programs/system/src/processor/process.rs (7 hunks)
✅ Files skipped from review due to trivial changes (1)
  • anchor-programs/system/src/errors.rs
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (20)
  • GitHub Check: cli-v2
  • GitHub Check: cli-v1
  • GitHub Check: Test program-libs-slow
  • GitHub Check: Test batched-merkle-tree-simulate
  • GitHub Check: Test program-libs-fast
  • GitHub Check: stateless-js-v2
  • GitHub Check: Test sdk-libs
  • GitHub Check: Test concurrent-merkle-tree
  • GitHub Check: lint
  • GitHub Check: system-programs (light-system-program, ["cargo-test-sbf -p system-test"])
  • GitHub Check: system-programs (system-cpi-test-v2-other, ["cargo-test-sbf -p system-cpi-v2-test -- --skip funct...
  • GitHub Check: system-programs (system-cpi-test, ["cargo-test-sbf -p system-cpi-test"])
  • GitHub Check: Forester e2e test
  • GitHub Check: system-programs (light-compressed-token, ["cargo-test-sbf -p compressed-token-test"])
  • GitHub Check: system-programs (random-e2e-test, ["cargo-test-sbf -p e2e-test"])
  • GitHub Check: system-programs (light-registry, ["cargo-test-sbf -p registry-test"])
  • GitHub Check: system-programs (system-cpi-test-v2-functional, ["cargo-test-sbf -p system-cpi-v2-test -- functio...
  • GitHub Check: system-programs (system-cpi-test-v2-event, ["cargo-test-sbf -p system-cpi-v2-test -- event::parse"])
  • GitHub Check: system-programs (account-compression, ["cargo-test-sbf -p account-compression-test"])
  • GitHub Check: stateless-js-v1
🔇 Additional comments (6)
programs/system/src/errors.rs (1)

188-189: LGTM: Error codes follow correct sequential pattern.

The error code assignments (6052, 6053) correctly follow the sequential numbering pattern and are positioned appropriately in the match statement.

program-tests/utils/src/e2e_test_env.rs (1)

2494-2496: LGTM! Effective duplicate prevention logic.

This change correctly prevents duplicate accounts from appearing in both input_accounts and read_only_accounts collections, which aligns with the new validation logic mentioned in the AI summary that rejects transactions with duplicate compressed accounts.

program-tests/system-cpi-v2-test/tests/invoke_cpi_with_read_only.rs (1)

2829-2930: LGTM: Well-structured test for duplicate account validation.

The new test function correctly validates the runtime check for duplicate accounts in inputs and read-only lists. The test setup is appropriate, creates the necessary state, and properly asserts the expected error condition.

A few observations:

  • The test follows established patterns from other tests in the file
  • Proper use of serial attribute to avoid conflicts with other tests
  • Correct error assertion using SystemProgramError::DuplicateAccountInInputsAndReadOnly
  • Good test isolation by creating its own compressed account
programs/system/src/processor/process.rs (3)

190-190: Good refactoring to enable duplicate account validation.

Moving the read_only_accounts retrieval earlier in the process enables the new duplicate account validation while maintaining the existing logic flow.


216-220: Essential security validation correctly placed.

The duplicate account check is appropriately positioned after input processing but before proof verification, ensuring that invalid transactions are caught early in the process.


228-348: Step numbering updates maintain clarity.

The comment updates correctly reflect the new step sequence after introducing the duplicate account validation step.

@SwenSchaeferjohann SwenSchaeferjohann merged commit 50778df into main Jul 23, 2025
30 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Oct 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants