| 1 | use base64::Engine as _; |
| 2 | use base64::engine::general_purpose::URL_SAFE_NO_PAD; |
| 3 | use rand::RngCore; |
| 4 | use serde::Deserialize; |
| 5 | use sha2::{Digest, Sha256}; |
| 6 | |
| 7 | use crate::error::{Error, Result}; |
| 8 | |
| 9 | pub const GOOGLE_CLIENT_ID_ENV: &str = "TEAMS_GOOGLE_CLIENT_ID"; |
| 10 | pub const GOOGLE_CLIENT_SECRET_ENV: &str = "TEAMS_GOOGLE_CLIENT_SECRET"; |
| 11 | const AUTH_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth"; |
| 12 | const TOKEN_URL: &str = "https://oauth2.googleapis.com/token"; |
| 13 | const SCOPES: &str = |
| 14 | "https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email"; |
| 15 | |
| 16 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 17 | pub struct GoogleOAuth { |
| 18 | pub client_id: String, |
| 19 | pub client_secret: String, |
| 20 | } |
| 21 | |
| 22 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 23 | pub struct AuthPending { |
| 24 | pub authorize_url: String, |
| 25 | pub redirect_uri: String, |
| 26 | pub state: String, |
| 27 | pub code_verifier: String, |
| 28 | } |
| 29 | |
| 30 | #[derive(Debug, Clone, PartialEq, Eq, Deserialize)] |
| 31 | pub struct TokenBundle { |
| 32 | pub access_token: String, |
| 33 | #[serde(default)] |
| 34 | pub refresh_token: String, |
| 35 | #[serde(default)] |
| 36 | pub expires_in: i64, |
| 37 | #[serde(default)] |
| 38 | pub token_type: String, |
| 39 | } |
| 40 | |
| 41 | pub fn client_id_from_env() -> Option<GoogleOAuth> { |
| 42 | let client_id = std::env::var(GOOGLE_CLIENT_ID_ENV).ok()?; |
| 43 | if client_id.trim().is_empty() { |
| 44 | return None; |
| 45 | } |
| 46 | let client_secret = std::env::var(GOOGLE_CLIENT_SECRET_ENV).unwrap_or_default(); |
| 47 | Some(GoogleOAuth { |
| 48 | client_id, |
| 49 | client_secret, |
| 50 | }) |
| 51 | } |
| 52 | |
| 53 | impl GoogleOAuth { |
| 54 | pub fn begin(&self, redirect_uri: &str) -> AuthPending { |
| 55 | let state = random_url_token(16); |
| 56 | let code_verifier = random_url_token(32); |
| 57 | let challenge = code_challenge(&code_verifier); |
| 58 | let mut url = url::Url::parse(AUTH_URL).expect("auth url"); |
| 59 | { |
| 60 | let mut query = url.query_pairs_mut(); |
| 61 | query.append_pair("client_id", &self.client_id); |
| 62 | query.append_pair("redirect_uri", redirect_uri); |
| 63 | query.append_pair("response_type", "code"); |
| 64 | query.append_pair("scope", SCOPES); |
| 65 | query.append_pair("access_type", "offline"); |
| 66 | query.append_pair("prompt", "consent"); |
| 67 | query.append_pair("state", &state); |
| 68 | query.append_pair("code_challenge", &challenge); |
| 69 | query.append_pair("code_challenge_method", "S256"); |
| 70 | } |
| 71 | AuthPending { |
| 72 | authorize_url: url.to_string(), |
| 73 | redirect_uri: redirect_uri.to_owned(), |
| 74 | state, |
| 75 | code_verifier, |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | pub async fn exchange_code( |
| 81 | oauth: &GoogleOAuth, |
| 82 | pending: &AuthPending, |
| 83 | code: &str, |
| 84 | ) -> Result<TokenBundle> { |
| 85 | let client = reqwest::Client::new(); |
| 86 | let mut form = vec![ |
| 87 | ("code", code.to_owned()), |
| 88 | ("client_id", oauth.client_id.clone()), |
| 89 | ("redirect_uri", pending.redirect_uri.clone()), |
| 90 | ("grant_type", "authorization_code".to_owned()), |
| 91 | ("code_verifier", pending.code_verifier.clone()), |
| 92 | ]; |
| 93 | if !oauth.client_secret.is_empty() { |
| 94 | form.push(("client_secret", oauth.client_secret.clone())); |
| 95 | } |
| 96 | let response = client |
| 97 | .post(TOKEN_URL) |
| 98 | .form(&form) |
| 99 | .send() |
| 100 | .await |
| 101 | .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?; |
| 102 | let status = response.status().as_u16(); |
| 103 | let body = response |
| 104 | .json::<serde_json::Value>() |
| 105 | .await |
| 106 | .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?; |
| 107 | if !(200..300).contains(&status) { |
| 108 | return Err(Error::Session(session::Error::api(status, TOKEN_URL, body))); |
| 109 | } |
| 110 | serde_json::from_value(body).map_err(|error| Error::UnexpectedAnswer(error.to_string())) |
| 111 | } |
| 112 | |
| 113 | pub async fn refresh_access_token(oauth: &GoogleOAuth, refresh_token: &str) -> Result<TokenBundle> { |
| 114 | let client = reqwest::Client::new(); |
| 115 | let mut form = vec![ |
| 116 | ("client_id", oauth.client_id.clone()), |
| 117 | ("grant_type", "refresh_token".to_owned()), |
| 118 | ("refresh_token", refresh_token.to_owned()), |
| 119 | ]; |
| 120 | if !oauth.client_secret.is_empty() { |
| 121 | form.push(("client_secret", oauth.client_secret.clone())); |
| 122 | } |
| 123 | let response = client |
| 124 | .post(TOKEN_URL) |
| 125 | .form(&form) |
| 126 | .send() |
| 127 | .await |
| 128 | .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?; |
| 129 | let status = response.status().as_u16(); |
| 130 | let body = response |
| 131 | .json::<serde_json::Value>() |
| 132 | .await |
| 133 | .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?; |
| 134 | if !(200..300).contains(&status) { |
| 135 | return Err(Error::Session(session::Error::api(status, TOKEN_URL, body))); |
| 136 | } |
| 137 | let mut bundle: TokenBundle = |
| 138 | serde_json::from_value(body).map_err(|error| Error::UnexpectedAnswer(error.to_string()))?; |
| 139 | if bundle.refresh_token.is_empty() { |
| 140 | bundle.refresh_token = refresh_token.to_owned(); |
| 141 | } |
| 142 | Ok(bundle) |
| 143 | } |
| 144 | |
| 145 | fn random_url_token(bytes: usize) -> String { |
| 146 | let mut buffer = vec![0_u8; bytes]; |
| 147 | rand::rng().fill_bytes(&mut buffer); |
| 148 | URL_SAFE_NO_PAD.encode(buffer) |
| 149 | } |
| 150 | |
| 151 | fn code_challenge(verifier: &str) -> String { |
| 152 | let digest = Sha256::digest(verifier.as_bytes()); |
| 153 | URL_SAFE_NO_PAD.encode(digest) |
| 154 | } |
| 155 | |
| 156 | #[cfg(test)] |
| 157 | mod tests { |
| 158 | use super::*; |
| 159 | |
| 160 | #[test] |
| 161 | fn begin_builds_pkce_authorize_url() { |
| 162 | let oauth = GoogleOAuth { |
| 163 | client_id: "cid".into(), |
| 164 | client_secret: String::new(), |
| 165 | }; |
| 166 | let pending = oauth.begin("http://127.0.0.1:8765/"); |
| 167 | assert!(pending.authorize_url.contains("client_id=cid")); |
| 168 | assert!(pending.authorize_url.contains("code_challenge_method=S256")); |
| 169 | assert!(!pending.code_verifier.is_empty()); |
| 170 | assert_eq!( |
| 171 | code_challenge("abc"), |
| 172 | URL_SAFE_NO_PAD.encode(Sha256::digest(b"abc")) |
| 173 | ); |
| 174 | } |
| 175 | |
| 176 | #[test] |
| 177 | fn token_bundle_deserializes() { |
| 178 | let json = |
| 179 | r#"{"access_token":"a","refresh_token":"r","expires_in":3600,"token_type":"Bearer"}"#; |
| 180 | let bundle: TokenBundle = serde_json::from_str(json).unwrap(); |
| 181 | assert_eq!(bundle.access_token, "a"); |
| 182 | assert_eq!(bundle.refresh_token, "r"); |
| 183 | assert_eq!(bundle.expires_in, 3600); |
| 184 | } |
| 185 | } |