This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: tauri-mobile-jni-ffi-envelope-memory-sandbox

Tauri 2.0 Mobile JNI/FFI Zero-Copy Byte-Buffer Envelope Validation

Enforces deterministic byte-buffer envelope validation and memory layout constraints across Tauri 2.0 Rust-to-mobile FFI boundaries (Android JNI DirectByteBuffer and iOS Swift UnsafeRawBufferPointer). Mandates strict validation of buffer length, alignment, capacity, and monotonic byte bounds to eliminate native buffer overruns and unaligned pointer dereferences during zero-copy IPC.

Prohibited Anti-Pattern: Unvalidated Raw Pointer Casting and Direct Unchecked Slice Slicing Over Native IPC

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Tauri 2.0 Mobile JNI/FFI Zero-Copy Byte-Buffer Envelope Validation - Enforces deterministic byte-buffer envelope validation and memory layout constraints across Tauri 2.0 Rust-to-mobile FFI boundaries (Android JNI DirectByteBuffer and iOS Swift UnsafeRawBufferPointer). Mandates strict validation of buffer length, alignment, capacity, and monotonic byte bounds to eliminate native buffer overruns and unaligned pointer dereferences during zero-copy IPC.
globs: src-tauri/src/**/*.rs, src-tauri/gen/android/**/*.kt, src-tauri/gen/android/**/*.java, src-tauri/gen/apple/**/*.swift, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tauri-mobile-jni-ffi-envelope-memory-sandbox"
---

# Tauri 2.0 Mobile JNI/FFI Zero-Copy Byte-Buffer Envelope Validation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unvalidated Raw Pointer Casting and Direct Unchecked Slice Slicing Over Native IPC

## System Constraints
You are a Principal Systems & Mobile Security Architect specializing in Tauri 2.0 FFI internals. Mandate and enforce non-negotiable memory sandboxing invariants across Rust FFI boundaries interacting with Android JNI and iOS Swift/Objective-C runtimes. Enforce strictly typed envelope headers, zero-copy byte-slice bounds validation, lifetime encapsulation, and explicit unaligned read protections.

## Strict Guidelines
- Engineers MUST ALWAYS enforce a fixed-size binary preamble/envelope header (containing magic bytes, version, payload length, and 64-bit alignment padding) before passing byte buffers across JNI/FFI boundaries.
- Engineers MUST NOT construct Rust slices using `std::slice::from_raw_parts` without verifying non-null pointers, host-platform memory alignment (`pointer.align_offset() == 0`), and total buffer capacity invariants against the host envelope length.
- Code SHOULD leverage Android JNI `GetDirectBufferAddress` and `GetDirectBufferCapacity` exclusively within an explicit JNI frame boundary, checking for a return of -1 or NULL before zero-copy reads.
- Services MUST ensure that native buffers shared across FFI are immutable for the duration of the cross-boundary execution, or use explicit copy-on-write guards to prevent race-condition-induced use-after-free (UAF) or heap corruptions.
- Components NEVER expose unbounded `ArrayBuffer` or raw typed array offsets from the webview layer directly to the native host plugin without bounds-checking against the maximum permitted FFI sandbox envelope size.

## Bad vs Good Implementations
### Rust FFI Direct Buffer Envelope Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly calling `std::slice::from_raw_parts` without verifying non-nullness, byte-boundary alignment, minimum header length, or allocation bounds allows native JNI/FFI callers to cause memory safety violations, out-of-bounds reads, and segmentation faults.
```rust
// CRITICAL VULNERABILITY: Raw pointer cast without alignment or envelope validation
#[no_mangle]
pub unsafe extern "C" fn process_native_payload(
    buf_ptr: *const u8,
    len: usize,
) -> i32 {
    // Dereferencing raw pointer blindly; prone to OOB read, unaligned memory faults, and UAF
    let slice = std::slice::from_raw_parts(buf_ptr, len);
    println!("Payload first byte: {}", slice[0]);
    0
}
```

#### Production Standard (Correct)
> **Standard**: Validates non-nullness, checks memory alignment, validates explicit envelope header signatures, guarantees the inner payload does not exceed total allocated buffer capacity, and enforces a strict memory ceiling against DoS allocations.
```rust
// PRODUCTION GUARDRAIL: Sandboxed envelope validation with strict alignment and capacity checks
#[repr(C, packed(8))]
pub struct EnvelopeHeader {
    pub magic: u32,
    pub payload_len: u32,
}

const MAGIC_BYTES: u32 = 0x54415552; // 'TAUR'
const MAX_BUFFER_LIMIT: usize = 16 * 1024 * 1024; // 16MB ceiling

#[no_mangle]
pub unsafe extern "C" fn process_native_payload(
    buf_ptr: *const u8,
    total_capacity: usize,
) -> i32 {
    if buf_ptr.is_null() {
        return -1;
    }
    
    let header_size = std::mem::size_of::<EnvelopeHeader>();
    if total_capacity < header_size || total_capacity > MAX_BUFFER_LIMIT {
        return -2;
    }

    // Verify pointer alignment for structured reads
    if (buf_ptr as usize) % std::mem::align_of::<u64>() != 0 {
        return -3;
    }

    let header = std::ptr::read_unaligned(buf_ptr as *const EnvelopeHeader);
    if header.magic != MAGIC_BYTES {
        return -4;
    }

    let declared_len = header.payload_len as usize;
    if declared_len > total_capacity - header_size {
        return -5;
    }

    // Safe slice construction within validated monotonic boundaries
    let payload_ptr = buf_ptr.add(header_size);
    let validated_slice = std::slice::from_raw_parts(payload_ptr, declared_len);
    
    // Safe read execution within sandbox
    let _ = validated_slice;
    0
}
```

