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.

5.6 KB
Raw Blame
use serde::Serialize;
use std::borrow::Cow;

use crate::{
    FusionAuthClient, Result, UnauthedClient,
    error::{FusionAuthClientError, GenericErrorResponse, OAuth2TokenError},
};

#[cfg(test)]
mod test;

#[derive(serde::Serialize, Debug)]
#[serde(rename_all = "snake_case")]
struct RefreshTokenGrantCompleteRequest<'a> {
    /// The client id
    pub client_id: Cow<'a, str>,
    /// The client secret
    pub client_secret: Cow<'a, str>,
    /// The refresh token
    pub refresh_token: Cow<'a, str>,
    /// The grant type (should always be refresh_token)
    pub grant_type: Cow<'a, str>,
}

#[derive(serde::Serialize, serde::Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
struct AuthorizationCodeGrantCompleteRequest<'a> {
    /// The client id
    pub client_id: Cow<'a, str>,
    /// The client secret
    pub client_secret: Cow<'a, str>,
    /// The authorization code
    pub code: Cow<'a, str>,
    /// The redirect uri
    pub redirect_uri: Cow<'a, str>,
    /// The grant type (should always be authorization_code)
    pub grant_type: Cow<'a, str>,
}

#[derive(serde::Serialize, serde::Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
struct AuthorizationCodeGrantCompleteResponse<'a> {
    /// The access token
    pub access_token: Cow<'a, str>,
    /// The refresh token
    pub refresh_token: Cow<'a, str>,
    /// The expiration time of the access token
    pub expires_in: u64,
    // TODO: add other fields if we start to need them
}

/// Tokens returned by a successful OAuth2 grant.
#[derive(Debug)]
pub struct OAuth2Grant {
    /// The access token.
    pub access_token: String,
    /// The refresh token.
    pub refresh_token: String,
    /// Seconds until the access token expires, as reported by FusionAuth.
    pub expires_in: u64,
}

/// Completes the authorization code grant
/// https://fusionauth.io/docs/lifecycle/authenticate-users/oauth/endpoints#complete-the-authorization-code-grant-request
/// Valid respones: 200, 400, 401, 500, 503
async fn complete(
    client: &UnauthedClient,
    base_url: &str,
    request: impl Serialize,
) -> Result<OAuth2Grant> {
    let body = serde_urlencoded::to_string(&request).map_err(|e| {
        FusionAuthClientError::Generic(GenericErrorResponse {
            message: e.to_string(),
        })
    })?;

    let res = client
        .client()
        .post(format!("{base_url}/oauth2/token"))
        .header(
            reqwest::header::CONTENT_TYPE,
            "application/x-www-form-urlencoded",
        )
        .body(body)
        .send()
        .await
        .map_err(FusionAuthClientError::transport)?;

    tracing::trace!("request sent");

    match res.status() {
        reqwest::StatusCode::OK => {
            tracing::info!("authorization code grant complete");
            let body = res
                .json::<AuthorizationCodeGrantCompleteResponse>()
                .await
                .map_err(FusionAuthClientError::transport)?;

            Ok(OAuth2Grant {
                access_token: body.access_token.into(),
                refresh_token: body.refresh_token.into(),
                expires_in: body.expires_in,
            })
        }
        status @ (reqwest::StatusCode::BAD_REQUEST | reqwest::StatusCode::UNAUTHORIZED) => {
            let headers = res.headers().clone();
            let body = res.text().await.map_err(FusionAuthClientError::transport)?;
            match serde_json::from_str::<OAuth2TokenError>(&body) {
                Ok(refusal) => {
                    tracing::warn!(
                        %status,
                        error = %refusal.error,
                        error_reason = refusal.error_reason.as_deref(),
                        error_description = refusal.error_description.as_deref(),
                        "fusionauth refused the oauth2 token request"
                    );
                    Err(FusionAuthClientError::OAuth2TokenRefused(refusal))
                }
                Err(_) => Err(FusionAuthClientError::unexpected(status, &headers, body)),
            }
        }
        _ => Err(FusionAuthClientError::unexpected_response(res).await),
    }
}

impl FusionAuthClient {
    /// Completes the OAuth2 authorization code grant flow.
    #[tracing::instrument(skip(self, code), fields(application_id=%self.client_id, fusion_auth_base_url=%self.fusion_auth_base_url))]
    pub async fn complete_authorization_code_grant(&self, code: &str) -> Result<OAuth2Grant> {
        complete(
            &self.unauth_client,
            &self.fusion_auth_base_url,
            AuthorizationCodeGrantCompleteRequest {
                client_id: Cow::Borrowed(&self.client_id),
                client_secret: Cow::Borrowed(&self.client_secret),
                code: Cow::Borrowed(code),
                redirect_uri: Cow::Borrowed(&self.oauth_redirect_uri),
                grant_type: Cow::Borrowed("authorization_code"),
            },
        )
        .await
    }

    /// complete the OAuth2 Refresh token grant flow.
    #[tracing::instrument(skip(self, refresh_token), fields(application_id=%self.client_id, fusion_auth_base_url=%self.fusion_auth_base_url))]
    pub async fn complete_refresh_token_grant(&self, refresh_token: &str) -> Result<OAuth2Grant> {
        complete(
            &self.unauth_client,
            &self.fusion_auth_base_url,
            RefreshTokenGrantCompleteRequest {
                client_id: Cow::Borrowed(&self.client_id),
                client_secret: Cow::Borrowed(&self.client_secret),
                refresh_token: Cow::Borrowed(refresh_token),
                grant_type: Cow::Borrowed("refresh_token"),
            },
        )
        .await
    }
}