Compare commits

..

3 Commits

Author SHA1 Message Date
21pages
28cca601b5 oidc: route auth requests through shared HTTP/tcp-proxy path while keeping TLS warmup
Signed-off-by: 21pages <sunboeasy@gmail.com>
2026-03-31 11:09:44 +08:00
21pages
93cfd56954 review: make is_public case-insensitive and cover mixed-case rustdesk URLs
Signed-off-by: 21pages <sunboeasy@gmail.com>
2026-03-31 11:05:15 +08:00
rustdesk
5e7484c51b review: extract fallback helper, fix Content-Type override, add overall timeout
- Extract duplicated TCP proxy fallback logic into generic
  `with_tcp_proxy_fallback` helper used by both `post_request` and
  `http_request_sync`, eliminating code drift risk
- Allow caller-supplied Content-Type to override the default in
  `parse_simple_header` instead of silently dropping it
- Take body by reference in `post_request_http` to avoid eager clone
  when no fallback is needed
- Wrap entire `tcp_proxy_request` flow (connect + handshake + send +
  receive) in an overall timeout to prevent indefinite stalls

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-30 20:55:15 +08:00
2 changed files with 161 additions and 139 deletions

View File

@@ -1086,6 +1086,7 @@ fn get_api_server_(api: String, custom: String) -> String {
#[inline] #[inline]
pub fn is_public(url: &str) -> bool { pub fn is_public(url: &str) -> bool {
let url = url.to_ascii_lowercase();
url.contains("rustdesk.com/") || url.ends_with("rustdesk.com") url.contains("rustdesk.com/") || url.ends_with("rustdesk.com")
} }
@@ -1187,6 +1188,10 @@ fn get_tcp_proxy_addr() -> String {
/// Send an HTTP request via the rendezvous server's TCP proxy using protobuf. /// Send an HTTP request via the rendezvous server's TCP proxy using protobuf.
/// Connects with `connect_tcp` + `secure_tcp`, sends `HttpProxyRequest`, /// Connects with `connect_tcp` + `secure_tcp`, sends `HttpProxyRequest`,
/// receives `HttpProxyResponse`. /// receives `HttpProxyResponse`.
///
/// The entire operation (connect + handshake + send + receive) is wrapped in
/// an overall timeout of `CONNECT_TIMEOUT + READ_TIMEOUT` so that a stall at
/// any stage cannot block the caller indefinitely.
async fn tcp_proxy_request( async fn tcp_proxy_request(
method: &str, method: &str,
url: &str, url: &str,
@@ -1212,6 +1217,8 @@ async fn tcp_proxy_request(
tcp_addr tcp_addr
); );
let overall_timeout = CONNECT_TIMEOUT + READ_TIMEOUT;
timeout(overall_timeout, async {
let mut conn = socket_client::connect_tcp(&*tcp_addr, CONNECT_TIMEOUT).await?; let mut conn = socket_client::connect_tcp(&*tcp_addr, CONNECT_TIMEOUT).await?;
let key = crate::get_key(true).await; let key = crate::get_key(true).await;
secure_tcp_silent(&mut conn, &key).await?; secure_tcp_silent(&mut conn, &key).await?;
@@ -1226,7 +1233,7 @@ async fn tcp_proxy_request(
msg_out.set_http_proxy_request(req); msg_out.set_http_proxy_request(req);
conn.send(&msg_out).await?; conn.send(&msg_out).await?;
match timeout(READ_TIMEOUT, conn.next()).await? { match conn.next().await {
Some(Ok(bytes)) => { Some(Ok(bytes)) => {
let msg_in = RendezvousMessage::parse_from_bytes(&bytes)?; let msg_in = RendezvousMessage::parse_from_bytes(&bytes)?;
match msg_in.union { match msg_in.union {
@@ -1237,19 +1244,21 @@ async fn tcp_proxy_request(
Some(Err(e)) => bail!("TCP proxy read error: {}", e), Some(Err(e)) => bail!("TCP proxy read error: {}", e),
None => bail!("TCP proxy connection closed without response"), None => bail!("TCP proxy connection closed without response"),
} }
})
.await?
} }
/// Build HeaderEntry list from "Key: Value" style header string (used by post_request). /// Build HeaderEntry list from "Key: Value" style header string (used by post_request).
/// If the caller supplies a Content-Type header it overrides the default `application/json`.
fn parse_simple_header(header: &str) -> Vec<HeaderEntry> { fn parse_simple_header(header: &str) -> Vec<HeaderEntry> {
let mut entries = vec![HeaderEntry { let mut entries = Vec::new();
name: "Content-Type".into(), let mut has_content_type = false;
value: "application/json".into(),
..Default::default()
}];
if !header.is_empty() { if !header.is_empty() {
let tmp: Vec<&str> = header.splitn(2, ": ").collect(); let tmp: Vec<&str> = header.splitn(2, ": ").collect();
if tmp.len() == 2 { if tmp.len() == 2 {
if !tmp[0].eq_ignore_ascii_case("Content-Type") { if tmp[0].eq_ignore_ascii_case("Content-Type") {
has_content_type = true;
}
entries.push(HeaderEntry { entries.push(HeaderEntry {
name: tmp[0].into(), name: tmp[0].into(),
value: tmp[1].into(), value: tmp[1].into(),
@@ -1257,6 +1266,15 @@ fn parse_simple_header(header: &str) -> Vec<HeaderEntry> {
}); });
} }
} }
if !has_content_type {
entries.insert(
0,
HeaderEntry {
name: "Content-Type".into(),
value: "application/json".into(),
..Default::default()
},
);
} }
entries entries
} }
@@ -1308,21 +1326,16 @@ fn parse_json_header_entries(header: &str) -> ResultType<Vec<HeaderEntry>> {
} }
} }
#[inline]
fn tcp_proxy_fallback_log_condition() -> &'static str {
"failed or 5xx"
}
/// Returns (status_code, body_text). Separating status so the wrapper can decide on fallback. /// Returns (status_code, body_text). Separating status so the wrapper can decide on fallback.
async fn post_request_http(url: String, body: String, header: &str) -> ResultType<(u16, String)> { async fn post_request_http(url: &str, body: &str, header: &str) -> ResultType<(u16, String)> {
let proxy_conf = Config::get_socks(); let proxy_conf = Config::get_socks();
let tls_url = get_url_for_tls(&url, &proxy_conf); let tls_url = get_url_for_tls(url, &proxy_conf);
let tls_type = get_cached_tls_type(tls_url); let tls_type = get_cached_tls_type(tls_url);
let danger_accept_invalid_cert = get_cached_tls_accept_invalid_cert(tls_url); let danger_accept_invalid_cert = get_cached_tls_accept_invalid_cert(tls_url);
let response = post_request_( let response = post_request_(
&url, url,
tls_url, tls_url,
body.clone(), body.to_owned(),
header, header,
tls_type, tls_type,
danger_accept_invalid_cert, danger_accept_invalid_cert,
@@ -1334,6 +1347,49 @@ async fn post_request_http(url: String, body: String, header: &str) -> ResultTyp
Ok((status, text)) Ok((status, text))
} }
/// Try `http_fn` first; on connection failure or 5xx, fall back to `tcp_fn`
/// if the URL is eligible. 4xx responses are returned as-is.
async fn with_tcp_proxy_fallback<HttpFut, TcpFut>(
url: &str,
method: &str,
http_fn: HttpFut,
tcp_fn: TcpFut,
) -> ResultType<String>
where
HttpFut: Future<Output = ResultType<(u16, String)>>,
TcpFut: Future<Output = ResultType<String>>,
{
if should_use_raw_tcp_for_api(url) {
return tcp_fn.await;
}
let http_result = http_fn.await;
let should_fallback = match &http_result {
Err(_) => true,
Ok((status, _)) => *status >= 500,
};
if should_fallback && can_fallback_to_raw_tcp(url) {
log::warn!(
"HTTP {} to {} failed or 5xx (result: {:?}), trying TCP proxy fallback",
method,
tcp_proxy_log_target(url),
http_result
.as_ref()
.map(|(s, _)| *s)
.map_err(|e| e.to_string()),
);
match tcp_fn.await {
Ok(resp) => return Ok(resp),
Err(tcp_err) => {
log::warn!("TCP proxy fallback also failed: {:?}", tcp_err);
}
}
}
http_result.map(|(_status, text)| text)
}
/// POST request with raw TCP proxy support. /// POST request with raw TCP proxy support.
/// - If `USE_RAW_TCP_FOR_API` is "Y" and WS is off, goes directly through TCP proxy. /// - If `USE_RAW_TCP_FOR_API` is "Y" and WS is off, goes directly through TCP proxy.
/// - Otherwise tries HTTP first; on connection failure or 5xx status, /// - Otherwise tries HTTP first; on connection failure or 5xx status,
@@ -1341,40 +1397,13 @@ async fn post_request_http(url: String, body: String, header: &str) -> ResultTyp
/// - 4xx responses are returned as-is (server is reachable, business logic error). /// - 4xx responses are returned as-is (server is reachable, business logic error).
/// - If fallback also fails, returns the original HTTP result (text or error). /// - If fallback also fails, returns the original HTTP result (text or error).
pub async fn post_request(url: String, body: String, header: &str) -> ResultType<String> { pub async fn post_request(url: String, body: String, header: &str) -> ResultType<String> {
if should_use_raw_tcp_for_api(&url) { with_tcp_proxy_fallback(
return post_request_via_tcp_proxy(&url, &body, header).await; &url,
} "POST",
post_request_http(&url, &body, header),
let http_result = post_request_http(url.clone(), body.clone(), header).await; post_request_via_tcp_proxy(&url, &body, header),
let should_fallback = match &http_result { )
Err(_) => true, .await
Ok((status, _)) => *status >= 500,
};
if should_fallback && can_fallback_to_raw_tcp(&url) {
log::warn!(
"HTTP POST to {} {} (result: {:?}), trying TCP proxy fallback",
tcp_proxy_log_target(&url),
tcp_proxy_fallback_log_condition(),
http_result
.as_ref()
.map(|(s, _)| *s)
.map_err(|e| e.to_string()),
);
match post_request_via_tcp_proxy(&url, &body, header).await {
Ok(resp) => return Ok(resp),
Err(tcp_err) => {
log::warn!("TCP proxy fallback also failed: {:?}", tcp_err);
// Fall through to return original HTTP result
}
}
}
// Return original HTTP result
match http_result {
Ok((_status, text)) => Ok(text),
Err(e) => Err(e),
}
} }
#[async_recursion] #[async_recursion]
@@ -1623,32 +1652,13 @@ pub async fn http_request_sync(
body: Option<String>, body: Option<String>,
header: String, header: String,
) -> ResultType<String> { ) -> ResultType<String> {
if should_use_raw_tcp_for_api(&url) { with_tcp_proxy_fallback(
return http_request_via_tcp_proxy(&url, &method, body.as_deref(), &header).await; &url,
} &method,
http_request_http(&url, &method, body.clone(), &header),
let http_result = http_request_http(&url, &method, body.clone(), &header).await; http_request_via_tcp_proxy(&url, &method, body.as_deref(), &header),
let should_fallback = match &http_result { )
Err(_) => true, .await
Ok((status, _)) => *status >= 500,
};
if should_fallback && can_fallback_to_raw_tcp(&url) {
log::warn!(
"HTTP {} to {} {}, trying TCP proxy fallback",
method,
tcp_proxy_log_target(&url),
tcp_proxy_fallback_log_condition()
);
match http_request_via_tcp_proxy(&url, &method, body.as_deref(), &header).await {
Ok(resp) => return Ok(resp),
Err(tcp_err) => {
log::warn!("TCP proxy fallback also failed: {:?}", tcp_err);
}
}
}
http_result.map(|(_status, json_str)| json_str)
} }
/// General HTTP request via TCP proxy. Header is a JSON string (used by http_request_sync). /// General HTTP request via TCP proxy. Header is a JSON string (used by http_request_sync).
@@ -2757,11 +2767,13 @@ mod tests {
assert!(is_public("https://rustdesk.com/")); assert!(is_public("https://rustdesk.com/"));
assert!(is_public("https://www.rustdesk.com/")); assert!(is_public("https://www.rustdesk.com/"));
assert!(is_public("https://api.rustdesk.com/v1")); assert!(is_public("https://api.rustdesk.com/v1"));
assert!(is_public("https://API.RUSTDESK.COM/v1"));
assert!(is_public("https://rustdesk.com/path")); assert!(is_public("https://rustdesk.com/path"));
// Test URLs ending with "rustdesk.com" // Test URLs ending with "rustdesk.com"
assert!(is_public("rustdesk.com")); assert!(is_public("rustdesk.com"));
assert!(is_public("https://rustdesk.com")); assert!(is_public("https://rustdesk.com"));
assert!(is_public("https://RustDesk.com"));
assert!(is_public("http://www.rustdesk.com")); assert!(is_public("http://www.rustdesk.com"));
assert!(is_public("https://api.rustdesk.com")); assert!(is_public("https://api.rustdesk.com"));
@@ -2874,7 +2886,7 @@ mod tests {
} }
#[test] #[test]
fn test_parse_simple_header_ignores_custom_content_type() { fn test_parse_simple_header_respects_custom_content_type() {
let headers = parse_simple_header("Content-Type: text/plain"); let headers = parse_simple_header("Content-Type: text/plain");
assert_eq!( assert_eq!(
@@ -2889,7 +2901,7 @@ mod tests {
.iter() .iter()
.find(|entry| entry.name.eq_ignore_ascii_case("Content-Type")) .find(|entry| entry.name.eq_ignore_ascii_case("Content-Type"))
.map(|entry| entry.value.as_str()), .map(|entry| entry.value.as_str()),
Some("application/json") Some("text/plain")
); );
} }
@@ -2917,11 +2929,6 @@ mod tests {
); );
} }
#[test]
fn test_tcp_proxy_fallback_log_condition() {
assert_eq!(tcp_proxy_fallback_log_condition(), "failed or 5xx");
}
#[test] #[test]
fn test_tcp_proxy_log_target_redacts_query_only() { fn test_tcp_proxy_log_target_redacts_query_only() {
assert_eq!( assert_eq!(

View File

@@ -1,9 +1,10 @@
use super::HbbHttpResponse; use super::HbbHttpResponse;
use crate::hbbs_http::create_http_client_with_url; use crate::hbbs_http::create_http_client_with_url;
use hbb_common::{config::LocalConfig, log, ResultType}; use hbb_common::{config::LocalConfig, log, ResultType};
use reqwest::blocking::Client; use serde::de::DeserializeOwned;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr}; use serde_repr::{Deserialize_repr, Serialize_repr};
use serde_json::{Map, Value};
use std::{ use std::{
collections::HashMap, collections::HashMap,
sync::{Arc, RwLock}, sync::{Arc, RwLock},
@@ -109,7 +110,7 @@ pub struct AuthBody {
} }
pub struct OidcSession { pub struct OidcSession {
client: Option<Client>, warmed_api_server: Option<String>,
state_msg: &'static str, state_msg: &'static str,
failed_msg: String, failed_msg: String,
code_url: Option<OidcAuthUrl>, code_url: Option<OidcAuthUrl>,
@@ -136,7 +137,7 @@ impl Default for UserStatus {
impl OidcSession { impl OidcSession {
fn new() -> Self { fn new() -> Self {
Self { Self {
client: None, warmed_api_server: None,
state_msg: REQUESTING_ACCOUNT_AUTH, state_msg: REQUESTING_ACCOUNT_AUTH,
failed_msg: "".to_owned(), failed_msg: "".to_owned(),
code_url: None, code_url: None,
@@ -149,11 +150,28 @@ impl OidcSession {
fn ensure_client(api_server: &str) { fn ensure_client(api_server: &str) {
let mut write_guard = OIDC_SESSION.write().unwrap(); let mut write_guard = OIDC_SESSION.write().unwrap();
if write_guard.client.is_none() { if write_guard.warmed_api_server.as_deref() == Some(api_server) {
return;
}
// This URL is used to detect the appropriate TLS implementation for the server. // This URL is used to detect the appropriate TLS implementation for the server.
let login_option_url = format!("{}/api/login-options", &api_server); let login_option_url = format!("{}/api/login-options", api_server);
let client = create_http_client_with_url(&login_option_url); let _ = create_http_client_with_url(&login_option_url);
write_guard.client = Some(client); write_guard.warmed_api_server = Some(api_server.to_owned());
}
fn parse_hbb_http_response<T: DeserializeOwned>(body: &str) -> ResultType<HbbHttpResponse<T>> {
let map = serde_json::from_str::<Map<String, Value>>(body)?;
if let Some(error) = map.get("error") {
if let Some(err) = error.as_str() {
Ok(HbbHttpResponse::Error(err.to_owned()))
} else {
Ok(HbbHttpResponse::ErrorFormat)
}
} else {
match serde_json::from_value(Value::Object(map)) {
Ok(v) => Ok(HbbHttpResponse::Data(v)),
Err(_) => Ok(HbbHttpResponse::DataTypeFormat),
}
} }
} }
@@ -164,26 +182,15 @@ impl OidcSession {
uuid: &str, uuid: &str,
) -> ResultType<HbbHttpResponse<OidcAuthUrl>> { ) -> ResultType<HbbHttpResponse<OidcAuthUrl>> {
Self::ensure_client(api_server); Self::ensure_client(api_server);
let resp = if let Some(client) = &OIDC_SESSION.read().unwrap().client { let body = serde_json::json!({
client
.post(format!("{}/api/oidc/auth", api_server))
.json(&serde_json::json!({
"op": op, "op": op,
"id": id, "id": id,
"uuid": uuid, "uuid": uuid,
"deviceInfo": crate::ui_interface::get_login_device_info(), "deviceInfo": crate::ui_interface::get_login_device_info(),
})) })
.send()? .to_string();
} else { let resp = crate::post_request_sync(format!("{}/api/oidc/auth", api_server), body, "")?;
hbb_common::bail!("http client not initialized"); Self::parse_hbb_http_response(&resp)
};
let status = resp.status();
match resp.try_into() {
Ok(v) => Ok(v),
Err(err) => {
hbb_common::bail!("Http status: {}, err: {}", status, err);
}
}
} }
fn query( fn query(
@@ -197,11 +204,19 @@ impl OidcSession {
&[("code", code), ("id", id), ("uuid", uuid)], &[("code", code), ("id", id), ("uuid", uuid)],
)?; )?;
Self::ensure_client(api_server); Self::ensure_client(api_server);
if let Some(client) = &OIDC_SESSION.read().unwrap().client { #[derive(Deserialize)]
Ok(client.get(url).send()?.try_into()?) struct HttpResponseBody {
} else { body: String,
hbb_common::bail!("http client not initialized")
} }
let resp = crate::http_request_sync(
url.to_string(),
"GET".to_owned(),
None,
"{}".to_owned(),
)?;
let resp = serde_json::from_str::<HttpResponseBody>(&resp)?;
Self::parse_hbb_http_response(&resp.body)
} }
fn reset(&mut self) { fn reset(&mut self) {