Skip to content

fix(rs-sdk-ffi): shrink signature allocation to len before leaking (capacity UB)#3798

Merged
QuantumExplorer merged 1 commit into
v3.1-devfrom
claude/fix-ffi-signer-capacity-ub
Jun 5, 2026
Merged

fix(rs-sdk-ffi): shrink signature allocation to len before leaking (capacity UB)#3798
QuantumExplorer merged 1 commit into
v3.1-devfrom
claude/fix-ffi-signer-capacity-ub

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Jun 4, 2026

Copy link
Copy Markdown
Member

Issue being fixed or feature implemented

Latent heap-corruption UB on the native signer's sign → free path.

dash_sdk_signer_sign (signer_simple.rs) returned the signature via:

let sig_vec = signature.to_vec();
let sig_ptr = sig_vec.leak().as_mut_ptr();   // leaks the source Vec's *capacity*

while dash_sdk_signature_free reclaims it with Vec::from_raw_parts(sig.signature, sig.signature_len, sig.signature_len). Vec::from_raw_parts(ptr, len, cap) requires cap to exactly equal the original allocation capacity. signature.to_vec() clones a BinaryData's inner Vec, whose capacity is not guaranteed to equal its length — when capacity > len, the global allocator is handed a wrong Layout on dealloc → undefined behavior / heap corruption.

This is the same bug class already fixed in DashSDKResult::success_binary (types.rs) via into_boxed_slice(), with a regression test noting it "was previously UB when capacity != len". The signer path never got the fix.

What was done?

The signing arm now routes through a small private helper that shrinks capacity to len before leaking:

fn leak_binary_to_ptr(bytes: Vec<u8>) -> (*mut u8, usize) {
    let boxed: Box<[u8]> = bytes.into_boxed_slice(); // shrinks cap to len
    let len = boxed.len();
    (Box::into_raw(boxed) as *mut u8, len)
}

A Box<[u8]> of length len owns an allocation of exactly len bytes with a Vec-compatible layout, so the existing Vec::from_raw_parts(ptr, len, len) free is now sound. The free fn and the #[repr(C)] DashSDKSignature struct are unchanged.

I also audited the rest of rs-sdk-ffi: this was the only .leak() in the crate, and every other Vec::from_raw_parts(ptr, len, len) site already consumes an exact-capacity allocation, so no other instances of this bug exist.

How Has This Been Tested?

cargo test -p rs-sdk-ffi --lib signer_simple6 passed, 0 failed, including the new test_leak_binary_to_ptr_preserves_capacity_via_shrink, which builds a 65-byte signature inside a Vec::with_capacity(128) (capacity 128 > len 65 — the exact mismatch the old .leak() mishandled), runs it through leak_binary_to_ptr + the real dash_sdk_signature_free, and asserts the bytes round-trip without corrupting the heap. The existing test_success_binary_preserves_capacity_via_shrink still passes. cargo fmt --all clean.

Breaking Changes

None. Internal allocation-layout correctness fix; extern "C" ABI unchanged.

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have added "!" to the title and described breaking changes in the corresponding section if my code contains any
  • I have made corresponding changes to the documentation if needed

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced signature memory management to prevent allocation mismatches and improve reliability.
  • Tests

    • Added edge-case tests for signature handling to validate stability.

…apacity UB)

`dash_sdk_signer_sign` did `signature.to_vec().leak()`, which leaks the
buffer keeping the source Vec's actual capacity, while
`dash_sdk_signature_free` reconstructs it with
`Vec::from_raw_parts(ptr, len, len)`. `from_raw_parts` requires the exact
original capacity; when the source `BinaryData`'s inner Vec had
`capacity > len`, the global allocator received a wrong `Layout` on
dealloc — undefined behavior / heap corruption.

This is the same bug class already fixed in
`DashSDKResult::success_binary` via `into_boxed_slice()`. The signing
path now routes through a small `leak_binary_to_ptr` helper that shrinks
capacity to len (`into_boxed_slice()`) before leaking, making the
`cap == len` free path sound. Audited the rest of rs-sdk-ffi: this was
the only `.leak()`; all other `from_raw_parts(ptr, len, len)` sites
already consume exact-capacity allocations.

