Compare commits

..

No commits in common. "1b1ce882a532c583848a8de70e01894b5550f741" and "cec0d22dc883ecaf4701685ffb12cf459951ab2d" have entirely different histories.

8 changed files with 198 additions and 174 deletions

View File

@ -25,9 +25,9 @@ jobs:
id: set-matrix id: set-matrix
run: | run: |
if [[ "${{ github.ref }}" == "refs/tags/"* ]]; then if [[ "${{ github.ref }}" == "refs/tags/"* ]]; then
echo 'matrix=[{"runner": "ubuntu-latest", "arch": "amd64"}, {"runner": "arm64", "arch": "arm64"]' >> $GITHUB_OUTPUT echo "matrix=[\"ubuntu-latest\", \"arm64\"]" >> $GITHUB_OUTPUT
else else
echo 'matrix=[{"runner": "ubuntu-latest", "arch": "amd64"}]' >> $GITHUB_OUTPUT echo "matrix=[\"ubuntu-latest\"]" >> $GITHUB_OUTPUT
fi fi
tarball: tarball:
@ -70,8 +70,7 @@ jobs:
matrix: matrix:
os: ${{fromJson(needs.setup-matrix.outputs.matrix)}} os: ${{fromJson(needs.setup-matrix.outputs.matrix)}}
package: [deb, rpm, pkg, binary] package: [deb, rpm, pkg, binary]
runs-on: ${{ matrix.os.runner }} runs-on: ${{ matrix.os }}
name: build-gp (${{ matrix.package }}, ${{ matrix.os.arch }})
steps: steps:
- name: Prepare workspace - name: Prepare workspace
run: | run: |
@ -99,7 +98,7 @@ jobs:
- name: Upload ${{ matrix.package }} package - name: Upload ${{ matrix.package }} package
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v3
with: with:
name: artifact-gp-${{ matrix.package }}-${{ matrix.os.arch }} name: artifact-gp-${{ matrix.os }}-${{ matrix.package }}
if-no-files-found: error if-no-files-found: error
path: | path: |
build-gp-${{ matrix.package }}/artifacts/* build-gp-${{ matrix.package }}/artifacts/*
@ -110,8 +109,7 @@ jobs:
strategy: strategy:
matrix: matrix:
os: ${{fromJson(needs.setup-matrix.outputs.matrix)}} os: ${{fromJson(needs.setup-matrix.outputs.matrix)}}
runs-on: ${{ matrix.os.runner }} runs-on: ${{ matrix.os }}
name: build-gpgui (${{ matrix.os.arch }})
steps: steps:
- uses: pnpm/action-setup@v2 - uses: pnpm/action-setup@v2
with: with:
@ -150,17 +148,16 @@ jobs:
- name: Upload gpgui - name: Upload gpgui
uses: actions/upload-artifact@v3 uses: actions/upload-artifact@v3
with: with:
name: artifact-gpgui-${{ matrix.os.arch }} name: artifact-gpgui-${{ matrix.os }}
if-no-files-found: error if-no-files-found: error
path: | path: |
gpgui-source/*.bin.tar.xz gpgui-source/*.bin.tar.xz
gpgui-source/*.bin.tar.xz.sha256 gpgui-source/*.bin.tar.xz.sha256
gh-release: gh-release:
if: ${{ github.ref == 'refs/heads/dev' || startsWith(github.ref, 'refs/tags/') }} if: startsWith(github.ref, 'refs/tags/') || github.ref == 'refs/heads/dev'
runs-on: ubuntu-latest runs-on: ubuntu-latest
needs: needs:
- tarball
- build-gp - build-gp
- build-gpgui - build-gpgui
@ -175,14 +172,12 @@ jobs:
env: env:
GH_TOKEN: ${{ secrets.GH_PAT }} GH_TOKEN: ${{ secrets.GH_PAT }}
RELEASE_TAG: ${{ github.ref == 'refs/heads/dev' && 'snapshot' || github.ref_name }} RELEASE_TAG: ${{ github.ref == 'refs/heads/dev' && 'snapshot' || github.ref_name }}
REPO: ${{ github.repository }}
NOTES: ${{ github.ref == 'refs/heads/dev' && '**!!! DO NOT USE THIS RELEASE IN PRODUCTION !!!**' || format('Release {0}', github.ref_name) }}
run: | run: |
gh -R "$REPO" release delete $RELEASE_TAG --yes --cleanup-tag || true gh release delete $RELEASE_TAG --yes --cleanup-tag || true
gh -R "$REPO" release create $RELEASE_TAG \ gh release create $RELEASE_TAG \
--title "$RELEASE_TAG" \ --title "$RELEASE_TAG" \
--notes "$NOTES" \ --notes "Release $RELEASE_TAG" \
--target ${{ github.ref }} \ --target ${{ github.ref}} \
${{ github.ref == 'refs/heads/dev' && '--prerelease' || '' }} \ ${{ github.ref == 'refs/heads/dev' && '--prerelease' || '' }} \
gh-release/artifact-source/* \ "gh-release/artifact-source/*" \
gh-release/artifact-gpgui-*/* "gh-release/artifact-gpgui-*/*"

