rskit-auth 0.2.0-alpha.1

JWT, OIDC, password hashing, and request-context auth helpers
Documentation
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use std::{fmt, time::Duration};

use rskit_util::SecretString;
use serde::Deserialize;

/// Public JWT algorithm policy for rskit.
#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[non_exhaustive]
pub enum JwtAlgorithm {
    /// HMAC-SHA256 for explicitly internal symmetric deployments only.
    Hs256Internal,
    /// RSA-SHA256 — preferred public-key default.
    Rs256,
    /// ECDSA P-256 / SHA-256.
    Es256,
    /// Ed25519 / `EdDSA`.
    EdDsa,
}

impl JwtAlgorithm {
    /// Return the `jsonwebtoken` algorithm for this policy entry.
    #[must_use]
    pub const fn as_jsonwebtoken(self) -> jsonwebtoken::Algorithm {
        match self {
            Self::Hs256Internal => jsonwebtoken::Algorithm::HS256,
            Self::Rs256 => jsonwebtoken::Algorithm::RS256,
            Self::Es256 => jsonwebtoken::Algorithm::ES256,
            Self::EdDsa => jsonwebtoken::Algorithm::EdDSA,
        }
    }

    /// True when the algorithm uses a symmetric shared secret.
    #[must_use]
    pub const fn is_symmetric(self) -> bool {
        matches!(self, Self::Hs256Internal)
    }
}

/// Asymmetric signing algorithm.
#[derive(Clone, Copy, PartialEq, Eq, Deserialize)]
#[non_exhaustive]
pub enum AsymmetricAlgorithm {
    /// RSA-SHA256.
    #[serde(rename = "RS256")]
    Rs256,
    /// ECDSA P-256 / SHA-256.
    #[serde(rename = "ES256")]
    Es256,
    /// Ed25519 / `EdDSA`.
    #[serde(rename = "EDDSA")]
    EdDsa,
}

impl AsymmetricAlgorithm {
    /// Map to the public-facing [`JwtAlgorithm`].
    #[must_use]
    pub const fn as_jwt_algorithm(self) -> JwtAlgorithm {
        match self {
            Self::Rs256 => JwtAlgorithm::Rs256,
            Self::Es256 => JwtAlgorithm::Es256,
            Self::EdDsa => JwtAlgorithm::EdDsa,
        }
    }
}

impl fmt::Debug for AsymmetricAlgorithm {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Rs256 => f.write_str("RS256"),
            Self::Es256 => f.write_str("ES256"),
            Self::EdDsa => f.write_str("EdDSA"),
        }
    }
}

// Algorithm identifier is not secret — no-op zeroize.
impl zeroize::Zeroize for AsymmetricAlgorithm {
    fn zeroize(&mut self) {}
}

/// PEM key pair for asymmetric algorithms.
#[derive(Clone, Deserialize, zeroize::Zeroize, zeroize::ZeroizeOnDrop)]
pub struct KeyPair {
    /// PKCS#8 (or PKCS#1 for RSA) private key PEM.
    pub private_key_pem: SecretString,
    /// `SubjectPublicKeyInfo` public key PEM.
    pub public_key_pem: SecretString,
}

impl fmt::Debug for KeyPair {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("KeyPair")
            .field("private_key_pem", &self.private_key_pem)
            .field("public_key_pem", &self.public_key_pem)
            .finish()
    }
}

/// Key material used to sign and verify JWTs.
#[derive(Clone, Deserialize, zeroize::Zeroize, zeroize::ZeroizeOnDrop)]
#[non_exhaustive]
pub enum JwtKeyMaterial {
    /// Explicit internal-only HMAC secret.
    Hs256Internal {
        /// Shared secret used for signing and verification.
        secret: SecretString,
    },
    /// Asymmetric PEM key pair (RS256, ES256, or `EdDSA`).
    Asymmetric {
        /// Which asymmetric algorithm this key pair is for.
        algorithm: AsymmetricAlgorithm,
        /// The PEM key pair.
        #[serde(flatten)]
        keys: KeyPair,
    },
}

impl JwtKeyMaterial {
    /// Return the algorithm implied by the key material.
    #[must_use]
    pub const fn algorithm(&self) -> JwtAlgorithm {
        match self {
            Self::Hs256Internal { .. } => JwtAlgorithm::Hs256Internal,
            Self::Asymmetric { algorithm, .. } => algorithm.as_jwt_algorithm(),
        }
    }
}

