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
mod error;

use crypto::digest::Digest;
use crypto::hmac::Hmac;
use crypto::mac::Mac;
use crypto::sha2::Sha256;
use serde::{Deserialize, Serialize};
use serde_json as json;
use std::fmt::Display;
use std::str::FromStr;

pub use error::Error;

pub type Result<T, E = error::Error> = std::result::Result<T, E>;

/// Decode base64 into a string.
///
/// Useful for converting incoming base64 tokens to json before deserializing. It is now necessary
/// to do this, as far as I can tell, because serde now supports deserializing to a struct that
/// only borrows the data it represents instead of owning it.
pub fn decode_base64(s: &str) -> Option<String> {
    let start_idx = match s.find('.').map(|idx| idx + 1) {
        None => return None,
        Some(idx) => idx,
    };

    let s = &s[start_idx..];
    base64::decode(s)
        .ok()
        .and_then(|bytes| String::from_utf8(bytes).ok())
}

/// Represents a web token.
///
/// For optimal usage, your payload should be any struct implementing `Serialize`, `Deserialize`,
/// and `FromStr`, but none of these are technically required.
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
pub struct Rwt<T> {
    pub payload: T,
    signature: String,
}

impl<T: Serialize> Rwt<T> {
    /// Create a web token with the provided payload.
    ///
    /// This function requires that the payload be `Serialize`.
    pub fn with_payload<S: AsRef<[u8]>>(payload: T, secret: S) -> Result<Rwt<T>> {
        let signature = derive_signature(&payload, Sha256::new(), secret.as_ref())?;
        Ok(Rwt {
            payload: payload,
            signature: signature,
        })
    }

    /// Encode the token as base64 in the usual format.
    ///
    /// In this case, "the usual format" means `xxx.xxx` where the left hand side is the token
    /// itself and the right hand side is the signature. The base64 implementation used currently
    /// introduces padding into the equation.
    pub fn encode(&self) -> Result<String> {
        let body = base64::encode(json::to_string(&self.payload)?.as_bytes());
        Ok(format!("{}.{}", body, self.signature))
    }

    /// Validate the token.
    ///
    /// This function compares the token as serialized against a freshly-derived signature to
    /// ensure that it is original and un-tampered-with. This version uses `rust-crypto` to
    /// compare the two results in order to protect against timing attacks.
    pub fn is_valid<S: AsRef<[u8]>>(&self, secret: S) -> bool {
        match derive_signature(&self.payload, Sha256::new(), secret.as_ref()) {
            Err(_) => false,
            Ok(signature) => {
                crypto::util::fixed_time_eq(self.signature.as_bytes(), signature.as_bytes())
            }
        }
    }
}

impl<T, E> FromStr for Rwt<T>
where
    E: Display,
    T: FromStr<Err = E>,
{
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        use std::str;

        let mut parts = s.split('.');
        let payload = parts
            .next()
            .ok_or_else(|| Error::Format(format!("Missing body: {:?}", s)))?;
        let signature = parts
            .next()
            .ok_or_else(|| Error::Format(format!("Missing signature: {:?}", s)))?;

        let payload = base64::decode(payload)?;
        let payload = str::from_utf8(&payload)?;
        let payload = payload
            .parse::<T>()
            .map_err(|e| Error::FromStr(format!("Unable to parse body as payload: {}", e)))?;

        Ok(Rwt {
            payload: payload,
            signature: signature.to_owned(),
        })
    }
}

fn derive_signature<D, T, S>(payload: &T, digest: D, secret: S) -> Result<String>
where
    T: Serialize,
    D: Digest,
    S: AsRef<[u8]>,
{
    let mut hmac = Hmac::new(digest, secret.as_ref());
    hmac.input(json::to_string(payload)?.as_bytes());
    Ok(base64::encode(hmac.result().code()))
}

#[cfg(test)]
mod tests {
    use super::Rwt;
    use serde::{Deserialize, Serialize};
    use serde_json;
    use std::str::FromStr;

    #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
    struct Payload {
        jti: String,
        exp: i64,
    }

    impl FromStr for Payload {
        type Err = &'static str;

        fn from_str(s: &str) -> Result<Self, Self::Err> {
            serde_json::from_str(s).map_err(|_| "Sorry, Charlie.")
        }
    }

    #[test]
    fn create_rwt_with_payload() {
        create_rwt();
    }

    #[test]
    fn validate_rwt() {
        let rwt = create_rwt();
        assert!(rwt.is_valid("secret"));
    }

    #[test]
    fn invalidate_rwt() {
        let rwt = create_rwt();
        assert!(!rwt.is_valid("other secret"));
    }

    #[test]
    fn serialize_rwt() {
        let rwt = create_rwt();
        assert_eq!(
            "eyJqdGkiOiJ0aGlzIG9uZSIsImV4cCI6MTN9.\
                    Ir9W3KCkyGNmsPFURs4Sj7aQSkuvcqpQ7kTk4F6wCyU=",
            rwt.encode().unwrap()
        );
    }

    #[test]
    fn deserialize_rwt() {
        let rwt = create_rwt().encode().unwrap();
        let rwt = rwt.parse::<Rwt<Payload>>().unwrap();
        assert_eq!(rwt, create_rwt());
    }

    fn create_rwt() -> Rwt<Payload> {
        Rwt::with_payload(
            Payload {
                jti: "this one".to_owned(),
                exp: 13,
            },
            "secret",
        )
        .unwrap()
    }
}