about summary refs log tree commit diff
path: root/kittybox-rs/indieauth/src/lib.rs
blob: cb99146b37555b485c0880d483ee32681a80d852 (plain) (blame)
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
use serde::{Serialize, Deserialize};
use url::Url;

mod scopes;
pub use self::scopes::{Scope, Scopes};
mod pkce;
pub use self::pkce::{PKCEMethod, PKCEVerifier, PKCEChallenge};

#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub enum IntrospectionEndpointAuthMethod {
    Bearer,
    #[serde(rename = "snake_case")]
    ClientSecretPost,
    #[serde(rename = "snake_case")]
    ClientSecretBasic,
    #[serde(rename = "snake_case")]
    TlsClientAuth,
    #[serde(rename = "snake_case")]
    SelfSignedTlsClientAuth
}

#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RevocationEndpointAuthMethod {
    None
}

#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResponseType {
    Code
}

#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GrantType {
    AuthorizationCode,
    RefreshToken
}

/// OAuth 2.0 Authorization Server Metadata in application to the IndieAuth protocol.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Metadata {
    /// The server's issuer identifier. The issuer identifier is a URL
    /// that uses the "https" scheme and has no query or fragment
    /// components. The identifier MUST be a prefix of the
    /// `indieauth-metadata` URL.
    pub issuer: Url,
    /// The Authorization Endpoint
    pub authorization_endpoint: Url,
    /// The Token Endpoint
    pub token_endpoint: Url,
    /// The Introspection Endpoint
    pub introspection_endpoint: Url,
    /// JSON array containing a list of client authentication methods supported by this introspection endpoint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub introspection_endpoint_auth_methods_supported: Option<Vec<IntrospectionEndpointAuthMethod>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub revocation_endpoint: Option<Url>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub revocation_endpoint_auth_methods_supported: Option<Vec<RevocationEndpointAuthMethod>>,
    // Note: Scopes isn't used here because this field should be
    // serialized as a list, not as a string
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scopes_supported: Option<Vec<Scope>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_types_supported: Option<Vec<ResponseType>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub grant_types_supported: Option<Vec<GrantType>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_documentation: Option<Url>,
    pub code_challenge_methods_supported: Vec<PKCEMethod>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authorization_response_iss_parameter_supported: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub userinfo_endpoint: Option<Url>
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Profile {
    pub name: String,
    pub url: Url,
    pub photo: Url,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>
}