View File

@ -7,7 +7,6 @@ use std::{
use anyhow::bail; use anyhow::bail;
use gpapi::{ use gpapi::{
auth::SamlAuthData, auth::SamlAuthData,
error::AuthDataParseError,
gp_params::GpParams, gp_params::GpParams,
portal::{prelogin, Prelogin}, portal::{prelogin, Prelogin},
utils::{redact::redact_uri, window::WindowExt}, utils::{redact::redact_uri, window::WindowExt},
@ -360,29 +359,32 @@ fn read_auth_data_from_html(html: &str) -> AuthResult {
return Err(AuthDataError::Invalid); return Err(AuthDataError::Invalid);
} }
let auth_data = match SamlAuthData::from_html(html) { match parse_xml_tag(html, "saml-auth-status") {
Ok(auth_data) => Ok(auth_data), Some(saml_status) if saml_status == "1" => {
Err(err) => { let username = parse_xml_tag(html, "saml-username");
if let Some(gpcallback) = extract_gpcallback(html) { let prelogin_cookie = parse_xml_tag(html, "prelogin-cookie");
info!("Found gpcallback from html..."); let portal_userauthcookie = parse_xml_tag(html, "portal-userauthcookie");
SamlAuthData::from_gpcallback(gpcallback)
} else { if SamlAuthData::check(&username, &prelogin_cookie, &portal_userauthcookie) {
Err(err) return Ok(SamlAuthData::new(
username.unwrap(),
prelogin_cookie,
portal_userauthcookie,
));
} }
info!("Found invalid auth data in HTML");
Err(AuthDataError::Invalid)
} }
}; Some(status) => {
info!("Found invalid SAML status {} in HTML", status);
auth_data.map_err(|err| match err { Err(AuthDataError::Invalid)
AuthDataParseError::NotFound => AuthDataError::NotFound, }
AuthDataParseError::Invalid => AuthDataError::Invalid, None => {
}) info!("No auth data found in HTML");
} Err(AuthDataError::NotFound)
}
fn extract_gpcallback(html: &str) -> Option<&str> { }
let re = Regex::new(r#"globalprotectcallback:[^"]+"#).unwrap();
re.captures(html)
.and_then(|captures| captures.get(0))
.map(|m| m.as_str())
} }
fn read_auth_data(main_resource: &WebResource, auth_result_tx: mpsc::UnboundedSender<AuthResult>) { fn read_auth_data(main_resource: &WebResource, auth_result_tx: mpsc::UnboundedSender<AuthResult>) {
@ -435,6 +437,13 @@ fn read_auth_data(main_resource: &WebResource, auth_result_tx: mpsc::UnboundedSe
} }
} }
fn parse_xml_tag(html: &str, tag: &str) -> Option<String> {
let re = Regex::new(&format!("<{}>(.*)</{}>", tag, tag)).unwrap();
re.captures(html)
.and_then(|captures| captures.get(1))
.map(|m| m.as_str().to_string())
}
pub(crate) async fn clear_webview_cookies(window: &Window) -> anyhow::Result<()> { pub(crate) async fn clear_webview_cookies(window: &Window) -> anyhow::Result<()> {
let (tx, rx) = oneshot::channel::<Result<(), String>>(); let (tx, rx) = oneshot::channel::<Result<(), String>>();
@ -480,27 +489,3 @@ pub(crate) async fn clear_webview_cookies(window: &Window) -> anyhow::Result<()>
rx.await?.map_err(|err| anyhow::anyhow!(err)) rx.await?.map_err(|err| anyhow::anyhow!(err))
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extract_gpcallback_some() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:PGh0bWw+PCEtLSA8c">
<meta http-equiv="refresh" content="0; URL=globalprotectcallback:PGh0bWw+PCEtLSA8c">
"#;
assert_eq!(extract_gpcallback(html), Some("globalprotectcallback:PGh0bWw+PCEtLSA8c"));
}
#[test]
fn extract_gpcallback_none() {
let html = r#"
<meta http-equiv="refresh" content="0; URL=PGh0bWw+PCEtLSA8c">
"#;
assert_eq!(extract_gpcallback(html), None);
}
}

