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
//! # For Auth0 settings
//!
//! ```no_run
//! use suzume::{verify, Auth0Header, Auth0Payload, Auth0Fetcher, Auth0JwksFetcher};
//!
//! struct ReqwestFetcher;
//!
//! impl Auth0JwksFetcher for ReqwestFetcher {
//!     fn fetch(self, url: String) -> Result<String, failure::Error> {
//!         Ok(reqwest::get(&url)?.text()?)
//!     }
//! }
//!
//! fn main() -> Result<(), failure::Error> {
//!     verify::<Auth0Header, Auth0Payload, _>("some.jwt.string".to_owned(), Auth0Fetcher {
//!         issuer: "your jwks issuer",
//!         jwks_fetcher: ReqwestFetcher,
//!     })?;
//!     Ok(())
//! }
//! ```
//!

use crate::{AlgorithmKind, Error, ErrorKind, HeaderItem, Jwks, PayloadItem};
use failure::Fail;
use openssl::hash::MessageDigest;
use openssl::pkey::{self, PKey};
use openssl::sign::Verifier;

/// fetch jwks.json from Auth0
pub trait Auth0JwksFetcher {
    /// fetch jwks.json from url
    fn fetch(self, url: String) -> Result<String, failure::Error>;
}

/// fetcher for auth0
pub struct Auth0Fetcher<'a, JF>
where
    JF: Auth0JwksFetcher,
{
    /// issuer
    pub issuer: &'a str,
    /// jwks fetcher
    pub jwks_fetcher: JF,
}

/// decryption key
pub struct Key {
    inner: PKey<pkey::Public>,
}

/// Auth0 jwt header
#[derive(Debug, Deserialize)]
pub struct Auth0Header {
    typ: String,
    alg: String,
    kid: String,
}

impl crate::Header for Auth0Header {
    fn get_alg(&self) -> Option<String> {
        Some(self.alg.to_string())
    }

    fn get_kid(&self) -> Option<String> {
        Some(self.kid.to_string())
    }
}

/// Auth0 jwt payload
#[derive(Debug, Deserialize)]
pub struct Auth0Payload {
    iss: String,
    sub: String,
    aud: String,
    iat: i64,
    exp: i64,
    at_hash: String,
    nonce: String,
}

impl crate::Payload for Auth0Payload {
    fn get_iss(&self) -> Option<String> {
        Some(self.iss.to_string())
    }

    fn get_exp(&self) -> Option<i64> {
        Some(self.exp)
    }

    fn is_not_before(&self) -> bool {
        false
    }
}

impl crate::Key for Key {
    fn verify(self, verify_targe: &str, signature: Vec<u8>) -> Result<bool, Error> {
        let mut verifier = Verifier::new(MessageDigest::sha256(), &self.inner)?;
        verifier.update(verify_targe.as_bytes())?;
        Ok(verifier.verify(&signature)?)
    }
}

impl<'a, JF> crate::KeyFetcher for Auth0Fetcher<'a, JF>
where
    JF: Auth0JwksFetcher,
{
    type Key = Key;
    fn fetch<H, P>(self, header: &H, payload: &P) -> Result<Self::Key, crate::Error>
    where
        H: crate::Header,
        P: crate::Payload,
    {
        let alg = header.get_alg().ok_or(ErrorKind::NotFoundHeaderItem {
            item: HeaderItem::ALG,
        })?;

        if alg != "RS256" {
            return Err(ErrorKind::DoesNotSupportAlgorithm {
                kind: AlgorithmKind::Others,
            }
            .into());
        }

        let kid = header.get_kid().ok_or(ErrorKind::NotFoundHeaderItem {
            item: HeaderItem::KID,
        })?;

        let iss = payload.get_iss().ok_or(ErrorKind::NotFoundPayloadItem {
            item: PayloadItem::ISS,
        })?;

        if self.issuer != iss {
            return Err(ErrorKind::NotExpectedIssuer.into());
        }

        let url_path = std::path::Path::new(&iss)
            .join(".well-known")
            .join("jwks.json");
        let url = url_path.to_str().ok_or(ErrorKind::FetchFailed)?;

        let jwks = serde_json::from_str::<Jwks>(&self.jwks_fetcher.fetch(url.to_owned())?)?;
        let key_string = jwks
            .keys
            .iter()
            .find(|x| x.kid == kid)
            .ok_or(ErrorKind::FetchFailed)?
            .x5c
            .iter()
            .next()
            .ok_or(ErrorKind::FetchFailed)?;
        let key_der = base64::decode(key_string)?;
        let key = openssl::x509::X509::from_der(key_der.as_ref())?.public_key()?;
        Ok(Key { inner: key })
    }
}

impl From<openssl::error::ErrorStack> for Error {
    fn from(origin: openssl::error::ErrorStack) -> Self {
        Error::new(origin.context(ErrorKind::OpenSSLError))
    }
}