zino_auth/
jwt_claims.rs

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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
use jwt_simple::{
    algorithms::MACLike,
    claims::{self, Audiences, Claims, JWTClaims},
    common::VerificationOptions,
};
use serde::{de::DeserializeOwned, Serialize};
use std::time::Duration;
use zino_core::{
    application::{Agent, Application},
    crypto,
    datetime::DateTime,
    error::Error,
    extension::{JsonObjectExt, TomlTableExt},
    state::State,
    JsonValue, LazyLock, Map,
};

/// JWT Claims.
#[derive(Debug, Clone)]
pub struct JwtClaims<T = Map>(JWTClaims<T>);

impl<T: Default + Serialize + DeserializeOwned> JwtClaims<T> {
    /// Creates a new instance.
    fn constructor(subject: String, data: T, max_age: Duration) -> Self {
        let mut claims = Claims::with_custom_claims(data, max_age.into());
        claims.invalid_before = None;
        claims.subject = Some(subject);
        Self(claims)
    }

    /// Creates a new instance with the default data and `max-age`.
    #[inline]
    pub fn new(subject: impl ToString) -> Self {
        Self::constructor(subject.to_string(), T::default(), *DEFAULT_MAX_AGE)
    }

    /// Creates a new instance with the custom data.
    #[inline]
    pub fn with_data(subject: impl ToString, data: T) -> Self {
        Self::constructor(subject.to_string(), data, *DEFAULT_MAX_AGE)
    }

    /// Creates a new instance, expiring in `max-age`.
    pub fn with_max_age(subject: impl ToString, max_age: Duration) -> Self {
        Self::constructor(subject.to_string(), T::default(), max_age)
    }

    /// Generates an access token signed with the shared secret access key.
    pub fn refresh_token(&self) -> Result<String, Error> {
        let mut claims = Claims::create((*DEFAULT_REFRESH_INTERVAL).into());
        claims.invalid_before = self
            .0
            .expires_at
            .map(|max_age| max_age - (*DEFAULT_TIME_TOLERANCE).into());
        claims.subject = self.0.subject.as_ref().cloned();
        JwtClaims::shared_key()
            .authenticate(claims)
            .map_err(|err| Error::new(err.to_string()))
    }

    /// Generates an access token signed with the shared secret access key.
    #[inline]
    pub fn access_token(self) -> Result<String, Error> {
        self.sign_with(JwtClaims::shared_key())
    }

    /// Generates a signature with the secret access key.
    #[inline]
    pub fn sign_with<K: MACLike>(self, key: &K) -> Result<String, Error> {
        key.authenticate(self.0)
            .map_err(|err| Error::new(err.to_string()))
    }
}

impl<T> JwtClaims<T> {
    /// Sets the issuer.
    #[inline]
    pub fn set_issuer(&mut self, issuer: impl ToString) {
        self.0.issuer = Some(issuer.to_string());
    }

    /// Sets the audience.
    #[inline]
    pub fn set_audience(&mut self, audience: impl ToString) {
        self.0.audiences = Some(Audiences::AsString(audience.to_string()));
    }

    /// Sets the JWT identifier.
    #[inline]
    pub fn set_jwt_id(&mut self, jwt_id: impl ToString) {
        self.0.jwt_id = Some(jwt_id.to_string());
    }

    /// Sets the nonce.
    #[inline]
    pub fn set_nonce(&mut self, nonce: impl ToString) {
        self.0.nonce = Some(nonce.to_string());
    }

    /// Sets the custom data.
    #[inline]
    pub fn set_data(&mut self, data: T) {
        self.0.custom = data;
    }

    /// Returns the time the claims were created at.
    #[inline]
    pub fn issued_at(&self) -> DateTime {
        self.0
            .issued_at
            .and_then(|d| i64::try_from(d.as_micros()).ok())
            .map(DateTime::from_timestamp_micros)
            .unwrap_or_default()
    }

    /// Returns the time the claims expire at.
    #[inline]
    pub fn expires_at(&self) -> DateTime {
        self.0
            .expires_at
            .and_then(|d| i64::try_from(d.as_micros()).ok())
            .map(DateTime::from_timestamp_micros)
            .unwrap_or_default()
    }

    /// Returns the time when the claims will expire in.
    #[inline]
    pub fn expires_in(&self) -> Duration {
        self.0
            .expires_at
            .and_then(|dt| {
                dt.as_secs()
                    .checked_add_signed(-DateTime::current_timestamp())
            })
            .map(Duration::from_secs)
            .unwrap_or_default()
    }

    /// Returns the subject.
    #[inline]
    pub fn subject(&self) -> Option<&str> {
        self.0.subject.as_deref()
    }

    /// Returns the nonce.
    #[inline]
    pub fn nonce(&self) -> Option<&str> {
        self.0.nonce.as_deref()
    }

    /// Returns the custom data.
    #[inline]
    pub fn data(&self) -> &T {
        &self.0.custom
    }
}

impl JwtClaims<Map> {
    /// Adds a key-value pair to the custom data.
    #[inline]
    pub fn add_data_entry(&mut self, key: impl Into<String>, value: impl Into<JsonValue>) {
        self.0.custom.upsert(key.into(), value.into());
    }

    /// Returns the Bearer auth as a JSON object.
    pub fn bearer_auth(self) -> Result<Map, Error> {
        let mut data = Map::new();
        data.upsert("token_type", "Bearer");
        data.upsert("expires_in", self.expires_in().as_secs());
        data.upsert("access_token", self.access_token()?);
        Ok(data)
    }
}