impl fmt::Debug for JwtKeyMaterial {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Hs256Internal { secret } => f
                .debug_struct("Hs256Internal")
                .field("secret", secret)
                .finish(),
            Self::Asymmetric { algorithm, keys } => f
                .debug_struct("Asymmetric")
                .field("algorithm", algorithm)
                .field("keys", keys)
                .finish(),
        }
    }
}

/// JWT validation policy.
#[derive(Clone, Deserialize)]
pub struct JwtConfig {
    /// Signing and verification key material.
    pub key_material: JwtKeyMaterial,
    /// Expected issuer claim.
    pub issuer: String,
    /// Accepted audience claims.
    pub audience: Vec<String>,
    /// Token time-to-live. Generation helpers may use this value.
    #[serde(default = "JwtConfig::default_ttl")]
    pub ttl: Duration,
    /// Clock-skew tolerance. Defaults to 30 seconds and must not exceed 60 seconds.
    #[serde(default = "JwtConfig::default_leeway")]
    pub leeway: Duration,
}

impl JwtConfig {
    const fn default_ttl() -> Duration {
        Duration::from_hours(1)
    }

    const fn default_leeway() -> Duration {
        Duration::from_secs(30)
    }

    /// Create an asymmetric key configuration.
    #[must_use]
    pub fn asymmetric(
        algorithm: AsymmetricAlgorithm,
        private_key_pem: impl Into<String>,
        public_key_pem: impl Into<String>,
        issuer: impl Into<String>,
        audience: Vec<String>,
    ) -> Self {
        Self {
            key_material: JwtKeyMaterial::Asymmetric {
                algorithm,
                keys: KeyPair {
                    private_key_pem: SecretString::new(private_key_pem),
                    public_key_pem: SecretString::new(public_key_pem),
                },
            },
            issuer: issuer.into(),
            audience,
            ttl: Self::default_ttl(),
            leeway: Self::default_leeway(),
        }
    }

    /// Create an explicit internal-only HS256 configuration.
    #[must_use]
    pub fn hs256_internal(
        secret: impl Into<String>,
        issuer: impl Into<String>,
        audience: Vec<String>,
    ) -> Self {
        Self {
            key_material: JwtKeyMaterial::Hs256Internal {
                secret: SecretString::new(secret),
            },
            issuer: issuer.into(),
            audience,
            ttl: Self::default_ttl(),
            leeway: Self::default_leeway(),
        }
    }

    /// Create an RS256 configuration from PEM-encoded keys.
    #[must_use]
    pub fn rs256(
        private_key_pem: impl Into<String>,
        public_key_pem: impl Into<String>,
        issuer: impl Into<String>,
        audience: Vec<String>,
    ) -> Self {
        Self::asymmetric(
            AsymmetricAlgorithm::Rs256,
            private_key_pem,
            public_key_pem,
            issuer,
            audience,
        )
    }

    /// Create an ES256 configuration from PEM-encoded keys.
    #[must_use]
    pub fn es256(
        private_key_pem: impl Into<String>,
        public_key_pem: impl Into<String>,
        issuer: impl Into<String>,
        audience: Vec<String>,
    ) -> Self {
        Self::asymmetric(
            AsymmetricAlgorithm::Es256,
            private_key_pem,
            public_key_pem,
            issuer,
            audience,
        )
    }

    /// Create an `EdDSA` configuration from PEM-encoded keys.
    #[must_use]
    pub fn eddsa(
        private_key_pem: impl Into<String>,
        public_key_pem: impl Into<String>,
        issuer: impl Into<String>,
        audience: Vec<String>,
    ) -> Self {
        Self::asymmetric(
            AsymmetricAlgorithm::EdDsa,
            private_key_pem,
            public_key_pem,
            issuer,
            audience,
        )
    }

    /// Override the configured token TTL.
    #[must_use]
    pub const fn with_ttl(mut self, ttl: Duration) -> Self {
        self.ttl = ttl;
        self
    }

    /// Override clock skew tolerance.
    #[must_use]
    pub const fn with_leeway(mut self, leeway: Duration) -> Self {
        self.leeway = leeway;
        self
    }

    /// Return the effective JWT algorithm.
    #[must_use]
    pub const fn algorithm(&self) -> JwtAlgorithm {
        self.key_material.algorithm()
    }
}

