larust_socialite/lib.rs
1//! Laravel's `laravel/socialite` - OAuth Authorization Code login
2//! ("Sign in with GitHub/Google"), narrowed to its real core. Two built-in
3//! providers ([`github`], [`google`]) plus a generic [`OAuthProvider`]
4//! shape a third provider can be built from directly (just URLs and a
5//! small mapping function - no plugin/registration mechanism to learn).
6//!
7//! **Owns no database table at all**, unlike `larust-permissions`/
8//! `larust-sanctum`/`larust-cache` - turning "an OAuth provider's user
9//! info" into "a real app user" is entirely app-owned logic via
10//! [`SocialiteUser::find_or_create_from_provider`], the same "provide the
11//! hook, the app owns persistence" shape `larust_auth::Authenticatable`
12//! itself already established (an app might add `provider`/
13//! `provider_user_id` columns to its own `users` table, or a separate
14//! pivot table - this crate has no opinion). This crate's own job is
15//! narrower: drive the OAuth protocol exchange and verify the anti-CSRF
16//! `state` parameter via the session, nothing else.
17//!
18//! Re-exported through `larust_support::socialite` (see `crates/
19//! larust-support/src/lib.rs`) so generated apps depend only on
20//! `larust-support`, never on this crate directly.
21//!
22//! A typical route pair (the app wires these itself - nothing here is
23//! auto-mounted, the same convention every other shim crate this session
24//! follows):
25//!
26//! ```ignore
27//! async fn redirect(session: Session) -> Result<impl IntoResponse, AppError> {
28//! let provider = larust_support::socialite::github()?;
29//! Ok(Redirect::to(&larust_support::socialite::redirect_url(&session, "github", &provider).await?))
30//! }
31//!
32//! async fn callback(
33//! session: Session,
34//! Query(params): Query<CallbackParams>,
35//! ) -> Result<impl IntoResponse, AppError> {
36//! let provider = larust_support::socialite::github()?;
37//! let user: User = larust_support::socialite::user_from_callback(
38//! &session, "github", &provider, ¶ms.code, ¶ms.state,
39//! ).await?;
40//! larust_support::auth::login(&session, &user).await?;
41//! larust_support::redirect().to("/")
42//! }
43//! ```
44//!
45//! ## Deliberately out of scope for this version
46//!
47//! - **No OpenID Connect ID-token verification** - plain OAuth2
48//! Authorization Code flow plus a userinfo `GET`, matching real
49//! Socialite's own default behavior (it doesn't verify ID tokens
50//! either).
51//! - **No token refresh / long-lived provider-token storage.** The
52//! provider's own access token is used once, to fetch userinfo, then
53//! discarded - only the resolved app user is persisted (via session
54//! login), same as every other login path in this codebase.
55//! - **No `extend()`-style provider registry.** A third provider is a
56//! third [`OAuthProvider`] value an app constructs directly - no
57//! plugin/registration mechanism, matching this crate's otherwise
58//! stateless design.
59
60use larust_auth::Authenticatable;
61use larust_core::AppError;
62use larust_http::session::Session;
63use serde::Deserialize;
64use std::future::Future;
65
66/// A configured OAuth2 provider - the two built-in constructors
67/// ([`github`]/[`google`]) build one from environment variables; a third
68/// provider is built the same way by hand.
69pub struct OAuthProvider {
70 client_id: String,
71 client_secret: String,
72 redirect_url: String,
73 authorize_url: &'static str,
74 token_url: &'static str,
75 userinfo_url: &'static str,
76 scope: &'static str,
77 /// Extracts the fields this crate needs from the provider's own
78 /// userinfo JSON shape - each provider names them differently (e.g.
79 /// GitHub's numeric `id` vs. Google's string `sub`), so this is the
80 /// one piece every provider must supply itself. `None` on a response
81 /// shape that doesn't match what was expected (missing/wrong-typed
82 /// id) rather than guessing.
83 map_user: fn(&serde_json::Value) -> Option<ProviderUser>,
84 /// Extra headers the token/userinfo requests need beyond the standard
85 /// `Authorization`/`Accept: application/json` - GitHub specifically
86 /// requires both a non-default `Accept` on its token endpoint (it
87 /// returns form-encoded by default otherwise) and a `User-Agent` on
88 /// its userinfo endpoint (rejected with no header at all otherwise).
89 /// Google needs neither.
90 extra_headers: &'static [(&'static str, &'static str)],
91}
92
93/// The fields this crate actually needs out of a provider's userinfo
94/// response - `email`/`name` are `Option`, not required: a provider can
95/// legitimately omit either (GitHub omits `email` entirely unless the
96/// `user:email` scope was granted), and pretending otherwise would mean
97/// silently creating users with an empty email. The app decides how to
98/// handle a missing one in its own `find_or_create_from_provider`.
99pub struct ProviderUser {
100 pub provider_user_id: String,
101 pub email: Option<String>,
102 pub name: Option<String>,
103}
104
105/// The hook an app implements to turn a [`ProviderUser`] into a real
106/// [`Authenticatable`] user - find an existing account (by provider id,
107/// by email, whatever the app's own schema tracks) or create a new one.
108/// Mirrors `demo/app/Http/Controllers/auth_controller.rs`'s own
109/// `register` handler (`User::create(...)`) - this crate calls the hook,
110/// the app owns everything about *how* a user gets resolved or created.
111pub trait SocialiteUser: Authenticatable {
112 fn find_or_create_from_provider(
113 provider: &str,
114 user: &ProviderUser,
115 ) -> impl Future<Output = Result<Self, AppError>> + Send;
116}
117
118fn required_env(key: &str) -> Result<String, AppError> {
119 std::env::var(key)
120 .ok()
121 .filter(|value| !value.is_empty())
122 .ok_or_else(|| {
123 AppError::Config(Box::new(std::io::Error::other(format!(
124 "{key} must be set to use this OAuth provider"
125 ))))
126 })
127}
128
129/// GitHub's `Authorization Code` OAuth app flow
130/// (`https://docs.github.com/en/apps/oauth-apps`). Reads `GITHUB_CLIENT_
131/// ID`/`GITHUB_CLIENT_SECRET`/`GITHUB_REDIRECT_URL` - `Err(AppError::
132/// Config)`, naming the missing variable, if any are unset, so a
133/// misconfigured provider fails clearly here rather than sending a
134/// broken authorize URL to the browser.
135pub fn github() -> Result<OAuthProvider, AppError> {
136 Ok(OAuthProvider {
137 client_id: required_env("GITHUB_CLIENT_ID")?,
138 client_secret: required_env("GITHUB_CLIENT_SECRET")?,
139 redirect_url: required_env("GITHUB_REDIRECT_URL")?,
140 authorize_url: "https://github.com/login/oauth/authorize",
141 token_url: "https://github.com/login/oauth/access_token",
142 userinfo_url: "https://api.github.com/user",
143 scope: "read:user user:email",
144 map_user: |json| {
145 Some(ProviderUser {
146 provider_user_id: json.get("id")?.as_i64()?.to_string(),
147 email: json
148 .get("email")
149 .and_then(|v| v.as_str())
150 .map(str::to_string),
151 name: json
152 .get("name")
153 .and_then(|v| v.as_str())
154 .map(str::to_string),
155 })
156 },
157 // GitHub's token endpoint returns `application/x-www-form-urlencoded`
158 // unless explicitly told otherwise; its userinfo endpoint 403s any
159 // request with no `User-Agent` at all (a real, easy-to-miss gotcha
160 // - the reqwest client itself sends none by default).
161 extra_headers: &[
162 ("Accept", "application/json"),
163 ("User-Agent", "larust-socialite"),
164 ],
165 })
166}
167
168/// Google's OAuth2 flow (`https://developers.google.com/identity/
169/// protocols/oauth2/web-server`) - plain OAuth2 userinfo, not OIDC
170/// ID-token verification (see this crate's own doc comment for why).
171/// Reads `GOOGLE_CLIENT_ID`/`GOOGLE_CLIENT_SECRET`/`GOOGLE_REDIRECT_URL`.
172pub fn google() -> Result<OAuthProvider, AppError> {
173 Ok(OAuthProvider {
174 client_id: required_env("GOOGLE_CLIENT_ID")?,
175 client_secret: required_env("GOOGLE_CLIENT_SECRET")?,
176 redirect_url: required_env("GOOGLE_REDIRECT_URL")?,
177 authorize_url: "https://accounts.google.com/o/oauth2/v2/auth",
178 token_url: "https://oauth2.googleapis.com/token",
179 userinfo_url: "https://www.googleapis.com/oauth2/v2/userinfo",
180 scope: "openid email profile",
181 map_user: |json| {
182 Some(ProviderUser {
183 provider_user_id: json.get("id")?.as_str()?.to_string(),
184 email: json
185 .get("email")
186 .and_then(|v| v.as_str())
187 .map(str::to_string),
188 name: json
189 .get("name")
190 .and_then(|v| v.as_str())
191 .map(str::to_string),
192 })
193 },
194 extra_headers: &[],
195 })
196}
197
198fn state_session_key(provider_name: &str) -> String {
199 format!("_socialite_state_{provider_name}")
200}
201
202/// Builds the URL to redirect the browser to for `provider`, generating a
203/// fresh anti-CSRF `state` value (`larust_http::random_hex(32)` - the
204/// same generator `csrf::token` uses) and storing it in the session under
205/// a provider-scoped key, so a user can plausibly have two concurrent
206/// OAuth attempts open in different tabs without one clobbering the
207/// other's `state`.
208pub async fn redirect_url(
209 session: &Session,
210 provider_name: &str,
211 provider: &OAuthProvider,
212) -> Result<String, AppError> {
213 let state = larust_http::random_hex(32);
214 session
215 .insert(&state_session_key(provider_name), state.clone())
216 .await
217 .map_err(|source| AppError::Internal(Box::new(source)))?;
218
219 let query = form_urlencoded::Serializer::new(String::new())
220 .append_pair("client_id", &provider.client_id)
221 .append_pair("redirect_uri", &provider.redirect_url)
222 .append_pair("scope", provider.scope)
223 .append_pair("state", &state)
224 .append_pair("response_type", "code")
225 .finish();
226 Ok(format!("{}?{query}", provider.authorize_url))
227}
228
229/// One generic rejection for every `state`-verification failure (missing,
230/// expired, or mismatched) - never reveals which, the same instinct a
231/// password check already follows elsewhere in this codebase.
232fn invalid_state() -> AppError {
233 AppError::Http {
234 status: reqwest::StatusCode::UNAUTHORIZED,
235 message: "invalid or expired OAuth state".to_string(),
236 }
237}
238
239/// Constant-time comparison, found missing in a security review: `state`
240/// is exactly the kind of value `larust_sanctum::hashes_match`'s own doc
241/// comment already identifies as needing this (a 256-bit CSPRNG anti-CSRF
242/// secret, not user-chosen data) - a plain `==`/`!=` short-circuits on the
243/// first differing byte, leaking timing information proportional to how
244/// much of the real value an attacker guessed correctly. A local duplicate
245/// of the identical few lines rather than a shared crate for one function,
246/// the same "just call the primitive directly" style `larust-sanctum`'s
247/// own `random_hex` already establishes for this codebase's shim crates.
248fn constant_time_eq(a: &str, b: &str) -> bool {
249 let (a, b) = (a.as_bytes(), b.as_bytes());
250 if a.len() != b.len() {
251 return false;
252 }
253 let mut diff = 0u8;
254 for (x, y) in a.iter().zip(b.iter()) {
255 diff |= x ^ y;
256 }
257 diff == 0
258}
259
260#[derive(Deserialize)]
261struct TokenResponse {
262 access_token: String,
263}
264
265/// Completes the flow [`redirect_url`] started: verifies `state` against
266/// the session (single-use - `session.remove`, not `.get`, so a replayed
267/// callback with the same `state` fails the second time), exchanges
268/// `code` for an access token, fetches the provider's userinfo, and
269/// resolves the app's own user via [`SocialiteUser::find_or_create_from_
270/// provider`]. Does **not** log the resolved user into the session itself -
271/// the caller does that explicitly (`larust_auth::login(&session,
272/// &user)`), the same shape `AuthController::register` already uses,
273/// rather than this function silently authenticating a session as a side
274/// effect.
275pub async fn user_from_callback<U: SocialiteUser>(
276 session: &Session,
277 provider_name: &str,
278 provider: &OAuthProvider,
279 code: &str,
280 state: &str,
281) -> Result<U, AppError> {
282 let stored_state = session
283 .remove::<String>(&state_session_key(provider_name))
284 .await
285 .map_err(|source| AppError::Internal(Box::new(source)))?;
286 let state_matches = stored_state
287 .as_deref()
288 .is_some_and(|stored| constant_time_eq(stored, state));
289 if !state_matches {
290 return Err(invalid_state());
291 }
292
293 let client = reqwest::Client::new();
294
295 let mut token_request = client
296 .post(provider.token_url)
297 .header("Accept", "application/json")
298 .form(&[
299 ("code", code),
300 ("client_id", &provider.client_id),
301 ("client_secret", &provider.client_secret),
302 ("redirect_uri", &provider.redirect_url),
303 ("grant_type", "authorization_code"),
304 ]);
305 for (name, value) in provider.extra_headers {
306 token_request = token_request.header(*name, *value);
307 }
308 let token_response: TokenResponse = token_request
309 .send()
310 .await
311 .map_err(|source| AppError::Internal(Box::new(source)))?
312 .error_for_status()
313 .map_err(|source| AppError::Internal(Box::new(source)))?
314 .json()
315 .await
316 .map_err(|source| AppError::Internal(Box::new(source)))?;
317
318 let mut userinfo_request = client
319 .get(provider.userinfo_url)
320 .bearer_auth(&token_response.access_token);
321 for (name, value) in provider.extra_headers {
322 userinfo_request = userinfo_request.header(*name, *value);
323 }
324 let userinfo: serde_json::Value = userinfo_request
325 .send()
326 .await
327 .map_err(|source| AppError::Internal(Box::new(source)))?
328 .error_for_status()
329 .map_err(|source| AppError::Internal(Box::new(source)))?
330 .json()
331 .await
332 .map_err(|source| AppError::Internal(Box::new(source)))?;
333
334 let provider_user = (provider.map_user)(&userinfo).ok_or_else(|| {
335 AppError::Internal(Box::new(std::io::Error::other(format!(
336 "{provider_name}'s userinfo response was missing an expected field"
337 ))))
338 })?;
339
340 U::find_or_create_from_provider(provider_name, &provider_user).await
341}
342
343#[cfg(test)]
344mod tests {
345 use super::*;
346 use axum::routing::{get, post};
347 use axum::Json;
348 use std::sync::atomic::{AtomicUsize, Ordering};
349 use std::sync::Arc;
350 // Pure test scaffolding for constructing a bare `Session` - not an
351 // app-level store, same reasoning `larust_auth::guard`'s own test
352 // module doc comment gives for the identical import.
353 use tower_sessions::MemoryStore;
354
355 #[derive(Debug, Clone)]
356 struct TestUser {
357 id: i64,
358 provider_user_id: String,
359 }
360
361 impl Authenticatable for TestUser {
362 fn auth_id(&self) -> i64 {
363 self.id
364 }
365
366 async fn find_for_auth(_id: i64) -> Result<Option<Self>, AppError> {
367 unreachable!("not exercised by these tests")
368 }
369 }
370
371 impl SocialiteUser for TestUser {
372 async fn find_or_create_from_provider(
373 _provider: &str,
374 user: &ProviderUser,
375 ) -> Result<Self, AppError> {
376 Ok(TestUser {
377 id: 42,
378 provider_user_id: user.provider_user_id.clone(),
379 })
380 }
381 }
382
383 fn new_session() -> Session {
384 Session::new(None, Arc::new(MemoryStore::default()), None)
385 }
386
387 #[derive(Clone, Default)]
388 struct Hits {
389 token: Arc<AtomicUsize>,
390 userinfo: Arc<AtomicUsize>,
391 }
392
393 /// A real, locally-bound server standing in for an OAuth provider -
394 /// `reqwest` makes real HTTP requests against it, so this exercises
395 /// the actual exchange logic, just not against the real internet
396 /// (unavailable in this environment - no real registered OAuth app
397 /// exists to test against).
398 async fn start_good_mock_provider() -> (String, Hits) {
399 let hits = Hits::default();
400 let app = axum::Router::new()
401 .route(
402 "/token",
403 post({
404 let hits = hits.clone();
405 move || {
406 let hits = hits.clone();
407 async move {
408 hits.token.fetch_add(1, Ordering::SeqCst);
409 Json(serde_json::json!({ "access_token": "mock-access-token" }))
410 }
411 }
412 }),
413 )
414 .route(
415 "/userinfo",
416 get({
417 let hits = hits.clone();
418 move || {
419 let hits = hits.clone();
420 async move {
421 hits.userinfo.fetch_add(1, Ordering::SeqCst);
422 Json(serde_json::json!({
423 "id": 999,
424 "email": "octocat@example.test",
425 "name": "The Octocat",
426 }))
427 }
428 }
429 }),
430 );
431 let base_url = spawn(app).await;
432 (base_url, hits)
433 }
434
435 /// A provider whose token endpoint always fails - for the "broken
436 /// response surfaces as `Err`, not a panic" scenario.
437 async fn start_broken_token_mock_provider() -> String {
438 let app = axum::Router::new().route(
439 "/token",
440 post(|| async { axum::http::StatusCode::INTERNAL_SERVER_ERROR }),
441 );
442 spawn(app).await
443 }
444
445 async fn spawn(app: axum::Router) -> String {
446 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
447 let addr = listener.local_addr().unwrap();
448 tokio::spawn(async move {
449 axum::serve(listener, app).await.unwrap();
450 });
451 format!("http://{addr}")
452 }
453
454 fn mock_provider(base_url: &str) -> OAuthProvider {
455 OAuthProvider {
456 client_id: "test-client-id".to_string(),
457 client_secret: "test-client-secret".to_string(),
458 redirect_url: "http://localhost/callback".to_string(),
459 authorize_url: Box::leak(format!("{base_url}/authorize").into_boxed_str()),
460 token_url: Box::leak(format!("{base_url}/token").into_boxed_str()),
461 userinfo_url: Box::leak(format!("{base_url}/userinfo").into_boxed_str()),
462 scope: "read",
463 map_user: |json| {
464 Some(ProviderUser {
465 provider_user_id: json.get("id")?.as_i64()?.to_string(),
466 email: json
467 .get("email")
468 .and_then(|v| v.as_str())
469 .map(str::to_string),
470 name: json
471 .get("name")
472 .and_then(|v| v.as_str())
473 .map(str::to_string),
474 })
475 },
476 extra_headers: &[],
477 }
478 }
479
480 #[tokio::test]
481 async fn oauth_flow_behaves_correctly_across_every_scenario() {
482 let (good_base, hits) = start_good_mock_provider().await;
483 let good_provider = mock_provider(&good_base);
484 let session = new_session();
485
486 // Happy path: redirect_url stores a state and the URL carries it;
487 // a matching callback exchanges the code, fetches userinfo, and
488 // resolves through find_or_create_from_provider.
489 let url = redirect_url(&session, "good", &good_provider)
490 .await
491 .unwrap();
492 assert!(url.starts_with(&format!("{good_base}/authorize?")));
493 let first_state: String = session
494 .get(&state_session_key("good"))
495 .await
496 .unwrap()
497 .unwrap();
498 assert!(url.contains(&format!("state={first_state}")));
499
500 let user = user_from_callback::<TestUser>(
501 &session,
502 "good",
503 &good_provider,
504 "any-code",
505 &first_state,
506 )
507 .await
508 .unwrap();
509 assert_eq!(user.provider_user_id, "999");
510 assert_eq!(hits.token.load(Ordering::SeqCst), 1);
511 assert_eq!(hits.userinfo.load(Ordering::SeqCst), 1);
512
513 // A missing state (nothing was ever stored for this provider name)
514 // is rejected before either mock endpoint is touched.
515 let err = user_from_callback::<TestUser>(
516 &session,
517 "never-redirected",
518 &good_provider,
519 "any-code",
520 "whatever",
521 )
522 .await
523 .unwrap_err();
524 assert!(matches!(
525 err,
526 AppError::Http { status, .. } if status == reqwest::StatusCode::UNAUTHORIZED
527 ));
528 assert_eq!(hits.token.load(Ordering::SeqCst), 1);
529 assert_eq!(hits.userinfo.load(Ordering::SeqCst), 1);
530
531 // A fresh redirect, then a *wrong* state - rejected, and the
532 // stored state is consumed (removed) regardless of the mismatch.
533 redirect_url(&session, "good", &good_provider)
534 .await
535 .unwrap();
536 let second_state: String = session
537 .get(&state_session_key("good"))
538 .await
539 .unwrap()
540 .unwrap();
541 let err = user_from_callback::<TestUser>(
542 &session,
543 "good",
544 &good_provider,
545 "any-code",
546 "totally-wrong",
547 )
548 .await
549 .unwrap_err();
550 assert!(matches!(err, AppError::Http { .. }));
551 assert_eq!(hits.token.load(Ordering::SeqCst), 1);
552 assert_eq!(hits.userinfo.load(Ordering::SeqCst), 1);
553
554 // The state is single-use: even the *correct* second value now
555 // fails, since the attempt above already consumed it.
556 let err = user_from_callback::<TestUser>(
557 &session,
558 "good",
559 &good_provider,
560 "any-code",
561 &second_state,
562 )
563 .await
564 .unwrap_err();
565 assert!(matches!(err, AppError::Http { .. }));
566
567 // A broken token endpoint surfaces as `Err`, not a panic.
568 let broken_base = start_broken_token_mock_provider().await;
569 let broken_provider = mock_provider(&broken_base);
570 redirect_url(&session, "broken", &broken_provider)
571 .await
572 .unwrap();
573 let broken_state: String = session
574 .get(&state_session_key("broken"))
575 .await
576 .unwrap()
577 .unwrap();
578 let result = user_from_callback::<TestUser>(
579 &session,
580 "broken",
581 &broken_provider,
582 "any-code",
583 &broken_state,
584 )
585 .await;
586 assert!(result.is_err());
587 }
588
589 #[test]
590 fn github_and_google_require_their_env_vars() {
591 for key in [
592 "GITHUB_CLIENT_ID",
593 "GITHUB_CLIENT_SECRET",
594 "GITHUB_REDIRECT_URL",
595 "GOOGLE_CLIENT_ID",
596 "GOOGLE_CLIENT_SECRET",
597 "GOOGLE_REDIRECT_URL",
598 ] {
599 std::env::remove_var(key);
600 }
601 assert!(matches!(github(), Err(AppError::Config(_))));
602 assert!(matches!(google(), Err(AppError::Config(_))));
603 }
604}