Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

9.7 KB
Raw Blame
use std::{collections::HashMap, time::Duration};

use crate::{
    Result, UnauthedClient,
    error::{FusionAuthClientError, GenericErrorResponse, GrantBlockReason},
};
use base64::{
    Engine,
    engine::general_purpose::{self},
};
use upstream_error::UpstreamFailure;

#[cfg(test)]
mod test;

#[derive(serde::Serialize, serde::Deserialize, Debug)]
/// Request to refresh a Google OAuth2 access token.
pub struct GoogleTokenRequest {
    client_id: String,
    client_secret: String,
    refresh_token: String,
    grant_type: String,
}

#[derive(serde::Serialize, serde::Deserialize, Debug)]
/// Response from refreshing a Google OAuth2 access token.
pub struct GoogleTokenResponse {
    /// The access token.
    pub access_token: String,
    /// The number of seconds until the token expires.
    pub expires_in: u64,
    /// The scope of the token.
    pub scope: String,
    /// The type of token.
    pub token_type: String,
    /// The ID token.
    pub id_token: String,
}

/// Google's name in error messages users see.
const GOOGLE: &str = "Google";
const GOOGLE_TOKEN_URL: &str = "https://oauth2.googleapis.com/token";

/// Refreshes a Google OAuth2 access token using a refresh token.
/// See https://developers.google.com/identity/protocols/oauth2/web-server#offline
pub(crate) async fn refresh_google_token(
    client: &UnauthedClient,
    client_id: &str,
    client_secret: &str,
    refresh_token: &str,
) -> Result<GoogleTokenResponse> {
    refresh_google_token_at(
        client,
        GOOGLE_TOKEN_URL,
        client_id,
        client_secret,
        refresh_token,
    )
    .await
}

async fn refresh_google_token_at(
    client: &UnauthedClient,
    token_url: &str,
    client_id: &str,
    client_secret: &str,
    refresh_token: &str,
) -> Result<GoogleTokenResponse> {
    let token_request = GoogleTokenRequest {
        client_id: client_id.to_string(),
        client_secret: client_secret.to_string(),
        refresh_token: refresh_token.to_string(),
        grant_type: "refresh_token".to_string(),
    };

    let res = client
        .client()
        .post(token_url)
        .json(&token_request)
        .send()
        .await
        .map_err(|e| FusionAuthClientError::provider_transport(GOOGLE, e))?;

    match res.status() {
        reqwest::StatusCode::OK => {
            let response = res
                .json::<GoogleTokenResponse>()
                .await
                .map_err(|e| FusionAuthClientError::provider_transport(GOOGLE, e))?;

            tracing::debug!(
                expires_in=?response.expires_in,
                scope=?response.scope,
                token_type=?response.token_type,
                "successfully refreshed Google access token"
            );

            Ok(response)
        }
        status => {
            let headers = res.headers().clone();
            let error_text = res
                .text()
                .await
                .unwrap_or_else(|_| "Unable to read error response".to_string());

            // If the user revoked Macro's access to their account, we get an invalid_grant error here
            if error_text.contains("invalid_grant") {
                tracing::warn!(status=?status, error=?error_text, "Google rejected the refresh token");
                return Err(FusionAuthClientError::InvalidGrant);
            }

            if let Some(reason) =
                grant_block_reason(&error_text).filter(|_| status.is_client_error())
            {
                tracing::warn!(status=?status, error=?error_text, "Google blocked the grant by policy");
                return Err(FusionAuthClientError::GrantBlocked { reason });
            }

            tracing::error!(
                status=?status,
                error=?error_text,
                "failed to refresh Google access token"
            );

            if let Some(failure) = UpstreamFailure::from_status(status, &headers) {
                return Err(FusionAuthClientError::Upstream {
                    service: GOOGLE,
                    failure,
                });
            }

            Err(FusionAuthClientError::Generic(GenericErrorResponse {
                message: format!(
                    "Google token refresh failed with status {}: {}",
                    status, error_text
                ),
            }))
        }
    }
}

/// The reason in a Google OAuth error body, when it is a policy block.
fn grant_block_reason(body: &str) -> Option<GrantBlockReason> {
    #[derive(serde::Deserialize)]
    struct OAuthError {
        error: String,
    }

    let OAuthError { error } = serde_json::from_str(body).ok()?;
    error.parse().ok()
}

#[derive(Debug, serde::Deserialize)]
/// Response from exchanging a Google authorization code for tokens.
pub struct GoogleExchangeTokenResponse {
    /// The access token.
    #[serde(default)]
    pub access_token: String,
    /// The refresh token.
    #[serde(default)]
    pub refresh_token: String,
    /// The ID token.
    pub id_token: String,
    /// The actual scopes granted by the user.
    #[serde(default)]
    pub scope: String,
}