impl fmt::Debug for JwtConfig {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("JwtConfig")
            .field("key_material", &self.key_material)
            .field("issuer", &self.issuer)
            .field("audience", &self.audience)
            .field("ttl", &self.ttl)
            .field("leeway", &self.leeway)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn jwt_key_material_debug_redacts_secret_values() {
        let symmetric = format!(
            "{:?}",
            JwtKeyMaterial::Hs256Internal {
                secret: SecretString::new("super-secret-value"),
            }
        );
        assert!(symmetric.contains("***"));
        assert!(!symmetric.contains("super-secret-value"));

        let asymmetric = format!(
            "{:?}",
            JwtKeyMaterial::Asymmetric {
                algorithm: AsymmetricAlgorithm::Rs256,
                keys: KeyPair {
                    private_key_pem: SecretString::new("private-pem"),
                    public_key_pem: SecretString::new("public-pem"),
                },
            }
        );
        assert!(asymmetric.contains("***"));
        assert!(asymmetric.contains("RS256"));
        assert!(!asymmetric.contains("private-pem"));
        assert!(!asymmetric.contains("public-pem"));
    }

    #[test]
    fn jwt_algorithm_policy_identifies_symmetric_internal_mode() {
        assert!(JwtAlgorithm::Hs256Internal.is_symmetric());
        assert!(!JwtAlgorithm::Rs256.is_symmetric());
        assert!(!JwtAlgorithm::Es256.is_symmetric());
        assert!(!JwtAlgorithm::EdDsa.is_symmetric());
    }

    #[test]
    fn jwt_config_builders_preserve_ttl_and_leeway_overrides() {
        let config = JwtConfig::hs256_internal(
            "secret-material-that-is-long-enough",
            "https://issuer.example",
            vec!["audience".into()],
        )
        .with_ttl(Duration::from_mins(5))
        .with_leeway(Duration::from_secs(10));

        assert_eq!(config.ttl, Duration::from_mins(5));
        assert_eq!(config.leeway, Duration::from_secs(10));
    }

    #[test]
    fn jwt_config_debug_redacts_nested_key_material() {
        let config = JwtConfig::hs256_internal(
            "another-secret-value",
            "issuer.example",
            vec!["audience".into()],
        );

        let formatted = format!("{config:?}");

        assert!(formatted.contains("***"));
        assert!(!formatted.contains("another-secret-value"));
        assert!(formatted.contains("issuer.example"));
    }

    #[test]
    fn convenience_constructors_delegate_to_asymmetric() {
        let rs = JwtConfig::rs256("priv", "pub", "iss", vec!["aud".into()]);
        assert_eq!(rs.algorithm(), JwtAlgorithm::Rs256);

        let es = JwtConfig::es256("priv", "pub", "iss", vec!["aud".into()]);
        assert_eq!(es.algorithm(), JwtAlgorithm::Es256);

        let ed = JwtConfig::eddsa("priv", "pub", "iss", vec!["aud".into()]);
        assert_eq!(ed.algorithm(), JwtAlgorithm::EdDsa);
    }

    #[test]
    fn asymmetric_algorithm_roundtrip_serde() {
        let json = r#""RS256""#;
        let alg: AsymmetricAlgorithm = serde_json::from_str(json).unwrap();
        assert_eq!(alg, AsymmetricAlgorithm::Rs256);

        let json = r#""EDDSA""#;
        let alg: AsymmetricAlgorithm = serde_json::from_str(json).unwrap();
        assert_eq!(alg, AsymmetricAlgorithm::EdDsa);
    }

    #[test]
    fn key_material_serde_symmetric() {
        let json = r#"{"Hs256Internal": {"secret": "my-secret"}}"#;
        let mat: JwtKeyMaterial = serde_json::from_str(json).unwrap();
        assert_eq!(mat.algorithm(), JwtAlgorithm::Hs256Internal);
    }

    #[test]
    fn key_material_serde_asymmetric() {
        let json = r#"{"Asymmetric": {"algorithm": "RS256", "private_key_pem": "priv", "public_key_pem": "pub"}}"#;
        let mat: JwtKeyMaterial = serde_json::from_str(json).unwrap();
        assert_eq!(mat.algorithm(), JwtAlgorithm::Rs256);
    }
}