Skip to main content

renox_oauth/
provider.rs

1//! What a provider is: where users approve, how a code becomes a token, and
2//! how the token becomes a [`Profile`]. Google and GitHub come with the
3//! crate; another provider is one small impl of [`Provider`]:
4//!
5//! ```
6//! use renox::http::Http;
7//! use renox::prelude::*;
8//! use renox_oauth::{BoxFuture, Credentials, Profile, Provider, Token};
9//!
10//! /// GitLab: users approve on gitlab.com, the profile comes from its API.
11//! struct GitLab {
12//!     credentials: Credentials,
13//! }
14//!
15//! impl Provider for GitLab {
16//!     fn name(&self) -> &str {
17//!         "gitlab"
18//!     }
19//!     fn label(&self) -> &str {
20//!         "GitLab"
21//!     }
22//!     fn credentials(&self) -> &Credentials {
23//!         &self.credentials
24//!     }
25//!     fn authorize_endpoint(&self) -> &str {
26//!         "https://gitlab.com/oauth/authorize"
27//!     }
28//!     fn token_endpoint(&self) -> &str {
29//!         "https://gitlab.com/oauth/token"
30//!     }
31//!     fn scopes(&self) -> &[&str] {
32//!         &["read_user"]
33//!     }
34//!     fn profile<'a>(&'a self, http: &'a Http, token: &'a Token) -> BoxFuture<'a, Result<Profile>> {
35//!         Box::pin(async move {
36//!             #[derive(serde::Deserialize)]
37//!             struct Me {
38//!                 id: i64,
39//!                 name: Option<String>,
40//!                 email: Option<String>,
41//!                 confirmed_at: Option<String>,
42//!                 avatar_url: Option<String>,
43//!             }
44//!             let me: Me = http
45//!                 .get("https://gitlab.com/api/v4/user")
46//!                 .bearer(&token.access_token)
47//!                 .send()
48//!                 .await?
49//!                 .error_for_status()?
50//!                 .json()?;
51//!             let mut profile = Profile::new(me.id.to_string());
52//!             if let Some(email) = me.email {
53//!                 profile = profile.email(email, me.confirmed_at.is_some());
54//!             }
55//!             Ok(profile.name(me.name).avatar(me.avatar_url))
56//!         })
57//!     }
58//! }
59//!
60//! # let _ =
61//! renox_oauth::OAuth::new().provider(GitLab {
62//!     credentials: Credentials::from_config("GITLAB"), // GITLAB_CLIENT_ID, GITLAB_CLIENT_SECRET
63//! })
64//! # ;
65//! ```
66
67use std::fmt;
68use std::future::Future;
69use std::pin::Pin;
70use std::sync::Arc;
71use std::time::Duration;
72
73use renox::Config;
74use renox::http::Http;
75use renox::prelude::*;
76use serde::{Deserialize, Serialize};
77
78/// A boxed future that is `Send`, what [`Provider`]'s methods return (so the
79/// trait works behind `dyn`, and handlers stay `Send`).
80pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
81
82/// How long a call to a provider may take.
83pub(crate) const TIMEOUT: Duration = Duration::from_secs(10);
84
85/// A sign-in provider (Google, GitHub, …): the OAuth 2.0 authorization code
86/// flow with PKCE. The module builds the authorization URL (with `state`
87/// and an S256 code challenge) from [`Provider::authorize_endpoint`],
88/// [`Provider::scopes`] and [`Provider::authorize_params`]; [`Provider::exchange`]
89/// turns the code into a [`Token`] (the standard request by default) and
90/// [`Provider::profile`] reads who the user is.
91pub trait Provider: Send + Sync + 'static {
92    /// The provider's name in URLs (`/auth/google/redirect`) and in the
93    /// `oauth_accounts` table: short, lower case, never changed once users
94    /// linked accounts.
95    fn name(&self) -> &str;
96
97    /// Its name for people, on buttons: `Google`.
98    fn label(&self) -> &str;
99
100    /// The app's client id and secret, from the provider's console.
101    fn credentials(&self) -> &Credentials;
102
103    /// Where the browser goes to approve the sign-in.
104    fn authorize_endpoint(&self) -> &str;
105
106    /// Where the code is exchanged for a token.
107    fn token_endpoint(&self) -> &str;
108
109    /// The scopes asked for, e.g. `openid email profile`.
110    fn scopes(&self) -> &[&str];
111
112    /// Other parameters for the authorization URL, e.g. Google's `prompt`.
113    fn authorize_params(&self) -> Vec<(&str, &str)> {
114        Vec::new()
115    }
116
117    /// Exchanges the authorization code for a token. The default sends the
118    /// standard request ([`exchange_code`]); override it for a provider that
119    /// does something else.
120    fn exchange<'a>(
121        &'a self,
122        http: &'a Http,
123        request: TokenRequest,
124    ) -> BoxFuture<'a, Result<Token>> {
125        Box::pin(exchange_code(http, self.token_endpoint(), request))
126    }
127
128    /// A copy of this provider with the settings it reads from the
129    /// configuration besides the credentials (Microsoft's `MICROSOFT_TENANT`),
130    /// resolved. The module calls it for each request; the default, `None`,
131    /// means there is nothing to resolve.
132    fn with_config(&self, _config: &Config) -> Option<Arc<dyn Provider>> {
133        None
134    }
135
136    /// Who the token belongs to. Return a [`Refused`] error when the account
137    /// is not one this app accepts (another tenant, another domain): the
138    /// visitor is told so, and `OAuthRefused` is announced.
139    fn profile<'a>(&'a self, http: &'a Http, token: &'a Token) -> BoxFuture<'a, Result<Profile>>;
140}
141
142/// Why a provider account was turned away although the provider vouched for
143/// it: it belongs to another organisation than the app accepts. Return it
144/// from [`Provider::profile`] (`Err(Refused::new(..).into())`); the module
145/// shows `message` to the visitor, announces
146/// [`OAuthRefused`](crate::OAuthRefused) with `reason`, and logs nobody in.
147///
148/// ```
149/// use renox_oauth::provider::Refused;
150///
151/// let refused = Refused::new("tenant", "That account belongs to another organisation.");
152/// assert_eq!(refused.reason(), "tenant");
153/// ```
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct Refused {
156    reason: String,
157    message: String,
158}
159
160impl Refused {
161    /// A refusal: `reason` is a short code for the activity log
162    /// (`tenant`, `domain`), `message` is shown to the visitor.
163    pub fn new(reason: impl Into<String>, message: impl Into<String>) -> Self {
164        Self {
165            reason: reason.into(),
166            message: message.into(),
167        }
168    }
169
170    /// The short code.
171    pub fn reason(&self) -> &str {
172        &self.reason
173    }
174
175    /// What the visitor is told.
176    pub fn message(&self) -> &str {
177        &self.message
178    }
179}
180
181impl fmt::Display for Refused {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        write!(f, "sign-in refused ({}): {}", self.reason, self.message)
184    }
185}
186
187impl std::error::Error for Refused {}
188
189/// The app's client id and secret at a provider: given, or read from the
190/// configuration when a request needs them (`config.var`, i.e. `.env` or the
191/// environment). A provider without them is off: no button, and its routes
192/// answer 404.
193#[derive(Clone)]
194pub struct Credentials(Source);
195
196#[derive(Clone)]
197enum Source {
198    Given { id: String, secret: String },
199    Config(String),
200}
201
202impl Credentials {
203    /// These credentials.
204    pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
205        Self(Source::Given {
206            id: client_id.into(),
207            secret: client_secret.into(),
208        })
209    }
210
211    /// `<PREFIX>_CLIENT_ID` and `<PREFIX>_CLIENT_SECRET` from the
212    /// configuration, e.g. `Credentials::from_config("GOOGLE")`.
213    pub fn from_config(prefix: impl Into<String>) -> Self {
214        Self(Source::Config(prefix.into()))
215    }
216
217    /// The client id and secret, or `None` when one is missing.
218    pub fn resolve(&self, config: &Config) -> Option<(String, String)> {
219        match &self.0 {
220            Source::Given { id, secret } if !id.is_empty() && !secret.is_empty() => {
221                Some((id.clone(), secret.clone()))
222            }
223            Source::Given { .. } => None,
224            Source::Config(prefix) => Some((
225                config.var(&format!("{prefix}_CLIENT_ID"))?,
226                config.var(&format!("{prefix}_CLIENT_SECRET"))?,
227            )),
228        }
229    }
230}
231
232impl fmt::Debug for Credentials {
233    /// Never prints the secret.
234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235        match &self.0 {
236            Source::Given { id, .. } => write!(f, "Credentials({id}, secret hidden)"),
237            Source::Config(prefix) => write!(f, "Credentials::from_config({prefix:?})"),
238        }
239    }
240}
241
242/// What [`Provider::exchange`] sends: the code from the callback, and what
243/// proves this app asked for it.
244#[non_exhaustive]
245pub struct TokenRequest {
246    /// The authorization code from the callback.
247    pub code: String,
248    /// The callback URL, the same as in the authorization URL.
249    pub redirect_uri: String,
250    /// The PKCE code verifier, whose challenge went in the authorization URL.
251    pub code_verifier: String,
252    /// The app's client id.
253    pub client_id: String,
254    /// The app's client secret.
255    pub client_secret: String,
256}
257
258impl fmt::Debug for TokenRequest {
259    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260        f.debug_struct("TokenRequest")
261            .field("redirect_uri", &self.redirect_uri)
262            .field("client_id", &self.client_id)
263            .finish_non_exhaustive()
264    }
265}
266
267/// The token a provider answered with. Renox uses it once, to read the
268/// profile, and doesn't store it.
269#[derive(Clone, Deserialize)]
270#[non_exhaustive]
271pub struct Token {
272    /// What API calls send as `Authorization: Bearer …`.
273    pub access_token: String,
274    /// Usually `Bearer`.
275    #[serde(default)]
276    pub token_type: Option<String>,
277    /// For new access tokens later, when the provider gives one.
278    #[serde(default)]
279    pub refresh_token: Option<String>,
280    /// Seconds the access token lasts.
281    #[serde(default)]
282    pub expires_in: Option<u64>,
283    /// The scopes granted (some providers grant fewer than asked).
284    #[serde(default)]
285    pub scope: Option<String>,
286    /// OpenID Connect's ID token, when the provider sends one.
287    #[serde(default)]
288    pub id_token: Option<String>,
289}
290
291impl Token {
292    /// A token with only its access token, e.g. from an overridden
293    /// [`Provider::exchange`].
294    pub fn new(access_token: impl Into<String>) -> Self {
295        Self {
296            access_token: access_token.into(),
297            token_type: None,
298            refresh_token: None,
299            expires_in: None,
300            scope: None,
301            id_token: None,
302        }
303    }
304}
305
306impl fmt::Debug for Token {
307    /// Never prints the tokens themselves.
308    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309        f.debug_struct("Token")
310            .field("token_type", &self.token_type)
311            .field("expires_in", &self.expires_in)
312            .field("scope", &self.scope)
313            .finish_non_exhaustive()
314    }
315}
316
317/// Who signed in, as every provider describes them.
318#[derive(Debug, Clone, Default, Serialize)]
319#[non_exhaustive]
320pub struct Profile {
321    /// Their id at the provider, which never changes (Google's `sub`).
322    pub id: String,
323    /// Their email address, if the provider shared one.
324    pub email: Option<String>,
325    /// Whether the provider checked that they own `email`. Accounts are
326    /// only ever linked or made by a verified address.
327    pub email_verified: bool,
328    /// Their name.
329    pub name: Option<String>,
330    /// A URL of their picture.
331    pub avatar: Option<String>,
332}
333
334impl Profile {
335    /// A profile with this id and nothing else.
336    pub fn new(id: impl Into<String>) -> Self {
337        Self {
338            id: id.into(),
339            ..Self::default()
340        }
341    }
342
343    /// With an email address, `verified` when the provider checked it.
344    pub fn email(mut self, email: impl Into<String>, verified: bool) -> Self {
345        self.email = Some(email.into());
346        self.email_verified = verified;
347        self
348    }
349
350    /// With a name (an empty one counts as none).
351    pub fn name(mut self, name: Option<String>) -> Self {
352        self.name = name.filter(|name| !name.trim().is_empty());
353        self
354    }
355
356    /// With a picture's URL.
357    pub fn avatar(mut self, avatar: Option<String>) -> Self {
358        self.avatar = avatar.filter(|url| !url.is_empty());
359        self
360    }
361
362    /// The email address, when the provider verified it.
363    pub fn verified_email(&self) -> Option<&str> {
364        self.email
365            .as_deref()
366            .filter(|email| self.email_verified && !email.is_empty())
367    }
368}
369
370/// The standard token request (RFC 6749 §4.1.3, with RFC 7636's
371/// `code_verifier`): a form POST to `endpoint` asking for JSON. A 2xx
372/// answer without an `access_token` (GitHub answers errors with 200) is an
373/// error too.
374pub async fn exchange_code(http: &Http, endpoint: &str, request: TokenRequest) -> Result<Token> {
375    let form = [
376        ("grant_type", "authorization_code"),
377        ("code", request.code.as_str()),
378        ("redirect_uri", request.redirect_uri.as_str()),
379        ("client_id", request.client_id.as_str()),
380        ("client_secret", request.client_secret.as_str()),
381        ("code_verifier", request.code_verifier.as_str()),
382    ];
383    let response = http
384        .post(endpoint)
385        .header("accept", "application/json")
386        .form(&form)
387        .timeout(TIMEOUT)
388        .send()
389        .await?;
390    let body: renox::serde_json::Value = response.json().unwrap_or_default();
391    if !response.ok() || body.get("access_token").is_none() {
392        let error = body
393            .get("error")
394            .and_then(|e| e.as_str())
395            .unwrap_or("no access token");
396        return Err(renox::anyhow::anyhow!(
397            "{endpoint}: the code wasn't exchanged ({}: {error})",
398            response.status()
399        )
400        .into());
401    }
402    Ok(renox::serde_json::from_value(body)?)
403}
404
405/// A GET to a provider's API with the token, read as JSON.
406pub(crate) async fn get_json<T: serde::de::DeserializeOwned>(
407    http: &Http,
408    url: &str,
409    token: &Token,
410    accept: &str,
411) -> Result<T> {
412    http.get(url)
413        .bearer(&token.access_token)
414        .header("accept", accept)
415        .timeout(TIMEOUT)
416        .send()
417        .await?
418        .error_for_status()?
419        .json()
420}
421
422#[cfg(test)]
423mod debug_tests {
424    use super::*;
425
426    /// Secrets, codes and tokens never show in `Debug` (logs); credentials
427    /// given in code need both halves.
428    #[test]
429    fn debug_hides_secrets_codes_and_tokens() {
430        let given = Credentials::new("client-1", "very-secret");
431        assert_eq!(format!("{given:?}"), "Credentials(client-1, secret hidden)");
432        assert_eq!(
433            given.resolve(&Config::default()),
434            Some(("client-1".to_owned(), "very-secret".to_owned()))
435        );
436        assert_eq!(
437            Credentials::new("client-1", "").resolve(&Config::default()),
438            None
439        );
440        assert_eq!(
441            format!("{:?}", Credentials::from_config("GOOGLE")),
442            "Credentials::from_config(\"GOOGLE\")"
443        );
444
445        let request = TokenRequest {
446            code: "the-code".into(),
447            redirect_uri: "https://app.test/auth/google/callback".into(),
448            code_verifier: "the-verifier".into(),
449            client_id: "client-1".into(),
450            client_secret: "very-secret".into(),
451        };
452        let shown = format!("{request:?}");
453        assert!(
454            shown.contains("client-1") && shown.contains("/callback"),
455            "{shown}"
456        );
457        for hidden in ["the-code", "the-verifier", "very-secret"] {
458            assert!(!shown.contains(hidden), "{shown}");
459        }
460
461        let mut token = Token::new("access-123");
462        assert_eq!(token.access_token, "access-123");
463        assert!(token.refresh_token.is_none() && token.id_token.is_none());
464        token.refresh_token = Some("refresh-456".into());
465        token.expires_in = Some(3600);
466        let shown = format!("{token:?}");
467        assert!(shown.contains("3600"), "{shown}");
468        assert!(
469            !shown.contains("access-123") && !shown.contains("refresh-456"),
470            "{shown}"
471        );
472    }
473}