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
/* auth.rs
 *
 * Developed by Tim Walls <[email protected]>
 * Copyright (c) All Rights Reserved, Tim Walls
 */
/**
 * Documentation comment for this file.
 */
// Imports ===================================================================
use std::pin::Pin;
use std::task::{Context, Poll};

use actix_web::{Error, ResponseError};
pub use actix_web::dev::{ServiceRequest,ServiceResponse};
use std::future::{Future, Ready, ready};
use actix_web::dev::{Transform, Service};
use actix_web::body::MessageBody;
use jwks_client::keyset::KeyStore;
use std::env;
use thiserror::Error;
use std::env::VarError;
pub use jwks_client::jwt::{Jwt, Payload, Header};
use std::rc::Rc;

use actix_web::http::StatusCode;


// Declarations ==============================================================
/**
 * Type definition for functions that will, given a request and a JWT, return
 * `true` if the request should be allowed to continue for processing, or `false`
 * otherwise.
 */
type JwtValidator = fn(&ServiceRequest,&Option<Jwt>)->bool;

/**
 * A simple validator function that simply returns true if the request had
 * a valid (that is, it exists, and the signature was checked) JWT.  It does
 * not check any claims or any other details within the token.
 */
#[allow(non_snake_case)]
pub fn CheckJwtValid(req: &ServiceRequest, jwt: &Option<Jwt>) -> bool {
  log::debug!("Default JWT validator called {:?} / {:?}", req, jwt);

  match jwt {
    None => {
      false
    },
    Some(_) => {
      true
    }
  }
}

/**
 * JWT validating middleware for Actix-Web.
 */
pub struct JwtAuth {
  jwks_url: String,
  validator: Rc<JwtValidator>
}

pub struct JwtAuthService<S> {
  service: S,
  jwks: KeyStore,
  validator: Rc<JwtValidator>
}

#[derive(Error,Debug)]
pub enum JwtAuthError {
  #[error("No JWKS keystore address specified")]
  NoKeystoreSpecified,

  #[error("Failed to load JWKS keystore from {0:?}")]
  FailedToLoadKeystore(jwks_client::error::Error),

  #[error("Bearer authentication token invalid: {0:?}")]
  InvalidBearerAuth(jwks_client::error::Error),

  #[error("Access to this resource is not authorised")]
  Unauthorised
}

// Code ======================================================================
impl JwtAuth
{
  /**
   * Create a new instance of JwtAuth.  The URL for the keystore must be
   * provided in the environment variable `JWKS_URL` at runtime.
   *
   * A validator function of type `JwtValidator` must be provided.  For every
   * request, this will be called with the request and token information, and
   * the function will determine whether the request should be processed
   * (`true`) or not (`false`).
   */
  pub fn new_from_env(validator: JwtValidator) -> Result<Self,JwtAuthError> {
    let jwks_url = env::var("JWKS_URL")?;

    JwtAuth::new_from_url(validator, jwks_url)
  }

  /**
   * Create a new instance of JwtAuth.  The keystore for validating token
   * signatures will be downloaded from the given `jwks_url`.
   *
   * A validator function of type `JwtValidator` must be provided.  For every
   * request, this will be called with the request and token information, and
   * the function will determine whether the request should be processed
   * (`true`) or not (`false`).
   */
  pub fn new_from_url(validator: JwtValidator, jwks_url: String) -> Result<Self,JwtAuthError> {

    // Even though we don't use it now, I want to fail-fast, so I check now
    // if I can download the keystore
    let _jwks = KeyStore::new_from(&jwks_url)?;

    Ok(JwtAuth {
      jwks_url,
      validator: Rc::new(validator)
    })
  }
}

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

  fn new_transform(&self, service: S) -> Self::Future {
    let jwks_url = self.jwks_url.clone();

    ready(match KeyStore::new_from(&jwks_url) {
      Ok(jwks) => {
        Ok(JwtAuthService {
          service,
          jwks,
          validator: self.validator.clone()
        })
      }
      Err(e) => {
        log::error!("Cannot load JWKS keystore from {}: {:?}", jwks_url, e);
        Err(())
      }
    })


  }
}

impl <S, B> Service<ServiceRequest> for JwtAuthService<S>
where
  S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
  S::Future: 'static,
  B: MessageBody,
  B: 'static
{
  type Response = S::Response;
  type Error = S::Error;
  type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

  fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
    self.service.poll_ready(ctx)
  }

  fn call(&self, req: ServiceRequest) -> Self::Future {
    let authorization = req.headers().get(actix_web::http::header::AUTHORIZATION);

    let jwt = {
      match authorization {
        Some(value) => {

          let value_str = value.to_str().unwrap().to_string();

          match value_str.strip_prefix("Bearer ") {
            Some(token) => {
              match self.jwks.verify(&token) {
                Ok(jwt) => {
                  Some(jwt)
                }
                Err(e) => {
                  return Box::pin(ready(Err(JwtAuthError::InvalidBearerAuth(e).into())))
                }
              }
            }
            _ => {
              None
            }
          }
        },
        None => {
          None
        }
      }
    };

    // OK, if we got this far, we have a possibly validated JWT (or None in
    // its stead, if it wasn't present or didn't validate)
    if (self.validator)(&req, &jwt) {
      let fut = self.service.call(req);
      Box::pin(async move {
        let res = fut.await?;

        Ok(res)
      })
    } else {
      Box::pin(ready(Err(JwtAuthError::Unauthorised.into())))
    }
  }
}


impl From<jwks_client::error::Error> for JwtAuthError {
  fn from(e: jwks_client::error::Error) -> Self {
    JwtAuthError::FailedToLoadKeystore(e)
  }
}

impl From<VarError> for JwtAuthError {
  fn from(_: VarError) -> Self {
    JwtAuthError::NoKeystoreSpecified
  }
}

impl ResponseError for JwtAuthError {
  fn status_code(&self) -> StatusCode {
    match self {
      JwtAuthError::NoKeystoreSpecified => StatusCode::INTERNAL_SERVER_ERROR,
      JwtAuthError::FailedToLoadKeystore(_) => StatusCode::INTERNAL_SERVER_ERROR,
      JwtAuthError::InvalidBearerAuth(_) => StatusCode::UNAUTHORIZED,
      JwtAuthError::Unauthorised => StatusCode::UNAUTHORIZED
    }
  }
}

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

  const TEST_KEYSET: &str = "https://snowgoons.eu.auth0.com/.well-known/jwks.json";

  #[actix_rt::test]
  async fn test_jwks_url() {
    let _middleware = JwtAuth::new_from_url(CheckJwtValid, String::from(TEST_KEYSET)).unwrap();
  }

  #[actix_rt::test]
  #[should_panic]
  async fn test_jwks_url_fail() {
    let _middleware = JwtAuth::new_from_url(CheckJwtValid, String::from("https://not.here/")).unwrap();
  }

  #[actix_rt::test]
  async fn test_jwks_env() {
    env::set_var("JWKS_URL", String::from(TEST_KEYSET));

    let _middleware = JwtAuth::new_from_env(CheckJwtValid).unwrap();
  }

  #[actix_rt::test]
  #[should_panic]
  async fn test_jwks_env_fail() {
    env::remove_var("JWKS_URL");

    let _middleware = JwtAuth::new_from_env(CheckJwtValid).unwrap();
  }
}