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
//! # actix-web-jwt
//! This is a JWT token validation middleware for actix-web.
//! This middleware will validate the JWT token and forward the request to the next middleware.
//! If the token is invalid then it will return a 401 response.
//!
//! JWKS is used to validate the token. Application must periodically invoke the JWKS endpoint using the *CertInvoker* to get the latest cert.
//!
//!
//! # Documentation
//! * [Examples Repository](https://github.com/keaz/actix-web-jwt/examples)
//!
use std::{
    fmt::{self, Display},
    future::{ready, Ready},
    sync::Arc,
};

use actix_web::{
    dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
    error, Error, HttpResponse,
};
use futures_util::future::LocalBoxFuture;
use jsonwebtoken::{decode, decode_header, DecodingKey, Validation};
use log::{debug, error, info, warn};
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;

pub struct Jwt {
    cert_invoker: Arc<CertInvoker>,
}

///
/// Use to crete a JWT middleware
///
impl Jwt {
    ///
    /// Creates a JWT from the CertInvoker
    ///
    pub fn from(cert_invoker: Arc<CertInvoker>) -> Self {
        Jwt { cert_invoker }
    }
}

impl<S, B> Transform<S, ServiceRequest> for Jwt
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = Error;
    type Transform = JwtMiddleware<S>;
    type InitError = ();
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(JwtMiddleware {
            service,
            cert_invoker: Arc::clone(&self.cert_invoker),
        }))
    }
}

///
/// JWT middleware for toke validation
///
pub struct JwtMiddleware<S> {
    service: S,
    cert_invoker: Arc<CertInvoker>,
}

const BEARER: &str = "Bearer ";

impl<S, B> Service<ServiceRequest> for JwtMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::error::Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = Error;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let headers = req.headers();
        let jwt_token = headers
            .iter()
            .filter(|(header, _)| header.as_str() == "authorization")
            .map(|(_, value)| String::from(value.to_str().unwrap()))
            .collect::<Vec<String>>();

        let fut = self.service.call(req);
        let cert = Arc::clone(&self.cert_invoker.cert);

        Box::pin(async move {
            if jwt_token.is_empty() {
                warn!("Missing JWT token");
                let x = actix_web::error::Error::from(JWTResponseError::missing_jwt());
                return Err(x);
            }

            let jwt_token = jwt_token.join("");

            if !jwt_token.starts_with(BEARER) {
                warn!("JWT is not started with Bearer");
                let x = actix_web::error::Error::from(JWTResponseError::invalid_jwt());
                return Err(x);
            }

            let jwt_token = jwt_token.replace(BEARER, "");
            let jwt_header = decode_header(&jwt_token);
            if jwt_header.is_err() {
                warn!("JWT header is invalid");
                let x = actix_web::error::Error::from(JWTResponseError::invalid_jwt());
                return Err(x);
            }
            let jwt_header = jwt_header.unwrap();
            let kid = jwt_header.kid.unwrap();

            let jwt_cert = cert.lock().await;
            let cert = jwt_cert.clone().unwrap(); // Cert should available at this point

            let key = cert.keys.iter().find(|key| key.kid == kid).unwrap();
            let de_key = DecodingKey::from_rsa_components(key.n.as_str(), key.e.as_str()).unwrap();
            let token = decode::<Claims>(&jwt_token, &de_key, &Validation::new(jwt_header.alg));

            match token {
                Ok(_) => Ok(fut.await?),
                Err(err) => {
                    match err.kind() {
                        jsonwebtoken::errors::ErrorKind::InvalidSignature => return Err(invalid_invalid_signature()),
                        jsonwebtoken::errors::ErrorKind::ExpiredSignature => return Err(expired_jwt()),
                        jsonwebtoken::errors::ErrorKind::InvalidIssuer => return Err(invalid_invalid_iss()),
                        _ => {
                            warn!("JWT is invalid {:?}", err);
                            return Err(invalid_jwt())
                        },
                    }
                }
            }
        })
    }
}

fn invalid_jwt() -> actix_web::Error {
    return actix_web::error::Error::from(
        JWTResponseError::invalid_jwt(),
    )
}

