about summary refs log tree commit diff
path: root/src/indieauth.rs
blob: bcc8bbef0d79eb185b85db0670a7360c05e5b83c (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
use url::Url;
use serde::{Serialize, Deserialize};
use warp::{Filter, Rejection, reject::MissingHeader};

#[derive(Deserialize, Serialize, Debug, PartialEq, Clone)]
pub struct User {
    pub me: Url,
    pub client_id: Url,
    scope: String,
}

#[derive(Debug, Clone, PartialEq, Copy)]
pub enum ErrorKind {
    PermissionDenied,
    NotAuthorized,
    TokenEndpointError,
    JsonParsing,
    Other
}

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct TokenEndpointError {
    error: String,
    error_description: String
}

#[derive(Debug)]
pub struct IndieAuthError {
    source: Option<Box<dyn std::error::Error + Send + Sync>>,
    kind: ErrorKind,
    msg: String
}

impl std::error::Error for IndieAuthError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source.as_ref().map(|e| e.as_ref() as &dyn std::error::Error)
    }
}

impl std::fmt::Display for IndieAuthError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match match self.kind {
            ErrorKind::TokenEndpointError => write!(f, "token endpoint returned an error: "),
            ErrorKind::JsonParsing => write!(f, "error while parsing token endpoint response: "),
            ErrorKind::NotAuthorized => write!(f, "token endpoint did not recognize the token: "),
            ErrorKind::PermissionDenied => write!(f, "token endpoint rejected the token: "),
            ErrorKind::Other => write!(f, "token endpoint communication error: "),
        } {
            Ok(_) => write!(f, "{}", self.msg),
            Err(err) => Err(err)
        }
    }
}

impl From<serde_json::Error> for IndieAuthError {
    fn from(err: serde_json::Error) -> Self {
        Self {
            msg: format!("{}", err),
            source: Some(Box::new(err)),
            kind: ErrorKind::JsonParsing,
        }
    }
}

impl From<hyper::Error> for IndieAuthError {
    fn from(err: hyper::Error) -> Self {
        Self {
            msg: format!("{}", err),
            source: Some(Box::new(err)),
            kind: ErrorKind::Other,
        }
    }
}

impl warp::reject::Reject for IndieAuthError {}

impl User {
    pub fn check_scope(&self, scope: &str) -> bool {
        self.scopes().any(|i| i == scope)
    }
    pub fn scopes(&self) -> std::str::SplitAsciiWhitespace<'_> {
        self.scope.split_ascii_whitespace()
    }
    pub fn new(me: &str, client_id: &str, scope: &str) -> Self {
        Self {
            me: Url::parse(me).unwrap(),
            client_id: Url::parse(client_id).unwrap(),
            scope: scope.to_string(),
        }
    }
}

pub fn require_token<T>(token_endpoint: String, http: hyper::Client<T, hyper::Body>) -> impl Filter<Extract = (User,), Error = Rejection> + Clone
where T: hyper::client::connect::Connect + Clone + Send + Sync + 'static {
    // It might be OK to panic here, because we're still inside the initialisation sequence for now.
    // Proper error handling on the top of this should be used though.
    let token_endpoint_uri = hyper::Uri::try_from(&token_endpoint)
        .expect("Couldn't parse the token endpoint URI!");
    warp::any()
        .map(move || token_endpoint_uri.clone())
        .and(warp::any().map(move || http.clone()))
        .and(warp::header::<String>("Authorization").recover(|err: Rejection| async move {
            if err.find::<MissingHeader>().is_some() {
                Err(IndieAuthError {
                    source: None,
                    msg: "No Authorization header provided.".to_string(),
                    kind: ErrorKind::NotAuthorized
                }.into())
            } else {
                Err(err)
            }
        }).unify())
        .and_then(|token_endpoint, http: hyper::Client<T, hyper::Body>, token| async move {
            let request = hyper::Request::builder()
                .method(hyper::Method::GET)
                .uri(token_endpoint)
                .header("Authorization", token)
                .header("Accept", "application/json")
                .body(hyper::Body::from(""))
                // TODO is it acceptable to panic here?
                .unwrap();

            use hyper::StatusCode;

            match http.request(request).await {
                Ok(mut res) => match res.status() {
                    StatusCode::OK => {
                        use hyper::body::HttpBody;
                        use bytes::BufMut;
                        let mut buf: Vec<u8> = Vec::default();
                        while let Some(chunk) = res.body_mut().data().await {
                            if let Err(err) = chunk {
                                return Err(IndieAuthError::from(err).into());
                            }
                            buf.put(chunk.unwrap());
                        }
                        match serde_json::from_slice(&buf) {
                            Ok(user) => Ok(user),
                            Err(err) => {
                                if let Ok(json) = serde_json::from_slice::<serde_json::Value>(&buf) {
                                    if Some(false) == json["active"].as_bool() {
                                        Err(IndieAuthError {
                                            source: None,
                                            kind: ErrorKind::NotAuthorized,
                                            msg: "The token endpoint deemed the token as not \"active\".".to_string()
                                        }.into())
                                    } else {
                                        Err(IndieAuthError::from(err).into())
                                    }
                                } else {
                                    Err(IndieAuthError::from(err).into())
                                }
                            }
                        }
                    },
                    StatusCode::BAD_REQUEST => {
                        use hyper::body::HttpBody;
                        use bytes::BufMut;
                        let mut buf: Vec<u8> = Vec::default();
                        while let Some(chunk) = res.body_mut().data().await {
                            if let Err(err) = chunk {
                                return Err(IndieAuthError::from(err).into());
                            }
                            buf.put(chunk.unwrap());
                        }
                        match serde_json::from_slice::<TokenEndpointError>(&buf) {
                            Ok(err) => {
                                if err.error == "unauthorized" {
                                    Err(IndieAuthError {
                                        source: None,
                                        kind: ErrorKind::NotAuthorized,
                                        msg: err.error_description
                                    }.into())
                                } else {
                                    Err(IndieAuthError {
                                        source: None,
                                        kind: ErrorKind::TokenEndpointError,
                                        msg: err.error_description
                                    }.into())
                                }
                            },
                            Err(err) => Err(IndieAuthError::from(err).into())
                        }
                    },
                    _ => Err(IndieAuthError {
                        source: None,
                        msg: format!("Token endpoint returned {}", res.status()).to_string(),
                        kind: ErrorKind::TokenEndpointError
                    }.into())
                },
                Err(err) => Err(warp::reject::custom(IndieAuthError::from(err)))
            }
        })
}