View File

@ -1,17 +1,13 @@
use log::{info, warn}; use anyhow::anyhow;
use regex::Regex; use regex::Regex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{error::AuthDataParseError, utils::base64::decode_to_string};
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct SamlAuthData { pub struct SamlAuthData {
#[serde(alias = "un")]
username: String, username: String,
prelogin_cookie: Option<String>, prelogin_cookie: Option<String>,
portal_userauthcookie: Option<String>, portal_userauthcookie: Option<String>,
token: Option<String>,
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
@ -36,11 +32,10 @@ impl SamlAuthData {
username, username,
prelogin_cookie, prelogin_cookie,
portal_userauthcookie, portal_userauthcookie,
token: None,
} }
} }
pub fn from_html(html: &str) -> anyhow::Result<SamlAuthData, AuthDataParseError> { pub fn from_html(html: &str) -> anyhow::Result<SamlAuthData> {
match parse_xml_tag(html, "saml-auth-status") { match parse_xml_tag(html, "saml-auth-status") {
Some(saml_status) if saml_status == "1" => { Some(saml_status) if saml_status == "1" => {
let username = parse_xml_tag(html, "saml-username"); let username = parse_xml_tag(html, "saml-username");
@ -54,36 +49,11 @@ impl SamlAuthData {
portal_userauthcookie, portal_userauthcookie,
)) ))
} else { } else {
Err(AuthDataParseError::Invalid) Err(anyhow!("Found invalid auth data in HTML"))
} }
} }
Some(_) => Err(AuthDataParseError::Invalid), Some(status) => Err(anyhow!("Found invalid SAML status {} in HTML", status)),
None => Err(AuthDataParseError::NotFound), None => Err(anyhow!("No auth data found in HTML")),
}
}
pub fn from_gpcallback(data: &str) -> anyhow::Result<SamlAuthData, AuthDataParseError> {
let auth_data = data.trim_start_matches("globalprotectcallback:");
if auth_data.starts_with("cas-as") {
info!("Got token auth data: {}", auth_data);
let token_cred: SamlAuthData = serde_urlencoded::from_str(auth_data).map_err(|e| {
warn!("Failed to parse token auth data: {}", e);
AuthDataParseError::Invalid
})?;
Ok(token_cred)
} else {
info!("Parsing SAML auth data...");
let auth_data = decode_to_string(auth_data).map_err(|e| {
warn!("Failed to decode SAML auth data: {}", e);
AuthDataParseError::Invalid
})?;
let auth_data = Self::from_html(&auth_data)?;
Ok(auth_data)
} }
} }
@ -95,10 +65,6 @@ impl SamlAuthData {
self.prelogin_cookie.as_deref() self.prelogin_cookie.as_deref()
} }
pub fn token(&self) -> Option<&str> {
self.token.as_deref()
}
pub fn check( pub fn check(
username: &Option<String>, username: &Option<String>,
prelogin_cookie: &Option<String>, prelogin_cookie: &Option<String>,
@ -108,16 +74,7 @@ impl SamlAuthData {
let prelogin_cookie_valid = prelogin_cookie.as_ref().is_some_and(|val| val.len() > 5); let prelogin_cookie_valid = prelogin_cookie.as_ref().is_some_and(|val| val.len() > 5);
let portal_userauthcookie_valid = portal_userauthcookie.as_ref().is_some_and(|val| val.len() > 5); let portal_userauthcookie_valid = portal_userauthcookie.as_ref().is_some_and(|val| val.len() > 5);
let is_valid = username_valid && (prelogin_cookie_valid || portal_userauthcookie_valid); username_valid && (prelogin_cookie_valid || portal_userauthcookie_valid)
if !is_valid {
warn!(
"Invalid SAML auth data: username: {:?}, prelogin-cookie: {:?}, portal-userauthcookie: {:?}",
username, prelogin_cookie, portal_userauthcookie
);
}
is_valid
} }
} }
@ -127,28 +84,3 @@ pub fn parse_xml_tag(html: &str, tag: &str) -> Option<String> {
.and_then(|captures| captures.get(1)) .and_then(|captures| captures.get(1))
.map(|m| m.as_str().to_string()) .map(|m| m.as_str().to_string())
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn auth_data_from_gpcallback_cas() {
let auth_data = "globalprotectcallback:cas-as=1&un=xyz@email.com&token=very_long_string";
let auth_data = SamlAuthData::from_gpcallback(auth_data).unwrap();
assert_eq!(auth_data.username(), "xyz@email.com");
assert_eq!(auth_data.token(), Some("very_long_string"));
}
#[test]
fn auth_data_from_gpcallback_non_cas() {
let auth_data = "PGh0bWw+PCEtLSA8c2FtbC1hdXRoLXN0YXR1cz4xPC9zYW1sLWF1dGgtc3RhdHVzPjxwcmVsb2dpbi1jb29raWU+cHJlbG9naW4tY29va2llPC9wcmVsb2dpbi1jb29raWU+PHNhbWwtdXNlcm5hbWU+eHl6QGVtYWlsLmNvbTwvc2FtbC11c2VybmFtZT48c2FtbC1zbG8+bm88L3NhbWwtc2xvPjxzYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+PC9zYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+IC0tPjwvaHRtbD4=";
let auth_data = SamlAuthData::from_gpcallback(auth_data).unwrap();
assert_eq!(auth_data.username(), "xyz@email.com");
assert_eq!(auth_data.prelogin_cookie(), Some("prelogin-cookie"));
}
}

