use anyhow::{bail, Context, Result};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use rand::seq::SliceRandom;
use rand::RngExt;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::io::{BufRead, BufReader, Write};
use std::net::{Ipv4Addr, Ipv6Addr, TcpListener, TcpStream};
use std::time::Duration;
use crate::config::{CredentialStorage, StoredOAuthTokens};
use crate::keyring_store;
const SCOPES: &[&str] = &["openid", "profile", "email", "offline_access"];
const CALLBACK_PORTS: &[u16] = &[21783, 24861, 27654, 31847, 38129];
pub struct OAuthEnvironment {
pub name: &'static str,
pub client_id: &'static str,
}
pub const KNOWN_ENVIRONMENTS: &[OAuthEnvironment] = &[
OAuthEnvironment {
name: "us1",
client_id: "2b6d0b5c-da8f-477e-907e-50cdad7b90e7",
},
OAuthEnvironment {
name: "us2",
client_id: "2820e159-5b12-432d-bc09-bef144f9b8c9",
},
OAuthEnvironment {
name: "us3",
client_id: "a489741c-c875-4652-9b2e-1ba680352b72",
},
OAuthEnvironment {
name: "eu1",
client_id: "cfb0915d-cb82-436c-b0fb-e8f75e4f9db4",
},
OAuthEnvironment {
name: "eu2",
client_id: "941d86ab-f652-4430-8153-9af5db5791e5",
},
OAuthEnvironment {
name: "ap1",
client_id: "091a273c-8194-4ad1-a09e-d787cc5e490a",
},
OAuthEnvironment {
name: "ap2",
client_id: "d827249c-0699-4abf-8d4c-d1d27dd8fe9a",
},
OAuthEnvironment {
name: "ap3",
client_id: "7c8d9c61-7d28-4c0f-803b-d4061f33282b",
},
];
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TokenResponse {
pub access_token: String,
pub token_type: String,
pub expires_in: Option<u64>,
pub refresh_token: Option<String>,
pub id_token: Option<String>,
pub scope: Option<String>,
}
#[derive(Deserialize)]
struct OpenIdConfig {
authorization_endpoint: String,
token_endpoint: String,
}
pub fn client_id_for_region(region_name: &str) -> Option<&'static str> {
KNOWN_ENVIRONMENTS
.iter()
.find(|e| e.name == region_name)
.map(|e| e.client_id)
}
fn unix_now_secs() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs()
}
pub fn token_seconds_remaining(access_token: &str) -> Option<i64> {
let parts: Vec<&str> = access_token.split('.').collect();
if parts.len() != 3 {
return None;
}
let payload = URL_SAFE_NO_PAD.decode(parts[1]).ok()?;
let json: serde_json::Value = serde_json::from_slice(&payload).ok()?;
let exp = json.get("exp")?.as_u64()?;
Some(exp as i64 - unix_now_secs() as i64)
}
enum PortBind {
Both(TcpListener, TcpListener),
Ipv4Only(TcpListener),
Unusable,
}
fn try_bind_port(port: u16) -> PortBind {
let Ok(v4) = TcpListener::bind((Ipv4Addr::LOCALHOST, port)) else {
return PortBind::Unusable;
};
match TcpListener::bind((Ipv6Addr::LOCALHOST, port)) {
Ok(v6) => PortBind::Both(v4, v6),
Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => PortBind::Unusable,
Err(_) => PortBind::Ipv4Only(v4),
}
}
pub fn bind_callback_listener() -> Result<(Vec<TcpListener>, u16)> {
let mut ports: Vec<u16> = CALLBACK_PORTS.to_vec();
ports.shuffle(&mut rand::rng());
let mut ipv4_only_fallback: Option<(Vec<TcpListener>, u16)> = None;
for &port in &ports {
match try_bind_port(port) {
PortBind::Both(v4, v6) => return Ok((vec![v4, v6], port)),
PortBind::Ipv4Only(v4) if ipv4_only_fallback.is_none() => {
ipv4_only_fallback = Some((vec![v4], port));
}
PortBind::Ipv4Only(_) | PortBind::Unusable => {}
}
}
if let Some(result) = ipv4_only_fallback {
return Ok(result);
}
bail!(
"Could not bind any OAuth callback port. All ports in the allow-list are in use: {}",
CALLBACK_PORTS
.iter()
.map(|p| p.to_string())
.collect::<Vec<_>>()
.join(", ")
)
}
fn generate_pkce() -> (String, String) {
let mut rng = rand::rng();
let verifier_bytes: Vec<u8> = (0..32).map(|_| rng.random::<u8>()).collect();
let verifier = URL_SAFE_NO_PAD.encode(&verifier_bytes);
let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()));
(verifier, challenge)
}
fn urlencode(s: &str) -> String {
url::form_urlencoded::byte_serialize(s.as_bytes()).collect()
}
fn wait_for_callback_blocking(
listeners: Vec<TcpListener>,
expected_state: String,
) -> Result<String> {
eprintln!("Waiting for browser callback...");
for listener in &listeners {
listener
.set_nonblocking(true)
.context("Failed to set OAuth callback listener to non-blocking")?;
}
loop {
for listener in &listeners {
match listener.accept() {
Ok((stream, _)) => {
stream
.set_nonblocking(false)
.context("Failed to set OAuth callback stream to blocking")?;
if let Some(code) = extract_and_respond(stream, &expected_state)? {
return Ok(code);
}
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
Err(e) => return Err(e).context("OAuth callback listener accept failed"),
}
}
std::thread::sleep(Duration::from_millis(50));
}
}
const SUCCESS_PAGE_HTML: &str = r##"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Authentication successful</title>
<style>
:root {
--text-primary: #0e141d;
--text-secondary: #5e6164;
--green-badge: #02763a;
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; }
body {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
padding: 24px;
background: linear-gradient(160deg, #edeff1 0%, #f7f8f9 45%, #ffffff 100%);
color: var(--text-primary);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
.card {
display: flex;
flex-direction: column;
align-items: center;
width: fit-content;
max-width: calc(100vw - 48px);
text-align: center;
}
.badge {
display: flex;
align-items: center;
justify-content: center;
width: 42px;
height: 42px;
margin-bottom: 8px;
border-radius: 50%;
background: var(--green-badge);
}
.badge svg { display: block; }
h1 {
margin: 0;
font-size: 20px;
font-weight: 700;
line-height: 1.5;
color: var(--text-primary);
}
.subtitle {
margin: 8px 0 0;
font-size: 14px;
font-weight: 500;
line-height: 1.5;
color: var(--text-secondary);
white-space: nowrap;
}
@media (max-width: 340px) { .subtitle { white-space: normal; } }
</style>
</head>
<body>
<main class="card">
<div class="badge">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" aria-hidden="true" focusable="false">
<path d="M5 12.5L10 17.5L19.5 7" stroke="#ffffff" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</div>
<h1>Authentication successful</h1>
<p class="subtitle">You are now connected to Coralogix.<br>You may close this tab and return to your application.</p>
</main>
</body>
</html>"##;
fn extract_and_respond(stream: TcpStream, expected_state: &str) -> Result<Option<String>> {
let mut reader = BufReader::new(&stream);
let mut request_line = String::new();
reader.read_line(&mut request_line)?;
drop(reader);
let path = request_line
.split_whitespace()
.nth(1)
.context("Malformed HTTP request in OAuth callback")?;
let Some(query) = path.split('?').nth(1) else {
send_http_response(&stream, 204, "");
return Ok(None);
};
let params: std::collections::HashMap<String, String> =
url::form_urlencoded::parse(query.as_bytes())
.into_owned()
.collect();
let (code, returned_state) = match (params.get("code"), params.get("state")) {
(Some(c), Some(s)) => (c.clone(), s.clone()),
_ => {
send_http_response(&stream, 204, "");
return Ok(None);
}
};
if returned_state != expected_state {
send_http_response(&stream, 400, "State mismatch.");
bail!("OAuth state mismatch – possible CSRF attempt, aborting.");
}
send_http_response(&stream, 200, SUCCESS_PAGE_HTML);
Ok(Some(code))
}
fn send_http_response(mut stream: &TcpStream, status: u16, body: &str) {
let status_text = match status {
200 => "200 OK",
204 => "204 No Content",
400 => "400 Bad Request",
_ => "200 OK",
};
let response = if body.is_empty() {
format!("HTTP/1.1 {status_text}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
} else {
format!(
"HTTP/1.1 {status_text}\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
)
};
let _ = stream.write_all(response.as_bytes());
let _ = stream.flush();
}
async fn fetch_openid_config(base_url: &str) -> Result<OpenIdConfig> {
let url = format!(
"{}/oauth/.well-known/openid-configuration",
base_url.trim_end_matches('/')
);
reqwest::get(&url)
.await?
.error_for_status()
.with_context(|| format!("OpenID discovery endpoint returned an error: {url}"))?
.json::<OpenIdConfig>()
.await
.with_context(|| format!("Failed to parse OpenID configuration from {url}"))
}
async fn exchange_code(
token_endpoint: &str,
client_id: &str,
code: &str,
code_verifier: &str,
redirect_uri: &str,
) -> Result<TokenResponse> {
let client = reqwest::Client::new();
let resp = client
.post(token_endpoint)
.form(&[
("grant_type", "authorization_code"),
("client_id", client_id),
("code", code),
("redirect_uri", redirect_uri),
("code_verifier", code_verifier),
])
.send()
.await?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
bail!("Token exchange failed ({status}): {body}");
}
resp.json::<TokenResponse>()
.await
.context("Failed to parse token exchange response")
}
async fn do_token_refresh(
token_endpoint: &str,
client_id: &str,
refresh_token: &str,
) -> Result<TokenResponse> {
let client = reqwest::Client::new();
let resp = client
.post(token_endpoint)
.form(&[
("grant_type", "refresh_token"),
("client_id", client_id),
("refresh_token", refresh_token),
])
.send()
.await?;
if !resp.status().is_success() {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
if matches!(status.as_u16(), 400 | 401) {
return Err(RefreshRejected { status, body }.into());
}
bail!("Token refresh failed ({status}): {body}");
}
resp.json::<TokenResponse>()
.await
.context("Failed to parse token refresh response")
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LoginOptions {
pub force_account_selection: bool,
pub team_id: Option<i64>,
pub signup: bool,
}
fn timeout_message(options: &LoginOptions, timeout: Duration) -> String {
let minutes = timeout.as_secs() / 60;
if options.signup {
format!(
"OAuth sign-up timed out after {minutes} minutes. If you finished signing up, \
run the same command again without `--signup` to sign in with your new account."
)
} else {
format!("OAuth login timed out after {minutes} minutes")
}
}
fn callback_timeout(options: &LoginOptions) -> Duration {
if options.signup {
Duration::from_secs(30 * 60)
} else {
Duration::from_secs(5 * 60)
}
}
fn build_authorization_url(
authorization_endpoint: &str,
client_id: &str,
redirect_uri: &str,
challenge: &str,
state: &str,
options: &LoginOptions,
) -> String {
let scopes = SCOPES.join(" ");
let mut auth_url = format!(
"{}?response_type=code&client_id={}&redirect_uri={}&scope={}&code_challenge={}&code_challenge_method=S256&state={}",
authorization_endpoint,
urlencode(client_id),
urlencode(redirect_uri),
urlencode(&scopes),
challenge,
state,
);
if options.signup {
auth_url.push_str("&prompt=create");
} else if options.force_account_selection {
auth_url.push_str("&prompt=select_account");
}
if let Some(team_id) = options.team_id {
auth_url.push_str(&format!("&cx_team_ids={team_id}"));
}
auth_url
}
pub async fn browser_login(
base_url: &str,
client_id: &str,
options: LoginOptions,
) -> Result<TokenResponse> {
let oidc = fetch_openid_config(base_url).await?;
let (verifier, challenge) = generate_pkce();
let state = {
let mut rng = rand::rng();
let bytes: Vec<u8> = (0..32).map(|_| rng.random::<u8>()).collect();
URL_SAFE_NO_PAD.encode(bytes)
};
let (listeners, port) = bind_callback_listener()?;
let redirect_uri = format!("http://localhost:{port}/callback");
let auth_url = build_authorization_url(
&oidc.authorization_endpoint,
client_id,
&redirect_uri,
&challenge,
&state,
&options,
);
eprintln!("Sign in by visiting:\n {auth_url}");
if open::that(&auth_url).is_ok() {
eprintln!("(opened in your default browser)");
}
let timeout = callback_timeout(&options);
let code = tokio::time::timeout(
timeout,
tokio::task::spawn_blocking(move || wait_for_callback_blocking(listeners, state)),
)
.await
.with_context(|| timeout_message(&options, timeout))?
.context("OAuth callback task failed")??;
eprintln!("Authorization code received, exchanging for tokens...");
exchange_code(
&oidc.token_endpoint,
client_id,
&code,
&verifier,
&redirect_uri,
)
.await
}
pub fn tokens_to_stored(tokens: &TokenResponse) -> StoredOAuthTokens {
let expiry = tokens.expires_in.map(|exp_in| unix_now_secs() + exp_in);
StoredOAuthTokens {
access_token: tokens.access_token.clone(),
refresh_token: tokens.refresh_token.clone(),
id_token: tokens.id_token.clone(),
expiry,
}
}
pub fn store_tokens_keyring(profile: &str, tokens: &TokenResponse) -> Result<()> {
keyring_store::store_secret(profile, "oauth_access_token", &tokens.access_token)?;
if let Some(ref rt) = tokens.refresh_token {
keyring_store::store_secret(profile, "oauth_refresh_token", rt)?;
}
if let Some(ref it) = tokens.id_token {
keyring_store::store_secret(profile, "oauth_id_token", it)?;
}
if let Some(exp_in) = tokens.expires_in {
let expiry = unix_now_secs() + exp_in;
keyring_store::store_secret(profile, "oauth_token_expiry", &expiry.to_string())?;
}
Ok(())
}
#[derive(Debug)]
pub struct TokenResolution {
pub bearer: String,
pub refreshed_tokens: Option<StoredOAuthTokens>,
pub os_store_fallback_reason: Option<String>,
}
fn os_store_refresh_result(tokens: &TokenResponse, store_result: Result<()>) -> TokenResolution {
match store_result {
Ok(()) => TokenResolution {
bearer: tokens.access_token.clone(),
refreshed_tokens: None,
os_store_fallback_reason: None,
},
Err(err) => TokenResolution {
bearer: tokens.access_token.clone(),
refreshed_tokens: Some(tokens_to_stored(tokens)),
os_store_fallback_reason: Some(format!("{err:#}")),
},
}
}
fn cached_token_is_valid(token: &str, expiry: Option<u64>) -> bool {
if let Some(exp) = expiry {
exp > unix_now_secs() + 30
} else {
token_seconds_remaining(token)
.map(|s| s > 30)
.unwrap_or(false)
}
}
#[derive(Debug)]
enum ReauthKind {
TokensMissing,
SessionExpired,
RefreshFailed,
}
#[derive(Debug)]
struct ReauthRequired {
profile_name: String,
kind: ReauthKind,
source: Option<anyhow::Error>,
}
impl std::fmt::Display for ReauthRequired {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let profile_name = &self.profile_name;
let detail = match self.kind {
ReauthKind::TokensMissing => "OAuth tokens missing",
ReauthKind::SessionExpired => "OAuth session expired",
ReauthKind::RefreshFailed => "OAuth token refresh failed",
};
write!(
f,
"{detail} for profile '{profile_name}'.\n\
Run `cx profiles refresh {profile_name}` to sign in again."
)
}
}
impl std::error::Error for ReauthRequired {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source.as_ref().map(AsRef::as_ref)
}
}
#[derive(Debug)]
struct RefreshRejected {
status: reqwest::StatusCode,
body: String,
}
impl std::fmt::Display for RefreshRejected {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Token refresh failed ({}): {}", self.status, self.body)
}
}
impl std::error::Error for RefreshRejected {}
fn is_refresh_rejected(err: &anyhow::Error) -> bool {
err.chain()
.any(|cause| cause.downcast_ref::<RefreshRejected>().is_some())
}
fn reauth_required(profile_name: &str, kind: ReauthKind) -> anyhow::Error {
ReauthRequired {
profile_name: profile_name.to_string(),
kind,
source: None,
}
.into()
}
fn reauth_required_with_source(
profile_name: &str,
kind: ReauthKind,
source: anyhow::Error,
) -> anyhow::Error {
ReauthRequired {
profile_name: profile_name.to_string(),
kind,
source: Some(source),
}
.into()
}
pub fn is_reauth_required(err: &anyhow::Error) -> bool {
err.chain()
.any(|cause| cause.downcast_ref::<ReauthRequired>().is_some())
}
pub async fn resolve_token(
profile_name: &str,
base_url: &str,
client_id: &str,
storage: CredentialStorage,
file_tokens: Option<&StoredOAuthTokens>,
) -> Result<TokenResolution> {
let (cached_access, cached_expiry, cached_refresh) = match storage {
CredentialStorage::OsStore => (
keyring_store::get_secret(profile_name, "oauth_access_token")?,
keyring_store::get_secret(profile_name, "oauth_token_expiry")?
.and_then(|s| s.parse::<u64>().ok()),
keyring_store::get_secret(profile_name, "oauth_refresh_token")?,
),
CredentialStorage::File => {
let t = file_tokens
.ok_or_else(|| reauth_required(profile_name, ReauthKind::TokensMissing))?;
(
Some(t.access_token.clone()),
t.expiry,
t.refresh_token.clone(),
)
}
};
if let Some(ref token) = cached_access {
if cached_token_is_valid(token, cached_expiry) {
return Ok(TokenResolution {
bearer: token.clone(),
refreshed_tokens: None,
os_store_fallback_reason: None,
});
}
}
let refresh_token =
cached_refresh.ok_or_else(|| reauth_required(profile_name, ReauthKind::SessionExpired))?;
let oidc = fetch_openid_config(base_url).await.with_context(|| {
format!(
"Failed to contact OAuth server while refreshing token for profile '{profile_name}'."
)
})?;
let tokens = match do_token_refresh(&oidc.token_endpoint, client_id, &refresh_token).await {
Ok(tokens) => tokens,
Err(err) if is_refresh_rejected(&err) => {
return Err(reauth_required_with_source(
profile_name,
ReauthKind::RefreshFailed,
err,
));
}
Err(err) => {
return Err(err.context(format!(
"Failed to refresh OAuth token for profile '{profile_name}'."
)));
}
};
match storage {
CredentialStorage::OsStore => Ok(os_store_refresh_result(
&tokens,
store_tokens_keyring(profile_name, &tokens),
)),
CredentialStorage::File => {
let stored = tokens_to_stored(&tokens);
Ok(TokenResolution {
bearer: tokens.access_token,
refreshed_tokens: Some(stored),
os_store_fallback_reason: None,
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::TcpStream;
#[test]
fn bind_callback_listener_serves_loopback_on_every_bound_stack() {
let (listeners, port) = bind_callback_listener().expect("a callback port must bind");
assert!(!listeners.is_empty(), "must bind at least one listener");
for l in &listeners {
assert_eq!(
l.local_addr().expect("local_addr").port(),
port,
"all listeners must share the chosen callback port"
);
}
TcpStream::connect((Ipv4Addr::LOCALHOST, port))
.expect("IPv4 loopback callback must be connectable");
let has_ipv6 = listeners
.iter()
.any(|l| l.local_addr().map(|a| a.is_ipv6()).unwrap_or(false));
if has_ipv6 {
TcpStream::connect((Ipv6Addr::LOCALHOST, port))
.expect("IPv6 loopback callback must be connectable when ::1 is bound");
}
}
#[test]
fn try_bind_port_does_not_fall_back_to_ipv4_when_ipv6_is_occupied() {
let Ok(v6_squatter) = TcpListener::bind((Ipv6Addr::LOCALHOST, 0)) else {
return;
};
let port = v6_squatter.local_addr().expect("local_addr").port();
match try_bind_port(port) {
PortBind::Unusable => {}
PortBind::Both(..) => panic!("::1 was occupied; must not report Both"),
PortBind::Ipv4Only(_) => {
panic!("must not fall back to IPv4-only while another process owns ::1")
}
}
}
fn sample_token_response(expires_in: Option<u64>, refresh: Option<&str>) -> TokenResponse {
TokenResponse {
access_token: "access-abc".to_string(),
token_type: "Bearer".to_string(),
expires_in,
refresh_token: refresh.map(str::to_string),
id_token: Some("id-xyz".to_string()),
scope: None,
}
}
#[test]
fn tokens_to_stored_sets_expiry_when_expires_in_present() {
let before = unix_now_secs();
let stored = tokens_to_stored(&sample_token_response(Some(3600), Some("refresh-1")));
let after = unix_now_secs();
let expiry = stored.expiry.expect("expiry computed from expires_in");
assert!(expiry >= before + 3600 && expiry <= after + 3600);
assert_eq!(stored.access_token, "access-abc");
assert_eq!(stored.refresh_token.as_deref(), Some("refresh-1"));
assert_eq!(stored.id_token.as_deref(), Some("id-xyz"));
}
#[test]
fn tokens_to_stored_leaves_expiry_none_when_expires_in_absent() {
let stored = tokens_to_stored(&sample_token_response(None, None));
assert!(stored.expiry.is_none());
assert!(stored.refresh_token.is_none());
}
#[test]
fn os_store_refresh_falls_back_to_file_storage() {
let tokens = sample_token_response(Some(3600), Some("refresh-1"));
let resolved = os_store_refresh_result(
&tokens,
Err(anyhow::anyhow!("credential blob exceeds the limit")),
);
assert_eq!(resolved.bearer, tokens.access_token);
assert_eq!(
resolved
.refreshed_tokens
.as_ref()
.and_then(|stored| stored.refresh_token.as_deref()),
Some("refresh-1")
);
assert!(resolved
.os_store_fallback_reason
.as_deref()
.is_some_and(|reason| reason.contains("credential blob exceeds the limit")));
}
#[test]
fn cached_token_is_valid_uses_expiry_when_present() {
let now = unix_now_secs();
assert!(cached_token_is_valid("ignored", Some(now + 300)));
assert!(!cached_token_is_valid("ignored", Some(now + 10)));
assert!(!cached_token_is_valid("ignored", Some(now - 1)));
}
#[test]
fn cached_token_is_valid_falls_back_to_jwt_exp_without_expiry() {
assert!(!cached_token_is_valid("not-a-jwt", None));
}
#[tokio::test]
async fn resolve_token_file_mode_errors_when_tokens_missing() {
let err = resolve_token(
"myprofile",
"https://example.invalid",
"client-id",
CredentialStorage::File,
None,
)
.await
.expect_err("missing file_tokens must error");
let msg = format!("{err:#}");
assert!(msg.contains("OAuth tokens missing"), "got: {msg}");
assert!(msg.contains("myprofile"), "got: {msg}");
assert!(is_reauth_required(&err));
}
#[tokio::test]
async fn resolve_token_file_mode_returns_cached_when_valid() {
let tokens = StoredOAuthTokens {
access_token: "still-good".to_string(),
refresh_token: Some("refresh".to_string()),
id_token: None,
expiry: Some(unix_now_secs() + 600),
};
let resolved = resolve_token(
"myprofile",
"https://example.invalid",
"client-id",
CredentialStorage::File,
Some(&tokens),
)
.await
.expect("cached path must not hit the network");
assert_eq!(resolved.bearer, "still-good");
assert!(resolved.refreshed_tokens.is_none());
assert!(resolved.os_store_fallback_reason.is_none());
}
#[tokio::test]
async fn resolve_token_file_mode_errors_when_expired_without_refresh() {
let tokens = StoredOAuthTokens {
access_token: "expired".to_string(),
refresh_token: None,
id_token: None,
expiry: Some(unix_now_secs() - 1),
};
let err = resolve_token(
"myprofile",
"https://example.invalid",
"client-id",
CredentialStorage::File,
Some(&tokens),
)
.await
.expect_err("expired access + no refresh token must error");
let msg = format!("{err:#}");
assert!(msg.contains("OAuth session expired"), "got: {msg}");
assert!(is_reauth_required(&err));
}
#[test]
fn refresh_rejection_requires_reauth() {
let err = reauth_required_with_source(
"myprofile",
ReauthKind::RefreshFailed,
RefreshRejected {
status: reqwest::StatusCode::BAD_REQUEST,
body: "invalid_grant".to_string(),
}
.into(),
);
let msg = format!("{err:?}");
assert!(msg.contains("OAuth token refresh failed"), "got: {msg}");
assert!(msg.contains("invalid_grant"), "got: {msg}");
assert!(is_reauth_required(&err));
assert!(is_refresh_rejected(&err));
}
#[test]
fn refresh_server_error_does_not_require_reauth() {
let err = anyhow::anyhow!(
"Failed to refresh OAuth token for profile 'myprofile'.\n\
Token refresh failed (503): unavailable"
);
assert!(!is_refresh_rejected(&err));
assert!(!is_reauth_required(&err));
}
#[test]
fn authorization_url_has_no_optional_params_by_default() {
let url = build_authorization_url(
"https://example.com/oauth/authorize",
"cli-client",
"http://localhost:21783/callback",
"CHALLENGE",
"STATE",
&LoginOptions::default(),
);
assert_eq!(
url,
"https://example.com/oauth/authorize?response_type=code&client_id=cli-client\
&redirect_uri=http%3A%2F%2Flocalhost%3A21783%2Fcallback\
&scope=openid+profile+email+offline_access\
&code_challenge=CHALLENGE&code_challenge_method=S256&state=STATE"
);
assert!(!url.contains("prompt="));
assert!(!url.contains("cx_team_ids="));
}
#[test]
fn authorization_url_restricts_to_the_profile_team() {
let url = build_authorization_url(
"https://example.com/oauth/authorize",
"cli-client",
"http://localhost:21783/callback",
"CHALLENGE",
"STATE",
&LoginOptions {
force_account_selection: false,
team_id: Some(53623),
signup: false,
},
);
assert!(
url.ends_with("&state=STATE&cx_team_ids=53623"),
"got: {url}"
);
assert!(!url.contains("prompt="));
}
#[test]
fn authorization_url_combines_account_picker_and_team_restriction() {
let url = build_authorization_url(
"https://example.com/oauth/authorize",
"cli-client",
"http://localhost:21783/callback",
"CHALLENGE",
"STATE",
&LoginOptions {
force_account_selection: true,
team_id: Some(7),
signup: false,
},
);
assert!(
url.ends_with("&state=STATE&prompt=select_account&cx_team_ids=7"),
"got: {url}"
);
}
#[test]
fn authorization_url_asks_for_signup_instead_of_an_account_picker() {
let url = build_authorization_url(
"https://example.com/oauth/authorize",
"cli-client",
"http://localhost:21783/callback",
"CHALLENGE",
"STATE",
&LoginOptions {
force_account_selection: true,
team_id: None,
signup: true,
},
);
assert!(url.ends_with("&state=STATE&prompt=create"), "got: {url}");
assert!(!url.contains("select_account"));
}
#[test]
fn signup_timeout_tells_the_user_to_rerun_their_own_command() {
let message = timeout_message(
&LoginOptions {
signup: true,
..LoginOptions::default()
},
Duration::from_secs(30 * 60),
);
assert!(
message.contains("same command again without `--signup`"),
"{message}"
);
assert!(!message.contains("cx init"), "{message}");
}
#[test]
fn signup_waits_long_enough_to_read_the_verification_email() {
let login = callback_timeout(&LoginOptions::default());
let signup = callback_timeout(&LoginOptions {
signup: true,
..LoginOptions::default()
});
assert_eq!(login, Duration::from_secs(5 * 60));
assert_eq!(signup, Duration::from_secs(30 * 60));
}
}