use std::time::{Duration, SystemTime, UNIX_EPOCH};
use oauth2::basic::BasicClient;
use oauth2::{
AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, RedirectUrl,
RefreshToken, Scope, TokenResponse, TokenUrl,
};
use reqwest::header::LOCATION;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use crate::api::{ApiError, normalize_instance};
use crate::config::{AuthType, Config, update_stored_credential};
use crate::credentials::StoredCredential;
const CALLBACK_TIMEOUT: Duration = Duration::from_secs(300);
const LOGIN_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(5);
const MAX_LOGIN_REDIRECTS: usize = 6;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum LoginProvider {
MicrosoftEntra,
ExternalSso(Option<String>),
Undetermined,
}
pub async fn discover_login_provider(instance: &str) -> Result<LoginProvider, ApiError> {
let site_url = normalize_instance(instance)?;
let origin = reqwest::Url::parse(&site_url)
.map_err(|error| ApiError::InvalidInput(format!("invalid instance URL: {error}")))?;
let mut url = origin
.join("/nav_to.do?uri=incident_list.do")
.map_err(|error| ApiError::InvalidInput(format!("invalid login URL: {error}")))?;
let http = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.timeout(LOGIN_DISCOVERY_TIMEOUT)
.build()?;
for _ in 0..MAX_LOGIN_REDIRECTS {
let response = http
.get(url.clone())
.header(reqwest::header::ACCEPT, "text/html,application/xhtml+xml")
.send()
.await?;
if response.status().is_redirection() {
let location = response
.headers()
.get(LOCATION)
.ok_or_else(|| ApiError::Other("login redirect omitted its location".into()))?
.to_str()
.map_err(|_| ApiError::Other("login redirect was not valid text".into()))?;
let location_lower = location.to_ascii_lowercase();
if contains_microsoft_login(&location_lower) {
return Ok(LoginProvider::MicrosoftEntra);
}
let next = url
.join(location)
.map_err(|error| ApiError::Other(format!("invalid login redirect: {error}")))?;
if !same_origin(&origin, &next) {
return Ok(external_provider(&next));
}
if is_sso_route(&next) {
return Ok(LoginProvider::ExternalSso(None));
}
url = next;
continue;
}
if !response.status().is_success() {
return Err(ApiError::Other(format!(
"login discovery returned HTTP {}",
response.status()
)));
}
let body = response.text().await?.to_ascii_lowercase();
if contains_microsoft_login(&body) {
return Ok(LoginProvider::MicrosoftEntra);
}
if [
"login_with_sso.do",
"glide_sso_id",
"external_login_complete.do",
"multi_sso",
]
.iter()
.any(|marker| body.contains(marker))
{
return Ok(LoginProvider::ExternalSso(None));
}
return Ok(LoginProvider::Undetermined);
}
Err(ApiError::Other(
"login discovery exceeded the redirect limit".into(),
))
}
fn is_sso_route(url: &reqwest::Url) -> bool {
matches!(
url.path().to_ascii_lowercase().as_str(),
"/auth_redirect.do" | "/login_with_sso.do" | "/external_login_complete.do"
)
}
fn same_origin(left: &reqwest::Url, right: &reqwest::Url) -> bool {
left.scheme() == right.scheme()
&& left.host_str() == right.host_str()
&& left.port_or_known_default() == right.port_or_known_default()
}
fn external_provider(url: &reqwest::Url) -> LoginProvider {
let host = url.host_str().map(str::to_ascii_lowercase);
if host.as_deref().is_some_and(is_microsoft_login_host) {
LoginProvider::MicrosoftEntra
} else {
LoginProvider::ExternalSso(host)
}
}
fn is_microsoft_login_host(host: &str) -> bool {
matches!(host, "login.microsoft.com" | "login.windows.net")
|| host == "login.microsoftonline.com"
|| host.ends_with(".microsoftonline.com")
}
fn contains_microsoft_login(body: &str) -> bool {
[
"login.microsoftonline.com",
"login.microsoft.com",
"login.windows.net",
]
.iter()
.any(|host| body.contains(host))
}
pub async fn oauth_login(
instance: &str,
client_id: &str,
client_secret: Option<String>,
scope: Option<&str>,
redirect_uri: &str,
open_browser: bool,
) -> Result<StoredCredential, ApiError> {
let site_url = normalize_instance(instance)?;
let redirect = reqwest::Url::parse(redirect_uri)
.map_err(|error| ApiError::InvalidInput(format!("invalid OAuth redirect URI: {error}")))?;
if redirect.scheme() != "http"
|| !matches!(redirect.host_str(), Some("127.0.0.1" | "localhost"))
|| redirect.port().is_none()
{
return Err(ApiError::InvalidInput(
"OAuth redirect URI must use http://127.0.0.1:<port>/path or localhost".into(),
));
}
let port = redirect.port().expect("validated redirect port");
let listener = TcpListener::bind(("127.0.0.1", port))
.await
.map_err(|error| {
ApiError::Other(format!(
"failed to listen for OAuth callback on port {port}: {error}"
))
})?;
let client = oauth_client(&site_url, client_id, client_secret.as_deref(), redirect_uri)?;
let (challenge, verifier) = PkceCodeChallenge::new_random_sha256();
let mut authorization = client
.authorize_url(CsrfToken::new_random)
.set_pkce_challenge(challenge);
if let Some(scope) = scope.filter(|value| !value.trim().is_empty()) {
for value in scope.split_whitespace() {
authorization = authorization.add_scope(Scope::new(value.into()));
}
}
let (authorization_url, csrf) = authorization.url();
eprintln!("Authorize this CLI in your browser:\n\n {authorization_url}\n");
if open_browser && let Err(error) = open::that(authorization_url.as_str()) {
eprintln!("Could not open the browser automatically: {error}");
}
let (code, returned_state) = tokio::time::timeout(
CALLBACK_TIMEOUT,
receive_callback(listener, redirect.path()),
)
.await
.map_err(|_| ApiError::Auth("OAuth authorization timed out after five minutes".into()))??;
if returned_state != csrf.secret().as_str() {
return Err(ApiError::Auth(
"OAuth state mismatch; authorization was rejected for safety".into(),
));
}
let http = oauth2::reqwest::ClientBuilder::new()
.redirect(oauth2::reqwest::redirect::Policy::none())
.build()
.map_err(|error| ApiError::Other(format!("failed to build OAuth client: {error}")))?;
let token = client
.exchange_code(AuthorizationCode::new(code))
.set_pkce_verifier(verifier)
.request_async(&http)
.await
.map_err(|error| ApiError::Auth(format!("OAuth token exchange failed: {error}")))?;
Ok(StoredCredential::OAuth {
access_token: token.access_token().secret().into(),
refresh_token: token.refresh_token().map(|value| value.secret().into()),
expires_at: token.expires_in().map(expires_at),
client_secret,
})
}
pub async fn refresh_if_needed(config: &mut Config) -> Result<bool, ApiError> {
if !matches!(config.auth_type, AuthType::OAuth) || !config.uses_persistent_store() {
return Ok(false);
}
let Some(session) = config.oauth.clone() else {
return Ok(false);
};
if session
.expires_at
.is_none_or(|expiry| expiry > epoch_seconds().saturating_add(60))
{
return Ok(false);
}
let Some(refresh_token) = session.refresh_token else {
return Err(ApiError::Auth(
"OAuth token expired and no refresh token is available; run `servicenow auth login`"
.into(),
));
};
let client_id = config.client_id.as_deref().ok_or_else(|| {
ApiError::InvalidInput("OAuth profile is missing client_id; log in again".into())
})?;
let redirect_uri = config
.redirect_uri
.as_deref()
.unwrap_or("http://127.0.0.1:8484/callback");
let site_url = normalize_instance(&config.instance)?;
let client = oauth_client(
&site_url,
client_id,
session.client_secret.as_deref(),
redirect_uri,
)?;
let http = oauth2::reqwest::ClientBuilder::new()
.redirect(oauth2::reqwest::redirect::Policy::none())
.build()
.map_err(|error| ApiError::Other(format!("failed to build OAuth client: {error}")))?;
let token = client
.exchange_refresh_token(&RefreshToken::new(refresh_token.clone()))
.request_async(&http)
.await
.map_err(|error| ApiError::Auth(format!("OAuth refresh failed: {error}")))?;
let access_token = token.access_token().secret().to_string();
let new_refresh = token
.refresh_token()
.map(|value| value.secret().to_string())
.or(Some(refresh_token));
let new_expiry = token.expires_in().map(expires_at);
update_stored_credential(
&config.profile,
StoredCredential::OAuth {
access_token: access_token.clone(),
refresh_token: new_refresh.clone(),
expires_at: new_expiry,
client_secret: session.client_secret.clone(),
},
)?;
config.secret = access_token;
config.oauth = Some(crate::config::OAuthSession {
refresh_token: new_refresh,
expires_at: new_expiry,
client_secret: session.client_secret,
});
Ok(true)
}
fn oauth_client(
site_url: &str,
client_id: &str,
client_secret: Option<&str>,
redirect_uri: &str,
) -> Result<
BasicClient<
oauth2::EndpointSet,
oauth2::EndpointNotSet,
oauth2::EndpointNotSet,
oauth2::EndpointNotSet,
oauth2::EndpointSet,
>,
ApiError,
> {
let mut client = BasicClient::new(ClientId::new(client_id.into()))
.set_auth_uri(
AuthUrl::new(format!("{site_url}/oauth_auth.do"))
.map_err(|error| ApiError::InvalidInput(format!("invalid OAuth URL: {error}")))?,
)
.set_token_uri(
TokenUrl::new(format!("{site_url}/oauth_token.do"))
.map_err(|error| ApiError::InvalidInput(format!("invalid token URL: {error}")))?,
)
.set_redirect_uri(RedirectUrl::new(redirect_uri.into()).map_err(|error| {
ApiError::InvalidInput(format!("invalid OAuth redirect URI: {error}"))
})?);
if let Some(secret) = client_secret.filter(|value| !value.is_empty()) {
client = client.set_client_secret(ClientSecret::new(secret.into()));
}
Ok(client)
}
async fn receive_callback(
listener: TcpListener,
expected_path: &str,
) -> Result<(String, String), ApiError> {
let (mut stream, _) = listener
.accept()
.await
.map_err(|error| ApiError::Other(format!("OAuth callback failed: {error}")))?;
let mut buffer = vec![0_u8; 16 * 1024];
let count = stream
.read(&mut buffer)
.await
.map_err(|error| ApiError::Other(format!("failed to read OAuth callback: {error}")))?;
let request = String::from_utf8_lossy(&buffer[..count]);
let target = request
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(1))
.ok_or_else(|| ApiError::Auth("invalid OAuth callback request".into()))?;
let callback = reqwest::Url::parse(&format!("http://127.0.0.1{target}"))
.map_err(|error| ApiError::Auth(format!("invalid OAuth callback: {error}")))?;
if callback.path() != expected_path {
return Err(ApiError::Auth("OAuth callback path did not match".into()));
}
let params: std::collections::HashMap<_, _> = callback.query_pairs().into_owned().collect();
let result = if let Some(error) = params.get("error") {
Err(ApiError::Auth(format!(
"OAuth authorization was denied: {}",
params.get("error_description").unwrap_or(error)
)))
} else {
let code = params
.get("code")
.cloned()
.ok_or_else(|| ApiError::Auth("OAuth callback omitted code".into()))?;
let state = params
.get("state")
.cloned()
.ok_or_else(|| ApiError::Auth("OAuth callback omitted state".into()))?;
Ok((code, state))
};
let (status, message) = if result.is_ok() {
("200 OK", "Authorization complete. You can close this tab.")
} else {
(
"400 Bad Request",
"Authorization failed. Return to your terminal.",
)
};
let body = format!(
"<!doctype html><meta charset=utf-8><title>ServiceNow CLI</title><style>body{{font:18px system-ui;max-width:42rem;margin:15vh auto;padding:2rem;color:#172b4d}}strong{{color:#2e844a}}</style><strong>{message}</strong>"
);
let response = format!(
"HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
let _ = stream.write_all(response.as_bytes()).await;
result
}
fn expires_at(duration: Duration) -> u64 {
epoch_seconds().saturating_add(duration.as_secs())
}
fn epoch_seconds() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
#[cfg(test)]
mod tests {
use super::*;
use wiremock::matchers::{method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};
#[tokio::test]
async fn detects_microsoft_entra_redirect_without_following_it() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/nav_to.do"))
.and(query_param("uri", "incident_list.do"))
.respond_with(ResponseTemplate::new(302).insert_header(
"location",
"https://login.microsoftonline.com/example/oauth2/v2.0/authorize",
))
.expect(1)
.mount(&server)
.await;
assert_eq!(
discover_login_provider(&server.uri()).await.unwrap(),
LoginProvider::MicrosoftEntra
);
}
#[tokio::test]
async fn follows_only_same_origin_login_redirects() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/nav_to.do"))
.and(query_param("uri", "incident_list.do"))
.respond_with(ResponseTemplate::new(302).insert_header("location", "/sso/start"))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/sso/start"))
.respond_with(
ResponseTemplate::new(302)
.insert_header("location", "https://id.example.com/sign-in"),
)
.expect(1)
.mount(&server)
.await;
assert_eq!(
discover_login_provider(&server.uri()).await.unwrap(),
LoginProvider::ExternalSso(Some("id.example.com".into()))
);
}
#[tokio::test]
async fn detects_sso_markers_in_the_login_page() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/nav_to.do"))
.and(query_param("uri", "incident_list.do"))
.respond_with(
ResponseTemplate::new(200)
.set_body_string(r#"<a href="login_with_sso.do">Use SSO</a>"#),
)
.mount(&server)
.await;
assert_eq!(
discover_login_provider(&server.uri()).await.unwrap(),
LoginProvider::ExternalSso(None)
);
}
#[tokio::test]
async fn detects_microsoft_entra_inside_a_same_origin_auth_redirect() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/nav_to.do"))
.and(query_param("uri", "incident_list.do"))
.respond_with(ResponseTemplate::new(302).insert_header(
"location",
"/auth_redirect.do?sysparm_stack=no&sysparm_url=https%3A%2F%2Flogin.microsoftonline.com%2Ftenant-guid%2Fsaml2%3FSAMLRequest%3Dexample",
))
.expect(1)
.mount(&server)
.await;
assert_eq!(
discover_login_provider(&server.uri()).await.unwrap(),
LoginProvider::MicrosoftEntra
);
}
#[tokio::test]
async fn local_login_form_does_not_prove_basic_authentication() {
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/nav_to.do"))
.and(query_param("uri", "incident_list.do"))
.respond_with(ResponseTemplate::new(302).insert_header("location", "/login.do"))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/login.do"))
.respond_with(ResponseTemplate::new(200).set_body_string("<form>Password</form>"))
.expect(1)
.mount(&server)
.await;
assert_eq!(
discover_login_provider(&server.uri()).await.unwrap(),
LoginProvider::Undetermined
);
}
#[tokio::test]
async fn rejects_non_loopback_oauth_redirects() {
let error = oauth_login(
"dev12345",
"client",
None,
None,
"https://example.com/callback",
false,
)
.await
.unwrap_err();
assert!(matches!(error, ApiError::InvalidInput(_)));
}
}