Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(app): guard local control server against browser abuse (#5520)

Divanshu8ba17ae0eff6
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
index 437654b05..4cfb9c009 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -11166,6 +11166,7 @@ dependencies = [
"tikv-jemallocator",
"tokio",
"tokio-tungstenite",
+ "tower 0.4.13",
"tower-http 0.4.4",
"tracing",
"tracing-appender",
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index 9315a0a12..47e18be5e 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -305,6 +305,7 @@ jemalloc = ["tikv-jemallocator"]
tempfile = "3"
wiremock = "0.6"
serial_test = "3"
+tower = { version = "0.4", features = ["util"] }
# MockRuntime for store.rs recovery tests that must exercise the real
# tauri-plugin-store registry (state + resources table).
tauri = { version = "=2.11.2", features = ["test"] }
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/server.rs b/apps/screenpipe-app-tauri/src-tauri/src/server.rs
index 813915e98..39ad21d3d 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/server.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/server.rs
@@ -12,7 +12,7 @@ use axum::{
http::{Method, StatusCode},
Json, Router,
};
-use http::header::{HeaderValue, CONTENT_TYPE};
+use http::header::{HeaderValue, CONTENT_TYPE, HOST, ORIGIN};
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
use tauri::Emitter;
@@ -231,15 +231,131 @@ async fn kill_process_on_port(port: u16) {
}
}
-pub async fn run_server(app_handle: tauri::AppHandle, port: u16) {
- let state = ServerState { app_handle };
+/// Loopback hostnames the control server treats as first-party. A `127.0.0.1`
+/// bind is reachable by any website the user visits and by any local process,
+/// so the only trustworthy `Origin`/`Host` values are these.
+fn is_local_hostname(host: &str) -> bool {
+ matches!(host, "localhost" | "127.0.0.1" | "::1" | "tauri.localhost")
+}
+
+/// Whether an `Origin` header names a local origin. Mirrors the engine
+/// server's `is_allowed_local_origin`. A browser cannot forge or omit `Origin`
+/// on a cross-origin request, so rejecting foreign origins blocks a malicious
+/// web page from POSTing to a state-changing local endpoint.
+fn is_allowed_local_origin(origin: &HeaderValue) -> bool {
+ let Ok(origin) = origin.to_str() else {
+ return false;
+ };
+ let Ok(uri) = origin.parse::<axum::http::Uri>() else {
+ return false;
+ };
+ match uri.host() {
+ Some(host) => is_local_hostname(host),
+ None => false,
+ }
+}
+
+/// The browser bridge intentionally calls `/focus` from its extension page so
+/// the user can approve pairing in the desktop app. Extension origins cannot
+/// be sent by an ordinary website, and this exception is limited to the focus
+/// route; sensitive endpoints such as `/auth` remain local-origin only.
+fn is_allowed_browser_extension_origin(origin: &HeaderValue) -> bool {
+ let Ok(origin) = origin.to_str() else {
+ return false;
+ };
+ let Ok(uri) = origin.parse::<axum::http::Uri>() else {
+ return false;
+ };
+
+ matches!(
+ uri.scheme_str(),
+ Some("chrome-extension") | Some("moz-extension")
+ ) && uri.host().is_some()
+}
+
+fn is_allowed_control_origin(path: &str, origin: &HeaderValue) -> bool {
+ is_allowed_local_origin(origin)
+ || (path == "/focus" && is_allowed_browser_extension_origin(origin))
+}
+
+/// Whether a `Host` header points at loopback. Defeats DNS rebinding, where a
+/// browser is tricked into resolving an attacker domain to `127.0.0.1` while
+/// keeping the attacker's `Host`. curl, pipes, and the webview all send a
+/// loopback `Host`.
+fn is_allowed_local_host(host: &HeaderValue) -> bool {
+ let Ok(raw) = host.to_str() else {
+ return false;
+ };
+ let raw = raw.trim();
+ let host = if let Some(rest) = raw.strip_prefix('[') {
+ // IPv6 literal, e.g. [::1] or [::1]:11435
+ match rest.split_once(']') {
+ Some((inner, _)) => inner,
+ None => return false,
+ }
+ } else {
+ // hostname or IPv4, optionally with :port
+ raw.split(':').next().unwrap_or(raw)
+ };
+ is_local_hostname(host)
+}
+
+/// Origin-validation guard for every control-server endpoint.
+/// Rejects any request carrying a non-local `Origin` (malicious web page) or a
+/// non-local `Host` (DNS rebinding). The one scoped exception is `/focus` from
+/// a browser-extension origin, which preserves the existing pairing flow.
+/// Requests with neither header — a local process using curl, a pipe, an agent
+/// — still pass: loopback bind is not an authorization boundary, so a same-user
+/// process can reach this regardless. Closing that residual requires a
+/// capability token handed to first-party callers (tracked as a follow-up);
+/// the token must not be dropped later just because "it's localhost".
+async fn control_server_origin_guard<B>(
+ req: axum::http::Request<B>,
+ next: axum::middleware::Next<B>,
+) -> axum::response::Response {
+ let headers = req.headers();
+ if let Some(origin) = headers.get(ORIGIN) {
+ if !is_allowed_control_origin(req.uri().path(), origin) {
+ tracing::warn!(
+ path = %req.uri().path(),
+ ?origin,
+ "control server rejected non-local Origin"
+ );
+ return StatusCode::FORBIDDEN.into_response();
+ }
+ }
+ if let Some(host) = headers.get(HOST) {
+ if !is_allowed_local_host(host) {
+ tracing::warn!(
+ path = %req.uri().path(),
+ ?host,
+ "control server rejected non-local Host"
+ );
+ return StatusCode::FORBIDDEN.into_response();
+ }
+ }
+ next.run(req).await
+}
+fn with_control_server_boundary<S>(app: Router<S>) -> Router<S>
+where
+ S: Clone + Send + Sync + 'static,
+{
let cors = CorsLayer::new()
.allow_origin("*".parse::<HeaderValue>().unwrap())
.allow_methods([Method::GET, Method::POST, Method::DELETE, Method::OPTIONS])
.allow_headers(Any)
.allow_credentials(false);
+ // Keep the Origin/Host guard outside CORS so foreign preflights are rejected
+ // before the permissive compatibility layer can short-circuit the request.
+ app.layer(cors)
+ .layer(axum::middleware::from_fn(control_server_origin_guard))
+}
+
+pub async fn run_server(app_handle: tauri::AppHandle, port: u16) {
+ let state = ServerState { app_handle };
+
let app = Router::new()
.route(
"/notify",
@@ -268,8 +384,9 @@ pub async fn run_server(app_handle: tauri::AppHandle, port: u16) {
axum::routing::get(list_installed_apps_handler),
)
.route("/window-size", axum::routing::post(set_window_size))
- .route("/focus", axum::routing::post(handle_focus))
- .layer(cors)
+ .route("/focus", axum::routing::post(handle_focus));
+
+ let app = with_control_server_boundary(app)
.layer(
TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().level(tracing::Level::INFO))
@@ -614,3 +731,226 @@ curl -X POST http://localhost:11435/notify \
}'
*/
+
+#[cfg(test)]
+mod tests {
+ use super::{
+ is_allowed_browser_extension_origin, is_allowed_local_host, is_allowed_local_origin,
+ with_control_server_boundary,
+ };
+ use axum::{
+ body::Body,
+ http::{Method, Request, StatusCode},
+ routing::post,
+ Router,
+ };
+ use http::header::{HeaderValue, ACCESS_CONTROL_REQUEST_METHOD, HOST, ORIGIN};
+ use tower::ServiceExt;
+
+ fn origin(v: &str) -> HeaderValue {
+ HeaderValue::from_str(v).unwrap()
+ }
+
+ #[test]
+ fn accepts_local_origins() {
+ for o in [
+ "http://localhost",
+ "http://localhost:3000",
+ "https://localhost",
+ "http://127.0.0.1",
+ "http://127.0.0.1:11435",
+ "tauri://localhost",
+ "http://tauri.localhost",
+ "https://tauri.localhost",
+ ] {
+ assert!(is_allowed_local_origin(&origin(o)), "should accept {o}");
+ }
+ }
+
+ #[test]
+ fn rejects_foreign_origins() {
+ for o in [
+ "https://evil.com",
+ "http://attacker.example",
+ "https://localhost.evil.com",
+ "https://127.0.0.1.evil.com",
+ "null",
+ ] {
+ assert!(!is_allowed_local_origin(&origin(o)), "should reject {o}");
+ }
+ }
+
+ #[test]
+ fn accepts_only_browser_extension_schemes_as_extension_origins() {
+ for o in [
+ "chrome-extension://abcdefghijklmnop",
+ "moz-extension://01234567-89ab-cdef-0123-456789abcdef",
+ ] {
+ assert!(
+ is_allowed_browser_extension_origin(&origin(o)),
+ "should accept {o}"
+ );
+ }
+ for o in ["https://evil.com", "file://extension.html", "null"] {
+ assert!(
+ !is_allowed_browser_extension_origin(&origin(o)),
+ "should reject {o}"
+ );
+ }
+ }
+
+ #[test]
+ fn accepts_local_hosts() {
+ for h in [
+ "localhost",
+ "localhost:11435",
+ "127.0.0.1",
+ "127.0.0.1:11435",
+ "[::1]",
+ "[::1]:11435",
+ "tauri.localhost",
+ ] {
+ assert!(is_allowed_local_host(&origin(h)), "should accept {h}");
+ }
+ }
+
+ #[test]
+ fn rejects_rebinding_hosts() {
+ // DNS rebinding keeps the attacker's Host while the IP resolves to
+ // loopback — reject anything that is not a loopback name.
+ for h in ["evil.com", "evil.com:11435", "attacker.example"] {
+ assert!(!is_allowed_local_host(&origin(h)), "should reject {h}");
+ }
+ }
+
+ fn guarded_router() -> Router {
+ with_control_server_boundary(
+ Router::new()
+ .route("/auth", post(|| async { StatusCode::NO_CONTENT }))
+ .route("/focus", post(|| async { StatusCode::NO_CONTENT })),
+ )
+ }
+
+ fn guarded_request(
+ method: Method,
+ path: &str,
+ origin: Option<&str>,
+ host: Option<&str>,
+ ) -> Request<Body> {
+ let mut request = Request::builder().method(method).uri(path);
+ if let Some(origin) = origin {
+ request = request.header(ORIGIN, origin);
+ }
+ if let Some(host) = host {
+ request = request.header(HOST, host);
+ }
+ request.body(Body::empty()).unwrap()
+ }
+
+ #[tokio::test]
+ async fn rejects_foreign_origin_on_non_notify_route() {
+ let response = guarded_router()
+ .oneshot(guarded_request(
+ Method::POST,
+ "/auth",
+ Some("https://evil.com"),
+ Some("localhost:11435"),
+ ))
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ }
+
+ #[tokio::test]
+ async fn rejects_rebinding_host_on_non_notify_route() {
+ let response = guarded_router()
+ .oneshot(guarded_request(
+ Method::POST,
+ "/auth",
+ None,
+ Some("evil.com:11435"),
+ ))
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ }
+
+ #[tokio::test]
+ async fn accepts_local_and_headerless_clients_on_non_notify_route() {
+ for request in [
+ guarded_request(
+ Method::POST,
+ "/auth",
+ Some("http://localhost:3000"),
+ Some("localhost:11435"),
+ ),
+ guarded_request(Method::POST, "/auth", None, Some("127.0.0.1:11435")),
+ guarded_request(Method::POST, "/auth", None, None),
+ ] {
+ let response = guarded_router().oneshot(request).await.unwrap();
+ assert_eq!(response.status(), StatusCode::NO_CONTENT);
+ }
+ }
+
+ #[tokio::test]
+ async fn allows_browser_extension_origin_only_on_focus_route() {
+ let extension_origin = Some("chrome-extension://abcdefghijklmnop");
+ let host = Some("127.0.0.1:11435");
+
+ let focus_response = guarded_router()
+ .oneshot(guarded_request(
+ Method::POST,
+ "/focus",
+ extension_origin,
+ host,
+ ))
+ .await
+ .unwrap();
+ assert_eq!(focus_response.status(), StatusCode::NO_CONTENT);
+
+ let auth_response = guarded_router()
+ .oneshot(guarded_request(
+ Method::POST,
+ "/auth",
+ extension_origin,
+ host,
+ ))
+ .await
+ .unwrap();
+ assert_eq!(auth_response.status(), StatusCode::FORBIDDEN);
+ }
+
+ #[tokio::test]
+ async fn rejects_web_origin_on_focus_route() {
+ let response = guarded_router()
+ .oneshot(guarded_request(
+ Method::POST,
+ "/focus",
+ Some("https://evil.com"),
+ Some("127.0.0.1:11435"),
+ ))
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ }
+
+ #[tokio::test]
+ async fn rejects_foreign_cors_preflight_before_it_reaches_cors() {
+ let mut request = guarded_request(
+ Method::OPTIONS,
+ "/auth",
+ Some("https://evil.com"),
+ Some("localhost:11435"),
+ );
+ request.headers_mut().insert(
+ ACCESS_CONTROL_REQUEST_METHOD,
+ HeaderValue::from_static("POST"),
+ );
+
+ let response = guarded_router().oneshot(request).await.unwrap();
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ }
+}