Skip to content

Commit a7ea86c

Browse files
jmecomelifoster-blockclaude
authored
fix(desktop): enable the content security policy (#4614)
This change enables a Tauri content security policy that limits executable content to the packaged application and does not allow inline scripts. Relay, media, asset, and Tauri IPC schemes remain available for desktop compatibility. The policy contains the impact of a future renderer injection; it does not itself remove an injection bug. ## Testing - `git diff --check origin/main...codex/security-desktop-csp` - Rebased onto `origin/main` at `5c98932` - Full CI pending Originating Buzz thread: `buzz://message?channel=3928fe05-df61-4b5d-b9c7-d623b9b10ea1&id=3c6c02312f763fbe0d2bfc33a6c1a362f91d0354f3d18b039cf7a0558c1439d1` --------- Signed-off-by: Jordan Mecom <[email protected]> Signed-off-by: Eli Foster <[email protected]> Co-authored-by: Eli Foster <[email protected]> Co-authored-by: Claude Opus 5 <[email protected]>
1 parent 06b60e6 commit a7ea86c

3 files changed

Lines changed: 206 additions & 2 deletions

File tree

‎desktop/src-tauri/tauri.conf.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
],
3737
"macOSPrivateApi": true,
3838
"security": {
39-
"csp": null
39+
"csp": "default-src 'self'; base-uri 'self'; form-action 'none'; frame-ancestors 'none'; object-src 'none'; script-src 'self' 'wasm-unsafe-eval' https://cdn.jsdelivr.net/npm/@mediapipe/; style-src 'self' 'unsafe-inline'; font-src 'self' data:; connect-src 'self' ipc: http://ipc.localhost buzz-media: http://buzz-media.localhost https: http: wss: ws:; img-src 'self' buzz-media: http://buzz-media.localhost data: blob: https: http:; media-src 'self' buzz-media: http://buzz-media.localhost data: blob: https: http:; worker-src 'self' blob:"
4040
}
4141
},
4242
"plugins": {

‎desktop/src-tauri/tests/csp.rs‎

Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
//! Guards on the packaged-app Content-Security-Policy in `tauri.conf.json`.
2+
//!
3+
//! The CSP is only enforced on assets Tauri itself serves, so neither
4+
//! `just dev` (loads the Vite `devUrl`) nor the Playwright suite (runs under
5+
//! `vite preview`) can catch a policy that breaks the app. These tests pin the
6+
//! non-obvious sources the frontend actually needs, so a future tightening
7+
//! fails here instead of in a signed build.
8+
//!
9+
//! Kept as an integration test so the policy can be checked without the app
10+
//! crate having to declare a test-only module.
11+
12+
use std::collections::HashMap;
13+
14+
const TAURI_CONF: &str = include_str!("../tauri.conf.json");
15+
16+
fn csp_directives() -> HashMap<String, Vec<String>> {
17+
let conf: serde_json::Value =
18+
serde_json::from_str(TAURI_CONF).expect("tauri.conf.json is valid JSON");
19+
let csp = conf["app"]["security"]["csp"]
20+
.as_str()
21+
.expect("app.security.csp is set as a policy string");
22+
23+
csp.split(';')
24+
.filter_map(|directive| {
25+
let mut parts = directive.split_whitespace();
26+
let name = parts.next()?;
27+
Some((name.to_owned(), parts.map(str::to_owned).collect()))
28+
})
29+
.collect()
30+
}
31+
32+
fn sources(directive: &str) -> Vec<String> {
33+
csp_directives()
34+
.remove(directive)
35+
.unwrap_or_else(|| panic!("csp is missing the {directive} directive"))
36+
}
37+
38+
#[test]
39+
fn script_src_allows_wasm_instantiation() {
40+
// Shiki's default engine (Oniguruma) instantiates inlined WebAssembly for
41+
// every code block; MediaPipe selfie segmentation does the same. Without
42+
// this token both silently degrade — highlighting drops to plain text and
43+
// animated avatars keep their background.
44+
assert!(sources("script-src").contains(&"'wasm-unsafe-eval'".to_owned()));
45+
}
46+
47+
/// The `MEDIAPIPE_WASM_BASE` literal the frontend hands to `FilesetResolver`.
48+
fn mediapipe_wasm_base() -> String {
49+
const CAPTURE: &str = include_str!("../../src/features/profile/lib/animatedAvatarCapture.ts");
50+
51+
let after = CAPTURE
52+
.split_once("const MEDIAPIPE_WASM_BASE =")
53+
.expect("animatedAvatarCapture.ts declares MEDIAPIPE_WASM_BASE")
54+
.1;
55+
let url = after
56+
.split_once('"')
57+
.expect("MEDIAPIPE_WASM_BASE is a double-quoted string literal")
58+
.1;
59+
url.split_once('"')
60+
.expect("MEDIAPIPE_WASM_BASE literal is terminated")
61+
.0
62+
.to_owned()
63+
}
64+
65+
/// The npm scope the MediaPipe loader must come from. A CSP source ending in
66+
/// `/` is a path *prefix* — paths can't be wildcarded — so this admits any
67+
/// `@mediapipe` package while excluding the rest of what jsDelivr serves.
68+
const MEDIAPIPE_SCOPE: &str = "https://cdn.jsdelivr.net/npm/@mediapipe/";
69+
70+
#[test]
71+
fn script_src_scopes_the_mediapipe_loader() {
72+
// `FilesetResolver.forVisionTasks` loads `vision_wasm[_nosimd]_internal.js`
73+
// via a `<script>` tag (which of the two depends on a runtime SIMD probe),
74+
// so the loader URL the frontend builds has to fall inside the allowlisted
75+
// prefix — checked here rather than discovered in a signed build.
76+
let allowed = sources("script-src");
77+
assert!(
78+
allowed.contains(&MEDIAPIPE_SCOPE.to_owned()),
79+
"script-src must allow {MEDIAPIPE_SCOPE}"
80+
);
81+
82+
let base = mediapipe_wasm_base();
83+
assert!(
84+
base.starts_with(MEDIAPIPE_SCOPE),
85+
"MEDIAPIPE_WASM_BASE ({base}) must sit under the allowlisted {MEDIAPIPE_SCOPE}"
86+
);
87+
}
88+
89+
/// How many path segments a source narrows to past its origin.
90+
fn path_depth(source: &str) -> usize {
91+
let Some((_scheme, authority)) = source.split_once("://") else {
92+
return 0;
93+
};
94+
match authority.split_once('/') {
95+
Some((_host, path)) => path.split('/').filter(|part| !part.is_empty()).count(),
96+
None => 0,
97+
}
98+
}
99+
100+
/// Whether a `script-src` source is narrow enough to be worth allowing. CSP
101+
/// keywords (`'self'`, `'wasm-unsafe-eval'`) pass. A remote source must name a
102+
/// non-wildcard host *and* a path reaching at least a publisher scope — a bare
103+
/// origin, a scheme, or a registry root would put arbitrary third-party code
104+
/// one injected `<script>` away.
105+
fn is_pinned_script_source(source: &str) -> bool {
106+
if source.starts_with('\'') {
107+
return true;
108+
}
109+
!source.contains('*') && path_depth(source) >= 2
110+
}
111+
112+
#[test]
113+
fn script_src_trusts_no_bare_origins() {
114+
for source in sources("script-src") {
115+
assert!(
116+
is_pinned_script_source(&source),
117+
"script-src must stay scoped, found broad source `{source}`"
118+
);
119+
}
120+
}
121+
122+
#[test]
123+
fn pinned_script_source_rejects_broad_sources() {
124+
// Guards the guard: the check above is only worth having if it fails on the
125+
// shapes that reopen the allowlist.
126+
for allowed in [
127+
"'self'",
128+
"'wasm-unsafe-eval'",
129+
MEDIAPIPE_SCOPE,
130+
"https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm/vision_wasm_internal.js",
131+
] {
132+
assert!(is_pinned_script_source(allowed), "{allowed} should pass");
133+
}
134+
for rejected in [
135+
"https://cdn.jsdelivr.net",
136+
"https://cdn.jsdelivr.net/",
137+
"https://cdn.jsdelivr.net/npm/",
138+
"https://cdn.jsdelivr.net/gh/",
139+
"https://*.jsdelivr.net/npm/@mediapipe/",
140+
"https:",
141+
"*",
142+
] {
143+
assert!(
144+
!is_pinned_script_source(rejected),
145+
"{rejected} should be rejected"
146+
);
147+
}
148+
}
149+
150+
#[test]
151+
fn media_directives_allow_the_buzz_media_scheme() {
152+
// `rewriteRelayUrl` emits `buzz-media://localhost/...` until the loopback
153+
// proxy port resolves, so cold-start media renders through the custom
154+
// scheme (mapped to `http://buzz-media.localhost` on Windows).
155+
for directive in ["img-src", "media-src", "connect-src"] {
156+
let allowed = sources(directive);
157+
assert!(
158+
allowed.contains(&"buzz-media:".to_owned()),
159+
"{directive} must allow buzz-media:"
160+
);
161+
assert!(
162+
allowed.contains(&"http://buzz-media.localhost".to_owned()),
163+
"{directive} must allow http://buzz-media.localhost"
164+
);
165+
}
166+
}
167+
168+
#[test]
169+
fn connect_src_allows_ipc_and_cleartext_relays() {
170+
// `ipc:` / `http://ipc.localhost` carry every Tauri command. Cleartext
171+
// `http:`/`ws:` stay allowed because a relay URL is user-supplied and the
172+
// app accepts plain `ws://` on any host (`communityStorage::normalizeRelayUrl`,
173+
// the community edit form): `relayProbe` opens a browser WebSocket to it,
174+
// so narrowing this to loopback would report reachable relays as dead —
175+
// while the real connection, which runs through tauri-plugin-websocket in
176+
// Rust, is not governed by CSP at all. Blanket `https:` is already allowed,
177+
// so restricting the cleartext schemes would close no exfiltration path.
178+
let allowed = sources("connect-src");
179+
for source in [
180+
"ipc:",
181+
"http://ipc.localhost",
182+
"https:",
183+
"http:",
184+
"wss:",
185+
"ws:",
186+
] {
187+
assert!(
188+
allowed.contains(&source.to_owned()),
189+
"connect-src must allow {source}"
190+
);
191+
}
192+
}
193+
194+
#[test]
195+
fn script_src_stays_free_of_unsafe_inline_and_eval() {
196+
let allowed = sources("script-src");
197+
// The inline boot script in index.html is covered by Tauri's build-time
198+
// sha256 hashing, so neither escape hatch is ever needed here.
199+
assert!(!allowed.contains(&"'unsafe-inline'".to_owned()));
200+
assert!(!allowed.contains(&"'unsafe-eval'".to_owned()));
201+
}

‎desktop/src/features/profile/lib/animatedAvatarCapture.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,10 @@ const PERSON_OUTLINE_OFFSETS = [
106106
] as const;
107107

108108
// Pinned to the installed @mediapipe/tasks-vision version so the wasm loader
109-
// always matches the JS API.
109+
// always matches the JS API. `script-src` in tauri.conf.json allowlists the
110+
// jsDelivr path prefix for the @mediapipe npm scope rather than the whole
111+
// origin, which also serves arbitrary npm and GitHub scripts; this URL must
112+
// stay under that prefix — `src-tauri/tests/csp.rs` checks that it does.
110113
const MEDIAPIPE_WASM_BASE =
111114
"https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm";
112115
const SELFIE_SEGMENTER_MODEL_URL =

0 commit comments

Comments
 (0)