impl JwtClaims<()> {
    /// Returns the shared secret access key for the HMAC algorithm.
    #[inline]
    pub fn shared_key() -> &'static JwtHmacKey {
        &SECRET_KEY
    }
}

impl<T> From<JWTClaims<T>> for JwtClaims<T> {
    #[inline]
    fn from(claims: JWTClaims<T>) -> Self {
        Self(claims)
    }
}

/// Returns the default time tolerance.
#[inline]
pub fn default_time_tolerance() -> Duration {
    *DEFAULT_TIME_TOLERANCE
}

/// Returns the default verfication options.
#[inline]
pub fn default_verification_options() -> VerificationOptions {
    SHARED_VERIFICATION_OPTIONS.clone()
}

/// Shared verfications options.
static SHARED_VERIFICATION_OPTIONS: LazyLock<VerificationOptions> = LazyLock::new(|| {
    if let Some(config) = State::shared().get_config("jwt") {
        VerificationOptions {
            accept_future: config.get_bool("accept-future").unwrap_or_default(),
            required_subject: config.get_str("required-subject").map(|s| s.to_owned()),
            time_tolerance: config.get_duration("time-tolerance").map(|d| d.into()),
            max_validity: config.get_duration("max-validity").map(|d| d.into()),
            max_token_length: config.get_usize("max-token-length"),
            max_header_length: config.get_usize("max-header-length"),
            ..VerificationOptions::default()
        }
    } else {
        VerificationOptions::default()
    }
});

/// Default time tolerance.
static DEFAULT_TIME_TOLERANCE: LazyLock<Duration> = LazyLock::new(|| {
    State::shared()
        .get_config("jwt")
        .and_then(|config| config.get_duration("time-tolerance"))
        .unwrap_or_else(|| Duration::from_secs(claims::DEFAULT_TIME_TOLERANCE_SECS))
});

/// Default max age for the access token.
static DEFAULT_MAX_AGE: LazyLock<Duration> = LazyLock::new(|| {
    State::shared()
        .get_config("jwt")
        .and_then(|config| config.get_duration("max-age"))
        .unwrap_or_else(|| Duration::from_secs(60 * 60 * 24))
});

/// Default refresh interval for the refresh token.
static DEFAULT_REFRESH_INTERVAL: LazyLock<Duration> = LazyLock::new(|| {
    State::shared()
        .get_config("jwt")
        .and_then(|config| config.get_duration("refresh-interval"))
        .unwrap_or_else(|| Duration::from_secs(60 * 60 * 24 * 30))
});

/// Shared secret access key for the HMAC algorithm.
static SECRET_KEY: LazyLock<JwtHmacKey> = LazyLock::new(|| {
    let app_config = State::shared().config();
    let config = app_config.get_table("jwt").unwrap_or(app_config);
    let checksum: [u8; 32] = config
        .get_str("checksum")
        .and_then(|checksum| checksum.as_bytes().try_into().ok())
        .unwrap_or_else(|| {
            let secret = config.get_str("secret").unwrap_or_else(|| {
                tracing::warn!("auto-generated `secret` is used for deriving a secret key");
                Agent::name()
            });
            crypto::digest(secret.as_bytes())
        });
    let info = config.get_str("info").unwrap_or("ZINO:JWT");
    let secret_key = crypto::derive_key(info, &checksum);
    JwtHmacKey::from_bytes(&secret_key)
});

cfg_if::cfg_if! {
    if #[cfg(feature = "crypto-sm")] {
        use hmac::{Hmac, Mac};
        use jwt_simple::{algorithms::HMACKey, common::KeyMetadata};
        use sm3::Sm3;

        /// HMAC-SM3 key type.
        #[derive(Debug, Clone)]
        pub struct HSm3Key {
            /// key.
            key: HMACKey,
            /// Key ID.
            key_id: Option<String>,
        }

        impl HSm3Key {
            /// Creates a new instance from bytes.
            pub fn from_bytes(raw_key: &[u8]) -> Self {
                Self {
                    key: HMACKey::from_bytes(raw_key),
                    key_id: None,
                }
            }

            /// Returns the bytes.
            pub fn to_bytes(&self) -> Vec<u8> {
                self.key.to_bytes()
            }

            /// Generates a new instance with random bytes.
            pub fn generate() -> Self {
                Self {
                    key: HMACKey::generate(),
                    key_id: None,
                }
            }

            /// Sets the key ID.
            pub fn with_key_id(mut self, key_id: &str) -> Self {
                self.key_id = Some(key_id.to_owned());
                self
            }
        }

        impl MACLike for HSm3Key {
            fn jwt_alg_name() -> &'static str {
                "HSM3"
            }

            fn key(&self) -> &HMACKey {
                &self.key
            }

            fn key_id(&self) -> &Option<String> {
                &self.key_id
            }

            fn set_key_id(&mut self, key_id: String) {
                self.key_id = Some(key_id);
            }

            fn metadata(&self) -> &Option<KeyMetadata> {
                &None
            }

            fn attach_metadata(&mut self, _metadata: KeyMetadata) -> Result<(), jwt_simple::Error> {
                Ok(())
            }

            fn authentication_tag(&self, authenticated: &str) -> Vec<u8> {
                let mut mac = Hmac::<Sm3>::new_from_slice(self.key().as_ref())
                    .expect("HMAC can take key of any size");
                mac.update(authenticated.as_bytes());
                mac.finalize().into_bytes().to_vec()
            }
        }

        /// HMAC key type for JWT.
        pub type JwtHmacKey = HSm3Key;
    } else {
        /// HMAC key type for JWT.
        pub type JwtHmacKey = jwt_simple::algorithms::HS256Key;
    }
}