Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 39 ยท Security and Permissions

Scopes and Input Validation in Tauri

Limit commands to certain paths, URLs and programs with Tauri scopes, and write Rust commands that validate untrusted input: path traversal, shell injection and size limits, with runnable models.

A permission says whether a command may be called at all. A scope says what it may touch. "The frontend may read text files" is dangerous; "the frontend may read text files under the notes folder" is a reasonable design. Scopes, together with careful input validation in your own Rust commands, are what keep a compromised webview from turning your app into a general file stealer.

This lesson is about both halves: the built-in scopes you configure, and the validation you write yourself. It continues from Capabilities and Permissions.

Real versus stand-in. The JSON and Rust are real Tauri 2 code to read. The runnable blocks are JavaScript models of the same checks, so you can experiment safely.

Scopes in configuration

Scopes are lists of allow and deny entries attached to a permission. The shape of an entry depends on the plugin:

JSON
{
  "permissions": [
    {
      "identifier": "fs:allow-read-text-file",
      "allow": [{ "path": "$APPDATA/notes/**" }],
      "deny": [{ "path": "$APPDATA/notes/.trash/**" }]
    },
    {
      "identifier": "opener:allow-open-url",
      "allow": [{ "url": "https://tauri.app/*" }, { "url": "https://github.com/*" }]
    },
    {
      "identifier": "shell:allow-execute",
      "allow": [
        { "name": "git-status", "cmd": "git", "args": ["status", "--short"] }
      ]
    }
  ]
}
  • Paths use globs. * matches within a folder, ** matches any depth. Variables such as $APPDATA, $APPCONFIG, $DOCUMENT, $DOWNLOAD, $HOME, $TEMP and $RESOURCE expand per platform.
  • URLs use patterns, for the opener and http plugins.
  • Commands for the shell plugin list exact programs and argument shapes. An argument can be a fixed string or a validator such as a regular expression for a single value, so the frontend cannot slip extra flags in.

Tip: a pattern ending in /* stops at one level and /** goes deeper. Another subtle point is that glob matching also resolves symbolic links, so a link inside the allowed folder that points outside it does not become a way out.

Dynamic scope at runtime

Dialog results are added to the allowed scope for the running session. When the user picks C:\Users\Ada\Desktop\resume.docx in an open dialog, your app may read that exact file, even though you never allowed Desktop in the capability. This is the pattern to prefer: let the user's own action grant access, instead of broad static scopes.

In Rust you can do the same thing, for example after the user picks a project folder:

Rust
use tauri_plugin_fs::FsExt;

#[tauri::command]
fn allow_project(app: tauri::AppHandle, folder: std::path::PathBuf) -> Result<(), String> {
    app.fs_scope()
        .allow_directory(&folder, true) // true = recursive
        .map_err(|e| e.to_string())
}

Only do this with paths that came from a dialog the user controlled, never with a path the webview made up.

Your own commands are your own responsibility

Tauri's scopes protect plugin commands. A #[tauri::command] function you write receives arguments straight from JavaScript, and nothing checks their meaning. Treat each argument like input from the internet.

Path traversal

The classic mistake:

Rust
// DANGEROUS: the frontend can pass "../../.ssh/id_rsa"
#[tauri::command]
fn read_note(app: tauri::AppHandle, name: String) -> Result<String, String> {
    let dir = app.path().app_data_dir().map_err(|e| e.to_string())?.join("notes");
    std::fs::read_to_string(dir.join(name)).map_err(|e| e.to_string())
}

A safer version rejects names that are anything but a plain file name, then double-checks the final location:

Rust
use std::path::{Component, Path, PathBuf};

fn safe_join(base: &Path, name: &str) -> Result<PathBuf, String> {
    let candidate = Path::new(name);
    let mut parts = candidate.components();
    match (parts.next(), parts.next()) {
        (Some(Component::Normal(_)), None) => {}
        _ => return Err("invalid note name".into()),
    }
    let full = base.join(candidate);
    let base_real = base.canonicalize().map_err(|e| e.to_string())?;
    if let Ok(real) = full.canonicalize() {
        if !real.starts_with(&base_real) {
            return Err("path escapes notes folder".into());
        }
    }
    Ok(full)
}

The same idea in JavaScript lets you play with attack strings:

Node.js Stand-in: reject names that are not a single plain file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

An allow-list of characters is stronger than a block-list of bad ones.

Never build shell strings

Rust
// DANGEROUS: "x; rm -rf ~" runs a second command
let cmd = format!("git log {}", branch);
std::process::Command::new("sh").arg("-c").arg(cmd).output();

// SAFER: the program and each argument are separate; no shell involved
std::process::Command::new("git")
    .args(["log", "--oneline", "-n", "20", "--", &branch])
    .output();

Even without a shell, a value starting with - can be read as an option. Put -- before user-provided values when the program supports it, and validate against a pattern (for example branch names ^[\w./-]{1,100}$).

Limits and types

  • Cap sizes: a command that accepts Vec<u8> or String should reject absurd lengths.
  • Prefer typed arguments (enums, numbers) over free text. A Mode enum cannot be anything but its variants, because the deserializer refuses other values.
  • Return errors with Result, with messages that do not leak internal paths.
Node.js Stand-in: validate command arguments before using them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A review checklist for each command

  1. Is it listed in the app manifest and granted only to windows that need it?
  2. Is every argument typed and range-checked?
  3. Are paths built with a base directory and checked for escapes?
  4. Does it avoid shells, string-built SQL and string-built HTML?
  5. Does it return a safe error rather than panic?
  6. Does it do only one job, so that granting it does not grant more than intended?

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between a permission and a scope?

    Permissions switch commands on or off; scopes restrict paths, URLs or programs for allowed commands.
  2. 2. How does a dialog help keep scopes small?

    The user's own choice grants access to exactly the selected file or folder.
  3. 3. Which Rust approach avoids command injection?

    Without a shell there is nothing to interpret metacharacters, and validation covers option-like values.
  4. 4. Why prefer an allow-list of characters for a file name?

    Rejecting everything except known-good input is safer than trying to list every bad input.

Summary

  • Scopes limit allowed commands to paths, URLs or exact programs; deny beats allow.
  • Prefer user-driven dynamic scope (dialogs) to broad static scopes.
  • Plugin scopes do not protect your own commands: validate paths, arguments, sizes and types in Rust.
  • Never build shell strings or trust file names; use allow-lists, base directories and canonical checks.

Next: CSP, Isolation and Hardening