feat: release GP Connect 3.3.0 with Native Shell support

This commit is contained in:
Kevin Yue committed 2026-11-05 23:05:14 +08:00
1 parent d12d677208
commit fd08cdbe66
226 files changed
+7700 -5225

No files matched your search

+163
View File
@@ -0,0 +1,163 @@
use super::*;
// ─── ClientOs ────────────────────────────────────────────────────────────────
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Type)]
pub enum ClientOs {
Linux,
Windows,
Mac,
Ios,
}
impl From<&str> for ClientOs {
fn from(os: &str) -> Self {
match os {
"Linux" => ClientOs::Linux,
"Windows" => ClientOs::Windows,
"Mac" => ClientOs::Mac,
"iOS" => ClientOs::Ios,
_ => ClientOs::Linux,
}
}
}
impl ClientOs {
pub fn as_str(&self) -> &'static str {
match self {
ClientOs::Linux => "Linux",
ClientOs::Windows => "Windows",
ClientOs::Mac => "Mac",
ClientOs::Ios => "iOS",
}
}
pub fn to_openconnect_os(&self) -> &str {
match self {
ClientOs::Linux => "linux",
ClientOs::Windows => "win",
ClientOs::Mac => "mac-intel",
ClientOs::Ios => "apple-ios",
}
}
pub fn default_client_version(&self) -> &'static str {
match self {
ClientOs::Linux => GP_CLIENT_VERSION_LINUX,
ClientOs::Windows => GP_CLIENT_VERSION_WINDOWS,
ClientOs::Mac => GP_CLIENT_VERSION_MACOS,
ClientOs::Ios => "6.3.5-28",
}
}
pub(crate) fn default_csc_support(&self) -> bool {
match self {
ClientOs::Linux | ClientOs::Ios => false,
ClientOs::Mac | ClientOs::Windows => true,
}
}
}
// ─── PreloginParamLocation ───────────────────────────────────────────────────
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PreloginParamLocation {
Body,
Query,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PreloginBrowserMode {
Embedded,
External,
}
// ─── WebviewUserAgent ───────────────────────────────────────────────────────
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WebviewUserAgent {
Native {
prefix: String,
transform: WebviewUserAgentTransform,
},
Projected {
prefix: String,
default_user_agent: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WebviewUserAgentTransform {
None,
LinuxPanGpuiVersion,
}
// ─── Target behavior ────────────────────────────────────────────────────────
pub(super) mod target {
use super::*;
pub(in crate::os_profile) fn prelogin_param_location(client_os: ClientOs) -> PreloginParamLocation {
match client_os {
ClientOs::Linux | ClientOs::Mac | ClientOs::Ios => PreloginParamLocation::Body,
ClientOs::Windows => PreloginParamLocation::Query,
}
}
pub(in crate::os_profile) fn saml_password(client_os: ClientOs) -> &'static str {
match client_os {
ClientOs::Linux => "SAMLPASS",
ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => "",
}
}
pub(in crate::os_profile) fn external_browser_os_value(client_os: ClientOs) -> &'static str {
match client_os {
ClientOs::Linux => "4",
ClientOs::Mac => "3",
ClientOs::Windows => "2",
ClientOs::Ios => "0",
}
}
pub(in crate::os_profile) fn supports_macos_plist_csc(client_os: ClientOs) -> bool {
matches!(client_os, ClientOs::Mac)
}
pub(in crate::os_profile) fn supports_linux_process_csc(client_os: ClientOs) -> bool {
matches!(client_os, ClientOs::Linux)
}
pub(in crate::os_profile) fn supports_windows_registry_csc(client_os: ClientOs) -> bool {
matches!(client_os, ClientOs::Windows)
}
pub(in crate::os_profile) fn kerberos_support_in_query(client_os: ClientOs) -> bool {
match client_os {
ClientOs::Linux | ClientOs::Ios => false,
ClientOs::Mac | ClientOs::Windows => true,
}
}
pub(in crate::os_profile) fn os_vendor(client_os: ClientOs) -> &'static str {
match client_os {
ClientOs::Linux => "Linux",
ClientOs::Mac | ClientOs::Ios => "Apple",
ClientOs::Windows => "Microsoft",
}
}
pub(in crate::os_profile) fn webview_user_agent_default(client_os: ClientOs) -> &'static str {
match client_os {
ClientOs::Linux => DEFAULT_LINUX_WEBVIEW_USER_AGENT,
ClientOs::Mac | ClientOs::Ios => DEFAULT_MACOS_WEBVIEW_USER_AGENT,
ClientOs::Windows => DEFAULT_WINDOWS_WEBVIEW_USER_AGENT,
}
}
pub(in crate::os_profile) fn webview_user_agent_transform(client_os: ClientOs) -> WebviewUserAgentTransform {
match client_os {
ClientOs::Linux => WebviewUserAgentTransform::LinuxPanGpuiVersion,
ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => WebviewUserAgentTransform::None,
}
}
}
+26
View File
@@ -0,0 +1,26 @@
use super::ClientOs;
pub(super) const DEFAULT_MACOS_VERSION: &str = "13.4.0";
pub(super) const DEFAULT_LINUX_DISTRO: &str = "Ubuntu 24.04.3 LTS";
pub(super) const DEFAULT_WINDOWS_DISTRO: &str = "Windows 11 Pro";
pub(super) const DEFAULT_WINDOWS_VERSION: &str = "10.0.22631.0";
pub(super) const DEFAULT_LINUX_WEBVIEW_USER_AGENT: &str =
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/602.1 (KHTML, like Gecko) PanGPUI Version/10.0 Safari/602.1";
pub(super) const DEFAULT_MACOS_WEBVIEW_USER_AGENT: &str =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko)";
pub(super) const DEFAULT_WINDOWS_WEBVIEW_USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36 Edg/144.0.0.0";
pub(crate) fn os_version(os: ClientOs) -> String {
match os {
ClientOs::Linux => format!("Linux {DEFAULT_LINUX_DISTRO}"),
ClientOs::Mac => format!("Apple Mac OS X {DEFAULT_MACOS_VERSION}"),
ClientOs::Windows => format!("Microsoft {DEFAULT_WINDOWS_DISTRO} , 64-bit"),
ClientOs::Ios => "Apple iOS".into(),
}
}
pub(crate) fn software_version(os: ClientOs) -> String {
match os {
ClientOs::Mac => DEFAULT_MACOS_VERSION.into(),
ClientOs::Windows => DEFAULT_WINDOWS_VERSION.into(),
ClientOs::Linux | ClientOs::Ios => String::new(),
}
}
@@ -0,0 +1,136 @@
use super::{
ClientOs, NativeHostIdentitySnapshot, derive_mac_address, fallback_hostname, normalize_mac_colon, primary_mac_colon,
resolve_host_id,
};
use crate::collection::CollectionControl;
use crate::process::collection::CollectorCommands;
use std::io;
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Mac
}
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn CollectionControl,
) -> io::Result<NativeHostIdentitySnapshot> {
let commands = CollectorCommands::new(control);
let native_mac = macos_builtin_mac(&commands)?.or_else(primary_mac_colon);
control.check()?;
let host_id = resolve_host_id(host_id_override, || {
native_mac
.clone()
.unwrap_or_else(|| derive_mac_address(&fallback_hostname()))
});
let computer = macos_computer_name(&commands)?.unwrap_or_else(fallback_hostname);
let serial_number = collect_macos_serial_number(&commands)?;
control.check()?;
Ok(NativeHostIdentitySnapshot {
host_id,
computer,
serial_number,
mac_address: native_mac,
})
}
}
fn output(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result<Option<String>> {
Ok(
commands
.run(program, args)?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok()),
)
}
fn macos_computer_name(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
for name in ["ComputerName", "LocalHostName"] {
if let Some(value) = output(commands, "scutil", &["--get", name])?
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
{
return Ok(Some(value));
}
}
Ok(None)
}
fn macos_builtin_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
if let Some(stdout) = output(commands, "networksetup", &["-listallhardwareports"])? {
for name in ["Wi-Fi", "AirPort"] {
if let Some(mac) = parse_hardware_port_mac(&stdout, name) {
return Ok(Some(mac));
}
}
}
macos_system_profiler_wifi_mac(commands)
}
fn parse_hardware_port_mac(stdout: &str, name: &str) -> Option<String> {
let mut in_port = false;
for line in stdout.lines() {
if let Some(port) = line.strip_prefix("Hardware Port: ") {
in_port = port == name;
continue;
}
if in_port && let Some(mac) = line.strip_prefix("Ethernet Address: ") {
return normalize_mac_colon(mac);
}
}
None
}
fn macos_system_profiler_wifi_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
let Some(stdout) = output(commands, "system_profiler", &["SPNetworkDataType"])? else {
return Ok(None);
};
let mut in_wifi = false;
for line in stdout.lines() {
let trimmed = line.trim();
if trimmed.ends_with(':') && !trimmed.starts_with("MAC Address:") {
in_wifi = trimmed == "Wi-Fi:" || trimmed == "AirPort:";
continue;
}
if in_wifi && let Some(mac) = trimmed.strip_prefix("MAC Address: ") {
return Ok(normalize_mac_colon(mac));
}
}
Ok(None)
}
fn collect_macos_serial_number(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
let Some(stdout) = output(commands, "ioreg", &["-rd1", "-c", "IOPlatformExpertDevice"])? else {
return Ok(None);
};
Ok(stdout.lines().find_map(|line| {
line
.split_once("IOPlatformSerialNumber")
.and_then(|(_, value)| value.split_once('='))
.map(|(_, value)| value.trim().trim_matches('"').to_string())
.filter(|value| !value.is_empty())
}))
}
impl RuntimeNativeHostIdentity {
pub(super) fn versions(control: &dyn super::CollectionControl) -> super::io::Result<(String, String)> {
let commands = crate::process::collection::CollectorCommands::new(control);
let version = commands
.run("sw_vers", &["-productVersion"])?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok())
.map(|version| version.trim().to_string())
.filter(|version| !version.is_empty())
.unwrap_or_else(|| super::DEFAULT_MACOS_VERSION.into());
control.check()?;
Ok((format!("Apple Mac OS X {version}"), version))
}
pub(super) fn fallback_versions() -> (String, String) {
(
super::defaults::os_version(ClientOs::Mac),
super::defaults::software_version(ClientOs::Mac),
)
}
}
+242
View File
@@ -0,0 +1,242 @@
use super::*;
use crate::collection::{CollectionBudget, CollectionControl};
use std::{io, time::Duration};
#[cfg(target_os = "macos")]
mod macos;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
mod unix;
#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "macos")]
use macos::RuntimeNativeHostIdentity;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))]
use unix::RuntimeNativeHostIdentity;
#[cfg(target_os = "windows")]
use windows::RuntimeNativeHostIdentity;
#[cfg(not(any(
target_os = "macos",
target_os = "windows",
target_os = "linux",
target_os = "freebsd",
target_os = "openbsd"
)))]
compile_error!("gpapi desktop collection is unsupported on this target; disable the desktop feature");
pub fn collect_identity() -> HostIdentity {
collect_with_host_id(None)
}
pub fn collect_identity_with_control(control: &dyn CollectionControl) -> io::Result<HostIdentity> {
collect_with_host_id_and_control(None, control)
}
pub(super) fn collect_with_host_id(host_id: Option<&str>) -> HostIdentity {
match collect_with_host_id_and_control(host_id, &CollectionBudget::new(Duration::from_secs(60))) {
Ok(identity) => identity,
Err(error) => {
log::warn!("Host identity collection was unavailable: {error}");
default_with_host_id(host_id)
}
}
}
/// Best-effort convenience callers retain the established derived identity
/// when native collection is unavailable. Controlled HIP callers get errors.
pub(super) fn default_with_host_id(host_id: Option<&str>) -> HostIdentity {
identity_from_parts(
fallback_hostname(),
resolve_host_id(host_id, fallback_host_id),
String::new(),
primary_mac_colon().unwrap_or_default(),
)
}
pub(super) fn collect_with_host_id_and_control(
host_id: Option<&str>,
control: &dyn CollectionControl,
) -> io::Result<HostIdentity> {
control.check()?;
let identity = RuntimeNativeHostIdentity::collect_with_control(host_id, control)?.into_host_identity();
control.check()?;
Ok(identity)
}
pub fn identity_from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> HostIdentity {
let host_id = non_empty(host_id, fallback_host_id());
let computer = non_empty(computer, fallback_hostname());
let serial_number = non_empty(serialno, derive_serial_number(&host_id));
let mac_address = normalize_mac_colon(&mac_addr).unwrap_or_else(|| derive_mac_address(&host_id));
HostIdentity::from_parts(computer, host_id, serial_number, mac_address)
}
pub(super) fn fallback_hostname() -> String {
whoami::hostname().unwrap_or_else(|_| String::from("localhost"))
}
#[derive(Debug, Clone)]
struct NativeHostIdentitySnapshot {
host_id: String,
computer: String,
serial_number: Option<String>,
mac_address: Option<String>,
}
impl NativeHostIdentitySnapshot {
fn into_host_identity(self) -> HostIdentity {
let host_id = non_empty(self.host_id, fallback_host_id());
identity_from_parts(
self.computer,
host_id.clone(),
self.serial_number.unwrap_or_else(|| derive_serial_number(&host_id)),
self.mac_address.unwrap_or_else(|| derive_mac_address(&host_id)),
)
}
}
fn non_empty(value: String, fallback: String) -> String {
if value.trim().is_empty() { fallback } else { value }
}
fn fallback_host_id() -> String {
derive_uuid_from_seed(&fallback_hostname(), &["runtime-host-id"])
}
fn resolve_host_id(host_id_override: Option<&str>, collect: impl FnOnce() -> String) -> String {
host_id_override
.filter(|value| !value.trim().is_empty())
.map(str::to_string)
.unwrap_or_else(collect)
}
fn derive_serial_number(host_id: &str) -> String {
serial_number::vmware_from_uuid(host_id).unwrap_or_else(|| {
let uuid = derive_uuid_from_seed(host_id, &["runtime-serialno"]);
serial_number::vmware_from_uuid(&uuid).expect("derived UUID should format as VMware serial")
})
}
fn derive_mac_address(host_id: &str) -> String {
let uuid = derive_uuid_from_seed(host_id, &["runtime-mac"]);
let compact = uuid.replace('-', "");
let bytes = compact
.as_bytes()
.chunks(2)
.take(6)
.map(|chunk| std::str::from_utf8(chunk).unwrap_or("00").to_lowercase())
.collect::<Vec<_>>();
bytes.join(":")
}
fn normalize_mac_colon(value: &str) -> Option<String> {
let compact = value
.trim()
.replace('-', ":")
.split(':')
.map(|part| part.to_lowercase())
.collect::<Vec<_>>();
let valid = compact.len() == 6
&& compact
.iter()
.all(|part| part.len() == 2 && part.chars().all(|ch| ch.is_ascii_hexdigit()));
valid.then(|| compact.join(":"))
}
fn primary_mac_colon() -> Option<String> {
netdev::get_default_interface()
.ok()
.and_then(|iface| iface.mac_addr.map(|mac| mac.address()))
.and_then(|mac| normalize_mac_colon(&mac))
}
fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String {
use uuid::Uuid;
let namespace = Uuid::NAMESPACE_DNS;
let name = format!("{}-{}", seed, parts.join("-"));
Uuid::new_v5(&namespace, name.as_bytes()).hyphenated().to_string()
}
pub fn runtime_client_os() -> ClientOs {
RuntimeNativeHostIdentity::runtime_os()
}
/// Strict native collection, followed by deterministic profile projection.
pub fn collect_profile_with_control(
builder: OsProfileBuilder,
host_id_override: Option<&str>,
control: &dyn CollectionControl,
) -> io::Result<OsProfile> {
control.check()?;
let identity = match &builder.host_identity {
Some(identity) => identity.clone(),
None => collect_with_host_id_and_control(host_id_override, control)?,
};
let runtime_os = runtime_client_os();
// Preserve the old behavior: only probe the native version when reporting it.
let (os_version, software_version) = if builder.client_os == runtime_os {
RuntimeNativeHostIdentity::versions(control)?
} else {
(defaults::os_version(runtime_os), defaults::software_version(runtime_os))
};
control.check()?;
Ok(builder.build(HostSnapshot {
runtime_os,
identity,
os_version,
software_version,
}))
}
/// Existing desktop best-effort policy; strict HIP callers use the controlled entry point.
pub fn collect_profile(builder: OsProfileBuilder, host_id_override: Option<&str>) -> OsProfile {
match collect_profile_with_control(
builder.clone(),
host_id_override,
&CollectionBudget::new(Duration::from_secs(60)),
) {
Ok(profile) => profile,
Err(error) => {
log::warn!("OS profile collection was unavailable: {error}");
let identity = builder
.host_identity
.clone()
.unwrap_or_else(|| default_with_host_id(host_id_override));
let runtime_os = runtime_client_os();
let (os_version, software_version) = RuntimeNativeHostIdentity::fallback_versions();
builder.build(HostSnapshot {
runtime_os,
identity,
os_version,
software_version,
})
}
}
}
pub fn default_computer_name(client_os: &ClientOs) -> String {
projection::project(runtime_client_os(), *client_os, &collect_identity(), None)
.computer()
.into()
}
pub fn default_os_version(client_os: &ClientOs) -> String {
if *client_os == runtime_client_os() {
RuntimeNativeHostIdentity::versions(&CollectionBudget::new(Duration::from_secs(60)))
.unwrap_or_else(|_| RuntimeNativeHostIdentity::fallback_versions())
.0
} else {
defaults::os_version(*client_os)
}
}
pub fn default_software_version(client_os: &ClientOs) -> String {
if *client_os == runtime_client_os() {
RuntimeNativeHostIdentity::versions(&CollectionBudget::new(Duration::from_secs(60)))
.unwrap_or_else(|_| RuntimeNativeHostIdentity::fallback_versions())
.1
} else {
defaults::software_version(*client_os)
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,180 @@
use super::*;
#[test]
fn controlled_identity_collection_propagates_cancellation() {
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
let error = collect_identity_with_control(&control).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
let error = collect_with_host_id_and_control(Some("supplied"), &control).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
}
#[test]
fn collect_produces_non_empty_identity() {
let identity = collect_identity();
assert!(!identity.computer().is_empty());
assert!(!identity.host_id().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
assert_mac(identity.mac_addr(), ':');
}
#[test]
fn collect_with_host_id_uses_provided_host_id() {
let identity = collect_with_host_id(Some("provided-host-id"));
assert_eq!(identity.host_id(), "provided-host-id");
assert!(!identity.computer().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
}
#[test]
fn collect_with_blank_host_id_falls_back_to_runtime_host_id() {
let identity = collect_with_host_id(Some(" "));
assert!(!identity.host_id().is_empty());
assert_ne!(identity.host_id(), " ");
}
#[test]
fn resolve_host_id_does_not_collect_when_override_is_provided() {
let host_id = resolve_host_id(Some("provided-host-id"), || {
panic!("runtime host id should not be collected")
});
assert_eq!(host_id, "provided-host-id");
}
#[test]
fn host_identity_normalizes_mac_to_lowercase_colon_format() {
let identity = identity_from_parts(
"computer".to_string(),
"host-id".to_string(),
"serial-number".to_string(),
"AA-BB-CC-DD-EE-FF".to_string(),
);
assert_eq!(identity.mac_addr(), "aa:bb:cc:dd:ee:ff");
}
#[test]
fn native_snapshot_uses_host_id_as_derivation_seed() {
let native =
RuntimeNativeHostIdentity::collect_with_control(None, &CollectionBudget::new(Duration::from_secs(60))).unwrap();
assert!(!native.host_id.is_empty());
}
#[test]
fn serialization_keeps_globalprotect_field_names() {
let identity = identity_from_parts(
"computer".to_string(),
"host-id".to_string(),
"serial-number".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
let value = serde_json::to_value(identity).unwrap();
assert_eq!(value["hostId"], "host-id");
assert_eq!(value["computer"], "computer");
assert!(value.get("osVersion").is_none());
assert!(value.get("softwareVersion").is_none());
assert_eq!(value["serialno"], "serial-number");
assert_eq!(value["macAddr"], "aa:bb:cc:dd:ee:ff");
}
#[test]
fn native_identity_falls_back_to_derived_values_when_missing() {
let native = NativeHostIdentitySnapshot {
host_id: "native-host-id".to_string(),
computer: "native-computer".to_string(),
serial_number: None,
mac_address: None,
};
let identity = native.into_host_identity();
assert_eq!(identity.computer(), "native-computer");
assert_eq!(identity.host_id(), "native-host-id");
assert!(identity.serialno().starts_with("VMware-"));
assert_mac(identity.mac_addr(), ':');
}
#[test]
fn derived_serial_uses_vmware_uuid_byte_order_when_host_id_is_uuid() {
let identity = identity_from_parts(
"computer".to_string(),
"5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string(),
String::new(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
assert_eq!(
identity.serialno(),
"VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef"
);
}
#[test]
fn empty_host_id_falls_back_to_non_empty_value() {
let identity = identity_from_parts(String::new(), String::new(), String::new(), String::new());
assert!(!identity.host_id().is_empty());
assert!(!identity.computer().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
}
fn assert_mac(value: &str, separator: char) {
let parts: Vec<&str> = value.split(separator).collect();
assert_eq!(parts.len(), 6, "MAC should have 6 octets");
for part in &parts {
assert_eq!(part.len(), 2);
assert!(part.chars().all(|c| c.is_ascii_hexdigit()));
}
}
#[test]
fn builder_delegates_default_identity_to_host_identity() {
let expected = collect_identity();
let profile = collect_profile(
OsProfileBuilder::new(runtime_client_os()).host_identity(expected.clone()),
None,
);
assert_eq!(profile.host_identity(), &expected);
}
#[test]
fn builder_host_id_override_uses_supplied_runtime_identity_seed() {
let profile = collect_profile(OsProfileBuilder::new(runtime_client_os()), Some("provided-host-id"));
assert_eq!(profile.host_identity().host_id(), "provided-host-id");
}
#[test]
fn builder_host_id_override_is_used_as_projected_identity_seed() {
let client_os = match runtime_client_os() {
ClientOs::Linux => ClientOs::Mac,
ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => ClientOs::Linux,
};
let first = collect_profile(OsProfileBuilder::new(client_os), Some("provided-host-id"));
let second = collect_profile(OsProfileBuilder::new(client_os), Some("provided-host-id"));
assert_eq!(first.host_identity().host_id(), "provided-host-id");
assert_eq!(first.host_id(), second.host_id());
assert_ne!(first.host_id(), "provided-host-id");
}
#[test]
fn controlled_profile_collection_propagates_cancellation_and_deadline() {
let cancelled = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
let error = collect_profile_with_control(OsProfileBuilder::new(ClientOs::Mac), None, &cancelled).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
let expired = CollectionBudget::new(Duration::ZERO);
let error = collect_profile_with_control(OsProfileBuilder::new(ClientOs::Linux), None, &expired).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
}
+136
View File
@@ -0,0 +1,136 @@
use super::{
ClientOs, NativeHostIdentitySnapshot, derive_uuid_from_seed, fallback_hostname, primary_mac_colon, resolve_host_id,
serial_number,
};
use log::debug;
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Linux
}
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn super::CollectionControl,
) -> super::io::Result<NativeHostIdentitySnapshot> {
control.check()?;
let identity = Self::collect(host_id_override);
control.check()?;
Ok(identity)
}
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
if let Some(host_id) = host_id_override.filter(|value| !value.trim().is_empty()) {
debug!("Runtime host-id source: explicit override ({})", host_id);
}
let host_id = resolve_host_id(host_id_override, Self::host_id);
NativeHostIdentitySnapshot {
host_id,
computer: fallback_hostname(),
serial_number: collect_linux_serial_number(),
mac_address: primary_mac_colon(),
}
}
fn host_id() -> String {
if let Some(host_id) = collect_linux_product_uuid() {
debug!("Runtime host-id source: /sys/class/dmi/id/product_uuid ({})", host_id);
return host_id;
}
let (source_name, source) = collect_linux_fallback_seed().unwrap_or_else(|| {
let hostname = fallback_hostname();
("hostname", hostname)
});
let host_id = derive_uuid_from_seed(&source, &[]);
debug!("Runtime host-id source: derived from {} ({})", source_name, host_id);
host_id
}
}
fn collect_linux_product_uuid() -> Option<String> {
read_linux_identity_file("/sys/class/dmi/id/product_uuid").and_then(|value| normalize_uuid(&value))
}
fn normalize_uuid(value: &str) -> Option<String> {
uuid::Uuid::parse_str(value.trim())
.ok()
.map(|uuid| uuid.hyphenated().to_string())
}
fn collect_linux_fallback_seed() -> Option<(&'static str, String)> {
["/etc/machine-id", "/var/lib/dbus/machine-id"]
.iter()
.find_map(|path| read_linux_identity_file(path).map(|value| (*path, value)))
}
fn read_linux_identity_file(path: &str) -> Option<String> {
std::fs::read_to_string(path)
.ok()
.map(|value| value.trim().to_string())
.filter(|value| is_usable_linux_identity_value(value))
}
fn is_usable_linux_identity_value(value: &str) -> bool {
!value.is_empty() && value != "None" && value != "To Be Filled By O.E.M."
}
fn collect_linux_serial_number() -> Option<String> {
resolve_linux_serial_number(
read_linux_identity_file("/sys/class/dmi/id/product_serial"),
collect_linux_product_uuid,
)
}
fn resolve_linux_serial_number(
product_serial: Option<String>,
product_uuid: impl FnOnce() -> Option<String>,
) -> Option<String> {
product_serial.or_else(|| product_uuid().and_then(|uuid| serial_number::vmware_from_uuid(&uuid)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalize_uuid_preserves_real_uuid_identity() {
assert_eq!(
normalize_uuid("5A784D56-6461-19AC-9EA9-D36A3B9C6CEF"),
Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string())
);
assert_eq!(normalize_uuid("not-a-uuid"), None);
}
#[test]
fn linux_serial_number_preserves_product_serial_and_formats_uuid_fallback() {
let uuid = Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string());
assert_eq!(
resolve_linux_serial_number(Some("product-serial".to_string()), || uuid.clone()),
Some("product-serial".to_string())
);
assert_eq!(
resolve_linux_serial_number(None, || uuid),
Some("VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef".to_string())
);
}
}
impl RuntimeNativeHostIdentity {
pub(super) fn versions(control: &dyn super::CollectionControl) -> super::io::Result<(String, String)> {
control.check()?;
Ok(Self::fallback_versions())
}
pub(super) fn fallback_versions() -> (String, String) {
(
format!(
"Linux {}",
whoami::distro().unwrap_or_else(|_| super::DEFAULT_LINUX_DISTRO.into())
),
String::new(),
)
}
}
@@ -0,0 +1,107 @@
use std::process::Command;
use super::{ClientOs, NativeHostIdentitySnapshot, fallback_hostname, primary_mac_colon, resolve_host_id};
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Windows
}
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn super::CollectionControl,
) -> super::io::Result<NativeHostIdentitySnapshot> {
control.check()?;
let identity = Self::collect(host_id_override);
control.check()?;
Ok(identity)
}
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
let host_id = resolve_host_id(host_id_override, Self::host_id);
NativeHostIdentitySnapshot {
host_id,
computer: fallback_hostname(),
serial_number: collect_windows_serial_number(),
mac_address: primary_mac_colon(),
}
}
fn host_id() -> String {
windows_machine_seed().unwrap_or_else(fallback_hostname)
}
}
fn collect_windows_serial_number() -> Option<String> {
let output = Command::new("wmic")
.args(["bios", "get", "serialnumber"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && *line != "SerialNumber")
.map(str::to_string)
.next()
}
fn windows_machine_seed() -> Option<String> {
collect_windows_csproduct_uuid().or_else(collect_windows_machine_guid)
}
fn collect_windows_csproduct_uuid() -> Option<String> {
let output = Command::new("wmic").args(["csproduct", "get", "uuid"]).output().ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && *line != "UUID")
.map(str::to_string)
.next()
}
fn collect_windows_machine_guid() -> Option<String> {
let output = Command::new("reg")
.args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8(output.stdout).ok()?;
stdout.lines().find_map(|line| {
let mut parts = line.split_whitespace();
if parts.next()? != "MachineGuid" {
return None;
}
parts.last().map(str::to_string)
})
}
impl RuntimeNativeHostIdentity {
pub(super) fn versions(control: &dyn super::CollectionControl) -> super::io::Result<(String, String)> {
control.check()?;
Ok(Self::fallback_versions())
}
pub(super) fn fallback_versions() -> (String, String) {
{
let info = os_info::get();
let edition = info
.edition()
.map(str::to_owned)
.unwrap_or_else(|| whoami::distro().unwrap_or_else(|_| super::DEFAULT_WINDOWS_DISTRO.into()));
let version = match info.version() {
os_info::Version::Unknown => super::DEFAULT_WINDOWS_VERSION.into(),
version => format!("{}.0", version),
};
(format!("Microsoft {} , 64-bit", edition), version)
}
}
}
@@ -1,670 +0,0 @@
use std::{io, time::Duration};
use crate::process::collection::{CollectionBudget, CollectionControl};
use serde::{Deserialize, Serialize};
use specta::Type;
use super::{ClientOs, serial_number};
use platform::RuntimeNativeHostIdentity;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HostIdentity {
computer: String,
host_id: String,
#[serde(rename = "serialno")]
serial_number: String,
#[serde(rename = "macAddr")]
mac_address: String,
}
impl HostIdentity {
pub fn collect() -> Self {
Self::collect_with_host_id(None)
}
pub fn collect_with_control(control: &dyn CollectionControl) -> io::Result<Self> {
Self::collect_with_host_id_and_control(None, control)
}
pub(crate) fn collect_with_host_id(host_id: Option<&str>) -> Self {
match Self::collect_with_host_id_and_control(host_id, &CollectionBudget::new(Duration::from_secs(60))) {
Ok(identity) => identity,
Err(error) => {
log::warn!("Host identity collection was unavailable: {error}");
Self::default_with_host_id(host_id)
}
}
}
/// Best-effort convenience callers retain the established derived identity
/// when native collection is unavailable. Controlled HIP callers get errors.
pub(crate) fn default_with_host_id(host_id: Option<&str>) -> Self {
Self::from_parts(
fallback_hostname(),
resolve_host_id(host_id, fallback_host_id),
String::new(),
primary_mac_colon().unwrap_or_default(),
)
}
pub(crate) fn collect_with_host_id_and_control(
host_id: Option<&str>,
control: &dyn CollectionControl,
) -> io::Result<Self> {
control.check()?;
let identity = RuntimeNativeHostIdentity::collect_with_control(host_id, control)?.into_host_identity();
control.check()?;
Ok(identity)
}
#[cfg(test)]
pub(crate) fn new(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
Self::from_parts(computer, host_id, serialno, mac_addr)
}
/// Construct a host identity from an already collected or negotiated snapshot.
pub fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
let host_id = non_empty(host_id, fallback_host_id());
let computer = non_empty(computer, fallback_hostname());
let serial_number = non_empty(serialno, derive_serial_number(&host_id));
let mac_address = normalize_mac_colon(&mac_addr).unwrap_or_else(|| derive_mac_address(&host_id));
Self {
computer,
host_id,
serial_number,
mac_address,
}
}
pub fn computer(&self) -> &str {
&self.computer
}
pub fn host_id(&self) -> &str {
&self.host_id
}
pub fn serialno(&self) -> &str {
&self.serial_number
}
pub fn mac_addr(&self) -> &str {
&self.mac_address
}
pub fn with_computer(mut self, computer: String) -> Self {
if !computer.trim().is_empty() {
self.computer = computer;
}
self
}
pub(crate) fn runtime_os() -> ClientOs {
RuntimeNativeHostIdentity::runtime_os()
}
}
pub(super) fn fallback_hostname() -> String {
whoami::hostname().unwrap_or_else(|_| String::from("localhost"))
}
#[derive(Debug, Clone)]
struct NativeHostIdentitySnapshot {
host_id: String,
computer: String,
serial_number: Option<String>,
mac_address: Option<String>,
}
impl NativeHostIdentitySnapshot {
fn into_host_identity(self) -> HostIdentity {
let host_id = non_empty(self.host_id, fallback_host_id());
HostIdentity::from_parts(
self.computer,
host_id.clone(),
self.serial_number.unwrap_or_else(|| derive_serial_number(&host_id)),
self.mac_address.unwrap_or_else(|| derive_mac_address(&host_id)),
)
}
}
fn non_empty(value: String, fallback: String) -> String {
if value.trim().is_empty() { fallback } else { value }
}
fn fallback_host_id() -> String {
derive_uuid_from_seed(&fallback_hostname(), &["runtime-host-id"])
}
fn resolve_host_id(host_id_override: Option<&str>, collect: impl FnOnce() -> String) -> String {
host_id_override
.filter(|value| !value.trim().is_empty())
.map(str::to_string)
.unwrap_or_else(collect)
}
fn derive_serial_number(host_id: &str) -> String {
serial_number::vmware_from_uuid(host_id).unwrap_or_else(|| {
let uuid = derive_uuid_from_seed(host_id, &["runtime-serialno"]);
serial_number::vmware_from_uuid(&uuid).expect("derived UUID should format as VMware serial")
})
}
fn derive_mac_address(host_id: &str) -> String {
let uuid = derive_uuid_from_seed(host_id, &["runtime-mac"]);
let compact = uuid.replace('-', "");
let bytes = compact
.as_bytes()
.chunks(2)
.take(6)
.map(|chunk| std::str::from_utf8(chunk).unwrap_or("00").to_lowercase())
.collect::<Vec<_>>();
bytes.join(":")
}
fn normalize_mac_colon(value: &str) -> Option<String> {
let compact = value
.trim()
.replace('-', ":")
.split(':')
.map(|part| part.to_lowercase())
.collect::<Vec<_>>();
let valid = compact.len() == 6
&& compact
.iter()
.all(|part| part.len() == 2 && part.chars().all(|ch| ch.is_ascii_hexdigit()));
valid.then(|| compact.join(":"))
}
fn primary_mac_colon() -> Option<String> {
netdev::get_default_interface()
.ok()
.and_then(|iface| iface.mac_addr.map(|mac| mac.address()))
.and_then(|mac| normalize_mac_colon(&mac))
}
fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String {
use uuid::Uuid;
let namespace = Uuid::NAMESPACE_DNS;
let name = format!("{}-{}", seed, parts.join("-"));
Uuid::new_v5(&namespace, name.as_bytes()).hyphenated().to_string()
}
#[cfg(target_os = "macos")]
mod platform {
use super::{
ClientOs, NativeHostIdentitySnapshot, derive_mac_address, fallback_hostname, normalize_mac_colon,
primary_mac_colon, resolve_host_id,
};
use crate::process::collection::{CollectionControl, CollectorCommands};
use std::io;
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Mac
}
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn CollectionControl,
) -> io::Result<NativeHostIdentitySnapshot> {
let commands = CollectorCommands::new(control);
let native_mac = macos_builtin_mac(&commands)?.or_else(primary_mac_colon);
control.check()?;
let host_id = resolve_host_id(host_id_override, || {
native_mac
.clone()
.unwrap_or_else(|| derive_mac_address(&fallback_hostname()))
});
let computer = macos_computer_name(&commands)?.unwrap_or_else(fallback_hostname);
let serial_number = collect_macos_serial_number(&commands)?;
control.check()?;
Ok(NativeHostIdentitySnapshot {
host_id,
computer,
serial_number,
mac_address: native_mac,
})
}
}
fn output(commands: &CollectorCommands<'_>, program: &str, args: &[&str]) -> io::Result<Option<String>> {
Ok(
commands
.run(program, args)?
.filter(|output| output.status.success())
.and_then(|output| String::from_utf8(output.stdout).ok()),
)
}
fn macos_computer_name(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
for name in ["ComputerName", "LocalHostName"] {
if let Some(value) = output(commands, "scutil", &["--get", name])?
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
{
return Ok(Some(value));
}
}
Ok(None)
}
fn macos_builtin_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
if let Some(stdout) = output(commands, "networksetup", &["-listallhardwareports"])? {
for name in ["Wi-Fi", "AirPort"] {
if let Some(mac) = parse_hardware_port_mac(&stdout, name) {
return Ok(Some(mac));
}
}
}
macos_system_profiler_wifi_mac(commands)
}
fn parse_hardware_port_mac(stdout: &str, name: &str) -> Option<String> {
let mut in_port = false;
for line in stdout.lines() {
if let Some(port) = line.strip_prefix("Hardware Port: ") {
in_port = port == name;
continue;
}
if in_port && let Some(mac) = line.strip_prefix("Ethernet Address: ") {
return normalize_mac_colon(mac);
}
}
None
}
fn macos_system_profiler_wifi_mac(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
let Some(stdout) = output(commands, "system_profiler", &["SPNetworkDataType"])? else {
return Ok(None);
};
let mut in_wifi = false;
for line in stdout.lines() {
let trimmed = line.trim();
if trimmed.ends_with(':') && !trimmed.starts_with("MAC Address:") {
in_wifi = trimmed == "Wi-Fi:" || trimmed == "AirPort:";
continue;
}
if in_wifi && let Some(mac) = trimmed.strip_prefix("MAC Address: ") {
return Ok(normalize_mac_colon(mac));
}
}
Ok(None)
}
fn collect_macos_serial_number(commands: &CollectorCommands<'_>) -> io::Result<Option<String>> {
let Some(stdout) = output(commands, "ioreg", &["-rd1", "-c", "IOPlatformExpertDevice"])? else {
return Ok(None);
};
Ok(stdout.lines().find_map(|line| {
line
.split_once("IOPlatformSerialNumber")
.and_then(|(_, value)| value.split_once('='))
.map(|(_, value)| value.trim().trim_matches('"').to_string())
.filter(|value| !value.is_empty())
}))
}
}
#[cfg(target_os = "windows")]
mod platform {
use std::process::Command;
use super::{ClientOs, NativeHostIdentitySnapshot, fallback_hostname, primary_mac_colon, resolve_host_id};
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Windows
}
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn super::CollectionControl,
) -> super::io::Result<NativeHostIdentitySnapshot> {
control.check()?;
let identity = Self::collect(host_id_override);
control.check()?;
Ok(identity)
}
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
let host_id = resolve_host_id(host_id_override, Self::host_id);
NativeHostIdentitySnapshot {
host_id,
computer: fallback_hostname(),
serial_number: collect_windows_serial_number(),
mac_address: primary_mac_colon(),
}
}
fn host_id() -> String {
windows_machine_seed().unwrap_or_else(fallback_hostname)
}
}
fn collect_windows_serial_number() -> Option<String> {
let output = Command::new("wmic")
.args(["bios", "get", "serialnumber"])
.output()
.ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && *line != "SerialNumber")
.map(str::to_string)
.next()
}
fn windows_machine_seed() -> Option<String> {
collect_windows_csproduct_uuid().or_else(collect_windows_machine_guid)
}
fn collect_windows_csproduct_uuid() -> Option<String> {
let output = Command::new("wmic").args(["csproduct", "get", "uuid"]).output().ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
stdout
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && *line != "UUID")
.map(str::to_string)
.next()
}
fn collect_windows_machine_guid() -> Option<String> {
let output = Command::new("reg")
.args(["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8(output.stdout).ok()?;
stdout.lines().find_map(|line| {
let mut parts = line.split_whitespace();
if parts.next()? != "MachineGuid" {
return None;
}
parts.last().map(str::to_string)
})
}
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
mod platform {
use super::{
ClientOs, NativeHostIdentitySnapshot, derive_uuid_from_seed, fallback_hostname, primary_mac_colon, resolve_host_id,
serial_number,
};
use log::debug;
pub(super) struct RuntimeNativeHostIdentity;
impl RuntimeNativeHostIdentity {
pub(super) fn runtime_os() -> ClientOs {
ClientOs::Linux
}
pub(super) fn collect_with_control(
host_id_override: Option<&str>,
control: &dyn super::CollectionControl,
) -> super::io::Result<NativeHostIdentitySnapshot> {
control.check()?;
let identity = Self::collect(host_id_override);
control.check()?;
Ok(identity)
}
fn collect(host_id_override: Option<&str>) -> NativeHostIdentitySnapshot {
if let Some(host_id) = host_id_override.filter(|value| !value.trim().is_empty()) {
debug!("Runtime host-id source: explicit override ({})", host_id);
}
let host_id = resolve_host_id(host_id_override, Self::host_id);
NativeHostIdentitySnapshot {
host_id,
computer: fallback_hostname(),
serial_number: collect_linux_serial_number(),
mac_address: primary_mac_colon(),
}
}
fn host_id() -> String {
if let Some(host_id) = collect_linux_product_uuid() {
debug!("Runtime host-id source: /sys/class/dmi/id/product_uuid ({})", host_id);
return host_id;
}
let (source_name, source) = collect_linux_fallback_seed().unwrap_or_else(|| {
let hostname = fallback_hostname();
("hostname", hostname)
});
let host_id = derive_uuid_from_seed(&source, &[]);
debug!("Runtime host-id source: derived from {} ({})", source_name, host_id);
host_id
}
}
fn collect_linux_product_uuid() -> Option<String> {
read_linux_identity_file("/sys/class/dmi/id/product_uuid").and_then(|value| normalize_uuid(&value))
}
fn normalize_uuid(value: &str) -> Option<String> {
uuid::Uuid::parse_str(value.trim())
.ok()
.map(|uuid| uuid.hyphenated().to_string())
}
fn collect_linux_fallback_seed() -> Option<(&'static str, String)> {
["/etc/machine-id", "/var/lib/dbus/machine-id"]
.iter()
.find_map(|path| read_linux_identity_file(path).map(|value| (*path, value)))
}
fn read_linux_identity_file(path: &str) -> Option<String> {
std::fs::read_to_string(path)
.ok()
.map(|value| value.trim().to_string())
.filter(|value| is_usable_linux_identity_value(value))
}
fn is_usable_linux_identity_value(value: &str) -> bool {
!value.is_empty() && value != "None" && value != "To Be Filled By O.E.M."
}
fn collect_linux_serial_number() -> Option<String> {
resolve_linux_serial_number(
read_linux_identity_file("/sys/class/dmi/id/product_serial"),
collect_linux_product_uuid,
)
}
fn resolve_linux_serial_number(
product_serial: Option<String>,
product_uuid: impl FnOnce() -> Option<String>,
) -> Option<String> {
product_serial.or_else(|| product_uuid().and_then(|uuid| serial_number::vmware_from_uuid(&uuid)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalize_uuid_preserves_real_uuid_identity() {
assert_eq!(
normalize_uuid("5A784D56-6461-19AC-9EA9-D36A3B9C6CEF"),
Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string())
);
assert_eq!(normalize_uuid("not-a-uuid"), None);
}
#[test]
fn linux_serial_number_preserves_product_serial_and_formats_uuid_fallback() {
let uuid = Some("5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string());
assert_eq!(
resolve_linux_serial_number(Some("product-serial".to_string()), || uuid.clone()),
Some("product-serial".to_string())
);
assert_eq!(
resolve_linux_serial_number(None, || uuid),
Some("VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef".to_string())
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn controlled_identity_collection_propagates_cancellation() {
let control = || Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
let error = HostIdentity::collect_with_control(&control).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
let error = HostIdentity::collect_with_host_id_and_control(Some("supplied"), &control).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
}
#[test]
fn collect_produces_non_empty_identity() {
let identity = HostIdentity::collect();
assert!(!identity.computer().is_empty());
assert!(!identity.host_id().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
assert_mac(identity.mac_addr(), ':');
}
#[test]
fn collect_with_host_id_uses_provided_host_id() {
let identity = HostIdentity::collect_with_host_id(Some("provided-host-id"));
assert_eq!(identity.host_id(), "provided-host-id");
assert!(!identity.computer().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
}
#[test]
fn collect_with_blank_host_id_falls_back_to_runtime_host_id() {
let identity = HostIdentity::collect_with_host_id(Some(" "));
assert!(!identity.host_id().is_empty());
assert_ne!(identity.host_id(), " ");
}
#[test]
fn resolve_host_id_does_not_collect_when_override_is_provided() {
let host_id = resolve_host_id(Some("provided-host-id"), || {
panic!("runtime host id should not be collected")
});
assert_eq!(host_id, "provided-host-id");
}
#[test]
fn host_identity_normalizes_mac_to_lowercase_colon_format() {
let identity = HostIdentity::new(
"computer".to_string(),
"host-id".to_string(),
"serial-number".to_string(),
"AA-BB-CC-DD-EE-FF".to_string(),
);
assert_eq!(identity.mac_addr(), "aa:bb:cc:dd:ee:ff");
}
#[test]
fn native_snapshot_uses_host_id_as_derivation_seed() {
let native =
RuntimeNativeHostIdentity::collect_with_control(None, &CollectionBudget::new(Duration::from_secs(60))).unwrap();
assert!(!native.host_id.is_empty());
}
#[test]
fn serialization_keeps_globalprotect_field_names() {
let identity = HostIdentity::new(
"computer".to_string(),
"host-id".to_string(),
"serial-number".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
let value = serde_json::to_value(identity).unwrap();
assert_eq!(value["hostId"], "host-id");
assert_eq!(value["computer"], "computer");
assert!(value.get("osVersion").is_none());
assert!(value.get("softwareVersion").is_none());
assert_eq!(value["serialno"], "serial-number");
assert_eq!(value["macAddr"], "aa:bb:cc:dd:ee:ff");
}
#[test]
fn native_identity_falls_back_to_derived_values_when_missing() {
let native = NativeHostIdentitySnapshot {
host_id: "native-host-id".to_string(),
computer: "native-computer".to_string(),
serial_number: None,
mac_address: None,
};
let identity = native.into_host_identity();
assert_eq!(identity.computer(), "native-computer");
assert_eq!(identity.host_id(), "native-host-id");
assert!(identity.serialno().starts_with("VMware-"));
assert_mac(identity.mac_addr(), ':');
}
#[test]
fn derived_serial_uses_vmware_uuid_byte_order_when_host_id_is_uuid() {
let identity = HostIdentity::new(
"computer".to_string(),
"5a784d56-6461-19ac-9ea9-d36a3b9c6cef".to_string(),
String::new(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
assert_eq!(
identity.serialno(),
"VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef"
);
}
#[test]
fn empty_host_id_falls_back_to_non_empty_value() {
let identity = HostIdentity::new(String::new(), String::new(), String::new(), String::new());
assert!(!identity.host_id().is_empty());
assert!(!identity.computer().is_empty());
assert!(!identity.serialno().is_empty());
assert!(!identity.mac_addr().is_empty());
}
fn assert_mac(value: &str, separator: char) {
let parts: Vec<&str> = value.split(separator).collect();
assert_eq!(parts.len(), 6, "MAC should have 6 octets");
for part in &parts {
assert_eq!(part.len(), 2);
assert!(part.chars().all(|c| c.is_ascii_hexdigit()));
}
}
}
+56
View File
@@ -0,0 +1,56 @@
use serde::{Deserialize, Serialize};
use specta::Type;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HostIdentity {
computer: String,
host_id: String,
#[serde(rename = "serialno")]
serial_number: String,
#[serde(rename = "macAddr")]
mac_address: String,
}
impl HostIdentity {
/// Values already collected by the caller. Missing observations stay empty.
pub fn from_parts(computer: String, host_id: String, serialno: String, mac_addr: String) -> Self {
Self {
computer,
host_id,
serial_number: serialno,
mac_address: mac_addr,
}
}
/// Identity supplied by an application; no hardware attributes are invented.
pub fn application(computer: String, installation_id: String) -> Self {
Self {
computer,
host_id: installation_id,
serial_number: String::new(),
mac_address: String::new(),
}
}
pub fn computer(&self) -> &str {
&self.computer
}
pub fn host_id(&self) -> &str {
&self.host_id
}
pub fn serialno(&self) -> &str {
&self.serial_number
}
pub fn mac_addr(&self) -> &str {
&self.mac_address
}
pub fn with_computer(mut self, computer: String) -> Self {
if !computer.trim().is_empty() {
self.computer = computer;
}
self
}
}
File diff suppressed because it is too large. Load diff
+277
View File
@@ -0,0 +1,277 @@
use super::*;
/// Observed host facts supplied by the platform owner.
#[derive(Debug, Clone)]
pub struct HostSnapshot {
pub runtime_os: ClientOs,
pub identity: HostIdentity,
pub os_version: String,
pub software_version: String,
}
// ─── ProfileHostIdentity ────────────────────────────────────────────────────
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct ProfileHostIdentity {
pub(super) computer: String,
pub(super) host_id: String,
pub(super) serial_number: String,
pub(super) mac_address: String,
}
impl ProfileHostIdentity {
pub(super) fn for_client_os(
runtime_os: ClientOs,
client_os: ClientOs,
host_identity: &HostIdentity,
computer_override: Option<String>,
) -> Self {
projection::project(runtime_os, client_os, host_identity, computer_override)
}
pub(super) fn computer(&self) -> &str {
&self.computer
}
pub(super) fn host_id(&self) -> &str {
&self.host_id
}
pub(super) fn serialno(&self) -> &str {
&self.serial_number
}
pub(super) fn mac_addr(&self) -> &str {
&self.mac_address
}
}
// ─── OsProfile ───────────────────────────────────────────────────────────────
#[derive(Debug, Clone)]
pub struct OsProfile {
runtime_os: ClientOs,
client_os: ClientOs,
os_version: String,
software_version: String,
os_vendor: &'static str,
client_version: String,
host_identity: HostIdentity,
profile_identity: ProfileHostIdentity,
user_agent: String,
}
impl OsProfile {
pub fn builder(client_os: ClientOs) -> OsProfileBuilder {
OsProfileBuilder::new(client_os)
}
// ─── Identity accessors ──────────────────────────────────────────────────
pub fn client_os(&self) -> ClientOs {
self.client_os
}
pub fn computer(&self) -> &str {
self.profile_identity.computer()
}
pub fn os_version(&self) -> &str {
&self.os_version
}
pub fn client_version(&self) -> &str {
&self.client_version
}
pub fn host_identity(&self) -> &HostIdentity {
&self.host_identity
}
pub fn user_agent(&self) -> &str {
&self.user_agent
}
pub fn webview_user_agent(&self) -> WebviewUserAgent {
if self.is_native() {
WebviewUserAgent::Native {
prefix: self.user_agent.clone(),
transform: target::webview_user_agent_transform(self.client_os),
}
} else {
WebviewUserAgent::Projected {
prefix: self.user_agent.clone(),
default_user_agent: target::webview_user_agent_default(self.client_os).to_string(),
}
}
}
pub fn host_id(&self) -> &str {
self.profile_identity.host_id()
}
pub fn serialno(&self) -> &str {
self.profile_identity.serialno()
}
pub fn mac_addr(&self) -> &str {
self.profile_identity.mac_addr()
}
/// Returns true when the target client OS matches the runtime OS.
///
/// Used to decide whether to consult real OS-level state (e.g. the actual
/// network interface) versus simulated values for emulation.
pub fn is_native(&self) -> bool {
self.runtime_os == self.client_os
}
/// Default software version string for the target OS, matching the
/// official client values.
pub fn software_version(&self) -> &str {
&self.software_version
}
// ─── Behavioral methods ──────────────────────────────────────────────────
pub(crate) fn prelogin_param_location(&self) -> PreloginParamLocation {
target::prelogin_param_location(self.client_os)
}
pub(crate) fn portal_default_browser(&self, browser_mode: PreloginBrowserMode) -> &'static str {
match browser_mode {
PreloginBrowserMode::Embedded => "-10",
PreloginBrowserMode::External => target::external_browser_os_value(self.client_os),
}
}
pub(crate) fn gateway_default_browser(&self, browser_mode: PreloginBrowserMode) -> &'static str {
match browser_mode {
PreloginBrowserMode::Embedded => "0",
PreloginBrowserMode::External => target::external_browser_os_value(self.client_os),
}
}
pub(crate) fn saml_password(&self) -> &'static str {
target::saml_password(self.client_os)
}
pub(crate) fn gateway_server_uses_resolved_ipv4(&self) -> bool {
true
}
pub(crate) fn supports_macos_plist_csc(&self) -> bool {
target::supports_macos_plist_csc(self.client_os)
}
pub(crate) fn supports_linux_process_csc(&self) -> bool {
target::supports_linux_process_csc(self.client_os)
}
pub(crate) fn supports_windows_registry_csc(&self) -> bool {
target::supports_windows_registry_csc(self.client_os)
}
pub(crate) fn kerberos_support_in_query(&self) -> bool {
target::kerberos_support_in_query(self.client_os)
}
pub fn os_vendor(&self) -> &'static str {
self.os_vendor
}
}
// ─── OsProfileBuilder ────────────────────────────────────────────────────────
#[derive(Debug, Clone)]
pub struct OsProfileBuilder {
pub(super) client_os: ClientOs,
pub(super) client_version: Option<String>,
pub(super) os_version_override: Option<String>,
pub(super) computer_name_override: Option<String>,
pub(super) host_identity: Option<HostIdentity>,
pub(super) user_agent: Option<String>,
}
impl OsProfileBuilder {
pub fn new(client_os: ClientOs) -> Self {
Self {
client_os,
client_version: None,
os_version_override: None,
computer_name_override: None,
host_identity: None,
user_agent: None,
}
}
pub fn computer_name_override(mut self, name: impl Into<String>) -> Self {
self.computer_name_override = Some(name.into());
self
}
pub fn client_version(mut self, version: impl Into<String>) -> Self {
self.client_version = Some(version.into());
self
}
/// Preserve an explicitly negotiated operating system version.
pub fn os_version(mut self, version: impl Into<String>) -> Self {
let version = version.into();
self.os_version_override = if version.trim().is_empty() { None } else { Some(version) };
self
}
pub fn host_identity(mut self, identity: HostIdentity) -> Self {
self.host_identity = Some(identity);
self
}
pub fn user_agent(mut self, ua: impl Into<String>) -> Self {
let ua = ua.into();
self.user_agent = if ua.trim().is_empty() { None } else { Some(ua) };
self
}
/// Project supplied host facts without inspecting the machine running this code.
pub fn build(self, snapshot: HostSnapshot) -> OsProfile {
let (os_version, software_version) = if self.client_os == snapshot.runtime_os {
(snapshot.os_version, snapshot.software_version)
} else {
(
defaults::os_version(self.client_os),
defaults::software_version(self.client_os),
)
};
let identity = self.host_identity.clone().unwrap_or(snapshot.identity);
self.finish(snapshot.runtime_os, identity, os_version, software_version)
}
fn finish(
self,
runtime_os: ClientOs,
host_identity: HostIdentity,
default_os_version: String,
software_version: String,
) -> OsProfile {
let client_version = self
.client_version
.filter(|version| !version.trim().is_empty())
.unwrap_or_else(|| self.client_os.default_client_version().into());
let profile_identity =
ProfileHostIdentity::for_client_os(runtime_os, self.client_os, &host_identity, self.computer_name_override);
let os_version = self.os_version_override.unwrap_or(default_os_version);
let user_agent = self
.user_agent
.unwrap_or_else(|| format!("{GP_USER_AGENT}/{client_version} ({os_version})"));
OsProfile {
client_os: self.client_os,
runtime_os,
os_version,
software_version,
os_vendor: target::os_vendor(self.client_os),
client_version,
host_identity,
profile_identity,
user_agent,
}
}
}
+171
View File
@@ -0,0 +1,171 @@
use super::*;
fn derive_uuid_from_seed(seed: &str, parts: &[&str]) -> String {
use uuid::Uuid;
let namespace = Uuid::NAMESPACE_DNS;
let name = format!("{}-{}", seed, parts.join("-"));
Uuid::new_v5(&namespace, name.as_bytes()).hyphenated().to_string()
}
fn derived_profile_mac(seed: &str, client_os: ClientOs) -> String {
let uuid = derive_uuid_from_seed(seed, &["os-profile", client_os.as_str(), "mac"]);
let compact = uuid.replace('-', "");
let bytes = compact
.as_bytes()
.chunks(2)
.take(6)
.map(|chunk| std::str::from_utf8(chunk).unwrap_or("00").to_lowercase())
.collect::<Vec<_>>();
match client_os {
ClientOs::Linux | ClientOs::Windows => bytes.join("-"),
ClientOs::Mac | ClientOs::Ios => bytes.join(":"),
}
}
fn compact_uuid(seed: &str, client_os: ClientOs, suffix: &str) -> String {
derive_uuid_from_seed(seed, &["os-profile", client_os.as_str(), suffix])
.replace('-', "")
.to_uppercase()
}
pub(super) fn project(
runtime_os: ClientOs,
client_os: ClientOs,
host_identity: &HostIdentity,
computer_override: Option<String>,
) -> ProfileHostIdentity {
if client_os == runtime_os {
return native::project(client_os, host_identity, computer_override);
}
match client_os {
ClientOs::Linux => linux::project(host_identity, computer_override),
ClientOs::Windows => windows::project(host_identity, computer_override),
ClientOs::Mac => macos::project(host_identity, computer_override),
ClientOs::Ios => native::project(client_os, host_identity, computer_override),
}
}
fn computer(host_identity: &HostIdentity, computer_override: Option<String>) -> String {
computer_override
.filter(|value| !value.trim().is_empty())
.unwrap_or_else(|| host_identity.computer().to_string())
}
fn profile_mac_for(client_os: ClientOs, mac_address: &str) -> String {
match client_os {
ClientOs::Linux | ClientOs::Windows => mac_address.replace(':', "-"),
ClientOs::Mac | ClientOs::Ios => mac_address.replace('-', ":"),
}
}
mod native {
use super::*;
pub(super) fn project(
client_os: ClientOs,
host_identity: &HostIdentity,
computer_override: Option<String>,
) -> ProfileHostIdentity {
ProfileHostIdentity {
computer: computer(host_identity, computer_override),
host_id: match client_os {
ClientOs::Mac => host_identity.host_id().replace('-', ":"),
ClientOs::Linux | ClientOs::Windows | ClientOs::Ios => host_identity.host_id().to_string(),
},
serial_number: host_identity.serialno().to_string(),
mac_address: profile_mac_for(client_os, host_identity.mac_addr()),
}
}
}
mod linux {
use super::*;
pub(super) fn project(host_identity: &HostIdentity, computer_override: Option<String>) -> ProfileHostIdentity {
let seed = host_identity.host_id();
let host_id = derive_uuid_from_seed(seed, &["os-profile", ClientOs::Linux.as_str(), "host-id"]);
ProfileHostIdentity {
computer: computer(host_identity, computer_override),
serial_number: serial_number::vmware_from_uuid(&host_id).expect("projected Linux host ID should be a UUID"),
host_id,
mac_address: derived_profile_mac(seed, ClientOs::Linux),
}
}
}
mod windows {
use super::*;
pub(super) fn project(host_identity: &HostIdentity, computer_override: Option<String>) -> ProfileHostIdentity {
let seed = host_identity.host_id();
ProfileHostIdentity {
computer: computer(host_identity, computer_override),
host_id: derive_uuid_from_seed(seed, &["os-profile", ClientOs::Windows.as_str(), "host-id"]),
serial_number: serial_number::vmware_from_compact_hex(&compact_uuid(seed, ClientOs::Windows, "serialno"))
.expect("projected Windows serial seed should be compact hex"),
mac_address: derived_profile_mac(seed, ClientOs::Windows),
}
}
}
mod macos {
use super::*;
pub(super) fn project(host_identity: &HostIdentity, computer_override: Option<String>) -> ProfileHostIdentity {
let seed = host_identity.host_id();
let mac_address = derived_profile_mac(seed, ClientOs::Mac);
ProfileHostIdentity {
computer: computer(host_identity, computer_override),
host_id: mac_address.clone(),
serial_number: compact_uuid(seed, ClientOs::Mac, "serialno").chars().take(10).collect(),
mac_address,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn host_identity() -> HostIdentity {
HostIdentity::from_parts(
"real-computer".to_string(),
"real-host-id".to_string(),
"real-serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
)
}
#[test]
fn native_linux_projection_uses_real_identity_with_dash_mac() {
let profile = native::project(ClientOs::Linux, &host_identity(), None);
assert_eq!(profile.computer(), "real-computer");
assert_eq!(profile.host_id(), "real-host-id");
assert_eq!(profile.serialno(), "real-serial");
assert_eq!(profile.mac_addr(), "aa-bb-cc-dd-ee-ff");
}
#[test]
fn native_windows_projection_uses_real_identity_with_dash_mac() {
let profile = native::project(ClientOs::Windows, &host_identity(), None);
assert_eq!(profile.computer(), "real-computer");
assert_eq!(profile.host_id(), "real-host-id");
assert_eq!(profile.serialno(), "real-serial");
assert_eq!(profile.mac_addr(), "aa-bb-cc-dd-ee-ff");
}
#[test]
fn native_macos_projection_uses_real_identity_with_colon_mac() {
let profile = native::project(ClientOs::Mac, &host_identity(), None);
assert_eq!(profile.computer(), "real-computer");
assert_eq!(profile.host_id(), "real:host:id");
assert_eq!(profile.serialno(), "real-serial");
assert_eq!(profile.mac_addr(), "aa:bb:cc:dd:ee:ff");
}
}
+634
View File
@@ -0,0 +1,634 @@
use super::*;
#[test]
fn negotiated_os_version_is_used_in_profile_and_user_agent() {
let identity = HostIdentity::from_parts(
"device".into(),
"host".into(),
"serial".into(),
"00:11:22:33:44:55".into(),
);
let profile = OsProfileBuilder::new(ClientOs::Mac)
.host_identity(identity)
.client_version("6.3.3")
.os_version("negotiated-system-version")
.build(test_snapshot());
assert_eq!(profile.os_version(), "negotiated-system-version");
assert!(profile.user_agent().contains("negotiated-system-version"));
}
#[test]
fn csc_support_defaults_match_official_profiles() {
assert!(!ClientOs::Linux.default_csc_support());
assert!(ClientOs::Mac.default_csc_support());
assert!(ClientOs::Windows.default_csc_support());
}
#[test]
fn prelogin_param_location_matches_official_profiles() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.prelogin_param_location(),
PreloginParamLocation::Body
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.prelogin_param_location(),
PreloginParamLocation::Body
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.prelogin_param_location(),
PreloginParamLocation::Query
);
}
#[test]
fn embedded_portal_default_browser_is_minus_ten_for_all() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.portal_default_browser(PreloginBrowserMode::Embedded),
"-10"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.portal_default_browser(PreloginBrowserMode::Embedded),
"-10"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.portal_default_browser(PreloginBrowserMode::Embedded),
"-10"
);
}
#[test]
fn embedded_gateway_default_browser_is_zero_for_all() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.gateway_default_browser(PreloginBrowserMode::Embedded),
"0"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.gateway_default_browser(PreloginBrowserMode::Embedded),
"0"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.gateway_default_browser(PreloginBrowserMode::Embedded),
"0"
);
}
#[test]
fn external_default_browser_values_match_official_profiles() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.portal_default_browser(PreloginBrowserMode::External),
"4"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.portal_default_browser(PreloginBrowserMode::External),
"3"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.portal_default_browser(PreloginBrowserMode::External),
"2"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.gateway_default_browser(PreloginBrowserMode::External),
"4"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.gateway_default_browser(PreloginBrowserMode::External),
"3"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.gateway_default_browser(PreloginBrowserMode::External),
"2"
);
}
#[test]
fn saml_password_matches_official_profiles() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.saml_password(),
"SAMLPASS"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.saml_password(),
""
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.saml_password(),
""
);
}
#[test]
fn gateway_server_uses_resolved_ipv4_for_all() {
assert!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.gateway_server_uses_resolved_ipv4()
);
assert!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.gateway_server_uses_resolved_ipv4()
);
assert!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.gateway_server_uses_resolved_ipv4()
);
}
#[test]
fn kerberos_support_in_query_matches_official_profiles() {
assert!(
!OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.kerberos_support_in_query()
);
assert!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.kerberos_support_in_query()
);
assert!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.kerberos_support_in_query()
);
}
#[test]
fn os_vendor_matches_official_profiles() {
assert_eq!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.os_vendor(),
"Linux"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Mac).build(test_snapshot()).os_vendor(),
"Apple"
);
assert_eq!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.os_vendor(),
"Microsoft"
);
}
#[test]
fn supports_macos_plist_csc_only_for_mac() {
assert!(
!OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.supports_macos_plist_csc()
);
assert!(
OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.supports_macos_plist_csc()
);
assert!(
!OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.supports_macos_plist_csc()
);
}
#[test]
fn supports_linux_process_csc_only_for_linux() {
assert!(
OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.supports_linux_process_csc()
);
assert!(
!OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.supports_linux_process_csc()
);
assert!(
!OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.supports_linux_process_csc()
);
}
#[test]
fn supports_windows_registry_csc_only_for_windows() {
assert!(
!OsProfileBuilder::new(ClientOs::Linux)
.build(test_snapshot())
.supports_windows_registry_csc()
);
assert!(
!OsProfileBuilder::new(ClientOs::Mac)
.build(test_snapshot())
.supports_windows_registry_csc()
);
assert!(
OsProfileBuilder::new(ClientOs::Windows)
.build(test_snapshot())
.supports_windows_registry_csc()
);
}
// ─── User Agent Tests ───────────────────────────────────────────────────────
#[test]
fn user_agent_derived_format_without_override() {
let profile = OsProfileBuilder::new(ClientOs::Linux)
.client_version("6.0.0")
.build(test_snapshot());
assert_eq!(
profile.user_agent(),
format!("PAN GlobalProtect/6.0.0 ({})", defaults::os_version(ClientOs::Linux))
);
}
#[test]
fn user_agent_explicit_override_returns_custom_value() {
let profile = OsProfileBuilder::new(ClientOs::Linux)
.client_version("6.0.0")
.user_agent("custom/1.0")
.build(test_snapshot());
assert_eq!(profile.user_agent(), "custom/1.0");
}
#[test]
fn user_agent_empty_override_falls_back_to_derived() {
let profile = OsProfileBuilder::new(ClientOs::Linux)
.client_version("6.0.0")
.user_agent("")
.build(test_snapshot());
assert_eq!(
profile.user_agent(),
format!("PAN GlobalProtect/6.0.0 ({})", defaults::os_version(ClientOs::Linux))
);
}
#[test]
fn user_agent_whitespace_only_override_falls_back_to_derived() {
let profile = OsProfileBuilder::new(ClientOs::Linux)
.client_version("6.0.0")
.user_agent(" ")
.build(test_snapshot());
assert_eq!(
profile.user_agent(),
format!("PAN GlobalProtect/6.0.0 ({})", defaults::os_version(ClientOs::Linux))
);
}
#[test]
fn user_agent_derived_is_non_empty_for_all_client_os_variants() {
for client_os in [ClientOs::Linux, ClientOs::Windows, ClientOs::Mac] {
let profile = OsProfileBuilder::new(client_os).build(test_snapshot());
assert!(
!profile.user_agent().is_empty(),
"user_agent() should be non-empty for {:?}",
client_os
);
}
}
#[test]
fn native_webview_user_agent_uses_native_default() {
let profile = OsProfileBuilder::new(ClientOs::Mac).build(test_snapshot());
let user_agent = profile.webview_user_agent();
assert_eq!(
user_agent,
WebviewUserAgent::Native {
prefix: profile.user_agent().to_string(),
transform: target::webview_user_agent_transform(ClientOs::Mac)
}
);
}
#[test]
fn projected_linux_webview_user_agent_uses_linux_default() {
if ClientOs::Mac == ClientOs::Linux {
return;
}
let client_os = ClientOs::Linux;
let profile = OsProfileBuilder::new(client_os).build(test_snapshot());
let user_agent = profile.webview_user_agent();
assert_eq!(
user_agent,
WebviewUserAgent::Projected {
prefix: profile.user_agent().to_string(),
default_user_agent: DEFAULT_LINUX_WEBVIEW_USER_AGENT.to_string()
}
);
}
#[test]
fn projected_macos_webview_user_agent_uses_macos_default() {
if ClientOs::Mac == ClientOs::Mac {
return;
}
let client_os = ClientOs::Mac;
let profile = OsProfileBuilder::new(client_os).build(test_snapshot());
let user_agent = profile.webview_user_agent();
assert_eq!(
user_agent,
WebviewUserAgent::Projected {
prefix: profile.user_agent().to_string(),
default_user_agent: DEFAULT_MACOS_WEBVIEW_USER_AGENT.to_string()
}
);
}
#[test]
fn projected_windows_webview_user_agent_uses_windows_default() {
if ClientOs::Mac == ClientOs::Windows {
return;
}
let client_os = ClientOs::Windows;
let profile = OsProfileBuilder::new(client_os).build(test_snapshot());
let user_agent = profile.webview_user_agent();
assert_eq!(
user_agent,
WebviewUserAgent::Projected {
prefix: profile.user_agent().to_string(),
default_user_agent: DEFAULT_WINDOWS_WEBVIEW_USER_AGENT.to_string()
}
);
}
#[test]
fn os_version_strings_match_profiles() {
assert!(defaults::os_version(ClientOs::Linux).starts_with("Linux "));
assert!(defaults::os_version(ClientOs::Mac).starts_with("Apple Mac OS X "));
assert!(defaults::os_version(ClientOs::Windows).starts_with("Microsoft "));
assert_eq!(defaults::software_version(ClientOs::Linux), "");
assert!(!defaults::software_version(ClientOs::Mac).is_empty());
assert!(!defaults::software_version(ClientOs::Windows).is_empty());
}
#[test]
fn builder_fills_defaults_when_nothing_specified() {
let profile = OsProfileBuilder::new(ClientOs::Linux).build(test_snapshot());
assert_eq!(profile.client_os(), ClientOs::Linux);
assert!(!profile.computer().is_empty());
assert!(profile.os_version().starts_with("Linux "));
assert_eq!(profile.client_version(), GP_CLIENT_VERSION_LINUX);
assert!(!profile.host_id().is_empty());
}
#[test]
fn builder_uses_explicit_values_when_provided() {
let identity = HostIdentity::from_parts(
"identity-computer".to_string(),
"test-host-id".to_string(),
"test-serial".to_string(),
"aa:bb:cc:dd:ee:ff".to_string(),
);
let profile = OsProfileBuilder::new(ClientOs::Mac)
.computer_name_override("MyMac")
.client_version("6.2.0-100")
.host_identity(identity.clone())
.build(test_snapshot());
assert_eq!(profile.client_os(), ClientOs::Mac);
assert_eq!(profile.computer(), "MyMac");
assert!(profile.os_version().starts_with("Apple Mac OS X "));
assert_eq!(profile.client_version(), "6.2.0-100");
assert_eq!(profile.host_identity(), &identity);
assert!(!profile.host_id().is_empty());
assert!(!profile.serialno().is_empty());
assert!(!profile.mac_addr().is_empty());
}
#[test]
fn builder_ignores_empty_strings() {
let profile = OsProfileBuilder::new(ClientOs::Windows)
.computer_name_override("")
.client_version("")
.build(test_snapshot());
// Should fall back to defaults, not use empty strings
assert!(!profile.computer().is_empty());
assert!(profile.os_version().starts_with("Microsoft "));
assert_eq!(profile.client_version(), GP_CLIENT_VERSION_WINDOWS);
}
#[test]
fn identity_accessors_delegate_to_host_identity() {
let identity = HostIdentity::from_parts(
"test-computer".to_string(),
"host-123".to_string(),
"serial-456".to_string(),
"11:22:33:44:55:66".to_string(),
);
let profile = OsProfileBuilder::new(ClientOs::Mac)
.host_identity(identity)
.build(test_snapshot());
assert!(!profile.host_id().is_empty());
assert_eq!(profile.serialno(), "serial-456");
assert!(!profile.mac_addr().is_empty());
}
#[test]
fn local_hostname_override_changes_only_projected_computer() {
let identity = HostIdentity::from_parts(
"real-computer".to_string(),
"real-host-id".to_string(),
"real-serial".to_string(),
"11:22:33:44:55:66".to_string(),
);
let profile = OsProfileBuilder::new(ClientOs::Mac)
.host_identity(identity)
.computer_name_override("profile-computer")
.build(test_snapshot());
assert_eq!(profile.computer(), "profile-computer");
assert_eq!(profile.host_identity().computer(), "real-computer");
}
#[test]
fn simulated_profile_identity_is_derived_from_real_host_id() {
let client_os = non_native_client_os();
let identity = HostIdentity::from_parts(
"real-computer".to_string(),
"stable-real-host-id".to_string(),
"real-serial".to_string(),
"11:22:33:44:55:66".to_string(),
);
let first = OsProfileBuilder::new(client_os)
.host_identity(identity.clone())
.build(test_snapshot());
let second = OsProfileBuilder::new(client_os)
.host_identity(identity)
.build(test_snapshot());
assert_eq!(first.host_identity().host_id(), "stable-real-host-id");
assert_ne!(first.host_id(), "stable-real-host-id");
assert_eq!(first.host_id(), second.host_id());
assert_eq!(first.serialno(), second.serialno());
assert_eq!(first.mac_addr(), second.mac_addr());
}
#[test]
fn simulated_linux_serial_uses_vmware_style_uuid_bytes() {
if ClientOs::Mac == ClientOs::Linux {
return;
}
let identity = HostIdentity::from_parts(
"real-computer".to_string(),
"stable-real-host-id".to_string(),
"real-serial".to_string(),
"11:22:33:44:55:66".to_string(),
);
let profile = OsProfileBuilder::new(ClientOs::Linux)
.host_identity(identity)
.build(test_snapshot());
assert!(profile.serialno().starts_with("VMware-"));
assert_eq!(
profile.serialno().len(),
"VMware-56 4d 78 5a 61 64 ac 19-9e a9 d3 6a 3b 9c 6c ef".len()
);
}
#[test]
fn profile_os_versions_are_not_host_identity_fields() {
let identity = HostIdentity::from_parts(
"real-computer".to_string(),
"stable-real-host-id".to_string(),
"real-serial".to_string(),
"11:22:33:44:55:66".to_string(),
);
let profile = OsProfileBuilder::new(ClientOs::Mac)
.host_identity(identity)
.build(test_snapshot());
let value = serde_json::to_value(profile.host_identity()).unwrap();
assert!(value.get("osVersion").is_none());
assert!(value.get("softwareVersion").is_none());
assert!(profile.os_version().starts_with("Apple Mac OS X "));
assert!(!profile.software_version().is_empty());
}
fn non_native_client_os() -> ClientOs {
match ClientOs::Mac {
ClientOs::Linux => ClientOs::Mac,
ClientOs::Mac | ClientOs::Windows | ClientOs::Ios => ClientOs::Linux,
}
}
// ─── Property-Based Tests ─────────────────────────────────────────────────
mod prop_tests {
use super::*;
use proptest::prelude::*;
// **Validates: Requirements 1.1, 1.2, 1.3, 1.4, 2.3, 12.1, 12.2**
//
// Property 1: Derived user agent format
// For any valid OsProfile built without a user agent override (with arbitrary
// non-empty client_version), user_agent() returns a non-empty string matching
// the format "PAN GlobalProtect/{client_version} ({profile.os_version})".
proptest! {
#[test]
fn derived_user_agent_format(
cv in "\\S{1,50}",
) {
let profile = OsProfileBuilder::new(ClientOs::Linux)
.client_version(cv.clone())
.build(test_snapshot());
let expected = format!("PAN GlobalProtect/{} ({})", cv, profile.os_version());
prop_assert_eq!(profile.user_agent(), expected.as_str());
prop_assert!(!profile.user_agent().is_empty());
}
}
// **Validates: Requirements 2.2, 12.3**
//
// Property 2: Override returns verbatim
// For any non-whitespace-only string provided to OsProfileBuilder::user_agent(),
// the resulting OsProfile::user_agent() returns the exact input.
proptest! {
#[test]
fn override_returns_verbatim(ua in "[^\\s][\\s\\S]{0,49}") {
let profile = OsProfileBuilder::new(ClientOs::Linux)
.user_agent(ua.clone())
.build(test_snapshot());
prop_assert_eq!(profile.user_agent(), ua.as_str());
}
}
// **Validates: Requirements 2.4**
//
// Property 3: Whitespace override falls back to derived
// For any string composed entirely of whitespace characters provided to
// OsProfileBuilder::user_agent(), the resulting OsProfile::user_agent()
// returns the derived format (not the whitespace string).
proptest! {
#[test]
fn whitespace_override_falls_back_to_derived(ws in "[ \\t\\n]{1,20}") {
let profile = OsProfileBuilder::new(ClientOs::Linux)
.client_version("6.0.0")
.user_agent(ws.clone())
.build(test_snapshot());
// The result must be the derived format, not the whitespace string
let expected = format!("PAN GlobalProtect/6.0.0 ({})", profile.os_version());
prop_assert_eq!(profile.user_agent(), expected.as_str());
prop_assert_ne!(profile.user_agent(), ws.as_str());
}
}
}