2015-10-31 11:37:15 -04:00
|
|
|
//! Create and parses JWT (JSON Web Tokens)
|
|
|
|
//!
|
|
|
|
|
|
|
|
#![cfg_attr(feature = "dev", allow(unstable_features))]
|
|
|
|
#![cfg_attr(feature = "dev", feature(plugin))]
|
|
|
|
#![cfg_attr(feature = "dev", plugin(clippy))]
|
|
|
|
|
|
|
|
extern crate rustc_serialize;
|
2015-11-01 14:32:43 -05:00
|
|
|
extern crate crypto;
|
|
|
|
|
|
|
|
use rustc_serialize::{json, Encodable, Decodable};
|
|
|
|
use rustc_serialize::base64::{self, ToBase64, FromBase64};
|
2015-11-02 17:34:20 -05:00
|
|
|
use crypto::sha2::{Sha256, Sha384, Sha512};
|
2015-11-01 14:32:43 -05:00
|
|
|
use crypto::hmac::Hmac;
|
|
|
|
use crypto::mac::Mac;
|
|
|
|
use crypto::digest::Digest;
|
2015-11-05 12:45:43 -05:00
|
|
|
use crypto::util::fixed_time_eq;
|
2015-10-31 11:37:15 -04:00
|
|
|
|
|
|
|
pub mod errors;
|
2015-11-01 14:32:43 -05:00
|
|
|
use errors::Error;
|
2015-10-31 11:37:15 -04:00
|
|
|
|
2015-11-05 14:29:42 -05:00
|
|
|
#[derive(Debug, PartialEq, Copy, Clone)]
|
2015-11-02 18:12:01 -05:00
|
|
|
/// The algorithms supported for signing/verifying
|
2015-10-31 11:37:15 -04:00
|
|
|
pub enum Algorithm {
|
2015-11-01 17:59:42 -05:00
|
|
|
HS256,
|
2015-11-02 17:34:20 -05:00
|
|
|
HS384,
|
|
|
|
HS512
|
2015-10-31 11:37:15 -04:00
|
|
|
}
|
|
|
|
|
2015-11-01 17:59:42 -05:00
|
|
|
/// A part of the JWT: header and claims specifically
|
|
|
|
/// Allows converting from/to struct with base64
|
2015-11-01 14:32:43 -05:00
|
|
|
pub trait Part {
|
2015-11-05 14:34:08 -05:00
|
|
|
type Encoded: AsRef<str>;
|
|
|
|
|
2015-11-05 11:22:04 -05:00
|
|
|
fn from_base64<B: AsRef<[u8]>>(encoded: B) -> Result<Self, Error> where Self: Sized;
|
2015-11-05 14:34:08 -05:00
|
|
|
fn to_base64(&self) -> Result<Self::Encoded, Error>;
|
2015-11-01 14:32:43 -05:00
|
|
|
}
|
2015-10-31 11:37:15 -04:00
|
|
|
|
2015-11-01 14:32:43 -05:00
|
|
|
impl<T> Part for T where T: Encodable + Decodable {
|
2015-11-05 14:34:08 -05:00
|
|
|
type Encoded = String;
|
|
|
|
|
|
|
|
fn to_base64(&self) -> Result<Self::Encoded, Error> {
|
2015-11-01 14:32:43 -05:00
|
|
|
let encoded = try!(json::encode(&self));
|
2015-11-01 17:31:46 -05:00
|
|
|
Ok(encoded.as_bytes().to_base64(base64::URL_SAFE))
|
2015-11-01 14:32:43 -05:00
|
|
|
}
|
|
|
|
|
2015-11-05 11:22:04 -05:00
|
|
|
fn from_base64<B: AsRef<[u8]>>(encoded: B) -> Result<T, Error> {
|
|
|
|
let decoded = try!(encoded.as_ref().from_base64());
|
2015-11-01 14:32:43 -05:00
|
|
|
let s = try!(String::from_utf8(decoded));
|
|
|
|
Ok(try!(json::decode(&s)))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-05 14:29:42 -05:00
|
|
|
#[derive(Debug, PartialEq)]
|
2015-11-01 17:59:42 -05:00
|
|
|
/// A basic JWT header part, the alg is automatically filled for use
|
|
|
|
/// It's missing things like the kid but that's for later
|
2015-11-01 14:32:43 -05:00
|
|
|
pub struct Header {
|
2015-11-05 14:29:42 -05:00
|
|
|
typ: &'static str,
|
2015-11-02 18:12:01 -05:00
|
|
|
alg: Algorithm,
|
2015-11-01 14:32:43 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Header {
|
2015-11-02 18:12:01 -05:00
|
|
|
pub fn new(algorithm: Algorithm) -> Header {
|
2015-11-01 14:32:43 -05:00
|
|
|
Header {
|
2015-11-05 14:29:42 -05:00
|
|
|
typ: "JWT",
|
2015-11-01 14:32:43 -05:00
|
|
|
alg: algorithm,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-05 14:29:42 -05:00
|
|
|
impl Part for Header {
|
2015-11-05 14:34:08 -05:00
|
|
|
type Encoded = &'static str;
|
|
|
|
|
2015-11-05 14:29:42 -05:00
|
|
|
fn from_base64<B: AsRef<[u8]>>(encoded: B) -> Result<Self, Error> where Self: Sized {
|
|
|
|
let algoritm = match encoded.as_ref() {
|
|
|
|
b"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" => { Algorithm::HS256 },
|
|
|
|
b"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzM4NCJ9" => { Algorithm::HS384 },
|
|
|
|
b"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9" => { Algorithm::HS512 },
|
|
|
|
_ => return Err(Error::InvalidToken)
|
|
|
|
};
|
|
|
|
|
|
|
|
Ok(Header::new(algoritm))
|
|
|
|
}
|
|
|
|
|
2015-11-05 14:34:08 -05:00
|
|
|
fn to_base64(&self) -> Result<Self::Encoded, Error> {
|
2015-11-05 14:29:42 -05:00
|
|
|
let encoded = match self.alg {
|
|
|
|
Algorithm::HS256 => { "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" },
|
|
|
|
Algorithm::HS384 => { "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzM4NCJ9" },
|
|
|
|
Algorithm::HS512 => { "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9" },
|
|
|
|
};
|
|
|
|
|
2015-11-05 14:34:08 -05:00
|
|
|
Ok(encoded)
|
2015-11-05 14:29:42 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-11-01 17:59:42 -05:00
|
|
|
/// Take the payload of a JWT and sign it using the algorithm given.
|
|
|
|
/// Returns the base64 url safe encoded of the hmac result
|
2015-11-01 14:32:43 -05:00
|
|
|
fn sign(data: &str, secret: &[u8], algorithm: Algorithm) -> String {
|
2015-11-02 17:34:20 -05:00
|
|
|
fn crypt<D: Digest>(digest: D, data: &str, secret: &[u8]) -> String {
|
|
|
|
let mut hmac = Hmac::new(digest, secret);
|
|
|
|
hmac.input(data.as_bytes());
|
|
|
|
hmac.result().code().to_base64(base64::URL_SAFE)
|
|
|
|
}
|
|
|
|
|
|
|
|
match algorithm {
|
|
|
|
Algorithm::HS256 => crypt(Sha256::new(), data, secret),
|
|
|
|
Algorithm::HS384 => crypt(Sha384::new(), data, secret),
|
|
|
|
Algorithm::HS512 => crypt(Sha512::new(), data, secret),
|
|
|
|
}
|
2015-11-01 17:31:46 -05:00
|
|
|
}
|
|
|
|
|
2015-11-01 17:59:42 -05:00
|
|
|
/// Compares the signature given with a re-computed signature
|
2015-11-01 17:31:46 -05:00
|
|
|
fn verify(signature: &str, data: &str, secret: &[u8], algorithm: Algorithm) -> bool {
|
2015-11-05 12:45:43 -05:00
|
|
|
fixed_time_eq(signature.as_ref(), sign(data, secret, algorithm).as_ref())
|
2015-11-01 14:32:43 -05:00
|
|
|
}
|
|
|
|
|
2015-11-01 17:59:42 -05:00
|
|
|
/// Encode the claims passed and sign the payload using the algorithm and the secret
|
2015-11-05 12:10:55 -05:00
|
|
|
pub fn encode<T: Part, B: AsRef<[u8]>>(claims: &T, secret: B, algorithm: Algorithm) -> Result<String, Error> {
|
2015-11-02 18:12:01 -05:00
|
|
|
let encoded_header = try!(Header::new(algorithm).to_base64());
|
2015-11-01 14:32:43 -05:00
|
|
|
let encoded_claims = try!(claims.to_base64());
|
|
|
|
// seems to be a tiny bit faster than format!("{}.{}", x, y)
|
2015-11-05 14:34:08 -05:00
|
|
|
let payload = [encoded_header, encoded_claims.as_ref()].join(".");
|
2015-11-05 12:10:55 -05:00
|
|
|
let signature = sign(&*payload, secret.as_ref(), algorithm);
|
2015-11-01 17:31:46 -05:00
|
|
|
|
|
|
|
Ok([payload, signature].join("."))
|
2015-11-01 14:32:43 -05:00
|
|
|
}
|
2015-10-31 11:37:15 -04:00
|
|
|
|
2015-11-01 17:59:42 -05:00
|
|
|
/// Decode a token into a Claims struct
|
|
|
|
/// If the token or its signature is invalid, it will return an error
|
2015-11-05 13:09:39 -05:00
|
|
|
pub fn decode<T: Part>(token: &str, secret: &str, algorithm: Algorithm) -> Result<T, Error> {
|
|
|
|
macro_rules! expect_two {
|
|
|
|
($iter:expr) => {{
|
|
|
|
let mut i = $iter; // evaluate the expr
|
|
|
|
match (i.next(), i.next(), i.next()) {
|
|
|
|
(Some(first), Some(second), None) => (first, second),
|
|
|
|
_ => return Err(Error::InvalidToken)
|
|
|
|
}
|
|
|
|
}}
|
2015-11-01 17:31:46 -05:00
|
|
|
}
|
2015-10-31 11:37:15 -04:00
|
|
|
|
2015-11-05 13:09:39 -05:00
|
|
|
let (signature, payload) = expect_two!(token.rsplitn(2, '.'));
|
|
|
|
|
2015-11-01 17:31:46 -05:00
|
|
|
let is_valid = verify(
|
2015-11-05 13:09:39 -05:00
|
|
|
signature,
|
|
|
|
payload,
|
2015-11-01 17:31:46 -05:00
|
|
|
secret.as_bytes(),
|
|
|
|
algorithm
|
|
|
|
);
|
|
|
|
|
|
|
|
if !is_valid {
|
|
|
|
return Err(Error::InvalidSignature);
|
|
|
|
}
|
|
|
|
|
2015-11-05 13:09:39 -05:00
|
|
|
let (claims, header) = expect_two!(payload.rsplitn(2, '.'));
|
|
|
|
|
|
|
|
let header = try!(Header::from_base64(header));
|
2015-11-02 18:12:01 -05:00
|
|
|
if header.alg != algorithm {
|
2015-11-02 16:22:21 -05:00
|
|
|
return Err(Error::WrongAlgorithmHeader);
|
|
|
|
}
|
2015-11-01 17:59:42 -05:00
|
|
|
|
2015-11-05 13:09:39 -05:00
|
|
|
T::from_base64(claims)
|
2015-11-01 17:31:46 -05:00
|
|
|
}
|
2015-10-31 11:37:15 -04:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2015-11-01 17:31:46 -05:00
|
|
|
use super::{encode, decode, Algorithm, Header, Part, sign, verify};
|
2015-11-01 14:32:43 -05:00
|
|
|
|
2015-11-01 17:31:46 -05:00
|
|
|
#[derive(Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
|
|
|
|
struct Claims {
|
|
|
|
sub: String,
|
|
|
|
company: String
|
|
|
|
}
|
|
|
|
|
2015-11-01 14:32:43 -05:00
|
|
|
#[test]
|
|
|
|
fn to_base64() {
|
|
|
|
let expected = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9".to_owned();
|
2015-11-02 18:12:01 -05:00
|
|
|
let result = Header::new(Algorithm::HS256).to_base64();
|
2015-11-01 14:32:43 -05:00
|
|
|
|
|
|
|
assert_eq!(expected, result.unwrap());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn from_base64() {
|
2015-11-05 11:22:04 -05:00
|
|
|
let encoded = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9";
|
2015-11-01 14:32:43 -05:00
|
|
|
let header = Header::from_base64(encoded).unwrap();
|
|
|
|
|
|
|
|
assert_eq!(header.typ, "JWT");
|
2015-11-02 18:12:01 -05:00
|
|
|
assert_eq!(header.alg, Algorithm::HS256);
|
2015-11-01 14:32:43 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2015-11-01 17:31:46 -05:00
|
|
|
fn round_trip_base64() {
|
2015-11-02 18:12:01 -05:00
|
|
|
let header = Header::new(Algorithm::HS256);
|
2015-11-01 14:32:43 -05:00
|
|
|
assert_eq!(Header::from_base64(header.to_base64().unwrap()).unwrap(), header);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn sign_hs256() {
|
2015-11-05 12:32:08 -05:00
|
|
|
let result = sign("hello world", b"secret", Algorithm::HS256);
|
2015-11-01 17:31:46 -05:00
|
|
|
let expected = "c0zGLzKEFWj0VxWuufTXiRMk5tlI5MbGDAYhzaxIYjo";
|
2015-11-01 14:32:43 -05:00
|
|
|
assert_eq!(result, expected);
|
|
|
|
}
|
|
|
|
|
2015-11-01 17:31:46 -05:00
|
|
|
#[test]
|
|
|
|
fn verify_hs256() {
|
|
|
|
let sig = "c0zGLzKEFWj0VxWuufTXiRMk5tlI5MbGDAYhzaxIYjo";
|
2015-11-05 12:32:08 -05:00
|
|
|
let valid = verify(sig, "hello world", b"secret", Algorithm::HS256);
|
|
|
|
assert!(valid);
|
2015-11-01 17:31:46 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn round_trip_claim() {
|
|
|
|
let my_claims = Claims {
|
|
|
|
sub: "b@b.com".to_owned(),
|
|
|
|
company: "ACME".to_owned()
|
|
|
|
};
|
2015-11-05 12:10:55 -05:00
|
|
|
let token = encode(&my_claims, "secret", Algorithm::HS256).unwrap();
|
2015-11-05 13:09:39 -05:00
|
|
|
let claims = decode::<Claims>(&token, "secret", Algorithm::HS256).unwrap();
|
2015-11-01 17:31:46 -05:00
|
|
|
assert_eq!(my_claims, claims);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2015-11-05 12:32:08 -05:00
|
|
|
#[should_panic(expected = "InvalidToken")]
|
2015-11-01 17:31:46 -05:00
|
|
|
fn decode_token_missing_parts() {
|
|
|
|
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
|
2015-11-05 13:09:39 -05:00
|
|
|
let claims = decode::<Claims>(token, "secret", Algorithm::HS256);
|
2015-11-05 12:32:08 -05:00
|
|
|
claims.unwrap();
|
2015-11-01 17:31:46 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2015-11-05 12:32:08 -05:00
|
|
|
#[should_panic(expected = "InvalidSignature")]
|
2015-11-01 17:31:46 -05:00
|
|
|
fn decode_token_invalid_signature() {
|
|
|
|
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJiQGIuY29tIiwiY29tcGFueSI6IkFDTUUifQ.wrong";
|
2015-11-05 13:09:39 -05:00
|
|
|
let claims = decode::<Claims>(token, "secret", Algorithm::HS256);
|
2015-11-05 12:32:08 -05:00
|
|
|
claims.unwrap();
|
2015-11-01 17:31:46 -05:00
|
|
|
}
|
2015-10-31 11:37:15 -04:00
|
|
|
}
|