feat: add gpclient session refresh support (#595)

* Add session info events for GUI warnings

* fix macOS local build

* fix session expiry parsing

* chore: remove session info debug logging

* fix: decouple session info from vpn connect

* refactor: share gpapi response helpers

* fix: restore blocking session info fetch

* refactor: remove service session info flow

* refactor: share session protocol helpers

* refactor: separate cli session runtime
This commit is contained in:
Kevin Yue committed 2026-05-06 23:20:57 +08:00
1 parent 1d715f059d
commit cdcf03ff2f
13 files changed
+800 -16

No files matched your search

+53 -6
View File
@@ -1,4 +1,9 @@
use std::{borrow::Cow, cell::RefCell, fs, sync::Arc};
use std::{
borrow::Cow,
cell::RefCell,
fs,
sync::{Arc, Mutex},
};
use anyhow::{Context, bail};
use clap::Args;
@@ -20,8 +25,13 @@ use gpapi::{
use inquire::{Password, PasswordDisplayMode, Select, Text};
use log::{info, warn};
use openconnect::Vpn;
use tokio::{runtime::Handle, task::JoinHandle};
use crate::{GP_CLIENT_LOCK_FILE, cli::SharedArgs};
use crate::{
GP_CLIENT_LOCK_FILE,
cli::SharedArgs,
session::{SessionContextInput, build_session_context, spawn_session_runtime},
};
#[derive(Args)]
pub(crate) struct ConnectArgs {
@@ -344,7 +354,7 @@ impl<'a> ConnectHandler<'a> {
// use the version from the portal config if available
let client_version = self.args.client_version.as_deref().or_else(|| portal_config.version());
self.connect_gateway(gateway, &cookie, client_version).await
self.connect_gateway(portal, gateway, &cookie, client_version).await
}
async fn connect_gateway_with_prelogin(&self, gateway: &str) -> anyhow::Result<()> {
@@ -361,7 +371,7 @@ impl<'a> ConnectHandler<'a> {
// When logging in to a gateway directly, there is no portal config to get the client version from
let client_version = self.args.client_version.as_deref();
self.connect_gateway(gateway, &cookie, client_version).await
self.connect_gateway(gateway, gateway, &cookie, client_version).await
}
async fn login_gateway(&self, gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<String> {
@@ -381,7 +391,13 @@ impl<'a> ConnectHandler<'a> {
}
}
async fn connect_gateway(&self, gateway: &str, cookie: &str, client_version: Option<&str>) -> anyhow::Result<()> {
async fn connect_gateway(
&self,
portal: &str,
gateway: &str,
cookie: &str,
client_version: Option<&str>,
) -> anyhow::Result<()> {
let mtu = self.args.mtu.unwrap_or(0);
let (hip, csd_wrapper) = self.determine_hip_script();
let hip_user = self.determine_hip_user();
@@ -390,6 +406,19 @@ impl<'a> ConnectHandler<'a> {
let os = ClientOs::from(&self.args.os).to_openconnect_os().to_owned();
let os_version = self.args.os_version().to_owned();
let client_version = client_version.map(|s| s.to_owned());
let session_ctx = build_session_context(SessionContextInput {
portal: portal.to_string(),
gateway: gateway.to_string(),
cookie: cookie.to_string(),
user_agent: self.user_agent().into_owned(),
os: ClientOs::from(&self.args.os),
os_version: os_version.clone(),
client_version: client_version.clone(),
certificate: self.args.certificate.clone(),
sslkey: self.args.sslkey.clone(),
key_password: self.latest_key_password.borrow().clone(),
disable_ipv6: self.args.disable_ipv6,
});
let vpn = Vpn::builder(gateway, cookie)
.script(self.args.script.clone())
.interface(self.args.interface.clone())
@@ -415,6 +444,11 @@ impl<'a> ConnectHandler<'a> {
let vpn = Arc::new(vpn);
let vpn_clone = vpn.clone();
let runtime_handle = Handle::current();
let session_ctx = Arc::new(Mutex::new(Some(session_ctx)));
let session_task: Arc<Mutex<Option<JoinHandle<()>>>> = Arc::new(Mutex::new(None));
let session_task_on_connect = Arc::clone(&session_task);
let session_ctx_on_connect = Arc::clone(&session_ctx);
// Listen for the interrupt signal in the background
tokio::spawn(async move {
@@ -423,7 +457,20 @@ impl<'a> ConnectHandler<'a> {
vpn_clone.disconnect();
});
vpn.connect(write_pid_file);
vpn.connect(move || {
write_pid_file();
let Some(session_ctx) = session_ctx_on_connect.lock().unwrap().take() else {
return;
};
let task = spawn_session_runtime(&runtime_handle, session_ctx);
session_task_on_connect.lock().unwrap().replace(task);
});
if let Some(task) = session_task.lock().unwrap().take() {
task.abort();
}
if fs::metadata(GP_CLIENT_LOCK_FILE).is_ok() {
info!("Removing PID file");
+1
View File
@@ -3,6 +3,7 @@ mod connect;
mod disconnect;
mod hip;
mod launch_gui;
mod session;
pub(crate) const GP_CLIENT_LOCK_FILE: &str = "/var/run/gpclient.lock";
+201
View File
@@ -0,0 +1,201 @@
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use common::constants::GP_CLIENT_VERSION;
use gpapi::{
gateway::{SessionContext, extend_session, retrieve_session_info_for_gateway},
gp_params::ClientOs,
service::session::{SessionInfo, SessionRequestArgs},
};
use log::{info, warn};
use tokio::{runtime::Handle, task::JoinHandle};
#[derive(Debug, PartialEq, Eq)]
struct SessionWarningSchedule {
delay: Duration,
message: String,
should_auto_extend: bool,
}
pub(crate) struct SessionContextInput {
pub(crate) portal: String,
pub(crate) gateway: String,
pub(crate) cookie: String,
pub(crate) user_agent: String,
pub(crate) os: ClientOs,
pub(crate) os_version: String,
pub(crate) client_version: Option<String>,
pub(crate) certificate: Option<String>,
pub(crate) sslkey: Option<String>,
pub(crate) key_password: Option<String>,
pub(crate) disable_ipv6: bool,
}
pub(crate) fn build_session_context(input: SessionContextInput) -> SessionContext {
let session_args = SessionRequestArgs::new(input.cookie)
.with_user_agent(Some(input.user_agent))
.with_os(Some(input.os))
.with_os_version(Some(input.os_version))
.with_client_version(Some(
input.client_version.unwrap_or_else(|| GP_CLIENT_VERSION.to_string()),
))
.with_certificate(input.certificate)
.with_sslkey(input.sslkey)
.with_key_password(input.key_password)
.with_disable_ipv6(input.disable_ipv6);
SessionContext::new(input.gateway, input.portal, session_args)
}
pub(crate) fn spawn_session_runtime(handle: &Handle, session_ctx: SessionContext) -> JoinHandle<()> {
handle.spawn(run_session_runtime(session_ctx))
}
async fn run_session_runtime(session_ctx: SessionContext) {
let mut session_info = match retrieve_session_info_for_gateway(session_ctx.server(), session_ctx.session_args()).await {
Ok(session_info) => session_info,
Err(err) => {
warn!("Failed to retrieve session info: {}", err);
return;
}
};
loop {
let Some(schedule) = build_session_warning_schedule(&session_info) else {
info!("No session warning schedule provided by the gateway");
return;
};
tokio::time::sleep(schedule.delay).await;
eprintln!("\nWARNING: {}", schedule.message);
if !schedule.should_auto_extend {
info!("Session extension is not allowed by the gateway");
return;
}
info!("Attempting to extend the session");
match extend_session(&session_ctx).await {
Ok(next_session_info) => {
eprintln!("Session extended.");
if warning_due_immediately(&next_session_info) {
warn!("Session warning remained due after extension, stopping automatic extension");
return;
}
session_info = next_session_info;
}
Err(err) => {
warn!("Failed to extend session: {}", err);
eprintln!("WARNING: Failed to extend session: {}", err);
return;
}
}
}
}
fn build_session_warning_schedule(session_info: &SessionInfo) -> Option<SessionWarningSchedule> {
let warning = session_info.lifetime_warning.as_ref()?;
let warning_secs = if let Some(user_expires) = session_info.user_expires {
let now = unix_timestamp();
user_expires.saturating_sub(warning.prior_secs).saturating_sub(now)
} else if let Some(lifetime_secs) = session_info.lifetime_secs {
lifetime_secs.saturating_sub(warning.prior_secs)
} else {
return None;
};
Some(SessionWarningSchedule {
delay: Duration::from_secs(warning_secs as u64),
message: warning.message.clone(),
should_auto_extend: session_info.allow_extend_session,
})
}
fn warning_due_immediately(session_info: &SessionInfo) -> bool {
build_session_warning_schedule(session_info)
.map(|schedule| schedule.delay.is_zero())
.unwrap_or(false)
}
fn unix_timestamp() -> u32 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as u32
}
#[cfg(test)]
mod tests {
use super::*;
use gpapi::service::session::SessionWarning;
fn sample_session_info(user_expires: Option<u32>, allow_extend_session: bool) -> SessionInfo {
SessionInfo {
user_expires,
lifetime_warning: Some(SessionWarning {
prior_secs: 1800,
message: "Session expires soon".to_string(),
}),
allow_extend_session,
..Default::default()
}
}
#[test]
fn builds_warning_schedule_for_auto_extend() {
let session_info = sample_session_info(Some(unix_timestamp() + 1830), true);
let schedule = build_session_warning_schedule(&session_info).unwrap();
assert_eq!(schedule.message, "Session expires soon");
assert!(schedule.delay <= Duration::from_secs(30));
assert!(schedule.should_auto_extend);
}
#[test]
fn builds_warning_schedule_without_auto_extend() {
let session_info = sample_session_info(Some(unix_timestamp() + 1830), false);
let schedule = build_session_warning_schedule(&session_info).unwrap();
assert!(!schedule.should_auto_extend);
}
#[test]
fn warning_due_immediately_when_deadline_has_passed() {
let session_info = sample_session_info(Some(unix_timestamp() + 1800), true);
assert!(warning_due_immediately(&session_info));
}
#[test]
fn builds_session_context_from_cli_runtime_values() {
let ctx = build_session_context(SessionContextInput {
portal: "portal.example.com".to_string(),
gateway: "vpn.example.com".to_string(),
cookie: "authcookie=AUTH".to_string(),
user_agent: "UA".to_string(),
os: ClientOs::Mac,
os_version: "macOS 15.0".to_string(),
client_version: Some("6.3.1-12".to_string()),
certificate: Some("/tmp/client.pem".to_string()),
sslkey: Some("/tmp/client.key".to_string()),
key_password: Some("secret".to_string()),
disable_ipv6: true,
});
assert_eq!(ctx.portal(), "portal.example.com");
assert_eq!(ctx.server(), "vpn.example.com");
assert_eq!(ctx.session_args().cookie(), "authcookie=AUTH");
assert_eq!(ctx.session_args().user_agent().as_deref(), Some("UA"));
assert!(matches!(ctx.session_args().os(), Some(ClientOs::Mac)));
assert_eq!(ctx.session_args().os_version().as_deref(), Some("macOS 15.0"));
assert_eq!(ctx.session_args().client_version().as_deref(), Some("6.3.1-12"));
assert_eq!(ctx.session_args().certificate().as_deref(), Some("/tmp/client.pem"));
assert_eq!(ctx.session_args().sslkey().as_deref(), Some("/tmp/client.key"));
assert_eq!(ctx.session_args().key_password().as_deref(), Some("secret"));
assert!(ctx.session_args().disable_ipv6());
}
}
+1 -1
View File
@@ -159,7 +159,7 @@ mod signals {
pub async fn handle_signals(vpn_ctx: Arc<VpnTaskContext>, ws_ctx: Arc<WsServerContext>) {
use gpapi::service::event::WsEvent;
use tokio::signal::unix::{Signal, SignalKind, signal};
use tokio::signal::unix::{signal, Signal, SignalKind};
let (mut user_sig1, mut user_sig2) = match || -> anyhow::Result<(Signal, Signal)> {
let user_sig1 = signal(SignalKind::user_defined1())?;
+1 -2
View File
@@ -9,7 +9,7 @@ use gpapi::{
};
use log::{info, warn};
use openconnect::Vpn;
use tokio::sync::{RwLock, mpsc, oneshot, watch};
use tokio::sync::{mpsc, oneshot, watch, RwLock};
use tokio_util::sync::CancellationToken;
pub(crate) struct VpnTaskContext {
@@ -112,7 +112,6 @@ impl VpnTaskContext {
} else {
info!("VPN is not connected, skip disconnect");
self.vpn_state_tx.send(VpnState::Disconnected).ok();
false
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ use openconnect::{find_csd_wrapper, find_vpnc_script};
use serde::de::DeserializeOwned;
use tokio::{
net::TcpListener,
sync::{RwLock, mpsc, watch},
sync::{mpsc, watch, RwLock},
};
use tokio_util::sync::CancellationToken;
+2
View File
@@ -1,8 +1,10 @@
pub mod hip;
mod login;
mod parse_gateways;
pub mod session;
pub use login::*;
pub use session::*;
pub(crate) use parse_gateways::*;
use serde::{Deserialize, Serialize};
+402
View File
@@ -0,0 +1,402 @@
use std::{
collections::HashMap,
time::{SystemTime, UNIX_EPOCH},
};
use anyhow::bail;
use log::{info, warn};
use reqwest::Client;
use xmltree::Element;
use crate::{
error::PortalError,
gp_params::GpParams,
service::{
session::{SessionInfo, SessionRequestArgs, SessionWarning},
},
utils::{normalize_server, parse_gp_response, xml::ElementExt},
};
const EXTEND_SESSION_MESSAGE: &str = "User Session Extension";
const EXTEND_SESSION_COMMENT: &str = "User extends the login lifetime";
#[derive(Debug, Clone)]
pub struct SessionContext {
server: String,
portal: String,
session_args: SessionRequestArgs,
}
impl SessionContext {
pub fn new(server: String, portal: String, session_args: SessionRequestArgs) -> Self {
Self {
server,
portal,
session_args,
}
}
pub fn server(&self) -> &str {
&self.server
}
pub fn portal(&self) -> &str {
&self.portal
}
pub fn session_args(&self) -> &SessionRequestArgs {
&self.session_args
}
}
pub async fn retrieve_session_info_for_gateway(server: &str, args: &SessionRequestArgs) -> anyhow::Result<SessionInfo> {
let base_url = normalize_server(server)?;
let client = build_session_client(args)?;
let form = build_session_form(args)?;
let url = format!("{base_url}/ssl-vpn/getconfig.esp");
info!("Retrieving gateway session info");
let response = client.post(&url).form(&form).send().await.map_err(|err| {
warn!("Network error: {:?}", err);
anyhow::anyhow!(PortalError::NetworkError(err))
})?;
let response = parse_gp_response(response).await?;
let response = response.trim();
if !response.starts_with('<') {
return Err(anyhow::anyhow!("Gateway session info error: {response}"));
}
let root = Element::parse(response.as_bytes())?;
let session_info = parse_session_info(&root)?;
info!("Parsed session info: {:?}", session_info);
Ok(session_info)
}
pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<SessionInfo> {
let base_url = normalize_server(ctx.server())?;
let client = build_session_client(ctx.session_args())?;
let form = build_extend_session_form(ctx)?;
let url = format!("{base_url}/ssl-vpn/agentmessage.esp");
info!("Sending extend-session request");
let response = client.post(&url).form(&form).send().await?;
let response = parse_gp_response(response).await?;
let root = Element::parse(response.as_bytes())?;
let status = parse_extend_session_status(&root, &response)?;
info!("Extend-session gateway response status: {}", status);
match status.as_str() {
"success" => {
let session_info = retrieve_session_info_for_gateway(ctx.server(), ctx.session_args()).await?;
info!("Extend-session refreshed session info: {:?}", session_info);
Ok(session_info)
}
status => bail!("Extend session rejected: {status}"),
}
}
fn build_session_client(args: &SessionRequestArgs) -> anyhow::Result<Client> {
let mut builder = GpParams::builder();
builder.user_agent(args.user_agent().as_deref().unwrap_or_default());
builder.client_os(args.os().unwrap_or_default());
builder.os_version(args.os_version());
builder.client_version(args.client_version());
builder.certificate(args.certificate());
builder.sslkey(args.sslkey());
builder.key_password(args.key_password());
Client::try_from(&builder.build())
}
fn build_session_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
let mut form = HashMap::from([
("client-type".to_string(), "1".to_string()),
("protocol-version".to_string(), "p1".to_string()),
("internal".to_string(), "no".to_string()),
(
"app-version".to_string(),
args.client_version().unwrap_or_else(|| "6.3.0-33".to_string()),
),
(
"ipv6-support".to_string(),
if args.disable_ipv6() { "no" } else { "yes" }.to_string(),
),
(
"clientos".to_string(),
args.os().unwrap_or_default().as_str().to_string(),
),
("hmac-algo".to_string(), "sha1,md5,sha256".to_string()),
("enc-algo".to_string(), "aes-128-cbc,aes-256-cbc".to_string()),
]);
if let Some(os_version) = args.os_version() {
form.insert("os-version".to_string(), os_version);
}
form.extend(serde_urlencoded::from_str::<HashMap<String, String>>(args.cookie())?);
Ok(form)
}
fn parse_session_info(root: &Element) -> anyhow::Result<SessionInfo> {
let user_expires = parse_optional_u32(root, "user-expires")?.or(parse_optional_u32(root, "user_expires")?);
let lifetime_secs = parse_optional_u32(root, "lifetime")?;
Ok(SessionInfo {
lifetime_secs,
user_expires,
expires_in_human: build_human_readable_expiry(user_expires, lifetime_secs),
lifetime_warning: parse_warning(root, "lifetime-notify-prior", "lifetime-notify-message")?,
inactivity_warning: parse_warning(root, "inactivity-notify-prior", "inactivity-notify-message")?,
admin_logout_message: root.descendant_text("admin-logout-notify-message"),
allow_extend_session: parse_bool_flag(root.descendant_text("allow-extend-session").as_deref()),
})
}
fn parse_warning(root: &Element, prior_tag: &str, message_tag: &str) -> anyhow::Result<Option<SessionWarning>> {
let prior_secs = parse_optional_u32(root, prior_tag)?;
let message = root.descendant_text(message_tag).filter(|value| !value.is_empty());
Ok(match (prior_secs, message) {
(Some(prior_secs), Some(message)) => Some(SessionWarning { prior_secs, message }),
_ => None,
})
}
fn parse_optional_u32(root: &Element, tag: &str) -> anyhow::Result<Option<u32>> {
let Some(value) = root.descendant_text(tag) else {
return Ok(None);
};
let value = value.trim();
if value.is_empty() {
return Ok(None);
}
Ok(Some(value.parse()?))
}
fn parse_bool_flag(value: Option<&str>) -> bool {
matches!(value, Some("yes" | "true" | "1"))
}
fn build_human_readable_expiry(user_expires: Option<u32>, lifetime_secs: Option<u32>) -> Option<String> {
if let Some(user_expires) = user_expires {
let now = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();
return Some(format_human_duration((user_expires as u64).saturating_sub(now)));
}
lifetime_secs.map(|secs| format_human_duration(secs as u64))
}
fn format_human_duration(total_secs: u64) -> String {
let days = total_secs / 86_400;
let hours = (total_secs % 86_400) / 3_600;
let minutes = (total_secs % 3_600) / 60;
let seconds = total_secs % 60;
let mut parts = Vec::new();
if days > 0 {
parts.push(format!("{days}days"));
}
if hours > 0 {
parts.push(format!("{hours}h"));
}
if minutes > 0 {
parts.push(format!("{minutes}m"));
}
if seconds > 0 || parts.is_empty() {
parts.push(format!("{seconds}s"));
}
parts.join(" ")
}
fn parse_cookie_form(args: &SessionRequestArgs) -> anyhow::Result<HashMap<String, String>> {
Ok(serde_urlencoded::from_str(args.cookie())?)
}
fn build_extend_session_form(ctx: &SessionContext) -> anyhow::Result<HashMap<String, String>> {
let mut form = parse_cookie_form(ctx.session_args())?;
form.insert("portal".to_string(), ctx.portal().to_string());
form.insert("timestamp".to_string(), unix_timestamp().to_string());
form.insert("message".to_string(), EXTEND_SESSION_MESSAGE.to_string());
form.insert("comment".to_string(), EXTEND_SESSION_COMMENT.to_string());
Ok(form)
}
fn parse_extend_session_status(root: &Element, response: &str) -> anyhow::Result<String> {
match root.attr("status") {
Some(status) => Ok(status.to_string()),
None => {
warn!("Malformed extend-session response body: {}", response.trim());
bail!("Malformed extend session response")
}
}
}
fn unix_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
#[cfg(test)]
mod tests {
use crate::{
gp_params::ClientOs,
service::session::SessionRequestArgs,
};
use super::*;
fn build_session_args() -> SessionRequestArgs {
SessionRequestArgs::new("authcookie=AUTH&portal=vpn.example.com&user=alice&preferred-ip=10.0.0.10".to_string())
.with_os(Some(ClientOs::Mac))
.with_os_version(Some("macOS 15.0".to_string()))
.with_client_version(Some("6.3.1-12".to_string()))
.with_disable_ipv6(true)
}
#[test]
fn builds_gateway_session_form() {
let form = build_session_form(&build_session_args()).unwrap();
assert_eq!(form.get("client-type").map(String::as_str), Some("1"));
assert_eq!(form.get("protocol-version").map(String::as_str), Some("p1"));
assert_eq!(form.get("internal").map(String::as_str), Some("no"));
assert_eq!(form.get("app-version").map(String::as_str), Some("6.3.1-12"));
assert_eq!(form.get("ipv6-support").map(String::as_str), Some("no"));
assert_eq!(form.get("clientos").map(String::as_str), Some("Mac"));
assert_eq!(form.get("os-version").map(String::as_str), Some("macOS 15.0"));
assert_eq!(form.get("authcookie").map(String::as_str), Some("AUTH"));
assert_eq!(form.get("portal").map(String::as_str), Some("vpn.example.com"));
assert_eq!(form.get("user").map(String::as_str), Some("alice"));
assert_eq!(form.get("preferred-ip").map(String::as_str), Some("10.0.0.10"));
}
#[test]
fn builds_gateway_session_form_with_ipv6_enabled() {
let args = SessionRequestArgs::new("authcookie=AUTH".to_string()).with_client_version(Some("6.3.1-12".to_string()));
let form = build_session_form(&args).unwrap();
assert_eq!(form.get("ipv6-support").map(String::as_str), Some("yes"));
}
#[test]
fn parses_session_info() {
let xml = r#"
<response>
<lifetime>43200</lifetime>
<user-expires>1776828409</user-expires>
<lifetime-notify-prior>1800</lifetime-notify-prior>
<lifetime-notify-message>The VPN will disconnect after 12 hours.</lifetime-notify-message>
<inactivity-notify-prior>300</inactivity-notify-prior>
<inactivity-notify-message>The VPN will disconnect after 5 minutes of inactivity.</inactivity-notify-message>
<admin-logout-notify-message>Logged out by administrator.</admin-logout-notify-message>
<allow-extend-session>yes</allow-extend-session>
</response>
"#;
let root = Element::parse(xml.as_bytes()).unwrap();
let info = parse_session_info(&root).unwrap();
assert_eq!(info.lifetime_secs, Some(43200));
assert_eq!(info.user_expires, Some(1776828409));
assert!(info.expires_in_human.as_ref().is_some_and(|value| !value.is_empty()));
assert_eq!(info.lifetime_warning.unwrap().prior_secs, 1800);
assert_eq!(info.inactivity_warning.unwrap().prior_secs, 300);
assert_eq!(
info.admin_logout_message.as_deref(),
Some("Logged out by administrator.")
);
assert!(info.allow_extend_session);
}
#[test]
fn parses_allow_extend_session_false() {
let xml = r#"<response><allow-extend-session>no</allow-extend-session></response>"#;
let root = Element::parse(xml.as_bytes()).unwrap();
let info = parse_session_info(&root).unwrap();
assert!(!info.allow_extend_session);
}
#[test]
fn parses_user_expires_underscore_variant() {
let xml = r#"
<response>
<user_expires>1779810767</user_expires>
</response>
"#;
let root = Element::parse(xml.as_bytes()).unwrap();
let info = parse_session_info(&root).unwrap();
assert_eq!(info.user_expires, Some(1779810767));
}
#[test]
fn active_session_context_preserves_connect_args_for_refresh() {
let session_args = build_session_args();
let ctx = SessionContext::new(
"vpn.example.com".to_string(),
"portal.example.com".to_string(),
session_args,
);
let form = build_session_form(ctx.session_args()).unwrap();
assert_eq!(form.get("ipv6-support").map(String::as_str), Some("no"));
assert_eq!(form.get("clientos").map(String::as_str), Some("Mac"));
assert_eq!(form.get("os-version").map(String::as_str), Some("macOS 15.0"));
}
#[test]
fn builds_extend_session_form() {
let session_args = build_session_args();
let ctx = SessionContext::new(
"vpn.example.com".to_string(),
"portal.example.com".to_string(),
session_args,
);
let form = build_extend_session_form(&ctx).unwrap();
assert_eq!(form.get("authcookie").map(String::as_str), Some("AUTH"));
assert_eq!(form.get("portal").map(String::as_str), Some("portal.example.com"));
assert_eq!(form.get("message").map(String::as_str), Some(EXTEND_SESSION_MESSAGE));
assert_eq!(form.get("comment").map(String::as_str), Some(EXTEND_SESSION_COMMENT));
assert!(form.contains_key("timestamp"));
}
#[test]
fn parses_extend_session_status_attribute() {
let root = Element::parse(r#"<response status="success"></response>"#.as_bytes()).unwrap();
assert_eq!(
parse_extend_session_status(&root, r#"<response status="success"></response>"#).unwrap(),
"success"
);
}
#[test]
fn rejects_extend_session_response_without_status() {
let root = Element::parse("<response><result>ok</result></response>".as_bytes()).unwrap();
assert_eq!(
parse_extend_session_status(&root, "<response><result>ok</result></response>")
.unwrap_err()
.to_string(),
"Malformed extend session response"
);
}
}
+1
View File
@@ -1,4 +1,5 @@
pub mod event;
pub mod request;
pub mod session;
pub mod vpn_env;
pub mod vpn_state;
+6 -2
View File
@@ -27,7 +27,7 @@ impl LaunchGuiRequest {
}
}
#[derive(Debug, Deserialize, Serialize, Type)]
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
pub struct ConnectArgs {
cookie: String,
vpnc_script: Option<String>,
@@ -95,6 +95,10 @@ impl ConnectArgs {
self.os.as_ref().map(|os| os.to_openconnect_os().to_string())
}
pub fn os(&self) -> Option<ClientOs> {
self.os.clone()
}
pub fn os_version(&self) -> Option<String> {
self.os_version.clone()
}
@@ -156,7 +160,7 @@ impl ConnectArgs {
}
}
#[derive(Debug, Deserialize, Serialize, Type)]
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
pub struct ConnectRequest {
info: ConnectInfo,
args: ConnectArgs,
+127
View File
@@ -0,0 +1,127 @@
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::gp_params::ClientOs;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct SessionWarning {
pub prior_secs: u32,
pub message: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct SessionRequestArgs {
cookie: String,
user_agent: Option<String>,
os: Option<ClientOs>,
os_version: Option<String>,
client_version: Option<String>,
certificate: Option<String>,
sslkey: Option<String>,
key_password: Option<String>,
disable_ipv6: bool,
}
impl SessionRequestArgs {
pub fn new(cookie: String) -> Self {
Self {
cookie,
user_agent: None,
os: None,
os_version: None,
client_version: None,
certificate: None,
sslkey: None,
key_password: None,
disable_ipv6: false,
}
}
pub fn with_user_agent<T: Into<Option<String>>>(mut self, user_agent: T) -> Self {
self.user_agent = user_agent.into();
self
}
pub fn with_os<T: Into<Option<ClientOs>>>(mut self, os: T) -> Self {
self.os = os.into();
self
}
pub fn with_os_version<T: Into<Option<String>>>(mut self, os_version: T) -> Self {
self.os_version = os_version.into();
self
}
pub fn with_client_version<T: Into<Option<String>>>(mut self, client_version: T) -> Self {
self.client_version = client_version.into();
self
}
pub fn with_certificate<T: Into<Option<String>>>(mut self, certificate: T) -> Self {
self.certificate = certificate.into();
self
}
pub fn with_sslkey<T: Into<Option<String>>>(mut self, sslkey: T) -> Self {
self.sslkey = sslkey.into();
self
}
pub fn with_key_password<T: Into<Option<String>>>(mut self, key_password: T) -> Self {
self.key_password = key_password.into();
self
}
pub fn with_disable_ipv6(mut self, disable_ipv6: bool) -> Self {
self.disable_ipv6 = disable_ipv6;
self
}
pub fn cookie(&self) -> &str {
&self.cookie
}
pub fn user_agent(&self) -> Option<String> {
self.user_agent.clone()
}
pub fn os(&self) -> Option<ClientOs> {
self.os.clone()
}
pub fn os_version(&self) -> Option<String> {
self.os_version.clone()
}
pub fn client_version(&self) -> Option<String> {
self.client_version.clone()
}
pub fn certificate(&self) -> Option<String> {
self.certificate.clone()
}
pub fn sslkey(&self) -> Option<String> {
self.sslkey.clone()
}
pub fn key_password(&self) -> Option<String> {
self.key_password.clone()
}
pub fn disable_ipv6(&self) -> bool {
self.disable_ipv6
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct SessionInfo {
pub lifetime_secs: Option<u32>,
pub user_expires: Option<u32>,
pub expires_in_human: Option<String>,
pub lifetime_warning: Option<SessionWarning>,
pub inactivity_warning: Option<SessionWarning>,
pub admin_logout_message: Option<String>,
pub allow_extend_session: bool,
}
+3 -3
View File
@@ -1,4 +1,4 @@
pub(crate) mod xml;
pub mod xml;
pub mod base64;
pub mod checksum;
@@ -48,7 +48,7 @@ pub fn remove_url_scheme(s: &str) -> String {
#[derive(Error, Debug)]
#[error("GP response error: reason={reason}, status={status}, body={body}")]
pub(crate) struct GpError {
pub struct GpError {
pub status: StatusCode,
pub reason: String,
body: String,
@@ -60,7 +60,7 @@ impl GpError {
}
}
pub(crate) async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError> {
pub async fn parse_gp_response(res: Response) -> anyhow::Result<String, GpError> {
let status = res.status();
if status.is_client_error() || status.is_server_error() {
+1 -1
View File
@@ -1,6 +1,6 @@
use xmltree::Element;
pub(crate) trait ElementExt {
pub trait ElementExt {
/// Recursively find all descendants with the given name
fn descendants(&self, name: &str) -> Vec<&Element>;