auths-oidc-port 0.1.13

OIDC port abstractions for Auths identity system
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
404
405
406
407
408
409
410
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::error::OidcError;

/// A JSON Web Signature algorithm accepted for token verification. Only asymmetric algorithms are
/// representable: there is deliberately no `none` variant (which would accept an unsigned token) and
/// no symmetric `HS*` variant (which a public-key verifier can be tricked into using as an HMAC key).
/// An algorithm allowlist therefore cannot be configured to permit either.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum JwsAlg {
    #[serde(rename = "RS256")]
    Rs256,
    #[serde(rename = "RS384")]
    Rs384,
    #[serde(rename = "RS512")]
    Rs512,
    #[serde(rename = "ES256")]
    Es256,
    #[serde(rename = "ES384")]
    Es384,
    #[serde(rename = "ES512")]
    Es512,
    #[serde(rename = "PS256")]
    Ps256,
    #[serde(rename = "PS384")]
    Ps384,
    #[serde(rename = "PS512")]
    Ps512,
}

/// A JWS algorithm name that is not an accepted asymmetric algorithm.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("unsupported or unsafe JWS algorithm: {0:?}")]
pub struct UnsupportedJwsAlg(pub String);

impl JwsAlg {
    /// Parse a JWS algorithm name (e.g. `"RS256"`). The match is exact and case-sensitive, so
    /// `"none"`, a symmetric `HS*` name, an unknown name, or a case variant is refused.
    ///
    /// Args:
    /// * `name`: the algorithm name from a JWT header or an allowlist entry.
    ///
    /// Usage:
    /// ```
    /// use auths_oidc_port::JwsAlg;
    /// assert_eq!(JwsAlg::parse("RS256").unwrap(), JwsAlg::Rs256);
    /// assert!(JwsAlg::parse("none").is_err());
    /// ```
    pub fn parse(name: &str) -> Result<JwsAlg, UnsupportedJwsAlg> {
        match name {
            "RS256" => Ok(JwsAlg::Rs256),
            "RS384" => Ok(JwsAlg::Rs384),
            "RS512" => Ok(JwsAlg::Rs512),
            "ES256" => Ok(JwsAlg::Es256),
            "ES384" => Ok(JwsAlg::Es384),
            "ES512" => Ok(JwsAlg::Es512),
            "PS256" => Ok(JwsAlg::Ps256),
            "PS384" => Ok(JwsAlg::Ps384),
            "PS512" => Ok(JwsAlg::Ps512),
            other => Err(UnsupportedJwsAlg(other.to_string())),
        }
    }

    /// The algorithm's JWS name (e.g. `"RS256"`).
    pub fn as_str(&self) -> &'static str {
        match self {
            JwsAlg::Rs256 => "RS256",
            JwsAlg::Rs384 => "RS384",
            JwsAlg::Rs512 => "RS512",
            JwsAlg::Es256 => "ES256",
            JwsAlg::Es384 => "ES384",
            JwsAlg::Es512 => "ES512",
            JwsAlg::Ps256 => "PS256",
            JwsAlg::Ps384 => "PS384",
            JwsAlg::Ps512 => "PS512",
        }
    }
}

impl std::fmt::Display for JwsAlg {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Configuration for OIDC token validation.
///
/// # Usage
///
/// ```ignore
/// use auths_oidc_port::{JwsAlg, OidcValidationConfig, OidcValidationConfigBuilder};
///
/// let config = OidcValidationConfig::builder()
///     .issuer("https://token.actions.githubusercontent.com")
///     .audience("sigstore")
///     .allowed_algorithms(vec![JwsAlg::Rs256])
///     .max_clock_skew_secs(60)
///     .jwks_cache_ttl_secs(3600)
///     .build();
/// ```
#[derive(Debug, Clone)]
pub struct OidcValidationConfig {
    /// The expected JWT issuer (e.g., "https://token.actions.githubusercontent.com" for GitHub Actions)
    pub issuer: String,
    /// The expected JWT audience (e.g., "sigstore")
    pub audience: String,
    /// Allowed JWT algorithms (e.g., vec![JwsAlg::Rs256])
    pub allowed_algorithms: Vec<JwsAlg>,
    /// Maximum clock skew tolerance in seconds
    pub max_clock_skew_secs: i64,
    /// JWKS cache TTL in seconds
    pub jwks_cache_ttl_secs: u64,
}

impl OidcValidationConfig {
    /// Create a new builder for `OidcValidationConfig`.
    pub fn builder() -> OidcValidationConfigBuilder {
        OidcValidationConfigBuilder::default()
    }
}

/// Builder for `OidcValidationConfig`.
#[derive(Debug, Default)]
pub struct OidcValidationConfigBuilder {
    issuer: Option<String>,
    audience: Option<String>,
    allowed_algorithms: Option<Vec<JwsAlg>>,
    max_clock_skew_secs: Option<i64>,
    jwks_cache_ttl_secs: Option<u64>,
}

impl OidcValidationConfigBuilder {
    /// Set the expected JWT issuer.
    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
        self.issuer = Some(issuer.into());
        self
    }

