renox-oauth 1.2.0

Social login (Sign in with Google, GitHub, …) linked to the users of a Renox app.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! What a provider is: where users approve, how a code becomes a token, and
//! how the token becomes a [`Profile`]. Google and GitHub come with the
//! crate; another provider is one small impl of [`Provider`]:
//!
//! ```
//! use renox::http::Http;
//! use renox::prelude::*;
//! use renox_oauth::{BoxFuture, Credentials, Profile, Provider, Token};
//!
//! /// GitLab: users approve on gitlab.com, the profile comes from its API.
//! struct GitLab {
//!     credentials: Credentials,
//! }
//!
//! impl Provider for GitLab {
//!     fn name(&self) -> &str {
//!         "gitlab"
//!     }
//!     fn label(&self) -> &str {
//!         "GitLab"
//!     }
//!     fn credentials(&self) -> &Credentials {
//!         &self.credentials
//!     }
//!     fn authorize_endpoint(&self) -> &str {
//!         "https://gitlab.com/oauth/authorize"
//!     }
//!     fn token_endpoint(&self) -> &str {
//!         "https://gitlab.com/oauth/token"
//!     }
//!     fn scopes(&self) -> &[&str] {
//!         &["read_user"]
//!     }
//!     fn profile<'a>(&'a self, http: &'a Http, token: &'a Token) -> BoxFuture<'a, Result<Profile>> {
//!         Box::pin(async move {
//!             #[derive(serde::Deserialize)]
//!             struct Me {
//!                 id: i64,
//!                 name: Option<String>,
//!                 email: Option<String>,
//!                 confirmed_at: Option<String>,
//!                 avatar_url: Option<String>,
//!             }
//!             let me: Me = http
//!                 .get("https://gitlab.com/api/v4/user")
//!                 .bearer(&token.access_token)
//!                 .send()
//!                 .await?
//!                 .error_for_status()?
//!                 .json()?;
//!             let mut profile = Profile::new(me.id.to_string());
//!             if let Some(email) = me.email {
//!                 profile = profile.email(email, me.confirmed_at.is_some());
//!             }
//!             Ok(profile.name(me.name).avatar(me.avatar_url))
//!         })
//!     }
//! }
//!
//! # let _ =
//! renox_oauth::OAuth::new().provider(GitLab {
//!     credentials: Credentials::from_config("GITLAB"), // GITLAB_CLIENT_ID, GITLAB_CLIENT_SECRET
//! })
//! # ;
//! ```

use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;

use renox::Config;
use renox::http::Http;
use renox::prelude::*;
use serde::{Deserialize, Serialize};

/// A boxed future that is `Send`, what [`Provider`]'s methods return (so the
/// trait works behind `dyn`, and handlers stay `Send`).
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// How long a call to a provider may take.
pub(crate) const TIMEOUT: Duration = Duration::from_secs(10);

/// A sign-in provider (Google, GitHub, …): the OAuth 2.0 authorization code
/// flow with PKCE. The module builds the authorization URL (with `state`
/// and an S256 code challenge) from [`Provider::authorize_endpoint`],
/// [`Provider::scopes`] and [`Provider::authorize_params`]; [`Provider::exchange`]
/// turns the code into a [`Token`] (the standard request by default) and
/// [`Provider::profile`] reads who the user is.
pub trait Provider: Send + Sync + 'static {
    /// The provider's name in URLs (`/auth/google/redirect`) and in the
    /// `oauth_accounts` table: short, lower case, never changed once users
    /// linked accounts.
    fn name(&self) -> &str;

    /// Its name for people, on buttons: `Google`.
    fn label(&self) -> &str;

    /// The app's client id and secret, from the provider's console.
    fn credentials(&self) -> &Credentials;

    /// Where the browser goes to approve the sign-in.
    fn authorize_endpoint(&self) -> &str;

    /// Where the code is exchanged for a token.
    fn token_endpoint(&self) -> &str;

    /// The scopes asked for, e.g. `openid email profile`.
    fn scopes(&self) -> &[&str];

    /// Other parameters for the authorization URL, e.g. Google's `prompt`.
    fn authorize_params(&self) -> Vec<(&str, &str)> {
        Vec::new()
    }

    /// Exchanges the authorization code for a token. The default sends the
    /// standard request ([`exchange_code`]); override it for a provider that
    /// does something else.
    fn exchange<'a>(
        &'a self,
        http: &'a Http,
        request: TokenRequest,
    ) -> BoxFuture<'a, Result<Token>> {
        Box::pin(exchange_code(http, self.token_endpoint(), request))
    }

    /// A copy of this provider with the settings it reads from the
    /// configuration besides the credentials (Microsoft's `MICROSOFT_TENANT`),
    /// resolved. The module calls it for each request; the default, `None`,
    /// means there is nothing to resolve.
    fn with_config(&self, _config: &Config) -> Option<Arc<dyn Provider>> {
        None
    }

    /// Who the token belongs to. Return a [`Refused`] error when the account
    /// is not one this app accepts (another tenant, another domain): the
    /// visitor is told so, and `OAuthRefused` is announced.
    fn profile<'a>(&'a self, http: &'a Http, token: &'a Token) -> BoxFuture<'a, Result<Profile>>;
}

