This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: tauri-v2-granular-ipc-permission-scope-guardrail

Tauri 2.0 Granular Mobile IPC Capability Scoping & Runtime Boundary Validation

Enforces strict principle-of-least-privilege capability manifests and runtime deserialization guards for Tauri 2.0 IPC commands targeting mobile viewports (iOS/Android). Prevents cross-context native privilege escalation by forbidding catch-all capabilities, unconstrained wildcard scopes, and unchecked dynamic arguments over the webview-to-Rust serialization boundary.

Prohibited Anti-Pattern: Monolithic Capability Grants and Untyped Invocations Exposing Native OS Primitives to Untrusted Mobile Viewport Contexts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Tauri 2.0 Granular Mobile IPC Capability Scoping & Runtime Boundary Validation - Enforces strict principle-of-least-privilege capability manifests and runtime deserialization guards for Tauri 2.0 IPC commands targeting mobile viewports (iOS/Android). Prevents cross-context native privilege escalation by forbidding catch-all capabilities, unconstrained wildcard scopes, and unchecked dynamic arguments over the webview-to-Rust serialization boundary.
globs: src-tauri/src/**/*.rs, src-tauri/capabilities/**/*.json, src-tauri/tauri.conf.json, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tauri-v2-granular-ipc-permission-scope-guardrail"
---

# Tauri 2.0 Granular Mobile IPC Capability Scoping & Runtime Boundary Validation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Monolithic Capability Grants and Untyped Invocations Exposing Native OS Primitives to Untrusted Mobile Viewport Contexts

## System Constraints
You are a Principal Mobile Systems Architect and Security Engineer auditing Tauri 2.0 applications. You mandate strict compliance with Tauri 2.0 capability isolation, mobile webview origin bounding, and granular runtime permission schemas. You strictly reject permissive capabilities (such as 'core:default' with wildcard scopes), arbitrary shell/fs plugin execution from mobile webviews, and unvalidated Rust command arguments.

## Strict Guidelines
- Engineers MUST ALWAYS isolate mobile capabilities into dedicated JSON capability files under `src-tauri/capabilities/` targeting explicit mobile platforms using the `"platforms": ["android", "iOS"]` constraint.
- Engineers MUST NOT grant catch-all permissions or use wildcard `*` scopes within mobile capability manifests (e.g., `fs:default` or `fs:allow-all` without constrained path scopes).
- Code MUST strictly validate incoming payload payloads using Serde structs deriving `Deserialize` with rigorous assertions (rejecting unknown fields via `#[serde(deny_unknown_fields)]`) before passing parameters into native mobile OS bridges.
- Services MUST verify the invocation caller context and window/webview label within Tauri commands using `tauri::ipc::Request` or explicit `WebviewWindow` checks when critical native capabilities (biometrics, secure storage, camera) are dispatched.
- Components NEVER invoke raw untyped `invoke()` calls from frontend mobile webviews; all calls must flow through strictly typed, schema-validated wrappers that sanitize input prior to traversing the boundary.

## Bad vs Good Implementations
### Unconstrained Capability and Untyped Mobile IPC Command Handler

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Exposing arbitrary filesystem APIs with coarse-grained permissions allows any injected XSS script or compromised third-party web dependency inside the mobile WebKit/WebView to traverse directory structures and extract sensitive application sandbox data.
```rust
// BAD: Arbitrary native file read command exposed without scope restrictions
// Capability grants global fs access, and Rust accepts untyped/unconstrained string input.

#[tauri::command]
pub async fn read_mobile_storage(file_path: String) -> Result<String, String> {
    // Directly accessing filesystem from untrusted webview input
    std::fs::read_to_string(&file_path)
        .map_err(|e| format!("Failed to read file: {}", e))
}

// In src-tauri/capabilities/mobile.json:
// {
//   "permissions": ["core:default", "fs:default"]
// }
```

#### Production Standard (Correct)
> **Standard**: The command enforces strong typing with Serde's `deny_unknown_fields`, validates inputs against path-traversal primitives, resolves safely inside the platform's sandboxed `app_data_dir`, and relies on a bespoke scoped permission declared strictly for mobile platforms.
```rust
// GOOD: Granular permission scope with Serde validation and explicit sandbox boundaries

use serde::Deserialize;
use std::path::{Path, PathBuf};
use tauri::ipc::CommandItem;
use tauri::{AppHandle, Manager, Runtime};

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SecureReadPayload {
    /// Restrict to strict identifier; absolute or traversing paths are rejected
    pub document_id: String,
}

#[tauri::command]
pub async fn read_mobile_document<R: Runtime>(
    app: AppHandle<R>,
    payload: SecureReadPayload,
) -> Result<String, String> {
    // Reject path traversal attempts explicitly
    if payload.document_id.contains("..") || payload.document_id.contains('/') || payload.document_id.contains('\\') {
        return Err("Invalid document identifier: path traversal detected".into());
    }

    // Bound access strictly to app-specific mobile documents directory
    let app_docs = app.path().app_data_dir().map_err(|e| e.to_string())?;
    let resolved_path: PathBuf = app_docs.join("documents").join(format!("{}.dat", payload.document_id));

    tokio::fs::read_to_string(resolved_path)
        .await
        .map_err(|_| "Document retrieval failed or permission denied".to_string())
}

// In src-tauri/capabilities/mobile-safe.json:
// {
//   "$schema": "../gen/schemas/desktop-schema.json",
//   "identifier": "mobile-document-capability",
//   "description": "Strictly scoped access to user documents on mobile",
//   "windows": ["main"],
//   "platforms": ["android", "iOS"],
//   "permissions": [
//     "allow-read-mobile-document"
//   ]
// }
```

