BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / google_calendar / oauth.rs

oauth.rs

78236dde History
oauth.rs 7.9 KiB Download Raw
1use base64::Engine as _;
2use base64::engine::general_purpose::URL_SAFE_NO_PAD;
3use rand::RngCore;
4use serde::Deserialize;
5use sha2::{Digest, Sha256};
6
7use crate::error::{Error, Result};
8
9pub const GOOGLE_CLIENT_ID_ENV: &str = "TEAMS_GOOGLE_CLIENT_ID";
10pub const GOOGLE_CLIENT_SECRET_ENV: &str = "TEAMS_GOOGLE_CLIENT_SECRET";
11const AUTH_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth";
12const TOKEN_URL: &str = "https://oauth2.googleapis.com/token";
13const SCOPES: &str =
14 "https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email";
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct GoogleOAuth {
18 pub client_id: String,
19 pub client_secret: String,
20}
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub 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)]
31pub 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/// Runtime env wins; otherwise the value baked in at compile time (`option_env!`).
42/// Empty strings count as missing. Used by Connect and token refresh.
43pub fn client_id_from_env() -> Option<GoogleOAuth> {
44 resolve_oauth(
45 std::env::var(GOOGLE_CLIENT_ID_ENV).ok().as_deref(),
46 std::env::var(GOOGLE_CLIENT_SECRET_ENV).ok().as_deref(),
47 option_env!("TEAMS_GOOGLE_CLIENT_ID"),
48 option_env!("TEAMS_GOOGLE_CLIENT_SECRET"),
49 )
50}
51
52fn resolve_oauth(
53 runtime_id: Option<&str>,
54 runtime_secret: Option<&str>,
55 compile_id: Option<&str>,
56 compile_secret: Option<&str>,
57) -> Option<GoogleOAuth> {
58 let client_id = first_non_empty(runtime_id).or_else(|| first_non_empty(compile_id))?;
59 let client_secret = first_non_empty(runtime_secret)
60 .or_else(|| first_non_empty(compile_secret))
61 .unwrap_or_default();
62 Some(GoogleOAuth {
63 client_id,
64 client_secret,
65 })
66}
67
68fn first_non_empty(value: Option<&str>) -> Option<String> {
69 value
70 .map(str::trim)
71 .filter(|text| !text.is_empty())
72 .map(str::to_owned)
73}
74
75impl GoogleOAuth {
76 pub fn begin(&self, redirect_uri: &str) -> AuthPending {
77 let state = random_url_token(16);
78 let code_verifier = random_url_token(32);
79 let challenge = code_challenge(&code_verifier);
80 let mut url = url::Url::parse(AUTH_URL).expect("auth url");
81 {
82 let mut query = url.query_pairs_mut();
83 query.append_pair("client_id", &self.client_id);
84 query.append_pair("redirect_uri", redirect_uri);
85 query.append_pair("response_type", "code");
86 query.append_pair("scope", SCOPES);
87 query.append_pair("access_type", "offline");
88 query.append_pair("prompt", "consent");
89 query.append_pair("state", &state);
90 query.append_pair("code_challenge", &challenge);
91 query.append_pair("code_challenge_method", "S256");
92 }
93 AuthPending {
94 authorize_url: url.to_string(),
95 redirect_uri: redirect_uri.to_owned(),
96 state,
97 code_verifier,
98 }
99 }
100}
101
102pub async fn exchange_code(
103 oauth: &GoogleOAuth,
104 pending: &AuthPending,
105 code: &str,
106) -> Result<TokenBundle> {
107 let client = reqwest::Client::new();
108 let mut form = vec![
109 ("code", code.to_owned()),
110 ("client_id", oauth.client_id.clone()),
111 ("redirect_uri", pending.redirect_uri.clone()),
112 ("grant_type", "authorization_code".to_owned()),
113 ("code_verifier", pending.code_verifier.clone()),
114 ];
115 if !oauth.client_secret.is_empty() {
116 form.push(("client_secret", oauth.client_secret.clone()));
117 }
118 let response = client
119 .post(TOKEN_URL)
120 .form(&form)
121 .send()
122 .await
123 .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
124 let status = response.status().as_u16();
125 let body = response
126 .json::<serde_json::Value>()
127 .await
128 .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
129 if !(200..300).contains(&status) {
130 return Err(Error::Session(session::Error::api(status, TOKEN_URL, body)));
131 }
132 serde_json::from_value(body).map_err(|error| Error::UnexpectedAnswer(error.to_string()))
133}
134
135pub async fn refresh_access_token(oauth: &GoogleOAuth, refresh_token: &str) -> Result<TokenBundle> {
136 let client = reqwest::Client::new();
137 let mut form = vec![
138 ("client_id", oauth.client_id.clone()),
139 ("grant_type", "refresh_token".to_owned()),
140 ("refresh_token", refresh_token.to_owned()),
141 ];
142 if !oauth.client_secret.is_empty() {
143 form.push(("client_secret", oauth.client_secret.clone()));
144 }
145 let response = client
146 .post(TOKEN_URL)
147 .form(&form)
148 .send()
149 .await
150 .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
151 let status = response.status().as_u16();
152 let body = response
153 .json::<serde_json::Value>()
154 .await
155 .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
156 if !(200..300).contains(&status) {
157 return Err(Error::Session(session::Error::api(status, TOKEN_URL, body)));
158 }
159 let mut bundle: TokenBundle =
160 serde_json::from_value(body).map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
161 if bundle.refresh_token.is_empty() {
162 bundle.refresh_token = refresh_token.to_owned();
163 }
164 Ok(bundle)
165}
166
167fn random_url_token(bytes: usize) -> String {
168 let mut buffer = vec![0_u8; bytes];
169 rand::rng().fill_bytes(&mut buffer);
170 URL_SAFE_NO_PAD.encode(buffer)
171}
172
173fn code_challenge(verifier: &str) -> String {
174 let digest = Sha256::digest(verifier.as_bytes());
175 URL_SAFE_NO_PAD.encode(digest)
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181
182 #[test]
183 fn begin_builds_pkce_authorize_url() {
184 let oauth = GoogleOAuth {
185 client_id: "cid".into(),
186 client_secret: String::new(),
187 };
188 let pending = oauth.begin("http://127.0.0.1:8765/");
189 assert!(pending.authorize_url.contains("client_id=cid"));
190 assert!(pending.authorize_url.contains("code_challenge_method=S256"));
191 assert!(!pending.code_verifier.is_empty());
192 assert_eq!(
193 code_challenge("abc"),
194 URL_SAFE_NO_PAD.encode(Sha256::digest(b"abc"))
195 );
196 }
197
198 #[test]
199 fn token_bundle_deserializes() {
200 let json =
201 r#"{"access_token":"a","refresh_token":"r","expires_in":3600,"token_type":"Bearer"}"#;
202 let bundle: TokenBundle = serde_json::from_str(json).unwrap();
203 assert_eq!(bundle.access_token, "a");
204 assert_eq!(bundle.refresh_token, "r");
205 assert_eq!(bundle.expires_in, 3600);
206 }
207
208 #[test]
209 fn resolve_prefers_runtime_over_compile() {
210 let oauth = resolve_oauth(
211 Some("runtime-id"),
212 Some("runtime-secret"),
213 Some("compile-id"),
214 Some("compile-secret"),
215 )
216 .unwrap();
217 assert_eq!(oauth.client_id, "runtime-id");
218 assert_eq!(oauth.client_secret, "runtime-secret");
219 }
220
221 #[test]
222 fn resolve_falls_back_to_compile_when_runtime_empty() {
223 let oauth =
224 resolve_oauth(Some(" "), None, Some("compile-id"), Some("compile-secret")).unwrap();
225 assert_eq!(oauth.client_id, "compile-id");
226 assert_eq!(oauth.client_secret, "compile-secret");
227 }
228
229 #[test]
230 fn resolve_returns_none_when_both_missing() {
231 assert!(resolve_oauth(None, None, None, None).is_none());
232 assert!(resolve_oauth(Some(""), None, Some(" "), None).is_none());
233 }
234
235 #[test]
236 fn resolve_allows_missing_secret() {
237 let oauth = resolve_oauth(Some("cid"), None, None, None).unwrap();
238 assert_eq!(oauth.client_id, "cid");
239 assert!(oauth.client_secret.is_empty());
240 }
241}