volga-oauth-core 0.14.1

Shared OAuth 2.1/OIDC foundation types for Volga Web Framework
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
//! OAuth 2.0/2.1 error models
//!
//! See [RFC 6749 Section 5.2](https://www.rfc-editor.org/rfc/rfc6749#section-5.2),
//! [RFC 6750 Section 3.1](https://www.rfc-editor.org/rfc/rfc6750#section-3.1) and
//! [RFC 8707 Section 2](https://www.rfc-editor.org/rfc/rfc8707#section-2).

use http::StatusCode;
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};

/// Machine-readable OAuth 2.0 error code
///
/// Covers the registered codes from RFC 6749 (authorization and token
/// endpoints), RFC 6750 (bearer token usage), RFC 8707 (resource
/// indicators), RFC 7591 (dynamic client registration) and RFC 9449
/// (DPoP). Unregistered extension codes are preserved as
/// [`OAuthErrorCode::Other`].
///
/// Serializes to/from its `snake_case` wire form:
/// ```
/// use volga_oauth_core::OAuthErrorCode;
///
/// let code = OAuthErrorCode::InvalidToken;
/// assert_eq!(code.as_str(), "invalid_token");
/// assert_eq!(OAuthErrorCode::from("invalid_token"), code);
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
#[non_exhaustive]
pub enum OAuthErrorCode {
    /// The request is missing a required parameter, includes an unsupported
    /// parameter value, repeats a parameter or is otherwise malformed
    InvalidRequest,
    /// Client authentication failed
    InvalidClient,
    /// The provided authorization grant or refresh token is invalid, expired or revoked
    InvalidGrant,
    /// The authenticated client is not authorized to use this authorization grant type
    UnauthorizedClient,
    /// The authorization grant type is not supported by the authorization server
    UnsupportedGrantType,
    /// The requested scope is invalid, unknown or malformed
    InvalidScope,
    /// The resource owner or authorization server denied the request
    AccessDenied,
    /// The authorization server does not support obtaining an authorization code using this method
    UnsupportedResponseType,
    /// The server encountered an unexpected condition
    ServerError,
    /// The server is currently unable to handle the request
    TemporarilyUnavailable,
    /// The access token is expired, revoked, malformed or otherwise invalid (RFC 6750)
    InvalidToken,
    /// The request requires higher privileges than provided by the access token (RFC 6750)
    InsufficientScope,
    /// The requested resource is invalid, missing, unknown or malformed (RFC 8707)
    InvalidTarget,
    /// The value of one or more redirection URIs is invalid (RFC 7591)
    InvalidRedirectUri,
    /// The value of one of the client metadata fields is invalid (RFC 7591)
    InvalidClientMetadata,
    /// The software statement presented is invalid (RFC 7591)
    InvalidSoftwareStatement,
    /// The software statement is not approved for use by this
    /// authorization server (RFC 7591)
    UnapprovedSoftwareStatement,
    /// The DPoP proof JWT is missing, malformed or does not match the
    /// request it accompanies (RFC 9449 Section 7.1)
    InvalidDpopProof,
    /// The request must be repeated with a DPoP proof carrying the nonce
    /// the response supplies in its `DPoP-Nonce` header
    /// (RFC 9449 Sections 8.2 and 9)
    UseDpopNonce,
    /// An unregistered extension error code
    Other(String),
}