    /// Set the expected JWT audience.
    pub fn audience(mut self, audience: impl Into<String>) -> Self {
        self.audience = Some(audience.into());
        self
    }

    /// Set the allowed JWT algorithms.
    pub fn allowed_algorithms(mut self, algorithms: Vec<JwsAlg>) -> Self {
        self.allowed_algorithms = Some(algorithms);
        self
    }

    /// Set the maximum clock skew tolerance in seconds.
    pub fn max_clock_skew_secs(mut self, secs: i64) -> Self {
        self.max_clock_skew_secs = Some(secs);
        self
    }

    /// Set the JWKS cache TTL in seconds.
    pub fn jwks_cache_ttl_secs(mut self, secs: u64) -> Self {
        self.jwks_cache_ttl_secs = Some(secs);
        self
    }

    /// Build the `OidcValidationConfig`.
    pub fn build(self) -> Result<OidcValidationConfig, String> {
        Ok(OidcValidationConfig {
            issuer: self
                .issuer
                .ok_or_else(|| "issuer is required".to_string())?,
            audience: self
                .audience
                .ok_or_else(|| "audience is required".to_string())?,
            allowed_algorithms: self
                .allowed_algorithms
                .unwrap_or_else(|| vec![JwsAlg::Rs256, JwsAlg::Es256]),
            max_clock_skew_secs: self.max_clock_skew_secs.unwrap_or(60),
            jwks_cache_ttl_secs: self.jwks_cache_ttl_secs.unwrap_or(3600),
        })
    }
}

/// Configuration for RFC 3161 timestamp authority operations.
///
/// # Usage
///
/// ```ignore
/// use auths_oidc_port::TimestampConfig;
///
/// let config = TimestampConfig {
///     tsa_uri: Some("http://timestamp.sigstore.dev/api/v1/timestamp".to_string()),
///     timeout_secs: 10,
///     fallback_on_error: true,
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimestampConfig {
    /// Optional URI to the RFC 3161 Timestamp Authority
    pub tsa_uri: Option<String>,
    /// Timeout in seconds for TSA requests
    pub timeout_secs: u64,
    /// Whether to gracefully degrade if TSA is unavailable
    pub fallback_on_error: bool,
}

impl Default for TimestampConfig {
    fn default() -> Self {
        Self {
            tsa_uri: Some("http://timestamp.sigstore.dev/api/v1/timestamp".to_string()),
            timeout_secs: 10,
            fallback_on_error: true,
        }
    }
}

/// Port trait for JWT validation.
///
/// Implementations of this trait handle JWT decoding, signature verification via JWKS,
/// and claims validation with configurable clock skew tolerance.
///
/// # Usage
///
/// ```ignore
/// use auths_oidc_port::{JwtValidator, OidcValidationConfig};
/// use chrono::Utc;
///
/// async fn validate_token(validator: &dyn JwtValidator, token: &str) {
///     let config = OidcValidationConfig::builder()
///         .issuer("https://token.actions.githubusercontent.com")
///         .audience("sigstore")
///         .build()
///         .unwrap();
///
///     let claims = validator.validate(token, &config, Utc::now()).await;
/// }
/// ```
#[async_trait::async_trait]
pub trait JwtValidator: Send + Sync {
    /// Validate and extract claims from a JWT token.
    ///
    /// # Args
    ///
    /// * `token`: The raw JWT string
    /// * `config`: OIDC validation configuration
    /// * `now`: Current UTC time for expiry checking
    ///
    /// # Returns
    ///
    /// Validated claims as a JSON value, or OidcError if validation fails
    async fn validate(
        &self,
        token: &str,
        config: &OidcValidationConfig,
        now: DateTime<Utc>,
    ) -> Result<serde_json::Value, OidcError>;
}

/// Port trait for JWKS (JSON Web Key Set) resolution and caching.
///
/// Implementations fetch and cache JWKS from OIDC provider endpoints.
/// Caching strategy (TTL, refresh-ahead) is implementation-dependent.
///
/// # Usage
///
/// ```ignore
/// use auths_oidc_port::JwksClient;
///
/// async fn fetch_keys(client: &dyn JwksClient) {
///     let jwks = client.fetch_jwks("https://token.actions.githubusercontent.com").await;
/// }
/// ```
#[async_trait::async_trait]
pub trait JwksClient: Send + Sync {
    /// Fetch the JWKS from the specified issuer endpoint.
    ///
    /// Implementations should cache the result to avoid repeated network calls.
    /// TTL and refresh strategies are implementation-defined.
    ///
    /// # Args
    ///
    /// * `issuer_url`: The base URL of the OIDC provider
    ///
    /// # Returns
    ///
    /// The JWKS (as a JSON object containing a "keys" array), or OidcError if fetch fails
    async fn fetch_jwks(&self, issuer_url: &str) -> Result<serde_json::Value, OidcError>;
}