#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct State(String);
impl State {
    fn new() -> Self {
        use rand::{Rng, distributions::Alphanumeric};
        let bytes = rand::thread_rng()
            .sample_iter(&Alphanumeric)
            .take(128)
            .collect::<Vec<u8>>();
        Self(String::from_utf8(bytes).unwrap())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthorizationRequest {
    pub response_type: ResponseType,
    pub client_id: Url,
    pub redirect_uri: Url,
    pub state: State,
    #[serde(flatten)]
    pub code_challenge: PKCEChallenge,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<Scopes>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub me: Option<Url>
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthorizationResponse {
    pub code: String,
    pub state: State,
    pub iss: Url
}

#[derive(PartialEq, Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "grant_type")]
#[serde(rename_all = "snake_case")]
pub enum GrantRequest {
    AuthorizationCode {
        code: String,
        client_id: Url,
        redirect_uri: Url,
        code_verifier: PKCEVerifier
    },
    RefreshToken {
        refresh_token: String,
        client_id: url::Url,
        scope: Option<Scopes>
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GrantResponse {
    AccessToken {
        me: Url,
        #[serde(skip_serializing_if = "Option::is_none")]
        profile: Option<Profile>,
        access_token: String,
        // TODO replace with std::time::Duration
        #[serde(skip_serializing_if = "Option::is_none")]
        expires_in: Option<u64>,
        #[serde(skip_serializing_if = "Option::is_none")]
        refresh_token: Option<String>
    },
    ProfileUrl {
        me: Url,
        #[serde(skip_serializing_if = "Option::is_none")]
        profile: Option<Profile>
    }
}

/// Describes requests that the authorization endpoint might want to handle.
///
/// This type mostly exists for ease-of-use with serde.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum RequestMaybeAuthorizationEndpoint {
    Authorization(AuthorizationRequest),
    Grant(GrantRequest)
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TokenIntrospectionRequest {
    pub token: String
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TokenData {
    pub me: Url,
    pub client_id: Url,
    pub scope: Scopes,
    // TODO replace these two with std::time::SystemTime
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exp: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iat: Option<u64>
}

impl TokenData {
    pub fn expired(&self) -> bool {
        use std::time::{Duration, SystemTime, UNIX_EPOCH};
        
        self.exp
            .map(|exp| SystemTime::now()
                 .duration_since(UNIX_EPOCH)
                 .unwrap_or(Duration::ZERO)
                 .as_secs() >= exp)
            .unwrap_or_default()
    }

    pub fn expires_at(&self) -> Option<std::time::SystemTime> {
        self.exp.map(|time| {
            std::time::UNIX_EPOCH + std::time::Duration::from_secs(time)
        })
    }
    
    pub fn issued_at(&self) -> Option<std::time::SystemTime> {
        self.iat.map(|time| {
            std::time::UNIX_EPOCH + std::time::Duration::from_secs(time)
        })
    }
}

// I don't like this type, because it could've been represented
// internally by Option<TokenData>. But the IndieAuth standard
// requires the "active" field to be present. I can't do anything
// about it.
#[derive(Debug, Serialize, Deserialize)]
pub struct TokenIntrospectionResponse {
    active: bool,
    #[serde(flatten)]
    #[serde(skip_serializing_if = "Option::is_none")]
    data: Option<TokenData>
}
// These wrappers and impls should take care of making use of this
// type as painless as possible.
impl TokenIntrospectionResponse {
    pub fn inactive() -> Self {
        Self { active: false, data: None }
    }
    pub fn active(data: TokenData) -> Self {
        Self { active: true, data: Some(data) }
    }

    pub fn is_active(&self) -> bool {
        self.active
    }

    pub fn data(&self) -> Option<&TokenData> {
        if !self.active {
            return None
        }
        self.data.as_ref()
    }
}
impl Default for TokenIntrospectionResponse {
    fn default() -> Self {
        Self::inactive()
    }
}
impl From<Option<TokenData>> for TokenIntrospectionResponse {
    fn from(data: Option<TokenData>) -> Self {
        Self { active: data.is_some(), data }
    }
}
impl From<TokenIntrospectionResponse> for Option<TokenData> {
    fn from(response: TokenIntrospectionResponse) -> Option<TokenData> {
        response.data
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct TokenRevocationRequest {
    pub token: String
}

/// Types of errors that a resource server (IndieAuth consumer) can
/// throw when authentication goes wrong.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResourceErrorKind {
    InvalidRequest,
    InvalidToken,
    InsufficientScope,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorKind {
    /// The request is missing a required parameter, includes an
    /// unsupported parameter value (other than grant type), repeats a
    /// parameter, includes multiple credentials, utilizes more than
    /// one mechanism for authenticating the client, or is otherwise
    /// malformed.
    InvalidRequest,
    /// Client authentication failed (e.g., unknown client, no client
    /// authentication included, or unsupported authentication
    /// method).  The authorization server MAY return an HTTP 401
    /// (Unauthorized) status code to indicate which HTTP
    /// authentication schemes are supported.  If the client attempted
    /// to authenticate via the "Authorization" request header field,
    /// the authorization server MUST respond with an HTTP 401
    /// (Unauthorized) status code and include the "WWW-Authenticate"
    /// response header field matching the authentication scheme used
    /// by the client.
    InvalidClient,
    /// The provided authorization grant (e.g., authorization
    /// code, resource owner credentials) or refresh token is
    /// invalid, expired, revoked, does not match the redirection
    /// URI used in the authorization request, or was issued to
    /// another client.
    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, malformed, or
    /// exceeds the scope granted by the resource owner.
    InvalidScope
}
// TODO consider relying on serde_variant for these conversions
impl AsRef<str> for ErrorKind {
    fn as_ref(&self) -> &str {
        match self {
            ErrorKind::InvalidRequest => "invalid_request",
            ErrorKind::InvalidClient => "invalid_client",
            ErrorKind::InvalidGrant => "invalid_grant",
            ErrorKind::UnauthorizedClient => "unauthorized_client",
            ErrorKind::UnsupportedGrantType => "unsupported_grant_type",
            ErrorKind::InvalidScope => "invalid_scope",
        }
    }
}
impl std::fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_ref())
    }
}


#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Error {
    #[serde(rename = "error")]
    pub kind: ErrorKind,
    #[serde(rename = "error_description")]
    pub msg: Option<String>,
    pub error_uri: Option<url::Url>
}

impl From<ErrorKind> for Error {
    fn from(kind: ErrorKind) -> Error {
        Error {
            kind, msg: None, error_uri: None
        }
    }
}

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

impl std::fmt::Display for self::Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "IndieAuth error ({})", self.kind)?;
        if let Some(msg) = self.msg.as_deref() {
            write!(f, ": {}", msg)?;
        }
        if let Some(error_uri) = &self.error_uri {
            write!(f, " (see `{}` for more info)", error_uri)?;
        }

        Ok(())
    }
}

#[cfg(feature = "axum")]
impl axum_core::response::IntoResponse for self::Error {
    fn into_response(self) -> axum_core::response::Response {
        use http::StatusCode;

        (StatusCode::BAD_REQUEST,
         [("Content-Type", "application/json")],
         serde_json::to_vec(&self).unwrap())
            .into_response()
    }
}

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

    #[test]
    fn test_serialize_deserialize_grant_request() {
        let authorization_code: GrantRequest = GrantRequest::AuthorizationCode {
            client_id: "https://kittybox.fireburn.ru/".parse().unwrap(),
            redirect_uri: "https://kittybox.fireburn.ru/.kittybox/login/redirect".parse().unwrap(),
            code_verifier: PKCEVerifier("helloworld".to_string()),
            code: "hithere".to_owned()
        };
        let serialized = serde_urlencoded::to_string(&[
            ("grant_type", "authorization_code"),
            ("code", "hithere"),
            ("client_id", "https://kittybox.fireburn.ru/"),
            ("redirect_uri", "https://kittybox.fireburn.ru/.kittybox/login/redirect"),
            ("code_verifier", "helloworld"),
        ]).unwrap();

        let deserialized = serde_urlencoded::from_str(&serialized).unwrap();

        assert_eq!(authorization_code, deserialized);

        assert_eq!(
            serialized,
            serde_urlencoded::to_string(authorization_code).unwrap()
        )
    }
}