Public `extern "C"` ABI and `DashSDKSignature` are unchanged. Adds a
regression test driving a `capacity > len` buffer through the real
alloc + free round-trip.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@QuantumExplorer QuantumExplorer requested a review from shumkov as a code owner June 4, 2026 14:14
@thepastaclaw

thepastaclaw commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator

✅ Review complete (commit 7edf6ba)

@coderabbitai

coderabbitai Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 16abd1b1-cd17-4d4b-9ceb-f1ec6f3c6beb

📥 Commits

Reviewing files that changed from the base of the PR and between 525674a and 7edf6ba.

📒 Files selected for processing (1)
  • packages/rs-sdk-ffi/src/signer_simple.rs

📝 Walkthrough

Walkthrough

This PR fixes an FFI memory safety issue in Rust-SDK signature serialization. A new leak_binary_to_ptr helper shrinks vector allocations to exact length before leaking for FFI, ensuring the deallocation path's reconstruction with Vec::from_raw_parts(ptr, len, len) matches the actual heap layout. The signing function integrates the helper, and comprehensive tests validate the fix handles capacity mismatches and edge cases safely.

Changes

FFI Memory Safety for Signature Serialization

Layer / File(s) Summary
FFI memory safety helper function
packages/rs-sdk-ffi/src/signer_simple.rs
Private leak_binary_to_ptr helper converts Vec<u8> to Box<[u8]> using into_boxed_slice(), shrinking capacity to length before leaking the raw pointer and length for FFI boundary crossing, preventing allocation metadata mismatch.
Signature serialization with safe leak path
packages/rs-sdk-ffi/src/signer_simple.rs
dash_sdk_signer_sign success path replaces direct Vec::leak() with leak_binary_to_ptr(signature.to_vec()), ensuring returned raw signature buffer has correct allocation layout for dash_sdk_signature_free deallocation.
FFI memory correctness tests
packages/rs-sdk-ffi/src/signer_simple.rs
Regression test forces capacity > len and validates bytes survive leak/free round-trip without corruption; additional tests cover empty signature allocation and dash_sdk_signature_free(null) as safe no-ops.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

ready for final review

Suggested reviewers

  • shumkov

Poem

🐰 A vector's dance in FFI land,
Now shrinks to size before it's fanned,
No more capacity's hidden game—
The leak and free at last align the same!
Safe signatures leap across the fence,
With tests that guard the heap's defence. ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main change: fixing undefined behavior in FFI signature allocation by shrinking capacity before leaking.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/fix-ffi-signer-capacity-ub

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Code Review

Tight, ABI-preserving soundness fix for a real latent UB in dash_sdk_signer_sign. The previous signature.to_vec().leak() retained the source Vec's capacity while dash_sdk_signature_free reclaimed via Vec::from_raw_parts(ptr, len, len) — a layout mismatch whenever cap > len. The new leak_binary_to_ptr shrinks via into_boxed_slice() so the free path is sound; the pattern mirrors the already-shipped DashSDKResult::success_binary fix, and regression/empty/null-free tests all pass verification. All six agents agree no in-scope issues remain.

@github-actions

github-actions Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

✅ DashSDKFFI.xcframework built for this PR.

SwiftPM (host the zip at a stable URL, then use):

.binaryTarget(
  name: "DashSDKFFI",
  url: "https://your.cdn.example/DashSDKFFI.xcframework.zip",
  checksum: "97ab878a4437e55f9ba7ada95999988bf04ffd3312a91ce8a0889cb63e794d25"
)

Xcode manual integration:

  • Download 'DashSDKFFI.xcframework' artifact from the run link above.
  • Drag it into your app target (Frameworks, Libraries & Embedded Content) and set Embed & Sign.
  • If using the Swift wrapper package, point its binaryTarget to the xcframework location or add the package and place the xcframework at the expected path.

@QuantumExplorer QuantumExplorer left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Self reviewed

@QuantumExplorer QuantumExplorer merged commit 8d60d3f into v3.1-dev Jun 5, 2026
22 checks passed
@QuantumExplorer QuantumExplorer deleted the claude/fix-ffi-signer-capacity-ub branch June 5, 2026 10:44
@QuantumExplorer QuantumExplorer added this to the v4.0.0 milestone Jun 7, 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.

2 participants