/// Google's token revocation endpoint. Revoking either token of a grant
/// revokes the whole grant, so the next consent screen lists every scope again.
/// See https://developers.google.com/identity/protocols/oauth2/web-server#tokenrevoke
pub(crate) const GOOGLE_REVOKE_URL: &str = "https://oauth2.googleapis.com/revoke";

/// Revokes the grant behind `token` (an access or refresh token) at `endpoint`.
/// Google answers an unknown or already revoked token with 400 `invalid_token`,
/// which counts as revoked so the call is safe to repeat.
pub(crate) async fn revoke_token(
    client: &UnauthedClient,
    endpoint: &str,
    token: &str,
) -> Result<()> {
    let response = client
        .client()
        .post(endpoint)
        .form(&[("token", token)])
        .timeout(Duration::from_secs(10))
        .send()
        .await
        .map_err(|e| {
            FusionAuthClientError::Generic(GenericErrorResponse {
                message: e.to_string(),
            })
        })?;

    match response.status() {
        reqwest::StatusCode::OK | reqwest::StatusCode::BAD_REQUEST => Ok(()),
        status => {
            let body = response.text().await.map_err(|e| {
                FusionAuthClientError::Generic(GenericErrorResponse {
                    message: e.to_string(),
                })
            })?;
            tracing::error!(%status, body=%body, "unexpected response from the Google revocation endpoint");
            Err(FusionAuthClientError::Generic(GenericErrorResponse {
                message: format!("Google token revocation failed with status {status}: {body}"),
            }))
        }
    }
}

#[derive(Debug, serde::Serialize)]
struct TokenExchangeRequest {
    client_id: String,
    client_secret: String,
    code: String,
    grant_type: String,
    redirect_uri: String,
}

/// Exchanges a Google authorization code for tokens.
pub(crate) async fn exchange_code_for_tokens(
    client: &UnauthedClient,
    client_id: &str,
    client_secret: &str,
    redirect_uri: &str,
    code: &str,
) -> Result<GoogleExchangeTokenResponse> {
    let token_request = TokenExchangeRequest {
        client_id: client_id.to_string(),
        client_secret: client_secret.to_string(),
        code: code.to_string(),
        grant_type: "authorization_code".to_string(),
        redirect_uri: redirect_uri.to_string(),
    };

    let response = client
        .client()
        .post("https://oauth2.googleapis.com/token")
        .form(&token_request)
        .timeout(Duration::from_secs(30))
        .send()
        .await
        .map_err(|e| {
            tracing::error!(error=?e, "failed to send google token request");
            FusionAuthClientError::Generic(GenericErrorResponse {
                message: e.to_string(),
            })
        })?;

    let status = response.status();

    if !status.is_success() {
        let error_body = response.text().await.map_err(|e| {
            tracing::error!(error=?e, "failed to get error body");
            FusionAuthClientError::Generic(GenericErrorResponse {
                message: e.to_string(),
            })
        })?;

        tracing::error!(status=?status, body=?error_body, "token exchange failed");
        return Err(FusionAuthClientError::Generic(GenericErrorResponse {
            message: format!(
                "token exchange failed with status {}: {}",
                status, error_body
            ),
        }));
    }

    let token_response: GoogleExchangeTokenResponse = response.json().await.map_err(|e| {
        tracing::error!(error=?e, "failed to parse token response");
        FusionAuthClientError::Generic(GenericErrorResponse {
            message: e.to_string(),
        })
    })?;

    Ok(token_response)
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
/// User info extracted from a Google ID token.
pub struct GoogleUserInfo {
    /// The Google user ID.
    pub sub: String,
    /// The user's email address.
    pub email: String,
    /// Additional claims from the ID token.
    #[serde(flatten)]
    pub other: HashMap<String, serde_json::Value>,
}

/// Decodes a Google ID token without signature verification.
pub(crate) fn decode_google_id_token(id_token: &str) -> anyhow::Result<GoogleUserInfo> {
    // Split the JWT into its three parts
    let parts: Vec<&str> = id_token.split('.').collect();
    if parts.len() != 3 {
        anyhow::bail!("invalid jwt format")
    }

    // The payload is the second part (index 1)
    let payload = parts[1];

    // Decode from base64
    let decoded_bytes = general_purpose::URL_SAFE_NO_PAD.decode(payload)?;
    let decoded_str = String::from_utf8(decoded_bytes)?;

    // Parse JSON into your struct
    let claims: GoogleUserInfo = serde_json::from_str(&decoded_str)?;

    Ok(claims)
}