Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
245 changes: 243 additions & 2 deletions desktop/src-tauri/src/connected/relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@ What keeps it to that:
the relay's own page is same-site, and carries it. That page has no script and no secret in it,
sends no referrer (the address it was opened at holds the secret), and replaces itself in the
window's history.
- A page load it refuses (a navigation of a window, not a request a page makes) is kept, by its path,
until the window enters again or a page load passes (`Relay::refused_page`), and every refusal is
written to the log with why, never with the secret. The window can come back without the cookie
(WebKit let it go, or the load began on another site), and the refusal is a page with no script:
the shell sends the window back through the entry at that page (`desktop_connected`). A request of
the window's page that comes without it (`Sec-Fetch-Site: same-origin`, which no other site's page
can send) tells the shell the same (`Ended::WindowLostItsCookie`). Before, a window that met the
refusal stayed on it until the app quit (1.2.0-rc.5, connected to OpenBot Cloud).
- It forwards to the typed address and nowhere else: only origin-form request targets (no absolute
URL, no CONNECT), and a redirect is handed back to the page, never followed.
- On the way out it drops `Origin`, `Cookie`, `Referer`, `Forwarded` and `X-Forwarded-*`, and any
Expand Down Expand Up @@ -122,11 +130,59 @@ pub enum Ended {
SessionEnded,
/// The OpenBot did not answer. The relay keeps going; said at most once in a while.
Unreachable,
/// A request of the window's own page came without the run's cookie: it says it is the page's
/// own (`Sec-Fetch-Site: same-origin`), and WebKit no longer sends the cookie. The relay keeps
/// going; the shell sends the window back through the entry.
WindowLostItsCookie,
}

/// How often `Ended::Unreachable` is said while the OpenBot stays unreachable.
const UNREACHABLE_SAID_EVERY: Duration = Duration::from_secs(30);

/// How often a refused request that is not a page load is written to the log, at most: a page that
/// lost the cookie asks several times a second. Every refused page load is written.
const REFUSAL_SAID_EVERY: Duration = Duration::from_secs(30);

/// How often the shell is told `Ended::WindowLostItsCookie`, at most, while the page keeps asking.
const LOST_COOKIE_TOLD_EVERY: Duration = Duration::from_secs(5);

/// Why the relay refused a request as not the OpenBot window's, for the log.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Refused {
/// Its `Origin` is not the relay's own.
AnotherOrigin,
/// `Sec-Fetch-Site` says another site sent it.
AnotherSite,
/// It came without the run's cookie.
NoCookie,
}

impl Refused {
fn said(self) -> &'static str {
match self {
Self::AnotherOrigin => "another site's page sent it (Origin)",
Self::AnotherSite => "another site sent it (Sec-Fetch-Site)",
Self::NoCookie => "it came without the window's cookie",
}
}
}

/// Whether the request is a window's page load (a navigation), not a request a page makes:
/// `Sec-Fetch-Dest: document`, or, from a webview that sends no `Sec-Fetch-Dest`, a `GET` that asks
/// for HTML.
fn page_load(method: &Method, headers: &HeaderMap) -> bool {
if method != Method::GET {
return false;
}
match headers.get("sec-fetch-dest") {
Some(destination) => destination == "document",
None => headers
.get(header::ACCEPT)
.and_then(|accept| accept.to_str().ok())
.is_some_and(|accept| accept.contains("text/html")),
}
}

/// How long a connection to OpenBot is kept open, idle, for the next request. A load balancer or
/// an ingress in front of OpenBot closes an idle connection on a timer of its own (AWS's load
/// balancer after 60 s, nginx after 75 s), and a request sent at the moment it does so is lost.
Expand Down Expand Up @@ -159,6 +215,13 @@ struct Shared {
on_ended: Box<OnEnded>,
session_ended: AtomicBool,
unreachable_said: Mutex<Option<Instant>>,
/// The path of the page load refused last, until the window enters again or a page load
/// passes (`Relay::refused_page`).
refused_page: Arc<Mutex<Option<String>>>,
/// When a refused request that is not a page load was last written to the log.
refusal_said: Mutex<Option<Instant>>,
/// When the shell was last told `Ended::WindowLostItsCookie`.
lost_cookie_told: Mutex<Option<Instant>>,
stop: tokio::sync::watch::Sender<bool>,
}

