scufflecloud_core/
google_api.rs

1use std::sync::Arc;
2
3use base64::Engine;
4
5pub(crate) const ADMIN_DIRECTORY_API_USER_SCOPE: &str = "https://www.googleapis.com/auth/admin.directory.user.readonly";
6const ALL_SCOPES: [&str; 4] = ["openid", "profile", "email", ADMIN_DIRECTORY_API_USER_SCOPE];
7const REQUIRED_SCOPES: [&str; 3] = ["openid", "profile", "email"];
8
9#[derive(serde_derive::Deserialize, Debug)]
10pub(crate) struct GoogleToken {
11    pub access_token: String,
12    pub expires_in: u64,
13    #[serde(deserialize_with = "deserialize_google_id_token")]
14    pub id_token: GoogleIdToken,
15    pub scope: String,
16    pub token_type: String,
17}
18
19/// https://developers.google.com/identity/openid-connect/openid-connect#obtainuserinfo
20#[derive(serde_derive::Deserialize, Debug, Clone)]
21pub(crate) struct GoogleIdToken {
22    pub sub: String,
23    pub email: String,
24    pub email_verified: bool,
25    pub family_name: Option<String>,
26    pub given_name: Option<String>,
27    pub hd: Option<String>,
28    pub name: Option<String>,
29    pub picture: Option<String>,
30}
31
32fn deserialize_google_id_token<'de, D>(deserialzer: D) -> Result<GoogleIdToken, D::Error>
33where
34    D: serde::Deserializer<'de>,
35{
36    let token: String = serde::Deserialize::deserialize(deserialzer)?;
37    let parts: Vec<&str> = token.split('.').collect();
38    if parts.len() != 3 {
39        return Err(serde::de::Error::custom("Invalid ID token format"));
40    }
41
42    let payload = base64::prelude::BASE64_URL_SAFE_NO_PAD
43        .decode(parts[1])
44        .map_err(serde::de::Error::custom)?;
45
46    serde_json::from_slice(&payload).map_err(serde::de::Error::custom)
47}
48
49#[derive(thiserror::Error, Debug)]
50pub(crate) enum GoogleTokenError {
51    #[error("invalid token type: {0}")]
52    InvalidTokenType(String),
53    #[error("missing scope: {0}")]
54    MissingScope(String),
55    #[error("HTTP request failed: {0}")]
56    RequestFailed(#[from] reqwest::Error),
57}
58
59fn redirect_uri(dashboard_origin: &url::Url) -> String {
60    dashboard_origin.join("/oauth2-callback/google").unwrap().to_string()
61}
62
63pub(crate) fn authorization_url<G: core_traits::Global>(
64    global: &Arc<G>,
65    dashboard_origin: &url::Url,
66    state: &str,
67) -> String {
68    format!(
69        "https://accounts.google.com/o/oauth2/v2/auth?client_id={}&redirect_uri={}&response_type=code&scope={}&state={state}",
70        global.google_oauth2_config().client_id,
71        urlencoding::encode(&redirect_uri(dashboard_origin)),
72        ALL_SCOPES.join("%20"), // URL-encoded space
73    )
74}
75
76pub(crate) async fn request_tokens<G: core_traits::Global>(
77    global: &Arc<G>,
78    dashboard_origin: &url::Url,
79    code: &str,
80) -> Result<GoogleToken, GoogleTokenError> {
81    let tokens: GoogleToken = global
82        .external_http_client()
83        .post("https://oauth2.googleapis.com/token")
84        .form(&[
85            ("client_id", global.google_oauth2_config().client_id.as_ref()),
86            ("client_secret", global.google_oauth2_config().client_secret.as_ref()),
87            ("code", code),
88            ("grant_type", "authorization_code"),
89            ("redirect_uri", &redirect_uri(dashboard_origin)),
90        ])
91        .send()
92        .await?
93        .json()
94        .await?;
95
96    if tokens.token_type != "Bearer" {
97        return Err(GoogleTokenError::InvalidTokenType(tokens.token_type));
98    }
99
100    if let Some(missing) = REQUIRED_SCOPES.iter().find(|scope| !tokens.scope.contains(*scope)) {
101        return Err(GoogleTokenError::MissingScope(missing.to_string()));
102    }
103
104    Ok(tokens)
105}
106
107#[derive(serde_derive::Deserialize, Debug)]
108pub(crate) struct GoogleWorkspaceUser {
109    #[serde(rename = "isAdmin")]
110    pub is_admin: bool,
111    #[serde(rename = "customerId")]
112    pub customer_id: String,
113}
114
115#[derive(thiserror::Error, Debug)]
116pub(crate) enum GoogleWorkspaceGetUserError {
117    #[error("HTTP request failed: {0}")]
118    RequestFailed(#[from] reqwest::Error),
119    #[error("invalid status code: {0}")]
120    InvalidStatusCode(reqwest::StatusCode),
121}
122
123pub(crate) async fn request_google_workspace_user<G: core_traits::Global>(
124    global: &Arc<G>,
125    access_token: &str,
126    user_id: &str,
127) -> Result<Option<GoogleWorkspaceUser>, GoogleWorkspaceGetUserError> {
128    let response = global
129        .external_http_client()
130        .get(format!("https://www.googleapis.com/admin/directory/v1/users/{user_id}"))
131        .bearer_auth(access_token)
132        .send()
133        .await?;
134
135    if response.status() == reqwest::StatusCode::FORBIDDEN {
136        return Ok(None);
137    }
138
139    if !response.status().is_success() {
140        return Err(GoogleWorkspaceGetUserError::InvalidStatusCode(response.status()));
141    }
142
143    Ok(Some(response.json().await?))
144}