/// Port trait for RFC 3161 timestamp authority operations.
///
/// Optional timestamp authority integration for proving signature creation time.
/// Graceful degradation if the TSA is unavailable or not configured.
///
/// # Usage
///
/// ```ignore
/// use auths_oidc_port::{TimestampClient, TimestampConfig};
///
/// async fn timestamp_signature(client: &dyn TimestampClient, data: &[u8]) {
///     let config = TimestampConfig::default();
///     let token = client.timestamp(data, &config).await;
/// }
/// ```
#[async_trait::async_trait]
pub trait TimestampClient: Send + Sync {
    /// Create an RFC 3161 timestamp for the given data.
    ///
    /// If TSA is not configured or unavailable, returns Ok(None) if fallback_on_error is true.
    ///
    /// # Args
    ///
    /// * `data`: The data to timestamp
    /// * `config`: Timestamp authority configuration
    ///
    /// # Returns
    ///
    /// RFC 3161 timestamp response (ASN.1 DER encoded), or None if TSA unavailable and fallback enabled
    async fn timestamp(
        &self,
        data: &[u8],
        config: &TimestampConfig,
    ) -> Result<Option<Vec<u8>>, OidcError>;
}

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

    #[test]
    fn an_unsigned_symmetric_or_unknown_algorithm_is_not_an_accepted_jws_algorithm() {
        assert_eq!(JwsAlg::parse("RS256").unwrap(), JwsAlg::Rs256);
        assert_eq!(JwsAlg::parse("ES256").unwrap(), JwsAlg::Es256);
        assert!(JwsAlg::parse("none").is_err());
        assert!(JwsAlg::parse("None").is_err());
        assert!(JwsAlg::parse("HS256").is_err());
        assert!(JwsAlg::parse("rs256").is_err());
        assert!(JwsAlg::parse("").is_err());
    }

    #[test]
    fn test_oidc_validation_config_builder() {
        let config = OidcValidationConfig::builder()
            .issuer("https://token.actions.githubusercontent.com")
            .audience("sigstore")
            .allowed_algorithms(vec![JwsAlg::Rs256])
            .max_clock_skew_secs(120)
            .jwks_cache_ttl_secs(7200)
            .build();

        assert!(config.is_ok());
        let cfg = config.unwrap();
        assert_eq!(cfg.issuer, "https://token.actions.githubusercontent.com");
        assert_eq!(cfg.audience, "sigstore");
        assert_eq!(cfg.allowed_algorithms, vec![JwsAlg::Rs256]);
        assert_eq!(cfg.max_clock_skew_secs, 120);
        assert_eq!(cfg.jwks_cache_ttl_secs, 7200);
    }

    #[test]
    fn test_oidc_validation_config_defaults() {
        let config = OidcValidationConfig::builder()
            .issuer("https://example.com")
            .audience("test")
            .build();

        assert!(config.is_ok());
        let cfg = config.unwrap();
        assert_eq!(cfg.max_clock_skew_secs, 60);
        assert_eq!(cfg.jwks_cache_ttl_secs, 3600);
        assert_eq!(cfg.allowed_algorithms, vec![JwsAlg::Rs256, JwsAlg::Es256]);
    }

    #[test]
    fn test_oidc_validation_config_missing_issuer() {
        let config = OidcValidationConfig::builder().audience("test").build();

        assert!(config.is_err());
    }

    #[test]
    fn test_oidc_validation_config_missing_audience() {
        let config = OidcValidationConfig::builder()
            .issuer("https://example.com")
            .build();

        assert!(config.is_err());
    }

    #[test]
    fn test_timestamp_config_default() {
        let config = TimestampConfig::default();
        assert!(config.tsa_uri.is_some());
        assert_eq!(config.timeout_secs, 10);
        assert!(config.fallback_on_error);
    }

    #[test]
    fn test_timestamp_config_custom() {
        let config = TimestampConfig {
            tsa_uri: Some("http://custom-tsa.example.com".to_string()),
            timeout_secs: 20,
            fallback_on_error: false,
        };
        assert_eq!(
            config.tsa_uri,
            Some("http://custom-tsa.example.com".to_string())
        );
        assert_eq!(config.timeout_secs, 20);
        assert!(!config.fallback_on_error);
    }
}