Expand All @@ -167,6 +230,7 @@ pub struct Relay {
address: SocketAddr,
secret: String,
organization: Arc<Mutex<Option<HeaderValue>>>,
refused_page: Arc<Mutex<Option<String>>>,
stop: tokio::sync::watch::Sender<bool>,
runtime: Option<tokio::runtime::Runtime>,
}
Expand Down Expand Up @@ -208,6 +272,7 @@ impl Relay {
.map_err(|error| format!("could not start the relay: {error}"))?;
let (stop, stopped) = tokio::sync::watch::channel(false);
let secret = crate::provider_oauth::random();
let refused_page = Arc::new(Mutex::new(None));
let shared = Arc::new(Shared {
session,
host: address.to_string(),
Expand All @@ -220,6 +285,9 @@ impl Relay {
on_ended: Box::new(on_ended),
session_ended: AtomicBool::new(false),
unreachable_said: Mutex::new(None),
refused_page: refused_page.clone(),
refusal_said: Mutex::new(None),
lost_cookie_told: Mutex::new(None),
stop: stop.clone(),
});
runtime.spawn(serve(listener, shared, stopped));
Expand All @@ -228,6 +296,7 @@ impl Relay {
address,
secret,
organization,
refused_page,
stop,
runtime: Some(runtime),
})
Expand Down Expand Up @@ -262,6 +331,13 @@ impl Relay {
}
format!("{}&to={to}", self.entry())
}

/// The page load the relay refused last as not the window's (a path from the root, such as
/// `/` or `/connections`), until the window enters again or a page load passes. A window on
/// that page sits on the refusal, and goes back through the entry at it (`entry_to`).
pub fn refused_page(&self) -> Option<String> {
self.refused_page.lock().unwrap().clone()
}
}