impl OAuthErrorCode {
    /// Returns the `snake_case` wire form of this error code
    pub fn as_str(&self) -> &str {
        match self {
            OAuthErrorCode::InvalidRequest => "invalid_request",
            OAuthErrorCode::InvalidClient => "invalid_client",
            OAuthErrorCode::InvalidGrant => "invalid_grant",
            OAuthErrorCode::UnauthorizedClient => "unauthorized_client",
            OAuthErrorCode::UnsupportedGrantType => "unsupported_grant_type",
            OAuthErrorCode::InvalidScope => "invalid_scope",
            OAuthErrorCode::AccessDenied => "access_denied",
            OAuthErrorCode::UnsupportedResponseType => "unsupported_response_type",
            OAuthErrorCode::ServerError => "server_error",
            OAuthErrorCode::TemporarilyUnavailable => "temporarily_unavailable",
            OAuthErrorCode::InvalidToken => "invalid_token",
            OAuthErrorCode::InsufficientScope => "insufficient_scope",
            OAuthErrorCode::InvalidTarget => "invalid_target",
            OAuthErrorCode::InvalidRedirectUri => "invalid_redirect_uri",
            OAuthErrorCode::InvalidClientMetadata => "invalid_client_metadata",
            OAuthErrorCode::InvalidSoftwareStatement => "invalid_software_statement",
            OAuthErrorCode::UnapprovedSoftwareStatement => "unapproved_software_statement",
            OAuthErrorCode::InvalidDpopProof => "invalid_dpop_proof",
            OAuthErrorCode::UseDpopNonce => "use_dpop_nonce",
            OAuthErrorCode::Other(code) => code,
        }
    }

    /// Returns the HTTP status code conventionally paired with this error code
    ///
    /// Bearer-usage codes follow RFC 6750 Section 3.1 (`invalid_token` -> 401,
    /// `insufficient_scope` -> 403); `invalid_client` maps to 401 and the
    /// remaining token/authorization endpoint codes to 400 per RFC 6749 Section 5.2,
    /// except `server_error` (500) and `temporarily_unavailable` (503).
    /// Extension codes default to 400.
    ///
    /// The two DPoP codes take that default, which is what the token
    /// endpoint answers with (RFC 9449 Section 5); a *resource* server
    /// returns the same codes with 401 and the challenge in
    /// `WWW-Authenticate` (RFC 9449 Section 7.1), so a status is chosen
    /// there by the endpoint rather than by the code.
    pub fn status(&self) -> StatusCode {
        match self {
            OAuthErrorCode::InvalidToken | OAuthErrorCode::InvalidClient => {
                StatusCode::UNAUTHORIZED
            }
            OAuthErrorCode::InsufficientScope | OAuthErrorCode::AccessDenied => {
                StatusCode::FORBIDDEN
            }
            OAuthErrorCode::ServerError => StatusCode::INTERNAL_SERVER_ERROR,
            OAuthErrorCode::TemporarilyUnavailable => StatusCode::SERVICE_UNAVAILABLE,
            _ => StatusCode::BAD_REQUEST,
        }
    }

    /// Maps a wire-form code to a known variant, if any
    fn from_known(code: &str) -> Option<Self> {
        let known = match code {
            "invalid_request" => OAuthErrorCode::InvalidRequest,
            "invalid_client" => OAuthErrorCode::InvalidClient,
            "invalid_grant" => OAuthErrorCode::InvalidGrant,
            "unauthorized_client" => OAuthErrorCode::UnauthorizedClient,
            "unsupported_grant_type" => OAuthErrorCode::UnsupportedGrantType,
            "invalid_scope" => OAuthErrorCode::InvalidScope,
            "access_denied" => OAuthErrorCode::AccessDenied,
            "unsupported_response_type" => OAuthErrorCode::UnsupportedResponseType,
            "server_error" => OAuthErrorCode::ServerError,
            "temporarily_unavailable" => OAuthErrorCode::TemporarilyUnavailable,
            "invalid_token" => OAuthErrorCode::InvalidToken,
            "insufficient_scope" => OAuthErrorCode::InsufficientScope,
            "invalid_target" => OAuthErrorCode::InvalidTarget,
            "invalid_redirect_uri" => OAuthErrorCode::InvalidRedirectUri,
            "invalid_client_metadata" => OAuthErrorCode::InvalidClientMetadata,
            "invalid_software_statement" => OAuthErrorCode::InvalidSoftwareStatement,
            "unapproved_software_statement" => OAuthErrorCode::UnapprovedSoftwareStatement,
            "invalid_dpop_proof" => OAuthErrorCode::InvalidDpopProof,
            "use_dpop_nonce" => OAuthErrorCode::UseDpopNonce,
            _ => return None,
        };
        Some(known)
    }
}