View File

@ -1,9 +1,10 @@
use std::collections::HashMap; use std::collections::HashMap;
use log::info;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use specta::Type; use specta::Type;
use crate::auth::SamlAuthData; use crate::{auth::SamlAuthData, utils::base64::decode_to_string};
#[derive(Debug, Serialize, Deserialize, Type, Clone)] #[derive(Debug, Serialize, Deserialize, Type, Clone)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
@ -39,16 +40,14 @@ impl From<&CachedCredential> for PasswordCredential {
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct PreloginCookieCredential { pub struct PreloginCookieCredential {
username: String, username: String,
prelogin_cookie: Option<String>, prelogin_cookie: String,
token: Option<String>,
} }
impl PreloginCookieCredential { impl PreloginCookieCredential {
pub fn new(username: &str, prelogin_cookie: Option<&str>, token: Option<&str>) -> Self { pub fn new(username: &str, prelogin_cookie: &str) -> Self {
Self { Self {
username: username.to_string(), username: username.to_string(),
prelogin_cookie: prelogin_cookie.map(|s| s.to_string()), prelogin_cookie: prelogin_cookie.to_string(),
token: token.map(|s| s.to_string()),
} }
} }
@ -56,22 +55,22 @@ impl PreloginCookieCredential {
&self.username &self.username
} }
pub fn prelogin_cookie(&self) -> Option<&str> { pub fn prelogin_cookie(&self) -> &str {
self.prelogin_cookie.as_deref() &self.prelogin_cookie
}
pub fn token(&self) -> Option<&str> {
self.token.as_deref()
} }
} }
impl From<SamlAuthData> for PreloginCookieCredential { impl TryFrom<SamlAuthData> for PreloginCookieCredential {
fn from(value: SamlAuthData) -> Self { type Error = anyhow::Error;
let username = value.username().to_string();
let prelogin_cookie = value.prelogin_cookie();
let token = value.token();
Self::new(&username, prelogin_cookie, token) fn try_from(value: SamlAuthData) -> Result<Self, Self::Error> {
let username = value.username().to_string();
let prelogin_cookie = value
.prelogin_cookie()
.ok_or_else(|| anyhow::anyhow!("Missing prelogin cookie"))?
.to_string();
Ok(Self::new(&username, &prelogin_cookie))
} }
} }
@ -156,12 +155,31 @@ impl From<PasswordCredential> for CachedCredential {
) )
} }
} }
#[derive(Debug, Serialize, Deserialize, Type, Clone)]
pub struct TokenCredential {
#[serde(alias = "un")]
username: String,
token: String,
}
impl TokenCredential {
pub fn username(&self) -> &str {
&self.username
}
pub fn token(&self) -> &str {
&self.token
}
}
#[derive(Debug, Serialize, Deserialize, Type, Clone)] #[derive(Debug, Serialize, Deserialize, Type, Clone)]
#[serde(tag = "type", rename_all = "camelCase")] #[serde(tag = "type", rename_all = "camelCase")]
pub enum Credential { pub enum Credential {
Password(PasswordCredential), Password(PasswordCredential),
PreloginCookie(PreloginCookieCredential), PreloginCookie(PreloginCookieCredential),
AuthCookie(AuthCookieCredential), AuthCookie(AuthCookieCredential),
TokenCredential(TokenCredential),
CachedCredential(CachedCredential), CachedCredential(CachedCredential),
} }
@ -169,9 +187,19 @@ impl Credential {
/// Create a credential from a globalprotectcallback:<base64 encoded string>, /// Create a credential from a globalprotectcallback:<base64 encoded string>,
/// or globalprotectcallback:cas-as=1&un=user@xyz.com&token=very_long_string /// or globalprotectcallback:cas-as=1&un=user@xyz.com&token=very_long_string
pub fn from_gpcallback(auth_data: &str) -> anyhow::Result<Self> { pub fn from_gpcallback(auth_data: &str) -> anyhow::Result<Self> {
let auth_data = SamlAuthData::from_gpcallback(auth_data)?; let auth_data = auth_data.trim_start_matches("globalprotectcallback:");
Ok(Self::from(auth_data)) if auth_data.starts_with("cas-as") {
info!("Got token auth data: {}", auth_data);
let token_cred: TokenCredential = serde_urlencoded::from_str(auth_data)?;
Ok(Self::TokenCredential(token_cred))
} else {
info!("Parsing SAML auth data...");
let auth_data = decode_to_string(auth_data)?;
let auth_data = SamlAuthData::from_html(&auth_data)?;
Self::try_from(auth_data)
}
} }
pub fn username(&self) -> &str { pub fn username(&self) -> &str {
@ -179,6 +207,7 @@ impl Credential {
Credential::Password(cred) => cred.username(), Credential::Password(cred) => cred.username(),
Credential::PreloginCookie(cred) => cred.username(), Credential::PreloginCookie(cred) => cred.username(),
Credential::AuthCookie(cred) => cred.username(), Credential::AuthCookie(cred) => cred.username(),
Credential::TokenCredential(cred) => cred.username(),
Credential::CachedCredential(cred) => cred.username(), Credential::CachedCredential(cred) => cred.username(),
} }
} }
@ -189,7 +218,7 @@ impl Credential {
let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie, token) = match self { let (passwd, prelogin_cookie, portal_userauthcookie, portal_prelogonuserauthcookie, token) = match self {
Credential::Password(cred) => (Some(cred.password()), None, None, None, None), Credential::Password(cred) => (Some(cred.password()), None, None, None, None),
Credential::PreloginCookie(cred) => (None, cred.prelogin_cookie(), None, None, cred.token()), Credential::PreloginCookie(cred) => (None, Some(cred.prelogin_cookie()), None, None, None),
Credential::AuthCookie(cred) => ( Credential::AuthCookie(cred) => (
None, None,
None, None,
@ -197,6 +226,7 @@ impl Credential {
Some(cred.prelogon_user_auth_cookie()), Some(cred.prelogon_user_auth_cookie()),
None, None,
), ),
Credential::TokenCredential(cred) => (None, None, None, None, Some(cred.token())),
Credential::CachedCredential(cred) => ( Credential::CachedCredential(cred) => (
cred.password(), cred.password(),
None, None,
@ -222,11 +252,13 @@ impl Credential {
} }
} }
impl From<SamlAuthData> for Credential { impl TryFrom<SamlAuthData> for Credential {
fn from(value: SamlAuthData) -> Self { type Error = anyhow::Error;
let cred = PreloginCookieCredential::from(value);
Self::PreloginCookie(cred) fn try_from(value: SamlAuthData) -> Result<Self, Self::Error> {
let prelogin_cookie = PreloginCookieCredential::try_from(value)?;
Ok(Self::PreloginCookie(prelogin_cookie))
} }
} }
@ -247,3 +279,38 @@ impl From<&CachedCredential> for Credential {
Self::CachedCredential(value.clone()) Self::CachedCredential(value.clone())
} }
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cred_from_gpcallback_cas() {
let auth_data = "globalprotectcallback:cas-as=1&un=xyz@email.com&token=very_long_string";
let cred = Credential::from_gpcallback(auth_data).unwrap();
match cred {
Credential::TokenCredential(token_cred) => {
assert_eq!(token_cred.username(), "xyz@email.com");
assert_eq!(token_cred.token(), "very_long_string");
}
_ => panic!("Expected TokenCredential"),
}
}
#[test]
fn cred_from_gpcallback_non_cas() {
let auth_data = "PGh0bWw+PCEtLSA8c2FtbC1hdXRoLXN0YXR1cz4xPC9zYW1sLWF1dGgtc3RhdHVzPjxwcmVsb2dpbi1jb29raWU+cHJlbG9naW4tY29va2llPC9wcmVsb2dpbi1jb29raWU+PHNhbWwtdXNlcm5hbWU+eHl6QGVtYWlsLmNvbTwvc2FtbC11c2VybmFtZT48c2FtbC1zbG8+bm88L3NhbWwtc2xvPjxzYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+PC9zYW1sLVNlc3Npb25Ob3RPbk9yQWZ0ZXI+IC0tPjwvaHRtbD4=";
let cred = Credential::from_gpcallback(auth_data).unwrap();
match cred {
Credential::PreloginCookie(cred) => {
assert_eq!(cred.username(), "xyz@email.com");
assert_eq!(cred.prelogin_cookie(), "prelogin-cookie");
}
_ => panic!("Expected PreloginCookieCredential")
}
}
}