fn expired_jwt() -> actix_web::Error {
    return actix_web::error::Error::from(
        JWTResponseError::expired_jwt(),
    )
}

fn invalid_invalid_signature() -> actix_web::Error {
    return actix_web::error::Error::from(
        JWTResponseError::invalid_invalid_signature(),
    )
}

fn invalid_invalid_iss() -> actix_web::Error {
    return actix_web::error::Error::from(
        JWTResponseError::invalid_invalid_issr(),
    )
}

async fn get_cert(cert_url: &String) -> Result<Cert, JWKSError> {
    debug!("Getting cert");
    let response = reqwest::get(cert_url).await;
    if response.is_err() {
        warn!("Error while getting cert");
        return Err(JWKSError::InvokingCertUrl(
            "Error while getting cert".to_string(),
        ));
    }
    let cert: Result<CertResponse, reqwest::Error> = response.unwrap().json().await;
    if cert.is_err() {
        warn!("Error while deserialize cert");
        return Err(JWKSError::ErrorDeserializingCert(format!(
            "Error while deserialize cert {:?}",
            cert.err().unwrap()
        )));
    }

    let keys = cert.unwrap().keys.iter().map(|key| {
        let de_key = DecodingKey::from_rsa_components(key.n.as_str(), key.e.as_str()).unwrap();
        Key::from(key.clone(), de_key)
    }).collect();
    
    Ok(Cert{keys})
}

///
/// This is use to invoke cert endpoint and store the cert in memory
///
pub struct CertInvoker {
    cert: Arc<Mutex<Option<Cert>>>,
    cert_url: String,
}

impl CertInvoker {
    ///
    /// Create a new CertInvoker form cert cert url
    /// # Arguments
    /// * `cert_url` - The cert url
    ///
    /// # Example
    /// ```
    /// use actix_web_jwt::CertInvoker;
    /// fn main() {
    ///     let cert_url = String::from("https://www.googleapis.com/oauth2/v3/certs");
    ///     let cert_invoker = CertInvoker::from(cert_url);
    /// }
    /// ```
    pub fn from(cert_url: String) -> Self {
        CertInvoker {
            cert: Arc::new(Mutex::new(None)),
            cert_url,
        }
    }

    ///
    /// Invoke the cert endpoint and store the cert in memory.
    /// This method should be called periodically to update the cert
    ///
    /// # Example
    /// ```
    /// use actix_web_jwt::CertInvoker;
    /// #[tokio::main]
    /// async fn main() {
    ///     let cert_url = String::from("https://www.googleapis.com/oauth2/v3/certs");
    ///     let cert_invoker = CertInvoker::from(cert_url);
    ///     cert_invoker.get_cert().await;
    /// }
    /// ```
    pub async fn get_cert(&self) {
        info!("Getting cert form {}", self.cert_url);
        let cert = get_cert(&self.cert_url).await;
        let mut jwt_cert = self.cert.lock().await;
        match cert {
            Ok(cert) => {
                *jwt_cert = Option::Some(cert);
            }
            Err(er) => {
                error!("Error while getting cert {:?}", er);
                *jwt_cert = Option::None;
            }
        }
    }
}

///
///
///
#[derive(Debug)]
pub enum JWKSError {
    ///
    /// Indicates error while invoking cert url
    ///
    InvokingCertUrl(String),
    ///
    /// Cert response is not valid
    ///
    ErrorDeserializingCert(String),
}

#[derive(Debug)]
struct JWTResponseError {
    status_code: StatusCode,
    message: String,
}

impl JWTResponseError {
    pub fn invalid_jwt() -> Self {
        JWTResponseError {
            status_code: StatusCode::UNAUTHORIZED,
            message: "Invalid JWT".to_string(),
        }
    }

    pub fn expired_jwt() -> Self {
        JWTResponseError {
            status_code: StatusCode::UNAUTHORIZED,
            message: "Expired JWT".to_string(),
        }
    }
    
    pub fn invalid_invalid_signature() -> Self {
        JWTResponseError {
            status_code: StatusCode::UNAUTHORIZED,
            message: "Invalid Invalid Signature".to_string(),
        }
    }