impl Drop for Relay {
Expand Down Expand Up @@ -344,6 +420,63 @@ fn has_cookie(headers: &HeaderMap, secret: &str) -> bool {
.any(|(name, value)| name == COOKIE && same_secret(value, secret))
}

/**
A request refused as not the window's (`why`): a page load is kept by its path (`refused_page`) and
written to the log, and anything else is written at most once in `REFUSAL_SAID_EVERY`. The method
and the path only: never a header, so never the cookie or the secret. A request of the window's own
page that came without the cookie tells the shell (`Ended::WindowLostItsCookie`).
*/
fn say_refused(
shared: &Arc<Shared>,
request: &Request<Incoming>,
why: Refused,
loading_a_page: bool,
) {
let path = request.uri().path();
if loading_a_page {
*shared.refused_page.lock().unwrap() = Some(path.to_owned());
}
let now = Instant::now();
let said = {
let mut said = shared.refusal_said.lock().unwrap();
let due = said.is_none_or(|at| now.duration_since(at) >= REFUSAL_SAID_EVERY);
if due && !loading_a_page {
*said = Some(now);
}
due || loading_a_page
};
if said {
let what = if loading_a_page {
"the page load"
} else {
"the request"
};
log::warn!(
"[relay] refused {what} {} {path} as not the OpenBot window's: {}",
request.method(),
why.said()
);
}
let the_pages_own = request
.headers()
.get("sec-fetch-site")
.is_some_and(|site| site == "same-origin");
if why == Refused::NoCookie && the_pages_own && !loading_a_page {
let due = {
let mut told = shared.lost_cookie_told.lock().unwrap();
let due = told.is_none_or(|at| now.duration_since(at) >= LOST_COOKIE_TOLD_EVERY);
if due {
*told = Some(now);
}
due
};
if due {
let shared = shared.clone();
std::thread::spawn(move || (shared.on_ended)(Ended::WindowLostItsCookie));
}
}
}

/// Headers that belong to one connection, not to the request (RFC 9110 §7.6.1).
fn hop_by_hop(name: &HeaderName) -> bool {
matches!(
Expand Down Expand Up @@ -430,6 +563,8 @@ async fn answer(mut request: Request<Incoming>, shared: Arc<Shared>) -> Response
.and_then(|query| query.split('&').find_map(|pair| pair.strip_prefix("to=")))
.filter(|to| app_page(to))
.unwrap_or("/");
// The window is entering again: whatever page it was refused before, it is let in now.
*shared.refused_page.lock().unwrap() = None;
// A page, not a redirect: see the module's documentation.
return Response::builder()
.status(StatusCode::OK)
Expand Down Expand Up @@ -466,12 +601,27 @@ async fn answer(mut request: Request<Incoming>, shared: Arc<Shared>) -> Response
.get_all("sec-fetch-site")
.iter()
.any(|site| site == "cross-site" || site == "same-site");
if foreign_origin || from_another_site || !has_cookie(request.headers(), &shared.secret) {
let refused = if foreign_origin {
Some(Refused::AnotherOrigin)
} else if from_another_site {
Some(Refused::AnotherSite)
} else if !has_cookie(request.headers(), &shared.secret) {
Some(Refused::NoCookie)
} else {
None
};
let loading_a_page = page_load(request.method(), request.headers());
if let Some(why) = refused {
say_refused(&shared, &request, why, loading_a_page);
return plain(
StatusCode::FORBIDDEN,
"This relay is for the OpenBot window.",
);
}
if loading_a_page {
// The window's page loads with the cookie: it sits on no refusal.
*shared.refused_page.lock().unwrap() = None;
}
if request.uri().path().starts_with(OWN_PREFIX) {
return plain(StatusCode::NOT_FOUND, "Not found.");
}
Expand Down Expand Up @@ -2124,7 +2274,20 @@ mod tests {
.filter(|(_, _, strict)| !strict || same_site(&began_on, &url))
.map(|(name, value, _)| format!("{name}={value}"))
.collect();
let mut request = http().get(url.clone());
// A page load, as WebKit sends one: where it began says which site sent it.
let site = if began_on.origin() == url.origin() {
"same-origin"
} else if same_site(&began_on, &url) {
"same-site"
} else {
"cross-site"
};
let mut request = http()
.get(url.clone())
.header("accept", "text/html,application/xhtml+xml,*/*;q=0.8")
.header("sec-fetch-dest", "document")
.header("sec-fetch-mode", "navigate")
.header("sec-fetch-site", site);
if !cookies.is_empty() {
request = request.header("cookie", cookies.join("; "));
}
Expand Down Expand Up @@ -2263,6 +2426,84 @@ mod tests {
assert!(app_page("/settings/computer"));
}

/**
The window's page load came without the run's cookie and was refused: the white page that says
"This relay is for the OpenBot window.", which a window sat on in dogfooding (1.2.0-rc.5, connected to
OpenBot Cloud) until the app quit. The relay keeps which page it refused, so the shell can
send the window back through the entry at that page, and the entry hands it the cookie again: the
page loads, and nothing is kept any more. A request the page makes (a fetch, an image) is never
taken for the page load. One of the page's own that came without the cookie
(`Sec-Fetch-Site: same-origin`) tells the shell once in a while; one from another site, or one
that doesn't say, never does.
*/
#[test]
fn a_page_load_refused_for_want_of_the_cookie_is_kept_until_the_window_enters_again() {
let rig = rig();
let origin = rig.relay.origin();
let mut window = WebKitWindow::new();
let arrived = window.navigate(SETUP_PAGE, &rig.relay.entry());
assert_eq!(arrived.status, 200);
assert_eq!(rig.relay.refused_page(), None);

// WebKit let the cookie go, and the page is loaded again.
window.jar.clear();
let page = format!("{origin}/landing");
let refused = window.navigate(&page, &page);
assert_eq!(refused.status, 403);
assert_eq!(refused.body, "This relay is for the OpenBot window.");
assert_eq!(rig.relay.refused_page().as_deref(), Some("/landing"));
assert_eq!(rig.openbot.seen_at("/landing").len(), 0);

// The page's own requests are refused as well, and are not the page load.
for (site, tells) in [
(Some("same-origin"), true),
(Some("cross-site"), false),
(None, false),
] {
let mut request = http().get(format!("{origin}{ECHO}"));
if let Some(site) = site {
request = request
.header("sec-fetch-site", site)
.header("sec-fetch-dest", "empty");
}
let answered = request.send().unwrap();
assert_eq!(answered.status(), 403, "{site:?}");
assert_eq!(
rig.relay.refused_page().as_deref(),
Some("/landing"),
"{site:?}"
);
let deadline = Instant::now() + Duration::from_secs(2);
let told = || {
rig.ended
.lock()
.unwrap()
.iter()
.filter(|why| **why == Ended::WindowLostItsCookie)
.count()
};
while tells && told() == 0 {
assert!(Instant::now() < deadline, "the shell was never told");
std::thread::sleep(Duration::from_millis(10));
}
std::thread::sleep(Duration::from_millis(100));
assert_eq!(told(), 1, "{site:?}: told once, for the page's own");
}
assert_eq!(rig.echoes(), 0);

// Back through the entry at that page: the cookie again, and the page loads.
let entered = window.navigate(&page, &rig.relay.entry_to("/landing"));
assert_eq!(entered.status, 200);
assert_eq!(entered.url.as_str(), page);
assert_eq!(rig.openbot.seen_at("/landing").len(), 1);
assert_eq!(rig.relay.refused_page(), None);
assert_eq!(
window.navigate(&page, &format!("{origin}{ECHO}")).status,
200
);
assert!(!rig.ended.lock().unwrap().contains(&Ended::SessionEnded));
}

/// The entry address holds the run's secret, and the log's redaction covers it.
#[test]
fn the_entry_address_and_the_cookie_are_redacted_in_a_log_line() {
Expand Down
Loading
Loading