/// Why a provider account was turned away although the provider vouched for
/// it: it belongs to another organisation than the app accepts. Return it
/// from [`Provider::profile`] (`Err(Refused::new(..).into())`); the module
/// shows `message` to the visitor, announces
/// [`OAuthRefused`](crate::OAuthRefused) with `reason`, and logs nobody in.
///
/// ```
/// use renox_oauth::provider::Refused;
///
/// let refused = Refused::new("tenant", "That account belongs to another organisation.");
/// assert_eq!(refused.reason(), "tenant");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refused {
    reason: String,
    message: String,
}

impl Refused {
    /// A refusal: `reason` is a short code for the activity log
    /// (`tenant`, `domain`), `message` is shown to the visitor.
    pub fn new(reason: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            reason: reason.into(),
            message: message.into(),
        }
    }

    /// The short code.
    pub fn reason(&self) -> &str {
        &self.reason
    }

    /// What the visitor is told.
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for Refused {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "sign-in refused ({}): {}", self.reason, self.message)
    }
}

impl std::error::Error for Refused {}

/// The app's client id and secret at a provider: given, or read from the
/// configuration when a request needs them (`config.var`, i.e. `.env` or the
/// environment). A provider without them is off: no button, and its routes
/// answer 404.
#[derive(Clone)]
pub struct Credentials(Source);

#[derive(Clone)]
enum Source {
    Given { id: String, secret: String },
    Config(String),
}

impl Credentials {
    /// These credentials.
    pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
        Self(Source::Given {
            id: client_id.into(),
            secret: client_secret.into(),
        })
    }

    /// `<PREFIX>_CLIENT_ID` and `<PREFIX>_CLIENT_SECRET` from the
    /// configuration, e.g. `Credentials::from_config("GOOGLE")`.
    pub fn from_config(prefix: impl Into<String>) -> Self {
        Self(Source::Config(prefix.into()))
    }

    /// The client id and secret, or `None` when one is missing.
    pub fn resolve(&self, config: &Config) -> Option<(String, String)> {
        match &self.0 {
            Source::Given { id, secret } if !id.is_empty() && !secret.is_empty() => {
                Some((id.clone(), secret.clone()))
            }
            Source::Given { .. } => None,
            Source::Config(prefix) => Some((
                config.var(&format!("{prefix}_CLIENT_ID"))?,
                config.var(&format!("{prefix}_CLIENT_SECRET"))?,
            )),
        }
    }
}

impl fmt::Debug for Credentials {
    /// Never prints the secret.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.0 {
            Source::Given { id, .. } => write!(f, "Credentials({id}, secret hidden)"),
            Source::Config(prefix) => write!(f, "Credentials::from_config({prefix:?})"),
        }
    }
}

/// What [`Provider::exchange`] sends: the code from the callback, and what
/// proves this app asked for it.
#[non_exhaustive]
pub struct TokenRequest {
    /// The authorization code from the callback.
    pub code: String,
    /// The callback URL, the same as in the authorization URL.
    pub redirect_uri: String,
    /// The PKCE code verifier, whose challenge went in the authorization URL.
    pub code_verifier: String,
    /// The app's client id.
    pub client_id: String,
    /// The app's client secret.
    pub client_secret: String,
}

impl fmt::Debug for TokenRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TokenRequest")
            .field("redirect_uri", &self.redirect_uri)
            .field("client_id", &self.client_id)
            .finish_non_exhaustive()
    }
}

/// The token a provider answered with. Renox uses it once, to read the
/// profile, and doesn't store it.
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct Token {
    /// What API calls send as `Authorization: Bearer …`.
    pub access_token: String,
    /// Usually `Bearer`.
    #[serde(default)]
    pub token_type: Option<String>,
    /// For new access tokens later, when the provider gives one.
    #[serde(default)]
    pub refresh_token: Option<String>,
    /// Seconds the access token lasts.
    #[serde(default)]
    pub expires_in: Option<u64>,
    /// The scopes granted (some providers grant fewer than asked).
    #[serde(default)]
    pub scope: Option<String>,
    /// OpenID Connect's ID token, when the provider sends one.
    #[serde(default)]
    pub id_token: Option<String>,
}

impl Token {
    /// A token with only its access token, e.g. from an overridden
    /// [`Provider::exchange`].
    pub fn new(access_token: impl Into<String>) -> Self {
        Self {
            access_token: access_token.into(),
            token_type: None,
            refresh_token: None,
            expires_in: None,
            scope: None,
            id_token: None,
        }
    }
}

impl fmt::Debug for Token {
    /// Never prints the tokens themselves.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Token")
            .field("token_type", &self.token_type)
            .field("expires_in", &self.expires_in)
            .field("scope", &self.scope)
            .finish_non_exhaustive()
    }
}