impl From<&str> for OAuthErrorCode {
    #[inline]
    fn from(code: &str) -> Self {
        Self::from_known(code).unwrap_or_else(|| OAuthErrorCode::Other(code.into()))
    }
}

impl From<String> for OAuthErrorCode {
    #[inline]
    fn from(code: String) -> Self {
        Self::from_known(&code).unwrap_or(OAuthErrorCode::Other(code))
    }
}

impl From<OAuthErrorCode> for String {
    #[inline]
    fn from(code: OAuthErrorCode) -> Self {
        match code {
            OAuthErrorCode::Other(code) => code,
            known => known.as_str().into(),
        }
    }
}

impl Display for OAuthErrorCode {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// OAuth 2.0 error response per RFC 6749 Section 5.2
///
/// Serializes to the standard JSON error body returned by token and other
/// OAuth endpoints:
///
/// ```json
/// { "error": "invalid_grant", "error_description": "..." }
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OAuthError {
    /// Machine-readable error code
    pub error: OAuthErrorCode,

    /// Human-readable ASCII text providing additional information
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_description: Option<String>,

    /// URI of a web page with information about the error
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_uri: Option<String>,
}

impl OAuthError {
    /// Creates a new error with the given code and no description
    pub fn new(error: OAuthErrorCode) -> Self {
        Self {
            error,
            error_description: None,
            error_uri: None,
        }
    }

    /// Sets the human-readable `error_description`
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.error_description = Some(description.into());
        self
    }

    /// Sets the `error_uri` pointing to a web page with details about the error
    pub fn with_error_uri(mut self, uri: impl Into<String>) -> Self {
        self.error_uri = Some(uri.into());
        self
    }
}

impl From<OAuthErrorCode> for OAuthError {
    #[inline]
    fn from(error: OAuthErrorCode) -> Self {
        Self::new(error)
    }
}

