fix(tauri): harden CSP, scope media CORS, block loopback redirects, allow --no-updater builds

This commit is contained in:
Erwan Leboucher committed 2026-07-26 15:47:58 +02:00
1 parent 63b4a686f9
commit 3d82cda286
11 files changed
+178 -67

No files matched your search

+22 -3
View File
@@ -11,6 +11,12 @@
*
* script/tauri cef dev --verbose
* → tauri dev --features cef,updater -- --verbose --no-default-features
*
* Pass `--no-updater` to omit the bundled auto-updater, for distro packagers and
* anyone building from source who updates through their own channel:
*
* script/tauri wry build --no-updater
* → tauri build --features wry -- --no-default-features
*/
import { run } from '@tauri-apps/cli';
@@ -45,22 +51,35 @@ async function main() {
return runTauri(cmdlineArgs);
}
const [platform, cmd, ...tauriArgs] = cmdlineArgs;
const [platform, cmd, ...rawTauriArgs] = cmdlineArgs;
if (!cmd) {
return runTauri(cmdlineArgs);
}
if (!['dev', 'build'].includes(cmd)) {
return runTauri([cmd, ...tauriArgs]);
return runTauri([cmd, ...rawTauriArgs]);
}
const args = [cmd, '--features', `${platform},updater`, ...tauriArgs];
// Consumed here, not forwarded: the tauri CLI does not know this flag.
const noUpdater = rawTauriArgs.includes('--no-updater');
const tauriArgs = rawTauriArgs.filter((arg) => arg !== '--no-updater');
if (noUpdater) {
logger.info('Building without the auto-updater (--no-updater)');
}
const features = noUpdater ? platform : `${platform},updater`;
const args = [cmd, '--features', features, ...tauriArgs];
if (!tauriArgs.includes('--')) {
args.push('--');
}
args.push('--no-default-features');
if (noUpdater && cmd === 'build') {
// Signed updater artifacts would otherwise demand TAURI_SIGNING_PRIVATE_KEY.
args.splice(1, 0, '--config', JSON.stringify({ bundle: { createUpdaterArtifacts: false } }));
}
if (platform === 'cef' && cmd === 'build' && !tauriArgs.includes('--no-bundle')) {
args.splice(1, 0, '--no-bundle');
}
+21 -32
View File
@@ -168,7 +168,7 @@ version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -179,7 +179,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -1011,7 +1011,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "117725a109d387c937a1533ce01b450cbde6b88abceea8473c4d7a85853cda3c"
dependencies = [
"lazy_static",
"windows-sys 0.59.0",
"windows-sys 0.48.0",
]
[[package]]
@@ -1553,7 +1553,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -1855,7 +1855,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -2822,12 +2822,12 @@ dependencies = [
"libc",
"percent-encoding",
"pin-project-lite",
"socket2 0.6.5",
"socket2 0.5.10",
"system-configuration",
"tokio",
"tower-service",
"tracing",
"windows-registry 0.6.1",
"windows-registry",
]
[[package]]
@@ -3652,7 +3652,7 @@ dependencies = [
"png 0.18.1",
"serde",
"thiserror 2.0.19",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -3776,7 +3776,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -4180,7 +4180,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.48.0",
]
[[package]]
@@ -4798,7 +4798,7 @@ dependencies = [
"quinn-udp",
"rustc-hash",
"rustls",
"socket2 0.6.5",
"socket2 0.5.10",
"thiserror 2.0.19",
"tokio",
"tracing",
@@ -4836,9 +4836,9 @@ dependencies = [
"cfg_aliases",
"libc",
"once_cell",
"socket2 0.6.5",
"socket2 0.5.10",
"tracing",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -5257,7 +5257,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -5315,7 +5315,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -6007,7 +6007,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -6563,7 +6563,7 @@ dependencies = [
"thiserror 2.0.19",
"tracing",
"url",
"windows-registry 0.5.3",
"windows-registry",
"windows-result 0.3.4",
]
@@ -7064,7 +7064,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -7689,7 +7689,7 @@ dependencies = [
"png 0.18.1",
"serde",
"thiserror 2.0.19",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -7763,7 +7763,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [
"memoffset",
"tempfile",
"windows-sys 0.61.2",
"windows-sys 0.60.2",
]
[[package]]
@@ -8393,7 +8393,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
"windows-sys 0.48.0",
]
[[package]]
@@ -8531,17 +8531,6 @@ dependencies = [
"windows-strings 0.4.2",
]
[[package]]
name = "windows-registry"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
dependencies = [
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
]
[[package]]
name = "windows-result"
version = "0.3.4"
+4 -1
View File
@@ -37,6 +37,9 @@ aes = "0.8"
ctr = "0.9"
infer = { version = "0.22", default-features = false }
percent-encoding = "2"
# Enables `stream` (for native_upload's `Body::wrap_stream`) on the reqwest that
# tauri-plugin-http pulls in without it. default-features = false keeps
# openssl-sys out of the Android cross-compile.
reqwest = { version = "0.12", default-features = false, features = ["stream"] }
async-stream = "0.3"
base64 = "0.22"
@@ -58,7 +61,7 @@ tauri-plugin-opener = "2.5.4"
tauri-plugin-os = "2"
tauri-plugin-deep-link = "2.4.9"
tauri-plugin-http = "2.5.9"
tauri-plugin-store = "2.4.3"
tauri-plugin-store = "2.4.4"
tauri-plugin-clipboard-manager = "2.3.2"
# Debug-only in practice: only initialized under #[cfg(debug_assertions)] in
+1 -1
View File
@@ -2,7 +2,7 @@
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "enables the default permissions",
"windows": ["*"],
"windows": ["main"],
"permissions": [
"core:default",
"core:window:allow-close",
-1
View File
@@ -9,7 +9,6 @@
"store:default",
"notifications:default",
"process:default",
"updater:default",
"dialog:default"
]
}
-1
View File
@@ -4,7 +4,6 @@
"platforms": ["android", "iOS"],
"windows": ["main"],
"permissions": [
"core:default",
"core:window:allow-set-badge-count",
"deep-link:default",
"edge-to-edge:default",
-1
View File
@@ -333,7 +333,6 @@ pub fn run() {
let _ = show_or_create_main_window(app);
}));
#[cfg(any(mobile, desktop))]
let builder = builder.plugin(tauri_plugin_notifications::init());
#[cfg(all(desktop, feature = "updater"))]
+41 -2
View File
@@ -7,7 +7,7 @@ use std::{
use serde::{Deserialize, Serialize};
use tauri_plugin_http::reqwest::{
header::{HeaderMap, HeaderName, HeaderValue},
Client, ClientBuilder, Method, Url,
redirect, Client, ClientBuilder, Method, Url,
};
use tokio::sync::watch;
@@ -17,6 +17,8 @@ static LOOPBACK_ABORT_SENDERS: LazyLock<Mutex<HashMap<String, watch::Sender<bool
static LOOPBACK_CLIENT: LazyLock<Client> = LazyLock::new(|| {
ClientBuilder::new()
.no_proxy()
// A followed 302 would escape validate_loopback_url.
.redirect(redirect::Policy::none())
.timeout(Duration::from_secs(30))
.connect_timeout(Duration::from_secs(10))
.build()
@@ -162,9 +164,27 @@ pub async fn loopback_fetch(
#[cfg(test)]
mod tests {
use super::{abort_loopback_fetch, register_abort_sender, validate_loopback_url};
use super::{
abort_loopback_fetch, loopback_fetch, register_abort_sender, validate_loopback_url,
LoopbackFetchRequest,
};
use std::io::{Read, Write};
use tokio::time::{timeout, Duration};
/// One-shot loopback server that answers with `response`, then closes.
fn spawn_once(response: &'static str) -> String {
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind loopback listener");
let port = listener.local_addr().expect("listener addr").port();
std::thread::spawn(move || {
if let Ok((mut stream, _)) = listener.accept() {
let mut buf = [0_u8; 1024];
let _ = stream.read(&mut buf);
let _ = stream.write_all(response.as_bytes());
}
});
format!("http://127.0.0.1:{port}/")
}
#[test]
fn allows_loopback_http_hosts() {
assert!(validate_loopback_url("http://localhost:8008").is_ok());
@@ -184,6 +204,25 @@ mod tests {
assert!(validate_loopback_url("http://localhost:[email protected]").is_err());
}
#[test]
fn does_not_follow_redirects_off_loopback() {
let url = spawn_once(
"HTTP/1.1 302 Found\r\nLocation: http://example.org/\r\nContent-Length: 0\r\n\r\n",
);
let response = tauri::async_runtime::block_on(loopback_fetch(LoopbackFetchRequest {
request_id: "redirect-1".into(),
method: "GET".into(),
url,
headers: Vec::new(),
body: None,
}))
.expect("loopback_fetch failed");
assert_eq!(response.status, 302);
assert!(response.body.is_empty());
}
#[test]
fn abort_command_signals_registered_requests() {
tauri::async_runtime::block_on(async {
+83 -23
View File
@@ -296,6 +296,29 @@ fn normalize_encryption_key(url: &str) -> String {
.unwrap_or_else(|_| url.to_string())
}
/// The app's own webview origins, which vary by platform and scheme.
fn is_webview_origin(origin: &str) -> bool {
matches!(
origin,
"tauri://localhost" | "http://tauri.localhost" | "https://tauri.localhost"
) || (cfg!(debug_assertions) && origin.starts_with("http://localhost:"))
}
/// Grants CORS only to our own webview. A request with no `Origin` (an `<img>`
/// load) is not a CORS request and needs no grant.
fn apply_cors_headers(response: &mut Response<Vec<u8>>, request_origin: Option<&str>) {
let Some(origin) = request_origin.filter(|origin| is_webview_origin(origin)) else {
return;
};
let Ok(value) = header::HeaderValue::from_str(origin) else {
return;
};
let headers = response.headers_mut();
headers.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, value);
// Responses are cached `immutable`, so the cache must key on Origin too.
headers.insert(header::VARY, header::HeaderValue::from_static("Origin"));
}
pub fn respond<R: Runtime>(
ctx: UriSchemeContext<'_, R>,
request: Request<Vec<u8>>,
@@ -303,15 +326,20 @@ pub fn respond<R: Runtime>(
) {
let app = ctx.app_handle().clone();
let uri = request.uri().clone();
let range = request
.headers()
.get(header::RANGE)
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let header_value = |name: header::HeaderName| {
request
.headers()
.get(name)
.and_then(|value| value.to_str().ok())
.map(str::to_owned)
};
let range = header_value(header::RANGE);
let origin = header_value(header::ORIGIN);
tauri::async_runtime::spawn(async move {
let response = handle_request(&app, uri, range)
let mut response = handle_request(&app, uri, range)
.await
.unwrap_or_else(error_response);
apply_cors_headers(&mut response, origin.as_deref());
responder.respond(response);
});
}
@@ -849,11 +877,6 @@ async fn write_cache(
.unwrap_or(false)
}
#[allow(dead_code)]
fn fits_in_cache(len: u64) -> bool {
len <= MAX_CACHE_BYTES
}
// Only a hit when the body file is also present, so a stray `.ct` counts as a miss.
async fn read_content_type(body_path: PathBuf, content_type_path: PathBuf) -> Option<String> {
tokio::task::spawn_blocking(move || {
@@ -1021,7 +1044,6 @@ fn media_response_builder(status: StatusCode, content_type: &str) -> ResponseBui
Response::builder()
.status(status)
.header(header::CONTENT_TYPE, content_type)
.header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
.header(header::ACCEPT_RANGES, "bytes")
.header(header::CACHE_CONTROL, cache_control)
.header(header::X_CONTENT_TYPE_OPTIONS, "nosniff")
@@ -1060,7 +1082,6 @@ fn partial_response(
fn range_not_satisfiable(total: u64) -> Response<Vec<u8>> {
Response::builder()
.status(StatusCode::RANGE_NOT_SATISFIABLE)
.header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
.header(header::CONTENT_RANGE, format!("bytes */{total}"))
.body(Vec::new())
.expect("failed to build range error response")
@@ -1070,7 +1091,6 @@ fn session_unavailable_response() -> Response<Vec<u8>> {
Response::builder()
.status(StatusCode::SERVICE_UNAVAILABLE)
.header(header::RETRY_AFTER, "1")
.header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
.body(Vec::new())
.expect("failed to build 503 media response")
}
@@ -1078,7 +1098,6 @@ fn session_unavailable_response() -> Response<Vec<u8>> {
fn error_response(status: StatusCode) -> Response<Vec<u8>> {
Response::builder()
.status(status)
.header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
.body(Vec::new())
.expect("failed to build media error response")
}
@@ -1113,7 +1132,7 @@ mod tests {
use tauri::http::{header, StatusCode};
use super::{
cache_key, fits_in_cache, ok_response, parse_range, partial_response, serve_range_memory,
cache_key, ok_response, parse_range, partial_response, serve_range_memory,
MediaSessionState,
};
@@ -1268,13 +1287,6 @@ mod tests {
);
}
#[test]
fn oversized_media_is_not_cacheable() {
assert!(fits_in_cache(0));
assert!(fits_in_cache(super::MAX_CACHE_BYTES));
assert!(!fits_in_cache(super::MAX_CACHE_BYTES + 1));
}
#[test]
fn serve_range_memory_slices_the_in_memory_body() {
let body: Vec<u8> = (0..200u8).collect();
@@ -1377,6 +1389,54 @@ mod tests {
);
}
#[test]
fn cors_is_granted_only_to_the_apps_own_webview_origins() {
for origin in [
"tauri://localhost",
"http://tauri.localhost",
"https://tauri.localhost",
] {
let mut response = ok_response(vec![0_u8; 4], "image/png");
super::apply_cors_headers(&mut response, Some(origin));
assert_eq!(
response
.headers()
.get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
.unwrap(),
origin,
"{origin} should be granted CORS"
);
assert_eq!(response.headers().get(header::VARY).unwrap(), "Origin");
}
}
#[test]
fn cors_is_denied_to_foreign_origins() {
for origin in [
"https://evil.example.org",
"https://tauri.localhost.evil.example.org",
"null",
] {
let mut response = ok_response(vec![0_u8; 4], "image/png");
super::apply_cors_headers(&mut response, Some(origin));
assert!(
!response
.headers()
.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN),
"{origin} must not be granted CORS"
);
}
}
#[test]
fn requests_without_an_origin_get_no_cors_header() {
let mut response = ok_response(vec![0_u8; 4], "image/png");
super::apply_cors_headers(&mut response, None);
assert!(!response
.headers()
.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN));
}
#[test]
fn image_response_is_cached_immutable() {
let response = super::media_response_builder(StatusCode::OK, "image/png")
+5 -1
View File
@@ -102,6 +102,8 @@ async fn wait_for_abort_signal(receiver: &mut watch::Receiver<bool>) {
std::future::pending::<()>().await;
}
/// Base64 rather than raw bytes because Android has no `InvokeBody::Raw`: a
/// `Uint8Array` degrades to a JSON `number[]` there and OOM-kills the renderer.
#[tauri::command]
pub async fn upload_write_chunk<R: Runtime>(
app: AppHandle<R>,
@@ -180,6 +182,9 @@ async fn run_upload(
return Err("native_upload only allows http(s) URLs".into());
}
// Registered before any awaiting work so an abort arriving during setup is not missed.
let mut abort_receiver = register_abort_sender(request_id);
let file = File::open(path)
.await
.map_err(|_| "no upload data for this request".to_string())?;
@@ -213,7 +218,6 @@ async fn run_upload(
builder = builder.header(AUTHORIZATION, auth);
}
let mut abort_receiver = register_abort_sender(request_id);
let response = tokio::select! {
response = builder.send() => response.map_err(|err| err.to_string())?,
_ = wait_for_abort_signal(&mut abort_receiver) => return Err("Upload aborted".into()),
+1 -1
View File
@@ -12,7 +12,7 @@
"app": {
"windows": [],
"security": {
"csp": "default-src 'self' blob: data: filesystem: ws: wss: http: https: tauri:; script-src 'self' 'unsafe-eval' 'unsafe-inline' blob: data: filesystem: ws: wss: tauri:; style-src 'self' 'unsafe-inline' blob: data: filesystem: http: https: tauri:; img-src 'self' data: blob: filesystem: http: https: sable-media:; media-src 'self' blob: data: http: https: sable-media:; connect-src 'self' ipc: ws: wss: http: https: http://ipc.localhost sable-media: http://sable-media.localhost"
"csp": "default-src 'self' blob: data: filesystem: tauri:; script-src 'self' 'wasm-unsafe-eval' 'unsafe-inline' filesystem: tauri:; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' blob: data: filesystem: http: https: tauri:; font-src 'self' blob: data: filesystem: http: https:; img-src 'self' data: blob: filesystem: http: https: sable-media:; media-src 'self' blob: data: http: https: sable-media:; frame-src 'self' blob: http: https: tauri:; connect-src 'self' ipc: ws: wss: http: https: http://ipc.localhost sable-media: http://sable-media.localhost; object-src 'none'; base-uri 'self'; form-action 'self'"
}
},
"bundle": {