View File

@ -9,11 +9,3 @@ pub enum PortalError {
#[error("Network error: {0}")] #[error("Network error: {0}")]
NetworkError(String), NetworkError(String),
} }
#[derive(Error, Debug)]
pub enum AuthDataParseError {
#[error("No auth data found")]
NotFound,
#[error("Invalid auth data")]
Invalid,
}

View File

@ -51,6 +51,7 @@ pub struct GpParams {
client_version: Option<String>, client_version: Option<String>,
computer: String, computer: String,
ignore_tls_errors: bool, ignore_tls_errors: bool,
prefer_default_browser: bool,
} }
impl GpParams { impl GpParams {
@ -78,6 +79,14 @@ impl GpParams {
self.ignore_tls_errors self.ignore_tls_errors
} }
pub fn prefer_default_browser(&self) -> bool {
self.prefer_default_browser
}
pub fn set_prefer_default_browser(&mut self, prefer_default_browser: bool) {
self.prefer_default_browser = prefer_default_browser;
}
pub fn client_os(&self) -> &str { pub fn client_os(&self) -> &str {
self.client_os.as_str() self.client_os.as_str()
} }
@ -126,6 +135,7 @@ pub struct GpParamsBuilder {
client_version: Option<String>, client_version: Option<String>,
computer: String, computer: String,
ignore_tls_errors: bool, ignore_tls_errors: bool,
prefer_default_browser: bool,
} }
impl GpParamsBuilder { impl GpParamsBuilder {
@ -138,6 +148,7 @@ impl GpParamsBuilder {
client_version: Default::default(), client_version: Default::default(),
computer: whoami::hostname(), computer: whoami::hostname(),
ignore_tls_errors: false, ignore_tls_errors: false,
prefer_default_browser: false,
} }
} }
@ -176,6 +187,11 @@ impl GpParamsBuilder {
self self
} }
pub fn prefer_default_browser(&mut self, prefer_default_browser: bool) -> &mut Self {
self.prefer_default_browser = prefer_default_browser;
self
}
pub fn build(&self) -> GpParams { pub fn build(&self) -> GpParams {
GpParams { GpParams {
is_gateway: self.is_gateway, is_gateway: self.is_gateway,
@ -185,6 +201,7 @@ impl GpParamsBuilder {
client_version: self.client_version.clone(), client_version: self.client_version.clone(),
computer: self.computer.clone(), computer: self.computer.clone(),
ignore_tls_errors: self.ignore_tls_errors, ignore_tls_errors: self.ignore_tls_errors,
prefer_default_browser: self.prefer_default_browser,
} }
} }
} }