### Kotlin JNI Direct Buffer Allocation and Boundary Pinning

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing a standard managed JVM `ByteArray` directly across FFI without direct byte buffer allocation or JNI primitive pinning leads to undefined memory reads because the garbage collector can relocate heap memory concurrently.
```kotlin
// CRITICAL VULNERABILITY: Raw non-direct buffer passed to JNI
fun sendDataToRust(data: ByteArray) {
    // Native side cannot access heap byte array without pinning or copy
    // Direct pointer casts in Rust will crash or read arbitrary Dalvik/ART heap memory
    rustNativeBridge.processNativePayload(data, data.size)
}
```

#### Production Standard (Correct)
> **Standard**: Uses off-heap `allocateDirect` with native byte ordering, prepends the mandatory sandbox envelope header, and passes a guaranteed pinned memory segment to Rust with strict capacity enforcement.
```kotlin
// PRODUCTION GUARDRAIL: DirectByteBuffer sandbox with monotonic envelope
import java.nio.ByteBuffer
import java.nio.ByteOrder

fun sendDataToRustSafely(payload: ByteArray): Int {
    val headerSize = 8
    val totalSize = headerSize + payload.size
    
    // Allocate direct off-heap buffer to prevent GC relocation during native FFI execution
    val directBuffer = ByteBuffer.allocateDirect(totalSize).apply {
        order(ByteOrder.nativeOrder())
        putInt(0x54415552) // Magic: 'TAUR'
        putInt(payload.size)
        put(payload)
        flip()
    }
    
    return rustNativeBridge.processDirectEnvelope(directBuffer, directBuffer.capacity())
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Tauri 2.0 Mobile JNI/FFI Zero-Copy Byte-Buffer Envelope Validation

Tauri 2.0 Mobile JNI/FFI Zero-Copy Byte-Buffer Envelope Validation defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic byte-buffer envelope validation and memory layout constraints across Tauri 2.0 Rust-to-mobile FFI boundaries (Android JNI DirectByteBuffer and iOS Swift UnsafeRawBufferPointer). Mandates strict validation of buffer length, alignment, capacity, and monotonic byte bounds to eliminate native buffer overruns and unaligned pointer dereferences during zero-copy IPC. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unvalidated Raw Pointer Casting and Direct Unchecked Slice Slicing Over Native IPC Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnvalidated Raw Pointer Casting and Direct Unchecked Slice Slicing Over Native IPCCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS enforce a fixed-size binary preamble/envelope header (containing magic bytes, version, payload length, and 64-bit alignment padding) before passing byte buffers across JNI/FFI boundaries.

Engineers MUST ALWAYS enforce a fixed-size binary preamble/envelope header (containing magic bytes, version, payload length, and 64-bit alignment padding) before passing byte buffers across JNI/FFI boundaries.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT construct Rust slices using `std

Engineers MUST NOT construct Rust slices using `std::slice::from_raw_parts` without verifying non-null pointers, host-platform memory alignment (`pointer.align_offset() == 0`), and total buffer capacity invariants against the host envelope length.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code SHOULD leverage Android JNI `GetDirectBufferAddress` and `GetDirectBufferCapacity` exclusively within an explicit JNI frame boundary, checking for a return of -1 or NULL before zero-copy reads.

Code SHOULD leverage Android JNI `GetDirectBufferAddress` and `GetDirectBufferCapacity` exclusively within an explicit JNI frame boundary, checking for a return of -1 or NULL before zero-copy reads.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services MUST ensure that native buffers shared across FFI are immutable for the duration of the cross-boundary execution, or use explicit copy-on-write guards to prevent race-condition-induced use-after-free (UAF) or heap corruptions.

Services MUST ensure that native buffers shared across FFI are immutable for the duration of the cross-boundary execution, or use explicit copy-on-write guards to prevent race-condition-induced use-after-free (UAF) or heap corruptions.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER expose unbounded `ArrayBuffer` or raw typed array offsets from the webview layer directly to the native host plugin without bounds-checking against the maximum permitted FFI sandbox envelope size.

Components NEVER expose unbounded `ArrayBuffer` or raw typed array offsets from the webview layer directly to the native host plugin without bounds-checking against the maximum permitted FFI sandbox envelope size.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Tauri 2.0 Mobile JNI/FFI Zero-Copy Byte-Buffer Envelope Validation critical for AI coding assistants?

Enforces deterministic byte-buffer envelope validation and memory layout constraints across Tauri 2.0 Rust-to-mobile FFI boundaries (Android JNI DirectByteBuffer and iOS Swift UnsafeRawBufferPointer). Mandates strict validation of buffer length, alignment, capacity, and monotonic byte bounds to eliminate native buffer overruns and unaligned pointer dereferences during zero-copy IPC. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unvalidated Raw Pointer Casting and Direct Unchecked Slice Slicing Over Native IPC) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Tauri