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
use crate::{Error, error::{JWTError,ConstructionError}, sign_algorithms::HS256, jwt_session::JWTSession, JWT};

use chrono::{NaiveDateTime, DateTime, Utc};
use std::collections::HashMap;
use cataclysm::{session::{SessionCreator, Session}, http::Request};

#[derive(Clone)]
/// Implementation of HS256 session, or symmetric session (the most common at least)
pub struct JWTHS256Session {
    pub aud: String,
    pub iss: String,
    pub verification_key: HS256
}

impl JWTHS256Session {

    /// Simple builder function
    pub fn builder() -> JWTHS256Builder {
        JWTHS256Builder::default()
    }

}

impl SessionCreator for JWTHS256Session {

    fn apply(&self, _values: &HashMap<String, String>, res: cataclysm::http::Response) -> cataclysm::http::Response {
        res
    }

    fn create(&self, req: &cataclysm::http::Request) -> Result<cataclysm::session::Session, cataclysm::Error> {
        match self.build_from_req(req) {
            Ok(payload) => {
                return Ok(Session::new_with_values(self.clone(),payload))
            },
            Err(_) => {
                return Err(cataclysm::Error::Custom(format!("Unable to create session!!")));
            }
        }
    }

}

impl JWTSession for JWTHS256Session {

    fn build_from_req(&self, req: &Request) -> Result<HashMap<String,String>, Error> {
        
        let jwt = Self::obtain_token_from_req(req)?;

        self.initial_validation(&jwt)?;

        return Ok(jwt.payload)


    }

    fn initial_validation(&self, jwt: &JWT) -> Result<(),Error> {

        // Check the algorithm on jwt is the same as the one in the key
        match jwt.header.get("alg") {
            Some(a) => {
                if a.to_lowercase().as_str() != self.verification_key.to_string() {
                    return Err(Error::JWT(JWTError::WrongAlgorithm));
                }
            },
            None => {
                return Err(Error::JWT(JWTError::NoAlgorithm));
            }
        };

        #[cfg(not(feature = "lax-security"))]
        {
            // Check the audience
            match jwt.payload.get("aud") {
                Some(a) => {
                    if a.as_str() != &self.aud {
                        return Err(Error::JWT(JWTError::WrongAudience));
                    }
                },
                None => {
                    return Err(Error::JWT(JWTError::NoAudience))
                }
            }

            // Check the issuer
            match jwt.payload.get("iss") {
                Some(i) => {
                    if i.as_str() != &self.iss {
                        return Err(Error::JWT(JWTError::WrongIss));
                    }
                },
                None => {
                    return Err(Error::JWT(JWTError::NoIss))
                }
            }

            // Check the expiration time
            match jwt.payload.get("exp") {
                Some(e) => {
                    let num_e = str::parse::<i64>(e)?;
                    let date = NaiveDateTime::from_timestamp_opt(num_e,0).ok_or(Error::ParseTimestamp)?;
                    let date_utc: DateTime<Utc> = DateTime::from_utc(date, Utc);
                    let now = Utc::now();

                    if date_utc < now {
                        return Err(Error::JWT(JWTError::Expired));
                    }
                },
                None => {
                    return Err(Error::JWT(JWTError::NoExp))
                }
            }
            
            // Check the iat
            match jwt.payload.get("iat") {
                Some(ia) => {
                    let num_ia = str::parse::<i64>(ia)?;
                    let date = NaiveDateTime::from_timestamp_opt(num_ia,0).ok_or(Error::ParseTimestamp)?;
                    let date_utc: DateTime<Utc> = DateTime::from_utc(date, Utc);
                    let now = Utc::now();

                    if date_utc > now {
                        return Err(Error::JWT(JWTError::ToBeValid));
                    }
                },
                None => {
                    return Err(Error::JWT(JWTError::NoIat))
                }
            }

            match jwt.payload.get("nbf") {
                Some(nb) => {
                    let num_nb = str::parse::<i64>(nb)?;
                    let date = NaiveDateTime::from_timestamp_opt(num_nb,0).ok_or(Error::ParseTimestamp)?;
                    let date_utc: DateTime<Utc> = DateTime::from_utc(date, Utc);
                    let now = Utc::now();

                    if date_utc > now {
                        return Err(Error::JWT(JWTError::ToBeValid));
                    }
                },
                None => {
                    return Err(Error::JWT(JWTError::NoNbf))
                }
            }
            
        }

        self.verification_key.verify_jwt(&jwt.raw_jwt)

    }

}

#[derive(Default)]
/// Simple builder for HS256 session
pub struct JWTHS256Builder {
    aud: Option<String>,
    iss: Option<String>,
    verification_key: Option<HS256>
}

impl JWTHS256Builder {
    
    /// Get audience
    pub fn aud<A: AsRef<str>>(self, aud: A) -> Self {
        Self {
            aud: Some(aud.as_ref().to_string()),
            ..self
        }
    }

    /// Get issuer
    pub fn iss<A: AsRef<str>>(self, iss: A) -> Self {
        Self {
            iss: Some(iss.as_ref().to_string()),
            ..self
        }
    }

    /// Create HS256 key from shared secret
    pub fn add_from_secret<A: AsRef<str>>(self, secret: A) -> Self {
        
        let verification_key = HS256::new(secret);

        Self {
            verification_key: Some(verification_key),
            ..self
        }

    }

    /// Simple builder
    pub fn build(self) -> Result<JWTHS256Session, Error> {
        
        let aud = match self.aud {
            Some(a) => a,
            None => {
                return Err(Error::Construction(ConstructionError::Aud));
            }
        };

        let iss = match self.iss {
            Some(i) => i,
            None => {
                return Err(Error::Construction(ConstructionError::Iss));
            }
        };

        let verification_key = match self.verification_key {
            Some(k) => k,
            None => {
                return Err(Error::Construction(ConstructionError::Keys))
            }
        };
        
        Ok(JWTHS256Session {
            aud,
            iss,
            verification_key,
        })
    }
}