View File

@ -29,6 +29,7 @@ pub struct SamlPrelogin {
is_gateway: bool, is_gateway: bool,
saml_request: String, saml_request: String,
support_default_browser: bool, support_default_browser: bool,
is_cas: bool,
} }
impl SamlPrelogin { impl SamlPrelogin {
@ -43,6 +44,14 @@ impl SamlPrelogin {
pub fn support_default_browser(&self) -> bool { pub fn support_default_browser(&self) -> bool {
self.support_default_browser self.support_default_browser
} }
pub fn is_cas(&self) -> bool {
self.is_cas
}
fn set_is_cas(&mut self, is_cas: bool) {
self.is_cas = is_cas;
}
} }
#[derive(Debug, Serialize, Type, Clone)] #[derive(Debug, Serialize, Type, Clone)]
@ -97,6 +106,29 @@ impl Prelogin {
} }
pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<Prelogin> { pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<Prelogin> {
match prelogin_impl(portal, gp_params).await {
Ok(prelogin) => Ok(prelogin),
Err(e) => {
if e.to_string().contains("CAS is not supported by the client") {
info!("CAS authentication detected, retrying with default browser");
let mut gp_params = gp_params.clone();
gp_params.set_prefer_default_browser(true);
let mut prelogin = prelogin_impl(portal, &gp_params).await?;
// Mark the prelogin as CAS
if let Prelogin::Saml(saml) = &mut prelogin {
saml.set_is_cas(true);
}
Ok(prelogin)
} else {
Err(e)
}
}
}
}
pub async fn prelogin_impl(portal: &str, gp_params: &GpParams) -> anyhow::Result<Prelogin> {
let user_agent = gp_params.user_agent(); let user_agent = gp_params.user_agent();
info!("Prelogin with user_agent: {}", user_agent); info!("Prelogin with user_agent: {}", user_agent);
@ -107,8 +139,11 @@ pub async fn prelogin(portal: &str, gp_params: &GpParams) -> anyhow::Result<Prel
let mut params = gp_params.to_params(); let mut params = gp_params.to_params();
params.insert("tmp", "tmp"); params.insert("tmp", "tmp");
params.insert("default-browser", "1"); // CAS support requires external browser
params.insert("cas-support", "yes"); if gp_params.prefer_default_browser() {
params.insert("default-browser", "1");
params.insert("cas-support", "yes");
}
params.retain(|k, _| REQUIRED_PARAMS.iter().any(|required_param| required_param == k)); params.retain(|k, _| REQUIRED_PARAMS.iter().any(|required_param| required_param == k));
@ -178,6 +213,7 @@ fn parse_res_xml(res_xml: String, is_gateway: bool) -> anyhow::Result<Prelogin>
is_gateway, is_gateway,
saml_request, saml_request,
support_default_browser, support_default_browser,
is_cas: false,
}; };
return Ok(Prelogin::Saml(saml_prelogin)); return Ok(Prelogin::Saml(saml_prelogin));

View File

@ -135,7 +135,7 @@ impl<'a> SamlAuthLauncher<'a> {
}; };
match auth_result { match auth_result {
SamlAuthResult::Success(auth_data) => Ok(Credential::from(auth_data)), SamlAuthResult::Success(auth_data) => Credential::try_from(auth_data),
SamlAuthResult::Failure(msg) => bail!(msg), SamlAuthResult::Failure(msg) => bail!(msg),
} }
} }