/// Who signed in, as every provider describes them.
#[derive(Debug, Clone, Default, Serialize)]
#[non_exhaustive]
pub struct Profile {
    /// Their id at the provider, which never changes (Google's `sub`).
    pub id: String,
    /// Their email address, if the provider shared one.
    pub email: Option<String>,
    /// Whether the provider checked that they own `email`. Accounts are
    /// only ever linked or made by a verified address.
    pub email_verified: bool,
    /// Their name.
    pub name: Option<String>,
    /// A URL of their picture.
    pub avatar: Option<String>,
}

impl Profile {
    /// A profile with this id and nothing else.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            ..Self::default()
        }
    }

    /// With an email address, `verified` when the provider checked it.
    pub fn email(mut self, email: impl Into<String>, verified: bool) -> Self {
        self.email = Some(email.into());
        self.email_verified = verified;
        self
    }

    /// With a name (an empty one counts as none).
    pub fn name(mut self, name: Option<String>) -> Self {
        self.name = name.filter(|name| !name.trim().is_empty());
        self
    }

    /// With a picture's URL.
    pub fn avatar(mut self, avatar: Option<String>) -> Self {
        self.avatar = avatar.filter(|url| !url.is_empty());
        self
    }

    /// The email address, when the provider verified it.
    pub fn verified_email(&self) -> Option<&str> {
        self.email
            .as_deref()
            .filter(|email| self.email_verified && !email.is_empty())
    }
}

/// The standard token request (RFC 6749 §4.1.3, with RFC 7636's
/// `code_verifier`): a form POST to `endpoint` asking for JSON. A 2xx
/// answer without an `access_token` (GitHub answers errors with 200) is an
/// error too.
pub async fn exchange_code(http: &Http, endpoint: &str, request: TokenRequest) -> Result<Token> {
    let form = [
        ("grant_type", "authorization_code"),
        ("code", request.code.as_str()),
        ("redirect_uri", request.redirect_uri.as_str()),
        ("client_id", request.client_id.as_str()),
        ("client_secret", request.client_secret.as_str()),
        ("code_verifier", request.code_verifier.as_str()),
    ];
    let response = http
        .post(endpoint)
        .header("accept", "application/json")
        .form(&form)
        .timeout(TIMEOUT)
        .send()
        .await?;
    let body: renox::serde_json::Value = response.json().unwrap_or_default();
    if !response.ok() || body.get("access_token").is_none() {
        let error = body
            .get("error")
            .and_then(|e| e.as_str())
            .unwrap_or("no access token");
        return Err(renox::anyhow::anyhow!(
            "{endpoint}: the code wasn't exchanged ({}: {error})",
            response.status()
        )
        .into());
    }
    Ok(renox::serde_json::from_value(body)?)
}

/// A GET to a provider's API with the token, read as JSON.
pub(crate) async fn get_json<T: serde::de::DeserializeOwned>(
    http: &Http,
    url: &str,
    token: &Token,
    accept: &str,
) -> Result<T> {
    http.get(url)
        .bearer(&token.access_token)
        .header("accept", accept)
        .timeout(TIMEOUT)
        .send()
        .await?
        .error_for_status()?
        .json()
}

#[cfg(test)]
mod debug_tests {
    use super::*;

    /// Secrets, codes and tokens never show in `Debug` (logs); credentials
    /// given in code need both halves.
    #[test]
    fn debug_hides_secrets_codes_and_tokens() {
        let given = Credentials::new("client-1", "very-secret");
        assert_eq!(format!("{given:?}"), "Credentials(client-1, secret hidden)");
        assert_eq!(
            given.resolve(&Config::default()),
            Some(("client-1".to_owned(), "very-secret".to_owned()))
        );
        assert_eq!(
            Credentials::new("client-1", "").resolve(&Config::default()),
            None
        );
        assert_eq!(
            format!("{:?}", Credentials::from_config("GOOGLE")),
            "Credentials::from_config(\"GOOGLE\")"
        );

        let request = TokenRequest {
            code: "the-code".into(),
            redirect_uri: "https://app.test/auth/google/callback".into(),
            code_verifier: "the-verifier".into(),
            client_id: "client-1".into(),
            client_secret: "very-secret".into(),
        };
        let shown = format!("{request:?}");
        assert!(
            shown.contains("client-1") && shown.contains("/callback"),
            "{shown}"
        );
        for hidden in ["the-code", "the-verifier", "very-secret"] {
            assert!(!shown.contains(hidden), "{shown}");
        }

        let mut token = Token::new("access-123");
        assert_eq!(token.access_token, "access-123");
        assert!(token.refresh_token.is_none() && token.id_token.is_none());
        token.refresh_token = Some("refresh-456".into());
        token.expires_in = Some(3600);
        let shown = format!("{token:?}");
        assert!(shown.contains("3600"), "{shown}");
        assert!(
            !shown.contains("access-123") && !shown.contains("refresh-456"),
            "{shown}"
        );
    }
}