Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
TypeScript apiapi-clientapi-restapi-testingdeveloper-toolsgraphqlhttphttp-clientpwarestrest-apispatestingtesting-toolstoolsvuevuejswebsocket
fix(desktop): pick the auth port on IPv4 loopback (#6729)
Shreyas9a550a31e437
diff --git a/packages/hoppscotch-desktop/src-tauri/Cargo.lock b/packages/hoppscotch-desktop/src-tauri/Cargo.lockindex abda01622..20c5d2cbc 100644--- a/packages/hoppscotch-desktop/src-tauri/Cargo.lock+++ b/packages/hoppscotch-desktop/src-tauri/Cargo.lock@@ -2329,8 +2329,8 @@ dependencies = ["axum","dirs 6.0.0","file-rotate",+ "libc","native-dialog",- "random-port","semver","serde","serde_json",@@ -3293,18 +3293,6 @@ dependencies = ["jni-sys",]-[[package]]-name = "network-interface"-version = "1.1.4"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a4a43439bf756eed340bdf8feba761e2d50c7d47175d87545cd5cbe4a137c4d1"-dependencies = [- "cc",- "libc",- "thiserror 1.0.69",- "winapi",-]-[[package]]name = "new_debug_unreachable"version = "1.0.6"@@ -4349,17 +4337,6 @@ dependencies = ["rand_core 0.5.1",]-[[package]]-name = "random-port"-version = "0.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d52b7d0e298a1b2f2f46c8d5da944c80ed1e5e6b032521cc44ee2b1dcbe2b94a"-dependencies = [- "network-interface",- "rand 0.8.5",- "thiserror 1.0.69",-]-[[package]]name = "raw-window-handle"version = "0.5.2"diff --git a/packages/hoppscotch-desktop/src-tauri/Cargo.toml b/packages/hoppscotch-desktop/src-tauri/Cargo.tomlindex beeb69ed7..1f2ae9a1b 100644--- a/packages/hoppscotch-desktop/src-tauri/Cargo.toml+++ b/packages/hoppscotch-desktop/src-tauri/Cargo.toml@@ -33,7 +33,6 @@ tauri-plugin-appload = { git = "https://github.com/CuriousCorrelation/tauri-plugtauri-plugin-relay = { git = "https://github.com/CuriousCorrelation/tauri-plugin-relay", rev = "273488c8f50a22ee707af6b50ccd5570851f8bc9" }axum = "0.8.1"tower-http = { version = "0.6.2", features = ["cors"] }-random-port = "0.1.1"tokio = "1.43.0"tauri-plugin-process = "2.2.0"file-rotate = "0.8.0"@@ -47,6 +46,9 @@ semver = "1.0"[dev-dependencies]tempfile = "3.20.0"+[target.'cfg(unix)'.dependencies]+libc = "0.2"+[target.'cfg(windows)'.dependencies]tempfile = { version = "3.13.0" }winreg = { version = "0.52.0" }diff --git a/packages/hoppscotch-desktop/src-tauri/src/lib.rs b/packages/hoppscotch-desktop/src-tauri/src/lib.rsindex 69f0b8d93..4db7da8cf 100644--- a/packages/hoppscotch-desktop/src-tauri/src/lib.rs+++ b/packages/hoppscotch-desktop/src-tauri/src/lib.rs@@ -15,8 +15,6 @@ use tauri::Emitter;use tauri_plugin_deep_link::DeepLinkExt;use tauri_plugin_window_state::StateFlags;-use random_port::{PortPicker, Protocol};-use config::HoppApploadConfig;use error::HoppError;@@ -61,11 +59,9 @@ fn setup_deep_link_handler(app: &tauri::App) -> Result<(), HoppError> {}fn setup_server(app: &tauri::App) -> Result<u16, HoppError> {- let server_port: u16 = PortPicker::new()- .protocol(Protocol::Tcp)- .port_range(15000..=25000)- .pick()- .map_err(|_| HoppError::ServerPortInitialization)?;+ let listener =+ server::bind_listener(15000..=25000).ok_or(HoppError::ServerPortInitialization)?;+ let server_port = listener.local_addr()?.port();tracing::info!("Selected server port: {}", server_port);SERVER_PORT@@ -77,7 +73,7 @@ fn setup_server(app: &tauri::App) -> Result<u16, HoppError> {.ok_or(HoppError::ServerPortInitialization)?;tracing::info!(port = port, "Initializing server with pre-selected port");- let port = server::init(port, app.handle().clone());+ let port = server::init(listener, app.handle().clone())?;tracing::info!(port = port, "Server initialization complete");Ok(port)diff --git a/packages/hoppscotch-desktop/src-tauri/src/server.rs b/packages/hoppscotch-desktop/src-tauri/src/server.rsindex 65362bad8..a566b827c 100644--- a/packages/hoppscotch-desktop/src-tauri/src/server.rs+++ b/packages/hoppscotch-desktop/src-tauri/src/server.rs@@ -1,4 +1,6 @@-use std::net::SocketAddr;+use std::io::{self, ErrorKind};+use std::net::{Ipv4Addr, Ipv6Addr, TcpListener};+use std::ops::RangeInclusive;use axum::{extract::Query,@@ -42,9 +44,61 @@ async fn device_token<R: Runtime>(StatusCode::OK.into_response()}-pub(crate) fn init<R: Runtime>(port: u16, handle: tauri::AppHandle<R>) -> u16 {+/// The OS error code for `EAFNOSUPPORT`, which a socket call returns on a+/// host with IPv6 disabled. `std` maps it to no `ErrorKind`, so the check+/// compares the raw code.+#[cfg(unix)]+const ADDRESS_FAMILY_NOT_SUPPORTED: i32 = libc::EAFNOSUPPORT;+#[cfg(windows)]+const ADDRESS_FAMILY_NOT_SUPPORTED: i32 = 10047;++/// Binds the first port in `range` that is free on `127.0.0.1` and that no+/// other process listens on at `::1`, and returns the `127.0.0.1` listener,+/// so the port stays reserved until `init` serves on it.+///+/// Login pages from earlier releases send the device token to `localhost`,+/// which a browser can resolve to `::1` first, so a port taken on `::1`+/// would send the token to that listener. A `::1` bind counts as free only+/// where it succeeds or where the host has no IPv6 loopback, as on a kernel+/// booted with `ipv6.disable=1`.+pub(crate) fn bind_listener(range: RangeInclusive<u16>) -> Option<TcpListener> {+ range.into_iter().find_map(|port| {+ let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, port)).ok()?;+ is_free_on_ipv6_loopback(TcpListener::bind((Ipv6Addr::LOCALHOST, port))).then_some(listener)+ })+}++/// Any other error, `AddrInUse` and the `PermissionDenied` Windows returns+/// for a port bound with `SO_EXCLUSIVEADDRUSE` among them, counts as taken.+fn is_free_on_ipv6_loopback(bind: io::Result<TcpListener>) -> bool {+ match bind {+ Ok(_) => true,+ Err(e) => {+ e.kind() == ErrorKind::AddrNotAvailable+ || e.raw_os_error() == Some(ADDRESS_FAMILY_NOT_SUPPORTED)+ }+ }+}++pub(crate) fn init<R: Runtime>(+ listener: TcpListener,+ handle: tauri::AppHandle<R>,+) -> io::Result<u16> {tracing::info!("Beginning server initialization");+ let addr = listener.local_addr()?;+ let port = addr.port();+ listener.set_nonblocking(true)?;+ // `from_std` registers the socket with the reactor of the runtime it is+ // called under, so it runs here under the runtime that serves it, and a+ // failure returns from `init` before startup reports a port.+ let listener = {+ let runtime = tauri::async_runtime::handle();+ let _guard = runtime.inner().enter();+ tokio::net::TcpListener::from_std(listener)?+ };+ tracing::info!(local_addr = %addr, "Server bound successfully");+let app = Router::new().route("/device-token",@@ -52,8 +106,6 @@ pub(crate) fn init<R: Runtime>(port: u16, handle: tauri::AppHandle<R>) -> u16 {).layer(CorsLayer::very_permissive());- let addr = SocketAddr::from(([127, 0, 0, 1], port));-tauri::async_runtime::spawn(async move {tracing::info!(address = %addr,@@ -61,25 +113,6 @@ pub(crate) fn init<R: Runtime>(port: u16, handle: tauri::AppHandle<R>) -> u16 {"Starting HTTP server");- let listener = match tokio::net::TcpListener::bind(addr).await {- Ok(l) => {- tracing::info!(- local_addr = %l.local_addr().unwrap_or(addr),- "Server bound successfully"- );- l- }- Err(e) => {- tracing::error!(- error.message = %e,- error.kind = ?e.kind(),- attempted_address = %addr,- "Server bind failed"- );- panic!("Could not bind to the unused port");- }- };-tracing::info!("Server starting");if let Err(e) = axum::serve(listener, app).await {tracing::error!(@@ -90,7 +123,7 @@ pub(crate) fn init<R: Runtime>(port: u16, handle: tauri::AppHandle<R>) -> u16 {}});- port+ Ok(port)}// `AuthTokensQuery` gets deserialized from query params on the `/device-token`@@ -152,4 +185,52 @@ mod tests {assert_eq!(query.access_token, "abc123");assert_eq!(query.refresh_token, None);}++ #[test]+ fn test_bind_listener_reserves_a_free_port() {+ let port = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))+ .unwrap()+ .local_addr()+ .unwrap()+ .port();++ let listener = bind_listener(port..=port).unwrap();++ assert_eq!(listener.local_addr().unwrap().port(), port);+ assert!(TcpListener::bind((Ipv4Addr::LOCALHOST, port)).is_err());+ }++ #[test]+ fn test_bind_listener_skips_port_taken_on_ipv4_loopback() {+ let taken = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();+ let port = taken.local_addr().unwrap().port();++ assert!(bind_listener(port..=port).is_none());+ }++ #[test]+ fn test_bind_listener_skips_port_taken_on_ipv6_loopback() {+ let Ok(taken) = TcpListener::bind((Ipv6Addr::LOCALHOST, 0)) else {+ return;+ };+ let port = taken.local_addr().unwrap().port();++ assert!(bind_listener(port..=port).is_none());+ }++ #[test]+ fn test_ipv6_loopback_counts_as_free_only_without_ipv6() {+ assert!(is_free_on_ipv6_loopback(Err(io::Error::from(+ ErrorKind::AddrNotAvailable+ ))));+ assert!(is_free_on_ipv6_loopback(Err(io::Error::from_raw_os_error(+ ADDRESS_FAMILY_NOT_SUPPORTED+ ))));+ assert!(!is_free_on_ipv6_loopback(Err(io::Error::from(+ ErrorKind::AddrInUse+ ))));+ assert!(!is_free_on_ipv6_loopback(Err(io::Error::from(+ ErrorKind::PermissionDenied+ ))));+ }}diff --git a/packages/hoppscotch-selfhost-web/src/components/Login.vue b/packages/hoppscotch-selfhost-web/src/components/Login.vueindex e9ba4ce18..f4d050d51 100644--- a/packages/hoppscotch-selfhost-web/src/components/Login.vue+++ b/packages/hoppscotch-selfhost-web/src/components/Login.vue@@ -74,7 +74,7 @@ async function openLink(url: string) {onMounted(async () => {const port = await invoke<number>("hopp_auth_port")- const redirectURI = `http://localhost:${port}/device-token`+ const redirectURI = `http://127.0.0.1:${port}/device-token`const openURL = `${import.meta.env.VITE_BASE_URL}/device-login?redirect_uri=${encodeURIComponent(redirectURI)}`await openLink(openURL)