    pub fn invalid_invalid_issr() -> Self {
        JWTResponseError {
            status_code: StatusCode::UNAUTHORIZED,
            message: "Invalid Invalid Issure".to_string(),
        }
    }

    pub fn missing_jwt() -> Self {
        JWTResponseError {
            status_code: StatusCode::UNAUTHORIZED,
            message: "Missing JWT".to_string(),
        }
    }
}

impl error::ResponseError for JWTResponseError {
    fn status_code(&self) -> StatusCode {
        self.status_code
    }

    fn error_response(&self) -> HttpResponse {
        HttpResponse::build(self.status_code()).json(JWTResponse {
            message: self.message.clone(),
        })
    }
}

impl Display for JWTResponseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        write!(f, "{:?}", self)
    }
}

#[derive(Serialize)]
pub struct JWTResponse {
    pub message: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct CertResponse {
    pub keys: Vec<KeyResponse>,
}

#[derive(Debug, Serialize, Deserialize)]
struct KeyResponse {
    pub kid: String,
    pub kty: String,
    #[serde(rename = "use")]
    pub use_key: String,
    pub n: String,
    pub e: String,
    pub x5c: Option<Vec<String>>,
    pub x5t: Option<String>,
    #[serde(rename = "x5t#S256")]
    pub x5t_s256: Option<String>,
    pub alg: String,
}

impl Clone for CertResponse {
    fn clone(&self) -> Self {
        CertResponse {
            keys: self.keys.clone(),
        }
    }
}

impl Clone for KeyResponse {
    fn clone(&self) -> Self {
        KeyResponse {
            kid: self.kid.clone(),
            kty: self.kty.clone(),
            use_key: self.use_key.clone(),
            n: self.n.clone(),
            e: self.e.clone(),
            x5c: self.x5c.clone(),
            x5t: self.x5t.clone(),
            x5t_s256: self.x5t_s256.clone(),
            alg: self.alg.clone(),
        }
    }
}

pub struct Cert {
    pub keys: Vec<Key>,
}


pub struct Key {
    pub kid: String,
    pub kty: String,
    pub use_key: String,
    pub n: String,
    pub e: String,
    pub x5c: Option<Vec<String>>,
    pub x5t: Option<String>,
    pub x5t_s256: Option<String>,
    pub alg: String,
    pub de_key: DecodingKey,
}

impl Clone for Cert {
    fn clone(&self) -> Self {
        Cert {
            keys: self.keys.clone(),
        }
    }
}

impl Clone for Key {
    fn clone(&self) -> Self {
        Key {
            kid: self.kid.clone(),
            kty: self.kty.clone(),
            use_key: self.use_key.clone(),
            n: self.n.clone(),
            e: self.e.clone(),
            x5c: self.x5c.clone(),
            x5t: self.x5t.clone(),
            x5t_s256: self.x5t_s256.clone(),
            alg: self.alg.clone(),
            de_key: self.de_key.clone(),
        }
    }
}


impl Key {
    
    fn from(key_response: KeyResponse, de_key: DecodingKey) -> Self {
        Key { kid: key_response.kid, kty: key_response.kty, use_key: key_response.use_key, 
            n: key_response.n, e: key_response.e, x5c: key_response.x5c, x5t: key_response.x5t, x5t_s256: key_response.x5t_s256, 
            alg: key_response.alg, de_key }
    }

}




#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
    pub iss: String,
    pub sub: String,
    pub aud: Option<String>,
    pub exp: usize,
    pub nbf: Option<usize>,
    pub iat: usize,
    pub jti: Option<String>,
    pub azp: Option<String>,
    pub scope: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::*;
    #[tokio::test]
    async fn get_cert_test() {
        let cert_url = String::from("https://www.googleapis.com/oauth2/v3/certs");
        let cert = get_cert(&cert_url).await;
        assert!(cert.is_ok());
    }

    #[tokio::test]
    async fn get_cert_wrong_url_test() {
        let cert_url = String::from("https://www.googleapis.com/oauth2/v3/certsx");
        let cert = get_cert(&cert_url).await;
        assert!(cert.is_err());
    }
}