From 7a571f9b27d935abb063977009e0ed26b8a1d4e7 Mon Sep 17 00:00:00 2001 From: Guangyuan Weng Date: Fri, 19 Jun 2026 02:38:17 -0400 Subject: [PATCH] feat(gpclient): cache portal-cookie to skip SAML on reconnect (#608) --- apps/gpclient/src/connect.rs | 76 +++++++++++++++++++- crates/gpapi/src/cookie_store.rs | 119 +++++++++++++++++++++++++++++++ crates/gpapi/src/lib.rs | 1 + 3 files changed, 195 insertions(+), 1 deletion(-) create mode 100644 crates/gpapi/src/cookie_store.rs diff --git a/apps/gpclient/src/connect.rs b/apps/gpclient/src/connect.rs index ead80cf..71eb168 100644 --- a/apps/gpclient/src/connect.rs +++ b/apps/gpclient/src/connect.rs @@ -11,6 +11,7 @@ use common::constants::{GP_CLIENT_VERSION, GP_USER_AGENT}; use gpapi::{ auth::SamlAuthResult, clap::{ToVerboseArg, args::Os}, + cookie_store, credential::{Credential, PasswordCredential}, error::PortalError, gateway::{GatewayLogin, SessionExtensionAuth, gateway_login}, @@ -55,6 +56,15 @@ pub(crate) struct ConnectArgs { #[arg(long, help = "Read the cookie from standard input")] cookie_on_stdin: bool, + #[arg( + long, + help = "Path to the portal-cookie cache file. Defaults to $HOME/.config/gpclient/cookie.json" + )] + cookie_file: Option, + + #[arg(long, help = "Do not read or write the portal-cookie cache")] + no_cookie_cache: bool, + #[arg(long, short, help = "The VPNC script to use", required_if_eq("script_tun", "true"))] script: Option, @@ -298,6 +308,12 @@ impl<'a> ConnectHandler<'a> { .await; } + if !self.args.no_cookie_cache && !self.args.cookie_on_stdin { + if let Some(()) = self.try_cached_cookie(server).await { + return Ok(()); + } + } + let Err(err) = self.connect_portal_with_prelogin(server).await else { return Ok(()); }; @@ -318,6 +334,50 @@ impl<'a> ConnectHandler<'a> { } } + async fn try_cached_cookie(&self, server: &str) -> Option<()> { + let path = cookie_store::cookie_path(self.args.cookie_file.as_deref()); + let stored = cookie_store::load(&path, server)?; + info!( + "Using cached portal cookie for {} (saved_at={}, gateway={})", + stored.server, stored.saved_at, stored.last_gateway + ); + + let cred: Credential = (&stored.auth_cookie).into(); + let mut gp_params = self.build_gp_params(); + gp_params.set_is_gateway(true); + + let login_session = match self.login_gateway(&stored.last_gateway, &cred, &gp_params).await { + Ok(s) => s, + Err(err) => { + warn!( + "Cached cookie rejected by gateway {}: {}. Clearing cache and falling back to SAML.", + stored.last_gateway, err + ); + cookie_store::clear(&path); + return None; + } + }; + + let result = self + .connect_gateway( + server, + &stored.last_gateway, + &login_session.cookie, + self.args.client_version.as_deref(), + false, + login_session.extension_auth, + ) + .await; + + match result { + Ok(()) => Some(()), + Err(err) => { + warn!("Gateway connect failed after cached-cookie login: {}", err); + None + } + } + } + async fn connect_portal_with_prelogin(&self, portal: &str) -> anyhow::Result<()> { let gp_params = self.build_gp_params(); @@ -348,7 +408,21 @@ impl<'a> ConnectHandler<'a> { }; let gateway = selected_gateway.server(); - let cred = portal_config.auth_cookie().into(); + let cred: Credential = portal_config.auth_cookie().into(); + + if !self.args.no_cookie_cache { + let path = cookie_store::cookie_path(self.args.cookie_file.as_deref()); + let stored = cookie_store::StoredCookie::new( + portal.to_string(), + cred.username().to_string(), + gateway.to_string(), + portal_config.auth_cookie().clone(), + ); + match cookie_store::save(&path, &stored) { + Ok(()) => info!("Saved portal cookie cache to {}", path.display()), + Err(e) => warn!("Failed to save cookie cache to {}: {}", path.display(), e), + } + } let login_session = match self.login_gateway(gateway, &cred, &gp_params).await { Ok(login_session) => login_session, diff --git a/crates/gpapi/src/cookie_store.rs b/crates/gpapi/src/cookie_store.rs new file mode 100644 index 0000000..9a9f523 --- /dev/null +++ b/crates/gpapi/src/cookie_store.rs @@ -0,0 +1,119 @@ +use std::{ + fs, + io::Write, + os::unix::fs::PermissionsExt, + path::{Path, PathBuf}, +}; + +use serde::{Deserialize, Serialize}; + +use crate::credential::AuthCookieCredential; + +const STORE_VERSION: u32 = 1; + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct StoredCookie { + pub version: u32, + pub server: String, + pub username: String, + pub last_gateway: String, + pub auth_cookie: AuthCookieCredential, + pub saved_at: u64, +} + +impl StoredCookie { + pub fn new(server: String, username: String, last_gateway: String, auth_cookie: AuthCookieCredential) -> Self { + let saved_at = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + Self { + version: STORE_VERSION, + server, + username, + last_gateway, + auth_cookie, + saved_at, + } + } +} + +pub fn cookie_path(custom: Option<&str>) -> PathBuf { + if let Some(p) = custom { + return PathBuf::from(p); + } + let home = std::env::var("HOME").unwrap_or_else(|_| "/root".to_string()); + PathBuf::from(home).join(".config/gpclient/cookie.json") +} + +pub fn load(path: &Path, server: &str) -> Option { + let bytes = fs::read(path).ok()?; + let stored: StoredCookie = serde_json::from_slice(&bytes).ok()?; + if stored.version != STORE_VERSION || stored.server != server { + return None; + } + Some(stored) +} + +pub fn save(path: &Path, stored: &StoredCookie) -> anyhow::Result<()> { + let parent = path + .parent() + .ok_or_else(|| anyhow::anyhow!("cookie path has no parent directory"))?; + fs::create_dir_all(parent)?; + fs::set_permissions(parent, fs::Permissions::from_mode(0o700))?; + + let mut tmp = tempfile::NamedTempFile::new_in(parent)?; + tmp.write_all(&serde_json::to_vec(stored)?)?; + tmp.flush()?; + fs::set_permissions(tmp.path(), fs::Permissions::from_mode(0o600))?; + tmp.persist(path)?; + Ok(()) +} + +pub fn clear(path: &Path) { + let _ = fs::remove_file(path); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample() -> StoredCookie { + StoredCookie::new( + "vpn.example.com".to_string(), + "alice".to_string(), + "gw1.example.com".to_string(), + AuthCookieCredential::new("alice", "user-auth", "prelogon-auth"), + ) + } + + #[test] + fn roundtrip_and_mode_0600() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("cookie.json"); + let s = sample(); + save(&path, &s).unwrap(); + + let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600, "cookie file must be mode 0600, got {:o}", mode); + + let loaded = load(&path, "vpn.example.com").unwrap(); + assert_eq!(loaded.username, "alice"); + assert_eq!(loaded.last_gateway, "gw1.example.com"); + assert_eq!(loaded.auth_cookie.user_auth_cookie(), "user-auth"); + + assert!(load(&path, "other.example.com").is_none(), "must reject mismatched server"); + clear(&path); + assert!(!path.exists()); + } + + #[test] + fn rejects_version_mismatch() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("cookie.json"); + let mut s = sample(); + s.version = STORE_VERSION + 1; + save(&path, &s).unwrap(); + assert!(load(&path, "vpn.example.com").is_none()); + } +} diff --git a/crates/gpapi/src/lib.rs b/crates/gpapi/src/lib.rs index 58f764b..c318242 100644 --- a/crates/gpapi/src/lib.rs +++ b/crates/gpapi/src/lib.rs @@ -1,4 +1,5 @@ pub mod auth; +pub mod cookie_store; pub mod credential; pub mod error; pub mod gateway;