use std::collections::BTreeSet;
use super::*;
use crate::review::diff::{Kind, Status};
pub fn run(cx: &Cx, out: &mut Vec<Finding>) {
let Some(t) = cx.tauri() else { return };
config(cx, &t, out);
capabilities(cx, &t, out);
commands(cx, &t, out);
invokes(cx, &t, out);
versions(cx, &t, out);
}
fn dev_cmd(cx: &Cx, t: &Tauri) -> String {
t.cli(cx.node(), "dev")
}
fn is_conf(t: &Tauri, path: &str) -> bool {
["tauri.conf.json", "tauri.conf.json5", "Tauri.toml"].iter().any(|n| path == t.path(n))
}
fn config(cx: &Cx, t: &Tauri, out: &mut Vec<Finding>) {
for f in cx.diff.files.iter().filter(|f| is_conf(t, &f.path) && f.status != Status::Deleted) {
let mut bundle_hit = None;
for l in f.added() {
let text = &l.text;
if let Some(i) = text.find("\"csp\"")
&& text[i + 5..].trim_start().trim_start_matches(':').trim_start().starts_with("null")
{
out.push(
Finding::new("TAU001", Level::Risk, "the Content-Security-Policy is switched off")
.at(&f.path, l, "null", "no CSP: the webview will load and run anything")
.note("a CSP is what limits the damage of an XSS bug in the webview, where it could otherwise call every Tauri command the app allows")
.check("DevTools console after launching: CSP violations show as `Refused to load ...`; each one is either a real hole or a source to allow on purpose")
.test(format!("`{}`, open DevTools, and use every screen that loads images, fonts or remote APIs", dev_cmd(cx, t)))
.help("set a policy such as `default-src 'self'; connect-src ipc: http://ipc.localhost` and add only the sources the app needs"),
);
}
for needle in ["unsafe-eval", "unsafe-inline"] {
if let Some(i) = text.find(needle) {
out.push(
Finding::new("TAU001", Level::Warn, format!("the Content-Security-Policy allows `{needle}`"))
.at_range(&f.path, l, i, i + needle.len(), "weakens the policy")
.note("inline or eval'd script is exactly what an injected payload uses")
.check("is it needed for a dev server only? Tauri adds nonces and hashes to its own scripts, so production rarely needs it")
.test(format!("`{}`: remove it and confirm the app still renders and every feature works", t.cli(cx.node(), "build"))),
);
}
}
if let Some(i) = text.find("\"all\"")
&& text[i + 5..].trim_start().trim_start_matches(':').trim_start().starts_with("true")
{
out.push(
Finding::new("TAU002", Level::Risk, "the allowlist enables every API in a group")
.at_range(&f.path, l, i, text.len(), "grants all of it to the webview")
.help("enable only the individual APIs the app uses"),
);
}
if ["\"pubkey\"", "\"endpoints\"", "\"updater\"", "createUpdaterArtifacts", "\"bundle\""].iter().any(|k| text.contains(k)) && bundle_hit.is_none() {
bundle_hit = Some(l);
}
}
for key in ["\"identifier\"", "\"productName\""] {
let (a, r) = (f.added().find(|l| l.text.contains(key)), f.removed().find(|l| l.text.contains(key)));
if let (Some(a), Some(r)) = (a, r) {
out.push(
Finding::new("TAU006", Level::Warn, format!("{key} changed", key = key.trim_matches('"')))
.at(&f.path, a, key, "this changes where the app keeps its data")
.note(format!("was `{}`; the app data, config and cache folders are named after the identifier, so existing installs start with nothing and the updater may treat it as another app", r.text.trim()))
.test("install the previous release, create some data, then install this build over it and check the data is still there")
.help("keep the old identifier, or migrate the old folder on first start"),
);
}
}
if let Some(l) = bundle_hit {
out.push(
Finding::new("TAU008", Level::Note, "bundle or updater settings changed")
.at(&f.path, l, "", "affects the installer or auto-update")
.check("installer icons, targets, `endpoints` URL and the public key that must match the key the release is signed with")
.test(format!("`{}`, then install the result on a clean machine or VM and launch it", t.cli(cx.node(), "build")))
.test("for the updater: run an older version and confirm it finds, downloads and installs this one"),
);
}
}
}
fn broad_permission(perm: &str) -> Option<&'static str> {
let any = |ps: &[&str]| ps.iter().any(|p| perm.starts_with(p));
if any(&["shell:allow-execute", "shell:allow-spawn", "shell:allow-kill"]) {
Some("lets the webview run programs")
} else if any(&["fs:allow-write", "fs:allow-remove", "fs:allow-rename", "fs:allow-mkdir", "fs:allow-copy", "fs:allow-create", "fs:allow-truncate"]) {
Some("lets the webview change files")
} else if any(&["http:default", "http:allow-fetch"]) {
Some("lets the webview call any allowed URL")
} else if any(&["process:allow-exit", "process:allow-restart"]) {
Some("lets the webview quit or restart the app")
} else if any(&["shell:allow-open", "opener:allow-open", "opener:default"]) {
Some("lets the webview open files, folders and URLs")
} else {
None
}
}
fn permissions_in(text: &str) -> Vec<(usize, usize, String)> {
let mut found = Vec::new();
let mut from = 0;
while let Some((s, e, q)) = string_at(text, from) {
from = e;
if q != '"' && q != '\'' {
continue;
}
let inner = &text[s + 1..e - 1];
let shaped = inner.contains(':')
&& inner.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == ':')
&& !inner.starts_with("http");
if shaped {
found.push((s + 1, e - 1, inner.to_string()));
}
}
found
}
fn capabilities(cx: &Cx, t: &Tauri, out: &mut Vec<Finding>) {
let prefix = t.path("capabilities/");
for f in cx.diff.files.iter().filter(|f| f.path.starts_with(&prefix) && f.status != Status::Deleted) {
let mut others: Vec<String> = Vec::new();
let mut first_other = None;
for l in f.added() {
for (s, e, perm) in permissions_in(&l.text) {
if let Some(why) = broad_permission(&perm) {
out.push(
Finding::new("TAU002", Level::Warn, format!("broad permission `{perm}`"))
.at_range(&f.path, l, s, e, why)
.note("every window this capability applies to gets it, including any page that window loads")
.check("does the window only ever load your own bundled pages? is the scope as narrow as it can be (one folder, one command)?")
.test(format!("use the feature that needs it, then delete `{perm}` and repeat: the call must now be rejected with a \"not allowed\" error in DevTools, which proves this file is what grants it"))
.help("grant the narrowest permission with an explicit `allow` scope instead"),
);
} else {
first_other.get_or_insert(l);
others.push(perm);
}
}
for wide in ["\"**\"", "\"$HOME/**\"", "\"/**\"", "\"$APPDATA/**\""] {
if let Some(i) = l.text.find(wide) {
out.push(
Finding::new("TAU002", Level::Warn, format!("scope {wide} covers every file below it"))
.at_range(&f.path, l, i, i + wide.len(), "a wildcard scope")
.check("which folder does the feature really need? scope to that")
.test("try to read or write a path outside the intended folder from DevTools: it should be refused"),
);
}
}
if let Some(i) = l.text.find("\"remote\"") {
out.push(
Finding::new("TAU002", Level::Warn, "capability applies to remote content")
.at_range(&f.path, l, i, i + 8, "remote URLs get these permissions")
.note("pages you do not ship (and anything injected into them) can then use the permissions listed in this file"),
);
}
}
if let (Some(l), false) = (first_other, others.is_empty()) {
let list = others.iter().map(|p| format!("`{p}`")).collect::<Vec<_>>().join(", ");
out.push(
Finding::new("TAU002", Level::Note, format!("{} permission(s) added: {list}", others.len()))
.at(&f.path, l, "", "new permission")
.test("use each feature that needs one of them once; a missing permission shows as a \"not allowed\" error in the DevTools console")
.check("is each one needed by a window that really has this capability?"),
);
}
}
}
fn fn_name(text: &str) -> Option<&str> {
let mut rest = text.trim_start();
'outer: loop {
for q in ["pub(crate) ", "pub(super) ", "pub ", "async ", "unsafe ", "const "] {
if let Some(r) = rest.strip_prefix(q) {
rest = r;
continue 'outer;
}
}
break;
}
let rest = rest.strip_prefix("fn ")?;
let end = rest.find(|c: char| !(c.is_alphanumeric() || c == '_')).unwrap_or(rest.len());
(end > 0).then(|| &rest[..end])
}
fn is_command_attr(text: &str) -> bool {
let t = text.trim_start();
t.starts_with("#[tauri::command") || t.starts_with("#[command")
}
fn commands_in(text: &str) -> Vec<String> {
let mut out = Vec::new();
let mut pending = false;
for line in text.lines() {
let t = line.trim();
if is_command_attr(t) {
pending = true;
} else if pending {
if let Some(n) = fn_name(t) {
out.push(n.to_string());
pending = false;
} else if !(t.is_empty() || t.starts_with("#[") || t.starts_with("//")) {
pending = false;
}
}
}
out
}
struct Declared<'a> {
name: String,
file: &'a FileDiff,
line: &'a Line,
was: Option<&'a Line>,
}
fn declared_commands<'a>(cx: &'a Cx, t: &Tauri) -> Vec<Declared<'a>> {
let mut found = Vec::new();
for f in cx.diff.files.iter().filter(|f| ext(&f.path) == "rs" && f.status != Status::Deleted && (t.dir == "." || f.path.starts_with(&t.path("")))) {
for h in &f.hunks {
for (i, l) in h.lines.iter().enumerate() {
if l.kind != Kind::Added {
continue;
}
let Some(name) = fn_name(&l.text) else { continue };
let is_cmd = h.lines[..i]
.iter()
.rev()
.filter(|p| p.kind != Kind::Removed)
.map(|p| p.text.trim())
.take_while(|p| p.is_empty() || p.starts_with("#[") || p.starts_with("//"))
.any(is_command_attr);
if !is_cmd {
continue;
}
let was = h.lines.iter().find(|r| r.kind == Kind::Removed && fn_name(&r.text) == Some(name));
found.push(Declared { name: name.to_string(), file: f, line: l, was });
}
}
}
found
}
fn registered(cx: &Cx, t: &Tauri) -> Option<(BTreeSet<String>, String)> {
let mut names = BTreeSet::new();
let mut place = None;
for (path, text) in cx.scan(&t.path("src"), &["rs"]) {
if text.contains("collect_commands!") {
return None; }
let mut from = 0;
while let Some(i) = text[from..].find("generate_handler!") {
let at = from + i;
from = at + 17;
let Some(open) = text[from..].find(['[', '(']).map(|o| from + o) else { continue };
let close_ch = if text.as_bytes()[open] == b'[' { ']' } else { ')' };
let Some(close) = text[open..].find(close_ch).map(|c| open + c) else { continue };
place.get_or_insert_with(|| format!("{path}:{}", text[..at].matches('\n').count() + 1));
for item in text[open + 1..close].split(',') {
let item: String = item.lines().filter(|l| !l.trim_start().starts_with("//")).collect::<Vec<_>>().join(" ");
let name = item.trim().rsplit("::").next().unwrap_or("").trim();
if !name.is_empty() {
names.insert(name.to_string());
}
}
}
}
place.map(|p| (names, p))
}
fn call_sites(cx: &Cx, name: &str) -> Vec<String> {
let mut sites = Vec::new();
for dir in ["src", "app", "frontend", "ui", "resources/js"] {
for (path, text) in cx.scan(dir, &["js", "jsx", "ts", "tsx", "vue", "svelte", "mjs"]) {
for (i, line) in text.lines().enumerate() {
if invoke_calls(line).iter().any(|c| c.2 == name) {
sites.push(format!("{path}:{}", i + 1));
}
}
}
}
sites
}
fn commands(cx: &Cx, t: &Tauri, out: &mut Vec<Finding>) {
let declared = declared_commands(cx, t);
if declared.is_empty() {
return;
}
let reg = registered(cx, t);
for d in &declared {
let path = &d.file.path;
let mut f = match d.was {
None => Finding::new("TAU004", Level::Note, format!("new Tauri command `{}`", d.name))
.at(path, d.line, &format!("fn {}", d.name), "callable from the webview once registered")
.check("the argument names: Rust `snake_case` parameters are `camelCase` keys on the JS side unless `rename_all` is set")
.check("the error type must implement `Serialize`, or the call cannot return it to JS")
.check("slow work belongs in an `async` command, or the call blocks the main thread"),
Some(old) => {
let mut f = Finding::new("TAU004", Level::Warn, format!("Tauri command `{}` changed", d.name))
.at(path, d.line, &format!("fn {}", d.name), "JS callers pass arguments the old way")
.note(format!("was `{}`", old.text.trim()))
.check("every `invoke()` call site: renamed or retyped parameters are `camelCase` keys, a changed return type changes what `await invoke()` resolves to");
let sites = call_sites(cx, &d.name);
if !sites.is_empty() {
f = f.note(format!("called from {}", sites.iter().take(6).cloned().collect::<Vec<_>>().join(", ")));
}
f
}
};
f = f.test(if t.major >= 2 {
format!("in the app's DevTools console: `await window.__TAURI_INTERNALS__.invoke('{}', {{ /* args */ }})`; try valid input and one that makes it fail", d.name)
} else {
format!("call `invoke('{}', {{ /* args */ }})` from the frontend; try valid input and one that makes it fail", d.name)
});
out.push(f);
if let Some((names, place)) = ®
&& !names.contains(&d.name)
{
out.push(
Finding::new("TAU003", Level::Risk, format!("command `{}` is not registered", d.name))
.at(path, d.line, &format!("fn {}", d.name), "missing from `generate_handler!`")
.note(format!("`invoke('{}')` will fail at runtime with \"Command {} not found\"; the compiler does not catch it", d.name, d.name))
.help(format!("add `{}` to the `tauri::generate_handler![...]` list at {place}", d.name)),
);
}
}
}
fn invoke_calls(text: &str) -> Vec<(usize, usize, String)> {
let mut found = Vec::new();
for (i, _) in text.match_indices("invoke") {
if text[..i].chars().next_back().is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$') {
continue;
}
let mut j = i + 6;
let rest = &text[j..];
if rest.starts_with('<') {
let mut depth = 0;
let mut end = None;
for (k, c) in rest.char_indices() {
match c {
'<' => depth += 1,
'>' => {
depth -= 1;
if depth == 0 {
end = Some(k + 1);
break;
}
}
_ => {}
}
}
let Some(end) = end else { continue };
j += end;
}
let after = text[j..].trim_start();
let Some(args) = after.strip_prefix('(') else { continue };
let args_start = text.len() - args.len();
let trimmed = args.trim_start();
let q_at = args_start + (args.len() - trimmed.len());
if !trimmed.starts_with(['"', '\'', '`']) {
continue;
}
let Some((s, e, _)) = string_at(text, q_at) else { continue };
found.push((s, e, text[s + 1..e - 1].to_string()));
}
found
}
fn edit_distance(a: &str, b: &str) -> usize {
let b: Vec<char> = b.chars().collect();
let mut prev: Vec<usize> = (0..=b.len()).collect();
for (i, ca) in a.chars().enumerate() {
let mut cur = vec![i + 1];
for (j, cb) in b.iter().enumerate() {
cur.push((prev[j] + usize::from(ca != *cb)).min(prev[j + 1] + 1).min(cur[j] + 1));
}
prev = cur;
}
prev[b.len()]
}
fn did_you_mean<'a>(name: &str, known: &'a BTreeSet<String>) -> Option<&'a str> {
let norm = |s: &str| s.replace('_', "").to_lowercase();
known
.iter()
.map(|k| (k.as_str(), if norm(k) == norm(name) { 0 } else { edit_distance(&norm(k), &norm(name)) }))
.filter(|&(_, d)| d <= 2.max(name.len() / 5))
.min_by_key(|&(_, d)| d)
.map(|(k, _)| k)
}
fn invokes(cx: &Cx, t: &Tauri, out: &mut Vec<Finding>) {
let mut known: BTreeSet<String> = BTreeSet::new();
for (_, text) in cx.scan(&t.path("src"), &["rs"]) {
known.extend(commands_in(&text));
}
known.extend(declared_commands(cx, t).into_iter().map(|d| d.name));
if known.is_empty() {
return; }
for f in cx.diff.files.iter().filter(|f| f.status != Status::Deleted && (t.dir == "." || !f.path.starts_with(&t.path("")))) {
if !matches!(ext(&f.path).as_str(), "js" | "jsx" | "ts" | "tsx" | "vue" | "svelte" | "mjs") || f.path.contains("node_modules/") {
continue;
}
for l in f.added() {
for (s, e, name) in invoke_calls(&l.text) {
if name.starts_with("plugin:") || name.contains("${") || known.contains(&name) {
continue;
}
let mut finding = Finding::new("TAU005", Level::Risk, format!("no Tauri command named `{name}`"))
.at_range(&f.path, l, s, e, "not defined on the Rust side")
.note(format!("`invoke` rejects at runtime with \"Command {name} not found\""));
finding = match did_you_mean(&name, &known) {
Some(k) => finding.help(format!("a command named `{k}` exists: did you mean it? (Rust `snake_case` names are called as written)")),
None => finding.help("define it with `#[tauri::command]` and register it in `generate_handler!`"),
};
out.push(finding);
}
}
}
}
fn versions(cx: &Cx, t: &Tauri, out: &mut Vec<Finding>) {
let cargo_path = t.path("Cargo.toml");
let crate_line = cx.file(&cargo_path).and_then(|f| {
f.added().find(|l| {
let tt = l.text.trim_start();
(tt.starts_with("tauri =") || tt.starts_with("tauri-build =") || tt.starts_with("tauri-plugin-")) && tt.contains(|c: char| c.is_ascii_digit())
})
});
let pkg = cx.diff.files.iter().find(|f| file_name(&f.path) == "package.json" && f.status != Status::Deleted);
let js_line = pkg.and_then(|f| f.added().find(|l| l.text.contains("\"@tauri-apps/") && l.text.contains(|c: char| c.is_ascii_digit())));
let info = t.cli(cx.node(), "info");
match (crate_line, js_line) {
(Some(l), None) => out.push(
Finding::new("TAU007", Level::Warn, "a `tauri` crate changed but no `@tauri-apps` package did")
.at(&cargo_path, l, "", "version changed here")
.note("the Rust crates and the JS packages are a matched set: a different minor version can break the IPC between them")
.test(format!("`{info}` lists both versions and warns when they do not match")),
),
(None, Some(l)) => out.push(
Finding::new("TAU007", Level::Warn, "an `@tauri-apps` package changed but no `tauri` crate did")
.at(&pkg.unwrap().path, l, "", "version changed here")
.note("the Rust crates and the JS packages are a matched set: a different minor version can break the IPC between them")
.test(format!("`{info}` lists both versions and warns when they do not match")),
),
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::super::testing::*;
use super::*;
use crate::review::project::Project;
use crate::review::testutil::Scratch;
#[test]
fn disabled_csp_is_a_risk_and_unsafe_eval_a_warning() {
let f = review(&[edit("src-tauri/tauri.conf.json", &["\"security\": {", "-\"csp\": \"default-src 'self'\"", "+\"csp\": null"])]);
let g = get(&f, "TAU001");
assert_eq!(g.level, Level::Risk);
assert_eq!(g.span.as_ref().unwrap().len, 4);
let w = review(&[edit("src-tauri/tauri.conf.json", &["+\"csp\": \"script-src 'self' 'unsafe-eval'\""])]);
assert_eq!(get(&w, "TAU001").level, Level::Warn);
}
#[test]
fn broad_and_ordinary_permissions() {
let f = review(&[add("src-tauri/capabilities/main.json", &["{", " \"permissions\": [", " \"core:default\",", " \"shell:allow-execute\",", " \"fs:allow-write-file\"", " ]", "}"])]);
let t2: Vec<_> = f.iter().filter(|f| f.code == "TAU002").collect();
assert_eq!(t2.iter().filter(|f| f.level == Level::Warn).count(), 2);
assert!(t2.iter().any(|f| f.level == Level::Note && f.title.contains("`core:default`")));
}
#[test]
fn identifier_change_is_flagged_but_adding_one_is_not() {
let f = review(&[edit("src-tauri/tauri.conf.json", &["-\"identifier\": \"com.old.app\",", "+\"identifier\": \"com.new.app\","])]);
assert!(get(&f, "TAU006").note[0].contains("com.old.app"));
assert!(!has(&review(&[add("src-tauri/tauri.conf.json", &["\"identifier\": \"com.new.app\""])]), "TAU006"));
}
#[test]
fn new_and_changed_commands() {
let f = review(&[edit(
"src-tauri/src/lib.rs",
&["#[tauri::command]", "+async fn save_note(note_id: u32) -> Result<(), String> {", "-fn rename(a: u32) {", "+fn rename(a: u32, b: u32) {", "}"],
)]);
assert_eq!(f.iter().filter(|f| f.code == "TAU004").count(), 1); let g = get(&f, "TAU004");
assert!(g.title.contains("save_note") && g.level == Level::Note);
assert!(g.test[0].contains("invoke('save_note'"));
let changed = review(&[edit("src-tauri/src/lib.rs", &["#[tauri::command]", "-fn load(id: u32) -> String {", "+fn load(id: u32, deep: bool) -> String {"])]);
let c = get(&changed, "TAU004");
assert_eq!(c.level, Level::Warn);
assert!(c.note[0].contains("fn load(id: u32)"));
}
#[test]
fn unregistered_command_and_unknown_invoke_are_found_on_disk() {
let s = Scratch::new("tauri-cmds");
s.write("src-tauri/tauri.conf.json", "{}");
s.write("src-tauri/Cargo.toml", "[dependencies]\ntauri = \"2\"\n");
s.write(
"src-tauri/src/lib.rs",
"mod cmds;\n#[tauri::command]\nfn save_note() {}\n#[tauri::command]\nfn forgotten() {}\npub fn run() {\n tauri::Builder::default().invoke_handler(tauri::generate_handler![\n save_note,\n cmds::other,\n ]);\n}\n",
);
let project = Project::detect(&s.0);
let f = review_with(
&[
edit("src-tauri/src/lib.rs", &["#[tauri::command]", "+fn forgotten() {}"]),
add("src/api.ts", &["await invoke('save_notes', { id: 1 });", "await invoke<string>(\"save_note\");", "await invoke('plugin:fs|read');", "invoke(`dyn_${x}`)"]),
],
&project,
None,
);
let unreg = get(&f, "TAU003");
assert!(unreg.title.contains("forgotten"));
assert!(unreg.help[0].contains("src-tauri/src/lib.rs:7"));
let unknown: Vec<_> = f.iter().filter(|f| f.code == "TAU005").collect();
assert_eq!(unknown.len(), 1);
assert!(unknown[0].help[0].contains("`save_note`"));
let s = unknown[0].span.as_ref().unwrap();
assert_eq!((s.line, s.col), (1, 14));
}
#[test]
fn version_skew_between_crate_and_npm_packages() {
let f = review(&[edit("src-tauri/Cargo.toml", &["-tauri = \"2.0\"", "+tauri = \"2.2\""])]);
assert!(has(&f, "TAU007"));
let both = review(&[edit("src-tauri/Cargo.toml", &["-tauri = \"2.0\"", "+tauri = \"2.2\""]), edit("package.json", &["-\"@tauri-apps/api\": \"^2.0.0\"", "+\"@tauri-apps/api\": \"^2.2.0\""])]);
assert!(!has(&both, "TAU007"));
}
#[test]
fn invoke_parsing_handles_generics_and_quotes() {
let c = invoke_calls("const a = await invoke<Array<string>>('list_all', {}); core.invoke(\"x\")");
let names: Vec<_> = c.iter().map(|c| c.2.as_str()).collect();
assert_eq!(names, vec!["list_all", "x"]);
assert!(invoke_calls("reinvoke('a')").is_empty());
assert!(invoke_calls("invoke(name)").is_empty());
}
}