BlueGit

ict rusty-teams

Files

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

oauth.rs

oauth.rs 9.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 when Settings has no saved pair.
43pub fn client_id_from_env() -> Option<GoogleOAuth> {
44 client_from_stored(None, None)
45}
46
47/// A saved id and secret win only together. Otherwise the same order as
48/// [`client_id_from_env`]: runtime env, then the compiled client.
49pub fn client_from_stored(
50 stored_id: Option<&str>,
51 stored_secret: Option<&str>,
52) -> Option<GoogleOAuth> {
53 resolve_oauth(
54 stored_id,
55 stored_secret,
56 std::env::var(GOOGLE_CLIENT_ID_ENV).ok().as_deref(),
57 std::env::var(GOOGLE_CLIENT_SECRET_ENV).ok().as_deref(),
58 option_env!("TEAMS_GOOGLE_CLIENT_ID"),
59 option_env!("TEAMS_GOOGLE_CLIENT_SECRET"),
60 )
61}
62
63fn resolve_oauth(
64 stored_id: Option<&str>,
65 stored_secret: Option<&str>,
66 runtime_id: Option<&str>,
67 runtime_secret: Option<&str>,
68 compile_id: Option<&str>,
69 compile_secret: Option<&str>,
70) -> Option<GoogleOAuth> {
71 if let (Some(client_id), Some(client_secret)) =
72 (first_non_empty(stored_id), first_non_empty(stored_secret))
73 {
74 return Some(GoogleOAuth {
75 client_id,
76 client_secret,
77 });
78 }
79 let client_id = first_non_empty(runtime_id).or_else(|| first_non_empty(compile_id))?;
80 let client_secret = first_non_empty(runtime_secret)
81 .or_else(|| first_non_empty(compile_secret))
82 .unwrap_or_default();
83 Some(GoogleOAuth {
84 client_id,
85 client_secret,
86 })
87}
88
89fn first_non_empty(value: Option<&str>) -> Option<String> {
90 value
91 .map(str::trim)
92 .filter(|text| !text.is_empty())
93 .map(str::to_owned)
94}
95
96impl GoogleOAuth {
97 pub fn begin(&self, redirect_uri: &str) -> AuthPending {
98 let state = random_url_token(16);
99 let code_verifier = random_url_token(32);
100 let challenge = code_challenge(&code_verifier);
101 let mut url = url::Url::parse(AUTH_URL).expect("auth url");
102 {
103 let mut query = url.query_pairs_mut();
104 query.append_pair("client_id", &self.client_id);
105 query.append_pair("redirect_uri", redirect_uri);
106 query.append_pair("response_type", "code");
107 query.append_pair("scope", SCOPES);
108 query.append_pair("access_type", "offline");
109 query.append_pair("prompt", "consent");
110 query.append_pair("state", &state);
111 query.append_pair("code_challenge", &challenge);
112 query.append_pair("code_challenge_method", "S256");
113 }
114 AuthPending {
115 authorize_url: url.to_string(),
116 redirect_uri: redirect_uri.to_owned(),
117 state,
118 code_verifier,
119 }
120 }
121}
122
123pub async fn exchange_code(
124 oauth: &GoogleOAuth,
125 pending: &AuthPending,
126 code: &str,
127) -> Result<TokenBundle> {
128 let client = reqwest::Client::new();
129 let mut form = vec![
130 ("code", code.to_owned()),
131 ("client_id", oauth.client_id.clone()),
132 ("redirect_uri", pending.redirect_uri.clone()),
133 ("grant_type", "authorization_code".to_owned()),
134 ("code_verifier", pending.code_verifier.clone()),
135 ];
136 if !oauth.client_secret.is_empty() {
137 form.push(("client_secret", oauth.client_secret.clone()));
138 }
139 let response = client
140 .post(TOKEN_URL)
141 .form(&form)
142 .send()
143 .await
144 .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
145 let status = response.status().as_u16();
146 let body = response
147 .json::<serde_json::Value>()
148 .await
149 .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
150 if !(200..300).contains(&status) {
151 return Err(Error::Session(session::Error::api(status, TOKEN_URL, body)));
152 }
153 serde_json::from_value(body).map_err(|error| Error::UnexpectedAnswer(error.to_string()))
154}
155
156pub async fn refresh_access_token(oauth: &GoogleOAuth, refresh_token: &str) -> Result<TokenBundle> {
157 let client = reqwest::Client::new();
158 let mut form = vec![
159 ("client_id", oauth.client_id.clone()),
160 ("grant_type", "refresh_token".to_owned()),
161 ("refresh_token", refresh_token.to_owned()),
162 ];
163 if !oauth.client_secret.is_empty() {
164 form.push(("client_secret", oauth.client_secret.clone()));
165 }
166 let response = client
167 .post(TOKEN_URL)
168 .form(&form)
169 .send()
170 .await
171 .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
172 let status = response.status().as_u16();
173 let body = response
174 .json::<serde_json::Value>()
175 .await
176 .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
177 if !(200..300).contains(&status) {
178 return Err(Error::Session(session::Error::api(status, TOKEN_URL, body)));
179 }
180 let mut bundle: TokenBundle =
181 serde_json::from_value(body).map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
182 if bundle.refresh_token.is_empty() {
183 bundle.refresh_token = refresh_token.to_owned();
184 }
185 Ok(bundle)
186}
187
188fn random_url_token(bytes: usize) -> String {
189 let mut buffer = vec![0_u8; bytes];
190 rand::rng().fill_bytes(&mut buffer);
191 URL_SAFE_NO_PAD.encode(buffer)
192}
193
194fn code_challenge(verifier: &str) -> String {
195 let digest = Sha256::digest(verifier.as_bytes());
196 URL_SAFE_NO_PAD.encode(digest)
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202
203 #[test]
204 fn begin_builds_pkce_authorize_url() {
205 let oauth = GoogleOAuth {
206 client_id: "cid".into(),
207 client_secret: String::new(),
208 };
209 let pending = oauth.begin("http://127.0.0.1:8765/");
210 assert!(pending.authorize_url.contains("client_id=cid"));
211 assert!(pending.authorize_url.contains("code_challenge_method=S256"));
212 assert!(!pending.code_verifier.is_empty());
213 assert_eq!(
214 code_challenge("abc"),
215 URL_SAFE_NO_PAD.encode(Sha256::digest(b"abc"))
216 );
217 }
218
219 #[test]
220 fn token_bundle_deserializes() {
221 let json =
222 r#"{"access_token":"a","refresh_token":"r","expires_in":3600,"token_type":"Bearer"}"#;
223 let bundle: TokenBundle = serde_json::from_str(json).unwrap();
224 assert_eq!(bundle.access_token, "a");
225 assert_eq!(bundle.refresh_token, "r");
226 assert_eq!(bundle.expires_in, 3600);
227 }
228
229 #[test]
230 fn resolve_prefers_runtime_over_compile() {
231 let oauth = resolve_oauth(
232 None,
233 None,
234 Some("runtime-id"),
235 Some("runtime-secret"),
236 Some("compile-id"),
237 Some("compile-secret"),
238 )
239 .unwrap();
240 assert_eq!(oauth.client_id, "runtime-id");
241 assert_eq!(oauth.client_secret, "runtime-secret");
242 }
243
244 #[test]
245 fn resolve_falls_back_to_compile_when_runtime_empty() {
246 let oauth = resolve_oauth(
247 None,
248 None,
249 Some(" "),
250 None,
251 Some("compile-id"),
252 Some("compile-secret"),
253 )
254 .unwrap();
255 assert_eq!(oauth.client_id, "compile-id");
256 assert_eq!(oauth.client_secret, "compile-secret");
257 }
258
259 #[test]
260 fn resolve_returns_none_when_both_missing() {
261 assert!(resolve_oauth(None, None, None, None, None, None).is_none());
262 assert!(resolve_oauth(None, None, Some(""), None, Some(" "), None).is_none());
263 }
264
265 #[test]
266 fn resolve_allows_missing_secret() {
267 let oauth = resolve_oauth(None, None, Some("cid"), None, None, None).unwrap();
268 assert_eq!(oauth.client_id, "cid");
269 assert!(oauth.client_secret.is_empty());
270 }
271
272 #[test]
273 fn stored_pair_wins_over_runtime_and_compile() {
274 let oauth = resolve_oauth(
275 Some(" stored-id "),
276 Some(" stored-secret "),
277 Some("runtime-id"),
278 Some("runtime-secret"),
279 Some("compile-id"),
280 Some("compile-secret"),
281 )
282 .unwrap();
283 assert_eq!(oauth.client_id, "stored-id");
284 assert_eq!(oauth.client_secret, "stored-secret");
285 }
286
287 #[test]
288 fn stored_id_without_secret_does_not_override() {
289 let oauth = resolve_oauth(
290 Some("stored-id"),
291 Some(" "),
292 Some("runtime-id"),
293 Some("runtime-secret"),
294 None,
295 None,
296 )
297 .unwrap();
298 assert_eq!(oauth.client_id, "runtime-id");
299 assert_eq!(oauth.client_secret, "runtime-secret");
300 }
301
302 #[test]
303 fn stored_secret_without_id_does_not_override() {
304 let oauth = resolve_oauth(
305 Some(""),
306 Some("stored-secret"),
307 None,
308 None,
309 Some("compile-id"),
310 Some("compile-secret"),
311 )
312 .unwrap();
313 assert_eq!(oauth.client_id, "compile-id");
314 assert_eq!(oauth.client_secret, "compile-secret");
315 }
316}