impl Display for OAuthError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match &self.error_description {
            Some(desc) => write!(f, "{}: {desc}", self.error),
            None => Display::fmt(&self.error, f),
        }
    }
}

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

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

    #[test]
    fn it_maps_known_codes_to_wire_form() {
        let cases = [
            (OAuthErrorCode::InvalidRequest, "invalid_request"),
            (OAuthErrorCode::InvalidClient, "invalid_client"),
            (OAuthErrorCode::InvalidGrant, "invalid_grant"),
            (OAuthErrorCode::UnauthorizedClient, "unauthorized_client"),
            (
                OAuthErrorCode::UnsupportedGrantType,
                "unsupported_grant_type",
            ),
            (OAuthErrorCode::InvalidScope, "invalid_scope"),
            (OAuthErrorCode::AccessDenied, "access_denied"),
            (
                OAuthErrorCode::UnsupportedResponseType,
                "unsupported_response_type",
            ),
            (OAuthErrorCode::ServerError, "server_error"),
            (
                OAuthErrorCode::TemporarilyUnavailable,
                "temporarily_unavailable",
            ),
            (OAuthErrorCode::InvalidToken, "invalid_token"),
            (OAuthErrorCode::InsufficientScope, "insufficient_scope"),
            (OAuthErrorCode::InvalidTarget, "invalid_target"),
            (OAuthErrorCode::InvalidRedirectUri, "invalid_redirect_uri"),
            (
                OAuthErrorCode::InvalidClientMetadata,
                "invalid_client_metadata",
            ),
            (
                OAuthErrorCode::InvalidSoftwareStatement,
                "invalid_software_statement",
            ),
            (
                OAuthErrorCode::UnapprovedSoftwareStatement,
                "unapproved_software_statement",
            ),
            (OAuthErrorCode::InvalidDpopProof, "invalid_dpop_proof"),
            (OAuthErrorCode::UseDpopNonce, "use_dpop_nonce"),
        ];
        for (code, wire) in cases {
            assert_eq!(code.as_str(), wire);
            assert_eq!(OAuthErrorCode::from(wire), code);
            assert_eq!(OAuthErrorCode::from(wire.to_string()), code);
        }
    }

    #[test]
    fn it_preserves_unknown_codes() {
        let code = OAuthErrorCode::from("urn:vendor:quota_exceeded");
        assert_eq!(
            code,
            OAuthErrorCode::Other("urn:vendor:quota_exceeded".into())
        );
        assert_eq!(code.as_str(), "urn:vendor:quota_exceeded");
        assert_eq!(String::from(code), "urn:vendor:quota_exceeded");
    }

    #[test]
    fn it_serializes_code_as_string() {
        let json = serde_json::to_string(&OAuthErrorCode::InvalidToken).unwrap();
        assert_eq!(json, r#""invalid_token""#);
    }

    #[test]
    fn it_deserializes_code_from_string() {
        let code: OAuthErrorCode = serde_json::from_str(r#""insufficient_scope""#).unwrap();
        assert_eq!(code, OAuthErrorCode::InsufficientScope);

        let code: OAuthErrorCode = serde_json::from_str(r#""something_custom""#).unwrap();
        assert_eq!(code, OAuthErrorCode::Other("something_custom".into()));
    }

    #[test]
    fn it_displays_code() {
        assert_eq!(
            OAuthErrorCode::TemporarilyUnavailable.to_string(),
            "temporarily_unavailable"
        );
    }

    #[test]
    fn it_serializes_error_without_optional_fields() {
        let err = OAuthError::new(OAuthErrorCode::InvalidGrant);
        let json = serde_json::to_string(&err).unwrap();
        assert_eq!(json, r#"{"error":"invalid_grant"}"#);
    }

    #[test]
    fn it_serializes_error_with_all_fields() {
        let err = OAuthError::new(OAuthErrorCode::InvalidRequest)
            .with_description("Missing code_verifier")
            .with_error_uri("https://example.com/errors/invalid_request");
        let json = serde_json::to_string(&err).unwrap();
        assert_eq!(
            json,
            r#"{"error":"invalid_request","error_description":"Missing code_verifier","error_uri":"https://example.com/errors/invalid_request"}"#
        );
    }

    #[test]
    fn it_deserializes_error_response() {
        let err: OAuthError = serde_json::from_str(
            r#"{"error":"invalid_token","error_description":"Token has expired"}"#,
        )
        .unwrap();
        assert_eq!(err.error, OAuthErrorCode::InvalidToken);
        assert_eq!(err.error_description.as_deref(), Some("Token has expired"));
        assert!(err.error_uri.is_none());
    }

    #[test]
    fn it_displays_error_with_and_without_description() {
        let err = OAuthError::new(OAuthErrorCode::InvalidToken);
        assert_eq!(err.to_string(), "invalid_token");

        let err = err.with_description("Token has expired");
        assert_eq!(err.to_string(), "invalid_token: Token has expired");
    }

    #[test]
    fn it_converts_code_into_error() {
        let err: OAuthError = OAuthErrorCode::AccessDenied.into();
        assert_eq!(err.error, OAuthErrorCode::AccessDenied);
        assert!(err.error_description.is_none());
    }

    #[test]
    fn it_maps_codes_to_status() {
        let cases = [
            (OAuthErrorCode::InvalidToken, StatusCode::UNAUTHORIZED),
            (OAuthErrorCode::InvalidClient, StatusCode::UNAUTHORIZED),
            (OAuthErrorCode::InsufficientScope, StatusCode::FORBIDDEN),
            (OAuthErrorCode::AccessDenied, StatusCode::FORBIDDEN),
            (
                OAuthErrorCode::ServerError,
                StatusCode::INTERNAL_SERVER_ERROR,
            ),
            (
                OAuthErrorCode::TemporarilyUnavailable,
                StatusCode::SERVICE_UNAVAILABLE,
            ),
            (OAuthErrorCode::InvalidRequest, StatusCode::BAD_REQUEST),
            (OAuthErrorCode::InvalidGrant, StatusCode::BAD_REQUEST),
            (OAuthErrorCode::InvalidTarget, StatusCode::BAD_REQUEST),
            (
                OAuthErrorCode::Other("custom".into()),
                StatusCode::BAD_REQUEST,
            ),
        ];
        for (code, status) in cases {
            assert_eq!(code.status(), status, "code: {code}");
        }
    }
}