Skip to main content

djs_rest/
oauth2.rs

1//! [OAuth2](https://docs.discord.com/developers/topics/oauth2) helpers: the client credentials
2//! of an application (D-132) and authorization URLs (D-133).
3//!
4//! The token endpoints themselves are methods of [`Rest`](crate::Rest):
5//! [`exchange_code`](crate::Rest::exchange_code),
6//! [`refresh_access_token`](crate::Rest::refresh_access_token),
7//! [`client_credentials_grant`](crate::Rest::client_credentials_grant) and
8//! [`revoke_token`](crate::Rest::revoke_token).
9//!
10//! # Examples
11//!
12//! The authorization code grant, from the URL a user opens to the user's own client:
13//!
14//! ```no_run
15//! # async fn example(rest: djs_rest::Rest, code: &str) -> Result<(), djs_rest::Error> {
16//! use djs_model::{id::ApplicationId, oauth2::Scope};
17//! use djs_rest::{
18//!     Rest,
19//!     oauth2::{AuthorizeUrl, OAuth2Credentials},
20//! };
21//!
22//! let client_id = ApplicationId::new(157_730_590_492_196_864);
23//! let redirect_uri = "https://example.com/callback";
24//! // 1. Send the user to the authorization page.
25//! let url = AuthorizeUrl::code(client_id, redirect_uri)
26//!     .scopes([Scope::Identify, Scope::Guilds])
27//!     .state("a-random-value-tied-to-the-session")
28//!     .build();
29//! // 2. Discord redirects back with `?code=…&state=…`; exchange the code.
30//! let credentials = OAuth2Credentials::new(client_id, std::env::var("CLIENT_SECRET").unwrap());
31//! let token = rest.exchange_code(&credentials, code, redirect_uri).await?;
32//! // 3. Act for the user.
33//! let user_rest = Rest::builder().bearer_token(token.access_token).build();
34//! let user = user_rest.get_current_user().await?;
35//! # Ok(())
36//! # }
37//! ```
38
39use core::fmt;
40
41use djs_model::{
42    application::IntegrationType,
43    id::{ApplicationId, GuildId},
44    oauth2::Scope,
45    permissions::Permissions,
46};
47
48use crate::route::write_text;
49
50/// The base [authorization URL](https://docs.discord.com/developers/topics/oauth2#shared-resources-oauth2-urls).
51pub const AUTHORIZE_URL: &str = "https://discord.com/oauth2/authorize";
52
53/// An application's client ID and client secret, which authenticate the token endpoints
54/// (D-132).
55///
56/// The secret is never shown in the `Debug` output. Keep it out of source code; load it from
57/// the environment or a secret store.
58///
59/// discord.js counterpart: none (the `client_id` and `client_secret` of a token request).
60///
61/// # Examples
62///
63/// ```
64/// use djs_model::id::ApplicationId;
65/// use djs_rest::oauth2::OAuth2Credentials;
66///
67/// let credentials = OAuth2Credentials::new(ApplicationId::new(1), "client-secret");
68/// assert!(!format!("{credentials:?}").contains("client-secret"));
69/// ```
70#[derive(Clone, PartialEq, Eq)]
71pub struct OAuth2Credentials {
72    client_id: ApplicationId,
73    client_secret: String,
74}
75
76impl OAuth2Credentials {
77    /// The credentials of the application `client_id` (its application ID).
78    ///
79    /// discord.js counterpart: none (the `client_id` and `client_secret` of a token request).
80    #[must_use]
81    pub fn new(client_id: ApplicationId, client_secret: impl Into<String>) -> Self {
82        Self {
83            client_id,
84            client_secret: client_secret.into(),
85        }
86    }
87
88    /// The application's client ID.
89    ///
90    /// discord.js counterpart: the `client_id` of `RESTPostOAuth2AccessTokenURLEncodedData` (discord-api-types).
91    #[must_use]
92    pub const fn client_id(&self) -> ApplicationId {
93        self.client_id
94    }
95}
96
97impl fmt::Debug for OAuth2Credentials {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        f.debug_struct("OAuth2Credentials")
100            .field("client_id", &self.client_id)
101            .field("client_secret", &"<redacted>")
102            .finish()
103    }
104}
105
106/// What kind of token [`revoke_token`](crate::Rest::revoke_token) revokes. Discord revokes
107/// every token of the authorization either way.
108///
109/// discord.js counterpart: the `token_type_hint` of `RESTPostOAuth2TokenRevocationQuery` (discord-api-types).
110#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
111#[non_exhaustive]
112pub enum TokenTypeHint {
113    /// An access token.
114    AccessToken,
115    /// A refresh token.
116    RefreshToken,
117}
118
119impl TokenTypeHint {
120    /// The hint as Discord expects it (`access_token` or `refresh_token`).
121    ///
122    /// discord.js counterpart: the `token_type_hint` of `RESTPostOAuth2TokenRevocationQuery` (discord-api-types).
123    #[must_use]
124    pub const fn as_str(self) -> &'static str {
125        match self {
126            Self::AccessToken => "access_token",
127            Self::RefreshToken => "refresh_token",
128        }
129    }
130}
131
132/// How the authorization page treats a user who already authorized the same scopes.
133///
134/// discord.js counterpart: the `prompt` of `RESTOAuth2AuthorizationQuery` (discord-api-types).
135#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
136#[non_exhaustive]
137pub enum Prompt {
138    /// Ask the user to approve again.
139    Consent,
140    /// Skip the page and redirect at once (not for `bot` and `webhook.incoming`, which always
141    /// ask).
142    None,
143}
144
145impl Prompt {
146    /// The value of the `prompt` parameter.
147    const fn as_str(self) -> &'static str {
148        match self {
149            Self::Consent => "consent",
150            Self::None => "none",
151        }
152    }
153}
154
155/// Builds an [authorization URL](https://docs.discord.com/developers/topics/oauth2#authorization-code-grant)
156/// (`https://discord.com/oauth2/authorize?…`) that adds a bot to a guild or asks a user to
157/// authorize the application (D-133).
158///
159/// discord.js counterpart: `Client#generateInvite` (bot invites only).
160///
161/// # Examples
162///
163/// ```
164/// use djs_model::{
165///     id::{ApplicationId, GuildId},
166///     oauth2::Scope,
167///     permissions::Permissions,
168/// };
169/// use djs_rest::oauth2::AuthorizeUrl;
170///
171/// let invite = AuthorizeUrl::bot(ApplicationId::new(157))
172///     .scopes([Scope::ApplicationsCommands])
173///     .permissions(Permissions::SEND_MESSAGES | Permissions::EMBED_LINKS)
174///     .guild_id(GuildId::new(42))
175///     .disable_guild_select(true);
176/// assert_eq!(
177///     invite.build(),
178///     "https://discord.com/oauth2/authorize?client_id=157&scope=bot%20applications.commands\
179///      &permissions=18432&guild_id=42&disable_guild_select=true"
180/// );
181///
182/// let login = AuthorizeUrl::code(ApplicationId::new(157), "https://example.com/callback")
183///     .scopes([Scope::Identify])
184///     .state("xyz");
185/// assert_eq!(
186///     login.to_string(),
187///     "https://discord.com/oauth2/authorize?response_type=code&client_id=157&scope=identify\
188///      &state=xyz&redirect_uri=https%3A%2F%2Fexample.com%2Fcallback"
189/// );
190/// ```
191#[derive(Clone, Debug, PartialEq, Eq)]
192#[must_use = "an authorization URL builder does nothing until it is built"]
193pub struct AuthorizeUrl {
194    client_id: ApplicationId,
195    code: bool,
196    scopes: Vec<Scope>,
197    state: Option<String>,
198    redirect_uri: Option<String>,
199    prompt: Option<Prompt>,
200    permissions: Option<Permissions>,
201    guild_id: Option<GuildId>,
202    disable_guild_select: bool,
203    integration_type: Option<IntegrationType>,
204}
205
206impl AuthorizeUrl {
207    /// A URL with only the client ID: Discord uses the application's default install settings
208    /// from the Developer Portal (unless scopes, an integration type or a redirect URI are
209    /// added).
210    ///
211    /// discord.js counterpart: `RESTOAuth2AuthorizationQuery` (discord-api-types).
212    pub const fn new(client_id: ApplicationId) -> Self {
213        Self {
214            client_id,
215            code: false,
216            scopes: Vec::new(),
217            state: None,
218            redirect_uri: None,
219            prompt: None,
220            permissions: None,
221            guild_id: None,
222            disable_guild_select: false,
223            integration_type: None,
224        }
225    }
226
227    /// A [bot authorization](https://docs.discord.com/developers/topics/oauth2#bot-authorization-flow)
228    /// URL: the `bot` scope, which adds the bot to a guild the user picks. No redirect is
229    /// needed.
230    ///
231    /// discord.js counterpart: `Client#generateInvite`.
232    pub fn bot(client_id: ApplicationId) -> Self {
233        Self::new(client_id).scopes([Scope::Bot])
234    }
235
236    /// An [authorization code grant](https://docs.discord.com/developers/topics/oauth2#authorization-code-grant)
237    /// URL: Discord redirects the user to `redirect_uri` (one registered for the application)
238    /// with a `code` to exchange with [`exchange_code`](crate::Rest::exchange_code).
239    ///
240    /// discord.js counterpart: `RESTOAuth2AuthorizationQuery` (discord-api-types).
241    pub fn code(client_id: ApplicationId, redirect_uri: impl Into<String>) -> Self {
242        let mut url = Self::new(client_id);
243        url.code = true;
244        url.redirect_uri(redirect_uri)
245    }
246
247    /// Adds scopes to request.
248    ///
249    /// discord.js counterpart: the `scopes` option of `Client#generateInvite`.
250    pub fn scopes(mut self, scopes: impl IntoIterator<Item = Scope>) -> Self {
251        self.scopes.extend(scopes);
252        self
253    }
254
255    /// Sets the [`state`](https://docs.discord.com/developers/topics/oauth2#state-and-security)
256    /// that Discord sends back with the redirect: a value tied to the user's session, which
257    /// protects against cross-site request forgery.
258    ///
259    /// discord.js counterpart: the `state` of `RESTOAuth2AuthorizationQuery` (discord-api-types).
260    pub fn state(mut self, state: impl Into<String>) -> Self {
261        self.state = Some(state.into());
262        self
263    }
264
265    /// Sets where Discord redirects the user after the authorization.
266    ///
267    /// discord.js counterpart: the `redirect_uri` of `RESTOAuth2AuthorizationQuery` (discord-api-types).
268    pub fn redirect_uri(mut self, redirect_uri: impl Into<String>) -> Self {
269        self.redirect_uri = Some(redirect_uri.into());
270        self
271    }
272
273    /// Sets how a user who already authorized the scopes is treated.
274    ///
275    /// discord.js counterpart: the `prompt` of `RESTOAuth2AuthorizationQuery` (discord-api-types).
276    pub const fn prompt(mut self, prompt: Prompt) -> Self {
277        self.prompt = Some(prompt);
278        self
279    }
280
281    /// Sets the permissions requested for the bot (with the `bot` scope).
282    ///
283    /// discord.js counterpart: the `permissions` option of `Client#generateInvite`.
284    pub const fn permissions(mut self, permissions: Permissions) -> Self {
285        self.permissions = Some(permissions);
286        self
287    }
288
289    /// Preselects a guild in the guild picker (with the `bot` scope).
290    ///
291    /// discord.js counterpart: the `guild` option of `Client#generateInvite`.
292    pub const fn guild_id(mut self, guild_id: GuildId) -> Self {
293        self.guild_id = Some(guild_id);
294        self
295    }
296
297    /// Whether the user may not pick another guild than [`guild_id`](Self::guild_id).
298    ///
299    /// discord.js counterpart: the `disableGuildSelect` option of `Client#generateInvite`.
300    pub const fn disable_guild_select(mut self, disable: bool) -> Self {
301        self.disable_guild_select = disable;
302        self
303    }
304
305    /// Sets where the application is installed: in a guild or for the user (only relevant
306    /// with the `applications.commands` scope).
307    ///
308    /// discord.js counterpart: the `integration_type` of `RESTOAuth2AuthorizationQuery` (discord-api-types).
309    pub const fn integration_type(mut self, integration_type: IntegrationType) -> Self {
310        self.integration_type = Some(integration_type);
311        self
312    }
313
314    /// Returns the URL.
315    ///
316    /// discord.js counterpart: `Client#generateInvite`.
317    #[must_use]
318    pub fn build(&self) -> String {
319        self.to_string()
320    }
321}
322
323impl fmt::Display for AuthorizeUrl {
324    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325        let mut url = String::with_capacity(128);
326        url.push_str(AUTHORIZE_URL);
327        url.push('?');
328        if self.code {
329            url.push_str("response_type=code&");
330        }
331        url.push_str("client_id=");
332        // Writing to a `String` cannot fail.
333        let _ = fmt::Write::write_fmt(&mut url, format_args!("{}", self.client_id));
334        if !self.scopes.is_empty() {
335            url.push_str("&scope=");
336            for (index, scope) in self.scopes.iter().enumerate() {
337                if index > 0 {
338                    url.push_str("%20");
339                }
340                write_text(&mut url, scope.as_str());
341            }
342        }
343        if let Some(state) = &self.state {
344            url.push_str("&state=");
345            write_text(&mut url, state);
346        }
347        if let Some(redirect_uri) = &self.redirect_uri {
348            url.push_str("&redirect_uri=");
349            write_text(&mut url, redirect_uri);
350        }
351        if let Some(prompt) = self.prompt {
352            url.push_str("&prompt=");
353            url.push_str(prompt.as_str());
354        }
355        if let Some(permissions) = self.permissions {
356            let _ = fmt::Write::write_fmt(
357                &mut url,
358                format_args!("&permissions={}", permissions.bits()),
359            );
360        }
361        if let Some(guild_id) = self.guild_id {
362            let _ = fmt::Write::write_fmt(&mut url, format_args!("&guild_id={guild_id}"));
363        }
364        if self.disable_guild_select {
365            url.push_str("&disable_guild_select=true");
366        }
367        if let Some(integration_type) = self.integration_type {
368            let _ = fmt::Write::write_fmt(
369                &mut url,
370                format_args!("&integration_type={}", integration_type.value()),
371            );
372        }
373        f.write_str(&url)
374    }
375}
376
377/// An `application/x-www-form-urlencoded` body for the token endpoints, ending with the
378/// client credentials.
379pub(crate) struct TokenForm(String);
380
381impl TokenForm {
382    /// A form with the `grant_type` (or, for revocation, the first field) `name=value`.
383    pub(crate) fn new(name: &str, value: &str) -> Self {
384        let mut form = Self(String::with_capacity(160));
385        form.0.push_str(name);
386        form.0.push('=');
387        write_text(&mut form.0, value);
388        form
389    }
390
391    /// Adds a field.
392    pub(crate) fn field(mut self, name: &str, value: &str) -> Self {
393        self.0.push('&');
394        self.0.push_str(name);
395        self.0.push('=');
396        write_text(&mut self.0, value);
397        self
398    }
399
400    /// Adds the client credentials and returns the body.
401    pub(crate) fn finish(self, credentials: &OAuth2Credentials) -> String {
402        let client_id = credentials.client_id.to_string();
403        self.field("client_id", &client_id)
404            .field("client_secret", &credentials.client_secret)
405            .0
406    }
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412
413    #[test]
414    fn token_form_is_percent_encoded() {
415        let credentials = OAuth2Credentials::new(ApplicationId::new(7), "s3cr&t=");
416        let body = TokenForm::new("grant_type", "authorization_code")
417            .field("code", "a b")
418            .field("redirect_uri", "https://example.com/cb?x=1")
419            .finish(&credentials);
420        assert_eq!(
421            body,
422            "grant_type=authorization_code&code=a%20b\
423             &redirect_uri=https%3A%2F%2Fexample.com%2Fcb%3Fx%3D1&client_id=7\
424             &client_secret=s3cr%26t%3D"
425        );
426    }
427
428    #[test]
429    fn authorize_url_parameters() {
430        let url = AuthorizeUrl::new(ApplicationId::new(1))
431            .scopes([Scope::ApplicationsCommands])
432            .integration_type(IntegrationType::UserInstall)
433            .prompt(Prompt::None);
434        assert_eq!(
435            url.build(),
436            "https://discord.com/oauth2/authorize?client_id=1&scope=applications.commands\
437             &prompt=none&integration_type=1"
438        );
439        assert_eq!(
440            AuthorizeUrl::new(ApplicationId::new(1)).build(),
441            "https://discord.com/oauth2/authorize?client_id=1"
442        );
443    }
444
445    #[test]
446    fn a_bot_invite_with_every_parameter() {
447        let url = AuthorizeUrl::bot(ApplicationId::new(2))
448            .scopes([Scope::ApplicationsCommands])
449            .permissions(Permissions::SEND_MESSAGES | Permissions::VIEW_CHANNEL)
450            .guild_id(GuildId::new(3))
451            .disable_guild_select(true)
452            .state("x y")
453            .prompt(Prompt::Consent);
454        let bits = (Permissions::SEND_MESSAGES | Permissions::VIEW_CHANNEL).bits();
455        assert_eq!(
456            url.to_string(),
457            format!(
458                "https://discord.com/oauth2/authorize?client_id=2\
459                 &scope=bot%20applications.commands&state=x%20y&prompt=consent\
460                 &permissions={bits}&guild_id=3&disable_guild_select=true"
461            )
462        );
463    }
464
465    #[test]
466    fn the_code_grant_asks_for_a_code_and_a_redirect() {
467        let url = AuthorizeUrl::code(ApplicationId::new(4), "https://example.com/cb")
468            .scopes([Scope::Identify])
469            .redirect_uri("https://example.com/other");
470        assert_eq!(
471            url.build(),
472            "https://discord.com/oauth2/authorize?response_type=code&client_id=4\
473             &scope=identify&redirect_uri=https%3A%2F%2Fexample.com%2Fother"
474        );
475    }
476
477    #[test]
478    fn credentials_never_show_the_secret() {
479        let credentials = OAuth2Credentials::new(ApplicationId::new(5), "very-secret");
480        assert_eq!(credentials.client_id(), ApplicationId::new(5));
481        let debug = format!("{credentials:?}");
482        assert!(
483            !debug.contains("very-secret") && debug.contains("<redacted>"),
484            "{debug}"
485        );
486        assert_eq!(TokenTypeHint::AccessToken.as_str(), "access_token");
487        assert_eq!(TokenTypeHint::RefreshToken.as_str(), "refresh_token");
488    }
489}