### Strictly Typed Frontend IPC Client Wrapper

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing untyped inputs directly via raw `invoke` permits tainted parameters and lacks compile-time validation, making the mobile boundary fragile and vulnerable to parameter injection.
```typescript
// BAD: Raw untyped invoke with dynamic arguments across mobile bridge
import { invoke } from '@tauri-apps/api/core';

export async function getDocument(unvalidatedInput: any) {
  // Arbitrary payload passed directly to IPC command
  return await invoke('read_mobile_storage', { filePath: unvalidatedInput });
}
```

#### Production Standard (Correct)
> **Standard**: Validates boundaries before invoking the bridge using Zod to reject malformed inputs before they cross the webview boundary, ensuring the IPC caller adheres strictly to backend Serde schema definitions.
```typescript
// GOOD: Runtime validated frontend bridge using Zod and isolated type contract
import { invoke } from '@tauri-apps/api/core';
import { z } from 'zod';

const DocumentIdSchema = z
  .string()
  .min(1)
  .max(64)
  .regex(/^[a-zA-Z0-9_-]+$/, 'Identifier must be strictly alphanumeric');

export type DocumentId = z.infer<typeof DocumentIdSchema>;

export async function getDocument(id: unknown): Promise<string> {
  const parseResult = DocumentIdSchema.safeParse(id);
  if (!parseResult.success) {
    throw new Error(`IPC Schema Validation Error: ${parseResult.error.message}`);
  }

  return await invoke<string>('read_mobile_document', {
    payload: {
      document_id: parseResult.data
    }
  });
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Tauri 2.0 Granular Mobile IPC Capability Scoping & Runtime Boundary Validation

Tauri 2.0 Granular Mobile IPC Capability Scoping & Runtime Boundary Validation defines an industrial-grade behavioral standard for mobile engineering. Enforces strict principle-of-least-privilege capability manifests and runtime deserialization guards for Tauri 2.0 IPC commands targeting mobile viewports (iOS/Android). Prevents cross-context native privilege escalation by forbidding catch-all capabilities, unconstrained wildcard scopes, and unchecked dynamic arguments over the webview-to-Rust serialization boundary. 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: Monolithic Capability Grants and Untyped Invocations Exposing Native OS Primitives to Untrusted Mobile Viewport Contexts 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 DriftMonolithic Capability Grants and Untyped Invocations Exposing Native OS Primitives to Untrusted Mobile Viewport ContextsCritical
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 isolate mobile capabilities into dedicated JSON capability files under `src-tauri/capabilities/` targeting explicit mobile platforms using the `"platforms"

Engineers MUST ALWAYS isolate mobile capabilities into dedicated JSON capability files under `src-tauri/capabilities/` targeting explicit mobile platforms using the `"platforms": ["android", "iOS"]` constraint.

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 grant catch-all permissions or use wildcard `*` scopes within mobile capability manifests (e.g., `fs

Engineers MUST NOT grant catch-all permissions or use wildcard `*` scopes within mobile capability manifests (e.g., `fs:default` or `fs:allow-all` without constrained path scopes).

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 MUST strictly validate incoming payload payloads using Serde structs deriving `Deserialize` with rigorous assertions (rejecting unknown fields via `#[serde(deny_unknown_fields)]`) before passing parameters into native mobile OS bridges.

Code MUST strictly validate incoming payload payloads using Serde structs deriving `Deserialize` with rigorous assertions (rejecting unknown fields via `#[serde(deny_unknown_fields)]`) before passing parameters into native mobile OS bridges.

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 verify the invocation caller context and window/webview label within Tauri commands using `tauri

Services MUST verify the invocation caller context and window/webview label within Tauri commands using `tauri::ipc::Request` or explicit `WebviewWindow` checks when critical native capabilities (biometrics, secure storage, camera) are dispatched.

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 invoke raw untyped `invoke()` calls from frontend mobile webviews

Components NEVER invoke raw untyped `invoke()` calls from frontend mobile webviews; all calls must flow through strictly typed, schema-validated wrappers that sanitize input prior to traversing the boundary.

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 Granular Mobile IPC Capability Scoping & Runtime Boundary Validation critical for AI coding assistants?

Enforces strict principle-of-least-privilege capability manifests and runtime deserialization guards for Tauri 2.0 IPC commands targeting mobile viewports (iOS/Android). Prevents cross-context native privilege escalation by forbidding catch-all capabilities, unconstrained wildcard scopes, and unchecked dynamic arguments over the webview-to-Rust serialization boundary. 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 (Monolithic Capability Grants and Untyped Invocations Exposing Native OS Primitives to Untrusted Mobile Viewport Contexts) 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