#[cfg(test)]
mod tests {
    use super::{User, IndieAuthError, require_token};
    use httpmock::prelude::*;
    
    #[test]
    fn user_scopes_are_checkable() {
        let user = User::new(
            "https://fireburn.ru/",
            "https://quill.p3k.io/",
            "create update media",
        );

        assert!(user.check_scope("create"));
        assert!(!user.check_scope("delete"));
    }

    fn get_http_client() -> hyper::Client<impl hyper::client::connect::Connect + Clone + Send + Sync + 'static, hyper::Body> {
        let builder = hyper::Client::builder();
        let https = hyper_rustls::HttpsConnectorBuilder::new()
            .with_webpki_roots()
            .https_or_http()
            .enable_http1()
            .enable_http2()
            .build();
        builder.build(https)
    }
    
    #[tokio::test]
    async fn test_require_token_with_token() {
        let server = MockServer::start_async().await;
        server.mock_async(|when, then| {
            when.path("/token")
                .header("Authorization", "Bearer token");

            then.status(200)
                .header("Content-Type", "application/json")
                .json_body(serde_json::to_value(User::new(
                    "https://fireburn.ru/",
                    "https://quill.p3k.io/",
                    "create update media",
                )).unwrap());
        }).await;
        
        let filter = require_token(server.url("/token"), get_http_client());

        let res: User = warp::test::request()
            .path("/")
            .header("Authorization", "Bearer token")
            .filter(&filter)
            .await
            .unwrap();

        assert_eq!(res.me.as_str(), "https://fireburn.ru/")
    }

    #[tokio::test]
    async fn test_require_token_fake_token() {
        let server = MockServer::start_async().await;
        server.mock_async(|when, then| {
            when.path("/refuse_token");

            then.status(200)
                .json_body(serde_json::json!({"active": false}));
        }).await;

        let filter = require_token(server.url("/refuse_token"), get_http_client());

        let res = warp::test::request()
            .path("/")
            .header("Authorization", "Bearer token")
            .filter(&filter)
            .await
            .unwrap_err();

        let err: &IndieAuthError = res.find().unwrap();
        assert_eq!(err.kind, super::ErrorKind::NotAuthorized);
    }

    #[tokio::test]
    async fn test_require_token_no_token() {
        let server = MockServer::start_async().await;
        let mock = server.mock_async(|when, then| {
            when.path("/should_never_be_called");

            then.status(500);
        }).await;
        let filter = require_token(server.url("/should_never_be_called"), get_http_client());

        let res = warp::test::request()
            .path("/")
            .filter(&filter)
            .await
            .unwrap_err();

        let err: &IndieAuthError = res.find().unwrap();
        assert_eq!(err.kind, super::ErrorKind::NotAuthorized);

        mock.assert_hits_async(0).await;
    }

    #[tokio::test]
    async fn test_require_token_400_error_unauthorized() {
        let server = MockServer::start_async().await;
        server.mock_async(|when, then| {
            when.path("/refuse_token_with_400");

            then.status(400)
                .json_body(serde_json::json!({
                    "error": "unauthorized",
                    "error_description": "The token provided was malformed"
                }));
        }).await;

        let filter = require_token(server.url("/refuse_token_with_400"), get_http_client());

        let res = warp::test::request()
            .path("/")
            .header("Authorization", "Bearer token")
            .filter(&filter)
            .await
            .unwrap_err();

        let err: &IndieAuthError = res.find().unwrap();
        assert_eq!(err.kind, super::ErrorKind::NotAuthorized);
    }
}