use anyhow::anyhow;
use serde::Deserialize;
use crate::api_client::CxClient;
use crate::error::CxError;
const WHOAMI_BASE: &str = "/identity/whoami";
#[derive(Debug, Deserialize)]
pub struct Whoami {
pub team_id: Option<i64>,
pub team_name: Option<String>,
pub user_name: Option<String>,
#[serde(default)]
pub team_url: Option<String>,
}
pub async fn verify_identity(client: &CxClient) -> anyhow::Result<Whoami> {
client
.get::<Whoami>(WHOAMI_BASE, &[])
.await
.map_err(|err| classify_health_error(client, err))
}
fn classify_health_error(client: &CxClient, err: CxError) -> anyhow::Error {
match err {
CxError::Auth(msg) => anyhow!("authentication failed — {msg}"),
CxError::Timeout => anyhow!("could not reach {} — request timed out", client.endpoint()),
CxError::Http(e) if e.is_connect() || e.is_timeout() || e.is_request() => anyhow!(
"could not reach {} — the region or URL may be incorrect ({e})",
client.endpoint()
),
other => anyhow!("{other}"),
}
}
pub async fn resolve_team_id(client: &CxClient) -> anyhow::Result<String> {
let whoami: Whoami = client
.get(WHOAMI_BASE, &[])
.await
.map_err(|e| anyhow!("failed to resolve team ID via /identity/whoami: {e:#}"))?;
whoami
.team_id
.map(|id| id.to_string())
.ok_or_else(|| anyhow!("/identity/whoami returned no team_id"))
}
pub async fn lookup_whoami(client: &CxClient) -> Option<Whoami> {
client.get(WHOAMI_BASE, &[]).await.ok()
}
#[cfg(test)]
mod tests {
use super::*;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
fn install_rustls_provider() {
rustls::crypto::ring::default_provider()
.install_default()
.ok();
}
#[test]
fn deserialize_whoami() {
let json = serde_json::json!({ "team_id": 53623, "team_name": "c4c", "user_name": "alice@example.com" });
let w: Whoami = serde_json::from_value(json).unwrap();
assert_eq!(w.team_id, Some(53623));
assert_eq!(w.team_name.as_deref(), Some("c4c"));
}
#[test]
fn deserialize_whoami_minimal() {
let json = serde_json::json!({ "team_id": 12345 });
let w: Whoami = serde_json::from_value(json).unwrap();
assert_eq!(w.team_id, Some(12345));
assert!(w.team_name.is_none());
}
#[test]
fn deserialize_whoami_with_team_url() {
let json = serde_json::json!({
"team_id": 12345,
"team_name": "C4C",
"team_url": "https://c4c.app.eu2.coralogix.com"
});
let w: Whoami = serde_json::from_value(json).unwrap();
assert_eq!(
w.team_url.as_deref(),
Some("https://c4c.app.eu2.coralogix.com")
);
}
#[tokio::test]
async fn lookup_whoami_returns_whoami_on_success() {
install_rustls_provider();
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/identity/whoami"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"team_id": 1,
"team_name": "C4C",
"team_url": "https://c4c.app.eu2.coralogix.com"
})))
.mount(&server)
.await;
let client = CxClient::new(server.uri(), "test-key").unwrap();
let whoami = lookup_whoami(&client).await.expect("whoami should succeed");
assert_eq!(whoami.team_id, Some(1));
assert_eq!(
whoami.team_url.as_deref(),
Some("https://c4c.app.eu2.coralogix.com")
);
}
#[tokio::test]
async fn verify_identity_returns_whoami_on_success() {
install_rustls_provider();
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/identity/whoami"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"team_id": 53623,
"team_name": "c4c",
"user_name": "alice@example.com"
})))
.mount(&server)
.await;
let client = CxClient::new(server.uri(), "test-key").unwrap();
let whoami = verify_identity(&client)
.await
.expect("whoami should succeed");
assert_eq!(whoami.team_id, Some(53623));
assert_eq!(whoami.user_name.as_deref(), Some("alice@example.com"));
}
#[tokio::test]
async fn verify_identity_classifies_auth_failure() {
install_rustls_provider();
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/identity/whoami"))
.respond_with(
ResponseTemplate::new(401)
.set_body_json(serde_json::json!({ "message": "invalid token" })),
)
.mount(&server)
.await;
let client = CxClient::new(server.uri(), "bad-key").unwrap();
let err = verify_identity(&client)
.await
.expect_err("401 should be an error");
let msg = format!("{err:#}");
assert!(
msg.contains("authentication failed"),
"expected auth classification, got: {msg}"
);
}
#[tokio::test]
async fn verify_identity_classifies_unreachable_endpoint() {
install_rustls_provider();
let client = CxClient::new("http://127.0.0.1:1", "test-key").unwrap();
let err = verify_identity(&client)
.await
.expect_err("connection refused should be an error");
let msg = format!("{err:#}");
assert!(
msg.contains("could not reach") && msg.contains("127.0.0.1:1"),
"expected region/URL classification naming the endpoint, got: {msg}"
);
}
#[tokio::test]
async fn lookup_whoami_none_when_whoami_fails() {
install_rustls_provider();
let server = MockServer::start().await;
Mock::given(method("GET"))
.and(path("/identity/whoami"))
.respond_with(ResponseTemplate::new(500))
.mount(&server)
.await;
let client = CxClient::new(server.uri(), "test-key").unwrap();
assert!(lookup_whoami(&client).await.is_none());
}
}