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
use crate::auth::OAuthReq;
use crate::oautherror::OAuthError;
use graph_error::GraphFailure;
use serde_json::Map;
use serde_json::Value;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::str::FromStr;

/// Enum for the type of JSON web token (JWT).
#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub enum JwtType {
    JWS,
    JWE,
}

impl AsRef<str> for JwtType {
    fn as_ref(&self) -> &str {
        match self {
            JwtType::JWE => "JWE",
            JwtType::JWS => "JWS",
        }
    }
}

impl TryFrom<usize> for JwtType {
    type Error = GraphFailure;

    fn try_from(value: usize) -> Result<Self, Self::Error> {
        match value {
            2 => Ok(JwtType::JWS),
            4 => Ok(JwtType::JWE),
            _ => OAuthError::invalid_data("Invalid Key"),
        }
    }
}

impl FromStr for JwtType {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "payload" => Ok(JwtType::JWS),
            "ciphertext" => Ok(JwtType::JWE),
            _ => Err(()),
        }
    }
}

/// Claims in a JSON web token (JWT).
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub struct Claim {
    key: String,
    value: Value,
}

impl Claim {
    pub fn new(key: String, value: Value) -> Claim {
        Claim { key, value }
    }

    pub fn key(&self) -> String {
        self.key.clone()
    }

    pub fn value(&self) -> Value {
        self.value.clone()
    }
}

impl Eq for Claim {}

/// Algorithms used in JSON web tokens (JWT).
/// Does not implement a complete set of Algorithms used in JWTs.
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Serialize, Deserialize, EnumIter)]
pub enum Algorithm {
    HS256,
    HS384,
    HS512,
    RS256,
    RS384,
    RS512,
    ES256,
    ES384,
    ES512,
    PS256,
    PS384,
}

impl FromStr for Algorithm {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "HS256" => Ok(Algorithm::HS256),
            "HS384" => Ok(Algorithm::HS384),
            "HS512" => Ok(Algorithm::HS512),
            "RS256" => Ok(Algorithm::RS256),
            "RS384" => Ok(Algorithm::RS384),
            "RS512" => Ok(Algorithm::RS512),
            "ES256" => Ok(Algorithm::ES256),
            "ES384" => Ok(Algorithm::ES384),
            "ES512" => Ok(Algorithm::ES512),
            "PS256" => Ok(Algorithm::PS256),
            "PS384" => Ok(Algorithm::PS384),
            _ => Err(()),
        }
    }
}

#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct Header {
    typ: Option<String>,
    alg: Algorithm,
}

impl Header {
    pub fn typ(&self) -> Option<String> {
        self.typ.clone()
    }

    pub fn alg(&self) -> Algorithm {
        self.alg
    }
}

#[derive(Debug, Default, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct JsonWebToken {
    jwt_type: Option<JwtType>,
    header: Option<Header>,
    payload: Option<Vec<Claim>>,
    signature: Option<String>,
}

impl JsonWebToken {
    pub fn header(&self) -> Option<Header> {
        self.header.clone()
    }

    pub fn claims(&self) -> Option<Vec<Claim>> {
        self.payload.clone()
    }

    pub fn signature(&self) -> Option<&String> {
        self.signature.as_ref()
    }
}

/// TODO(#4): JWT Validation - https://github.com/sreeise/rust-onedrive/issues/4
///
/// JSON web token (JWT) verification for RFC 7619
///
/// The JWT implementation does not implement full JWT verification.
/// The validation here is best effort to follow section 7.2 of RFC 7519 for
/// JWT validation: https://tools.ietf.org/html/rfc7519#section-7.2
///
/// Callers should not rely on this alone to verify JWTs
pub struct JwtParser;

impl JwtParser {
    pub fn parse(input: &str) -> OAuthReq<JsonWebToken> {
        // Step 1.
        if !input.contains('.') {
            return OAuthError::invalid_data("Invalid Key");
        }

        // Step 2.
        let index = input
            .find('.')
            .ok_or_else(|| OAuthError::invalid("Invalid Key"))?;

        // Step 3.
        let header = base64::decode_config(&input[..index], base64::URL_SAFE_NO_PAD)?;
        for byte in header.iter() {
            let b = *byte;
            if b == b'\n' || b == b' ' {
                return OAuthError::invalid_data("Invalid Key");
            }
        }

        // Step 4.
        let utf8_header = std::str::from_utf8(&header)?;

        // Step 5.
        let value = utf8_header.to_owned();
        let jwt_header: Header = serde_json::from_str(&value)?;

        let mut jwt = JsonWebToken {
            header: Some(jwt_header),
            ..Default::default()
        };

        // Step 6
        let count: usize = input.matches('.').count();
        let jwt_type = JwtType::try_from(count)?;

        jwt.jwt_type = Some(jwt_type);

        // Step 7.
        match jwt_type {
            JwtType::JWS => {}
            JwtType::JWE => {}
        }

        // Step 8.
        let mut claims: Vec<Claim> = Vec::new();
        let key_vec: Vec<&str> = input.split('.').collect();
        let payload = key_vec.get(1);

        if let Some(p) = payload {
            let t = base64::decode(&**p)?;
            let v_utf8 = std::str::from_utf8(&t)?;
            let v_owned = v_utf8.to_owned();

            let claims_map: Map<String, Value> = serde_json::from_str(&v_owned)?;

            claims = claims_map
                .iter()
                .map(|(key, value)| Claim {
                    key: key.to_owned(),
                    value: value.to_owned(),
                })
                .collect();
        };

        if let Some(c) = claims.iter().find(|v| v.key == "cty") {
            let cty = c
                .value
                .as_str()
                .ok_or_else(|| OAuthError::invalid("Invalid Key"))?;
            if cty.eq("JWT") {
                return JwtParser::parse(cty);
            }
        } else {
            // Step 9.
        }
        // Step 10.

        jwt.payload = Some(claims);
        Ok(jwt)
    }

    #[allow(dead_code)]
    fn contains_duplicates(&mut self, claims: Vec<Claim>) -> OAuthReq<()> {
        // https://tools.ietf.org/html/rfc7515#section-5.2
        // Step 4  this restriction includes that the same
        // Header Parameter name also MUST NOT occur in distinct JSON object
        // values that together comprise the JOSE Header.
        let mut set = HashMap::new();
        for claim in claims.iter() {
            if set.contains_key(&claim.key) {
                return OAuthError::invalid_data("Duplicate claims");
            }
            set.insert(&claim.key, &claim.value);
        }
        Ok(())
    }
}