refactor: update session extension flow

This commit is contained in:
Kevin Yue committed 2026-05-06 23:20:57 +08:00
1 parent cdcf03ff2f
commit ab58dd6cec
19 files changed
+927 -419

No files matched your search

+2
View File
@@ -34,6 +34,8 @@ md5.workspace = true
sha256.workspace = true
machine-uid.workspace = true
uuid = { workspace = true, features = ["v5"] }
chrono.workspace = true
humantime.workspace = true
# Optional dependencies for features
tauri = { workspace = true, optional = true }
+66 -6
View File
@@ -1,4 +1,4 @@
use std::borrow::Cow;
use std::{borrow::Cow, collections::HashMap};
use anyhow::bail;
use log::{debug, info, warn};
@@ -19,17 +19,30 @@ pub enum GatewayLogin {
}
pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParams) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, false).await
}
pub async fn gateway_login_with_extend_lifetime(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
) -> anyhow::Result<GatewayLogin> {
gateway_login_with_options(gateway, cred, gp_params, true).await
}
async fn gateway_login_with_options(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
extend_lifetime: bool,
) -> anyhow::Result<GatewayLogin> {
let url = normalize_server(gateway)?;
let gateway = remove_url_scheme(&url);
let login_url = format!("{}/ssl-vpn/login.esp", url);
let client = Client::try_from(gp_params)?;
let mut params = cred.to_params();
let extra_params = gp_params.to_params();
params.extend(extra_params);
params.insert("server", &gateway);
let params = build_gateway_login_params(&gateway, cred, gp_params, extend_lifetime);
info!("Perform gateway login, user_agent: {}", gp_params.user_agent());
@@ -67,6 +80,33 @@ pub async fn gateway_login(gateway: &str, cred: &Credential, gp_params: &GpParam
Ok(GatewayLogin::Cookie(cookie))
}
fn build_gateway_login_params(
gateway: &str,
cred: &Credential,
gp_params: &GpParams,
extend_lifetime: bool,
) -> HashMap<String, String> {
let mut params = cred
.to_params()
.into_iter()
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect::<HashMap<_, _>>();
params.extend(
gp_params
.to_params()
.into_iter()
.map(|(key, value)| (key.to_string(), value.to_string())),
);
params.insert("server".to_string(), gateway.to_string());
if extend_lifetime {
params.insert("extend-lifetime".to_string(), "true".to_string());
}
params
}
fn build_gateway_token(element: &Element, computer: &str) -> anyhow::Result<String> {
let args = element
.descendants("argument")
@@ -165,6 +205,26 @@ thisForm.inputStr.value = "5ef64e83000119ed";"#;
assert_eq!(input_str, "5ef64e83000119ed");
}
#[test]
fn normal_gateway_login_params_do_not_extend_lifetime() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, false);
assert!(!params.contains_key("extend-lifetime"));
}
#[test]
fn extension_gateway_login_params_extend_lifetime() {
let cred = Credential::Password(crate::credential::PasswordCredential::new("alice", "secret"));
let gp_params = GpParams::builder().build();
let params = build_gateway_login_params("vpn.example.com", &cred, &gp_params, true);
assert_eq!(params.get("extend-lifetime").map(String::as_str), Some("true"));
}
#[test]
fn gateway_token_keeps_upstream_cookie_fields() {
let res = r#"
+1 -1
View File
@@ -4,8 +4,8 @@ mod parse_gateways;
pub mod session;
pub use login::*;
pub use session::*;
pub(crate) use parse_gateways::*;
pub use session::*;
use serde::{Deserialize, Serialize};
use specta::Type;
+70 -226
View File
@@ -9,22 +9,43 @@ use reqwest::Client;
use xmltree::Element;
use crate::{
error::PortalError,
credential::Credential,
gateway::login::{GatewayLogin, gateway_login_with_extend_lifetime},
gp_params::GpParams,
service::{
session::{SessionInfo, SessionRequestArgs, SessionWarning},
},
session::SessionRequestArgs,
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(Clone)]
pub struct SessionExtensionAuth {
credential: Credential,
gp_params: GpParams,
}
impl SessionExtensionAuth {
pub fn new(credential: Credential, gp_params: GpParams) -> Self {
Self { credential, gp_params }
}
}
impl std::fmt::Debug for SessionExtensionAuth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SessionExtensionAuth")
.field("username", &self.credential.username())
.field("gp_params", &"<redacted>")
.finish()
}
}
#[derive(Debug, Clone)]
pub struct SessionContext {
server: String,
portal: String,
session_args: SessionRequestArgs,
extension_auth: Option<SessionExtensionAuth>,
}
impl SessionContext {
@@ -33,9 +54,15 @@ impl SessionContext {
server,
portal,
session_args,
extension_auth: None,
}
}
pub fn with_extension_auth(mut self, extension_auth: SessionExtensionAuth) -> Self {
self.extension_auth = Some(extension_auth);
self
}
pub fn server(&self) -> &str {
&self.server
}
@@ -47,35 +74,15 @@ impl SessionContext {
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}"));
fn extension_auth(&self) -> Option<&SessionExtensionAuth> {
self.extension_auth.as_ref()
}
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> {
pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<()> {
extend_session_lifetime(ctx).await?;
let base_url = normalize_server(ctx.server())?;
let client = build_session_client(ctx.session_args())?;
let form = build_extend_session_form(ctx)?;
@@ -91,15 +98,27 @@ pub async fn extend_session(ctx: &SessionContext) -> anyhow::Result<SessionInfo>
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)
}
"success" => Ok(()),
status => bail!("Extend session rejected: {status}"),
}
}
async fn extend_session_lifetime(ctx: &SessionContext) -> anyhow::Result<()> {
let auth = ctx
.extension_auth()
.ok_or_else(|| anyhow::anyhow!("Session extension requires retained gateway auth state"))?;
let login = gateway_login_with_extend_lifetime(ctx.server(), &auth.credential, &auth.gp_params).await?;
validate_extension_login(login)
}
fn validate_extension_login(login: GatewayLogin) -> anyhow::Result<()> {
match login {
GatewayLogin::Cookie(_) => Ok(()),
GatewayLogin::Mfa(_, _) => bail!("Session extension requires an interactive gateway challenge"),
}
}
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());
@@ -113,109 +132,6 @@ fn build_session_client(args: &SessionRequestArgs) -> anyhow::Result<Client> {
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())?)
}
@@ -249,10 +165,7 @@ fn unix_timestamp() -> u64 {
#[cfg(test)]
mod tests {
use crate::{
gp_params::ClientOs,
service::session::SessionRequestArgs,
};
use crate::{gp_params::ClientOs, session::SessionRequestArgs};
use super::*;
@@ -265,87 +178,7 @@ mod tests {
}
#[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() {
fn active_session_context_preserves_connect_args_for_extension() {
let session_args = build_session_args();
let ctx = SessionContext::new(
"vpn.example.com".to_string(),
@@ -353,11 +186,12 @@ mod tests {
session_args,
);
let form = build_session_form(ctx.session_args()).unwrap();
let form = parse_cookie_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"));
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]
@@ -399,4 +233,14 @@ mod tests {
"Malformed extend session response"
);
}
#[test]
fn rejects_extension_login_mfa_challenge() {
assert_eq!(
validate_extension_login(GatewayLogin::Mfa("MFA required".to_string(), "input".to_string()))
.unwrap_err()
.to_string(),
"Session extension requires an interactive gateway challenge"
);
}
}
+1
View File
@@ -6,6 +6,7 @@ pub mod gp_params;
pub mod portal;
pub mod process;
pub mod service;
pub mod session;
pub mod utils;
#[cfg(feature = "logger")]
-1
View File
@@ -1,5 +1,4 @@
pub mod event;
pub mod request;
pub mod session;
pub mod vpn_env;
pub mod vpn_state;
-127
View File
@@ -1,127 +0,0 @@
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,
}
+51 -2
View File
@@ -1,7 +1,7 @@
use serde::{Deserialize, Serialize};
use specta::Type;
use crate::gateway::Gateway;
use crate::{gateway::Gateway, session::SessionInfo};
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
pub struct ConnectInfo {
@@ -10,6 +10,30 @@ pub struct ConnectInfo {
gateways: Vec<Gateway>,
}
#[derive(Debug, Deserialize, Serialize, Type, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ConnectedInfo {
info: Box<ConnectInfo>,
session_info: Option<SessionInfo>,
}
impl ConnectedInfo {
pub fn new(info: ConnectInfo, session_info: Option<SessionInfo>) -> Self {
Self {
info: Box::new(info),
session_info,
}
}
pub fn info(&self) -> &ConnectInfo {
&self.info
}
pub fn session_info(&self) -> Option<&SessionInfo> {
self.session_info.as_ref()
}
}
impl ConnectInfo {
pub fn new(portal: String, gateway: Gateway, gateways: Vec<Gateway>) -> Self {
Self {
@@ -29,6 +53,31 @@ impl ConnectInfo {
pub enum VpnState {
Disconnected,
Connecting(Box<ConnectInfo>),
Connected(Box<ConnectInfo>),
Connected(Box<ConnectedInfo>),
Disconnecting,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn connected_state_serializes_session_info() {
let gateway = Gateway::new("vpn".to_string(), "vpn.example.com".to_string());
let connect_info = ConnectInfo::new("portal.example.com".to_string(), gateway.clone(), vec![gateway]);
let session_info = SessionInfo {
lifetime_secs: Some(43_200),
allow_extend_session: true,
..Default::default()
};
let value = serde_json::to_value(VpnState::Connected(Box::new(ConnectedInfo::new(
connect_info,
Some(session_info),
))))
.unwrap();
assert_eq!(value["connected"]["sessionInfo"]["lifetimeSecs"], 43_200);
assert_eq!(value["connected"]["sessionInfo"]["allowExtendSession"], true);
}
}
+302
View File
@@ -0,0 +1,302 @@
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use chrono::{Local, TimeZone};
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,
}
impl SessionInfo {
pub fn with_computed_human_times(mut self) -> Self {
self.expires_in_human = build_human_readable_expiry(self.user_expires, self.lifetime_secs);
self
}
pub fn from_vpn_session_fields(
lifetime_secs: Option<u32>,
user_expires: Option<u32>,
lifetime_warning: Option<SessionWarning>,
allow_extend_session: bool,
) -> Self {
Self {
lifetime_secs,
user_expires,
expires_in_human: None,
lifetime_warning,
inactivity_warning: None,
admin_logout_message: None,
allow_extend_session,
}
.with_computed_human_times()
}
pub fn rescheduled_after_extension(&self) -> Option<Self> {
let lifetime_secs = self.lifetime_secs?;
let mut session_info = self.clone();
session_info.user_expires = Some(unix_timestamp().saturating_add(lifetime_secs));
Some(session_info.with_computed_human_times())
}
pub fn log_summary(&self) -> String {
let lifetime_secs = self
.lifetime_secs
.map(format_secs_with_duration)
.unwrap_or_else(|| "none".to_string());
let user_expires = self
.user_expires
.map(format_epoch_with_local_time)
.unwrap_or_else(|| "none".to_string());
let lifetime_warning_prior = self
.lifetime_warning
.as_ref()
.map(|warning| format_secs_with_duration(warning.prior_secs))
.unwrap_or_else(|| "none".to_string());
format!(
"lifetime_secs={lifetime_secs}, user_expires={user_expires}, lifetime_warning_prior={lifetime_warning_prior}, allow_extend_session={}",
self.allow_extend_session
)
}
}
pub fn format_duration_secs(total_secs: u32) -> String {
humantime::format_duration(Duration::from_secs(total_secs as u64)).to_string()
}
fn format_secs_with_duration(secs: u32) -> String {
format!("{secs} ({})", format_duration_secs(secs))
}
fn format_epoch_with_local_time(epoch: u32) -> String {
let local_time = Local
.timestamp_opt(epoch as i64, 0)
.single()
.map(|time| time.format("%Y-%m-%d %H:%M:%S").to_string())
.unwrap_or_else(|| "invalid time".to_string());
let now = unix_timestamp();
let relative = if epoch >= now {
format!("in {}", format_duration_secs(epoch.saturating_sub(now)))
} else {
format!("{} ago", format_duration_secs(now.saturating_sub(epoch)))
};
format!("{epoch} ({local_time}, {relative})")
}
fn build_human_readable_expiry(user_expires: Option<u32>, lifetime_secs: Option<u32>) -> Option<String> {
if let Some(user_expires) = user_expires {
let now = unix_timestamp();
return Some(format_duration_secs(user_expires.saturating_sub(now)));
}
lifetime_secs.map(format_duration_secs)
}
fn unix_timestamp() -> u32 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as u32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_duration_secs() {
assert_eq!(format_duration_secs(43_200), "12h");
assert_eq!(format_duration_secs(1_830), "30m 30s");
}
#[test]
fn logs_session_info_with_human_readable_times() {
let info = SessionInfo {
lifetime_secs: Some(43_200),
user_expires: Some(unix_timestamp().saturating_add(43_200)),
lifetime_warning: Some(SessionWarning {
prior_secs: 1_800,
message: "Session expires soon".to_string(),
}),
allow_extend_session: true,
..Default::default()
};
let summary = info.log_summary();
assert!(summary.contains("lifetime_secs=43200 (12h)"));
assert!(summary.contains("user_expires="));
assert!(summary.contains(", in "));
assert!(summary.contains("lifetime_warning_prior=1800 (30m)"));
assert!(summary.contains("allow_extend_session=true"));
}
#[test]
fn computes_expires_in_human_from_lifetime_or_epoch() {
let from_lifetime = SessionInfo {
lifetime_secs: Some(43_200),
..Default::default()
}
.with_computed_human_times();
assert_eq!(from_lifetime.expires_in_human.as_deref(), Some("12h"));
let from_epoch = SessionInfo {
user_expires: Some(unix_timestamp().saturating_add(1_830)),
..Default::default()
}
.with_computed_human_times();
assert!(
from_epoch
.expires_in_human
.as_deref()
.is_some_and(|value| value.starts_with("30m"))
);
}
#[test]
fn reschedules_after_extension_from_lifetime() {
let now = unix_timestamp();
let info = SessionInfo {
lifetime_secs: Some(7_200),
user_expires: Some(now.saturating_add(1_830)),
..Default::default()
};
let next = info.rescheduled_after_extension().unwrap();
assert!(
next
.user_expires
.is_some_and(|expires| expires >= now.saturating_add(7_200))
);
assert!(next.expires_in_human.is_some());
}
#[test]
fn reschedule_after_extension_requires_lifetime() {
assert!(SessionInfo::default().rescheduled_after_extension().is_none());
}
}