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
use crate::algorithm::store::Store;
use crate::algorithm::SigningAlgorithm;
use crate::error::Error;
use crate::header::{BorrowedKeyHeader, Header, JoseHeader};
use crate::token::{Signed, Unsigned};
use crate::{ToBase64, Token, SEPARATOR};

/// Allow objects to be signed with a key.
pub trait SignWithKey<T> {
    fn sign_with_key(self, key: &dyn SigningAlgorithm) -> Result<T, Error>;
}

/// Allow objects to be signed with a store.
pub trait SignWithStore<T> {
    fn sign_with_store<S, A>(self, store: &S) -> Result<T, Error>
    where
        S: Store<Algorithm = A>,
        A: SigningAlgorithm;
}

impl<H, C> Token<H, C, Unsigned> {
    /// Create a new unsigned token, with mutable headers and claims.
    pub fn new(header: H, claims: C) -> Self {
        Token {
            header,
            claims,
            signature: Unsigned,
        }
    }

    pub fn header_mut(&mut self) -> &mut H {
        &mut self.header
    }

    pub fn claims_mut(&mut self) -> &mut C {
        &mut self.claims
    }
}

impl<H, C> Default for Token<H, C, Unsigned>
where
    H: Default,
    C: Default,
{
    fn default() -> Self {
        Token::new(H::default(), C::default())
    }
}

impl<C: ToBase64> SignWithKey<String> for C {
    fn sign_with_key(self, key: &dyn SigningAlgorithm) -> Result<String, Error> {
        let header = Header {
            algorithm: key.algorithm_type(),
            ..Default::default()
        };

        let token = Token::new(header, self).sign_with_key(key)?;
        Ok(token.signature.token_string)
    }
}

impl<'a, C: ToBase64> SignWithStore<String> for (&'a str, C) {
    fn sign_with_store<S, A>(self, store: &S) -> Result<String, Error>
    where
        S: Store<Algorithm = A>,
        A: SigningAlgorithm,
    {
        let (key_id, claims) = self;
        let key = store
            .get(key_id)
            .ok_or_else(|| Error::NoKeyWithKeyId(key_id.to_owned()))?;

        let header = BorrowedKeyHeader {
            algorithm: key.algorithm_type(),
            key_id,
        };

        let token = Token::new(header, claims).sign_with_key(key)?;
        Ok(token.signature.token_string)
    }
}

impl<H, C> SignWithKey<Token<H, C, Signed>> for Token<H, C, Unsigned>
where
    H: ToBase64 + JoseHeader,
    C: ToBase64,
{
    fn sign_with_key(self, key: &dyn SigningAlgorithm) -> Result<Token<H, C, Signed>, Error> {
        let header_algorithm = self.header.algorithm_type();
        let key_algorithm = key.algorithm_type();
        if header_algorithm != key_algorithm {
            return Err(Error::AlgorithmMismatch(header_algorithm, key_algorithm));
        }

        let header = self.header.to_base64()?;
        let claims = self.claims.to_base64()?;
        let signature = key.sign(&header, &claims)?;

        let token_string = [&*header, &*claims, &signature].join(SEPARATOR);

        Ok(Token {
            header: self.header,
            claims: self.claims,
            signature: Signed { token_string },
        })
    }
}

impl<H, C> SignWithStore<Token<H, C, Signed>> for Token<H, C, Unsigned>
where
    H: ToBase64 + JoseHeader,
    C: ToBase64,
{
    fn sign_with_store<S, A>(self, store: &S) -> Result<Token<H, C, Signed>, Error>
    where
        S: Store<Algorithm = A>,
        A: SigningAlgorithm,
    {
        let key_id = self.header.key_id().ok_or(Error::NoKeyId)?;
        let key = store
            .get(key_id)
            .ok_or_else(|| Error::NoKeyWithKeyId(key_id.to_owned()))?;
        self.sign_with_key(key)
    }
}

impl<'a, H, C> Token<H, C, Signed> {
    /// Get the string representation of the token.
    pub fn as_str(&self) -> &str {
        &self.signature.token_string
    }
}

impl<H, C> Into<String> for Token<H, C, Signed> {
    fn into(self) -> String {
        self.signature.token_string
    }
}

#[cfg(test)]
mod tests {
    use crate::algorithm::AlgorithmType;
    use crate::error::Error;
    use crate::header::Header;
    use crate::token::signed::{SignWithKey, SignWithStore};
    use crate::Token;
    use hmac::{Hmac, Mac};
    use sha2::{Sha256, Sha512};
    use std::collections::BTreeMap;

    #[derive(Serialize)]
    struct Claims<'a> {
        name: &'a str,
    }

    #[test]
    pub fn sign_claims() -> Result<(), Error> {
        let claims = Claims { name: "John Doe" };
        let key: Hmac<Sha256> = Hmac::new_varkey(b"secret")?;

        let signed_token = claims.sign_with_key(&key)?;

        assert_eq!(signed_token, "eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.LlTGHPZRXbci-y349jXXN0byQniQQqwKGybzQCFIgY0");
        Ok(())
    }

    #[test]
    pub fn sign_unsigned_with_store() -> Result<(), Error> {
        let mut key_store = BTreeMap::new();
        let key1: Hmac<Sha512> = Hmac::new_varkey(b"first")?;
        let key2: Hmac<Sha512> = Hmac::new_varkey(b"second")?;
        key_store.insert("first_key".to_owned(), key1);
        key_store.insert("second_key".to_owned(), key2);

        let header = Header {
            algorithm: AlgorithmType::Hs512,
            key_id: Some(String::from("second_key")),
            ..Default::default()
        };
        let claims = Claims { name: "Jane Doe" };
        let token = Token::new(header, claims);
        let signed_token = token.sign_with_store(&key_store)?;

        assert_eq!(signed_token.as_str(), "eyJhbGciOiJIUzUxMiIsImtpZCI6InNlY29uZF9rZXkifQ.eyJuYW1lIjoiSmFuZSBEb2UifQ.t2ON5s8DDb2hefBIWAe0jaEcp-T7b2Wevmj0kKJ8BFxKNQURHpdh4IA-wbmBmqtiCnqTGoRdqK45hhW0AOtz0A");
        Ok(())
    }
}