rvoip-auth-core 0.3.8

OAuth2 and token-based authentication for RVoIP services
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! JWT-based [`BearerValidator`] for production deployments.
//!
//! Validates RFC 7519 JWTs against a pre-configured signing key
//! (symmetric HMAC, or asymmetric RSA / EC PEM), checks `exp`, and
//! optionally enforces `iss` / `aud` constraints. On success, maps the
//! token's `sub` claim onto a `rvoip_core::identity::IdentityAssurance::UserAuthorized`
//! with whatever `scope` / `scopes` claim the token carried.
//!
//! This is one of the production Bearer validator options in auth-core.
//! [`crate::bearer::bearer_stub`] remains available for local tests, but it
//! accepts any non-empty token and must not be used as a production gate.
//! JWKS/OIDC, OAuth2 introspection, AAuth, DPoP, and RFC 9421 signed-request
//! primitives are provided as separate validators/building blocks.

use std::collections::{HashMap, HashSet};
use std::fmt;
use std::sync::Arc;
use std::time::SystemTime;

use async_trait::async_trait;
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use rvoip_core_traits::identity::IdentityAssurance;
use rvoip_core_traits::ids::IdentityId;
use serde::Deserialize;

use crate::bearer::{
    unix_time_from_seconds, validate_optional_token_id, AuthenticatedPrincipal,
    AuthenticationMethod, BearerAuthError, BearerValidator, ValidatedBearer,
};
use crate::providers::{
    CredentialAuthError, TokenRevocationChecker, TokenRevocationContext, TokenRevocationStatus,
};

/// Claims `JwtValidator` decodes from each token. Only `sub` and the
/// scope claim are required for the IdentityAssurance mapping; `iss` /
/// `aud` / `exp` are checked by `jsonwebtoken` against the
/// [`Validation`] config the validator was built with.
///
/// Both `scope` (space-separated string) and `scopes` (array form) are
/// accepted to match the variety of issuer conventions in the wild.
/// Tokens with neither map to an empty scopes Vec.
#[derive(Deserialize)]
struct Claims {
    sub: String,
    #[serde(default)]
    iss: Option<String>,
    #[serde(default)]
    iat: Option<u64>,
    #[serde(default)]
    exp: Option<u64>,
    #[serde(default)]
    jti: Option<String>,
    #[serde(default)]
    scope: Option<String>,
    #[serde(default)]
    scopes: Option<Vec<String>>,
    #[serde(default)]
    roles: Option<Vec<String>>,
    #[serde(default)]
    realm_access: Option<RoleAccess>,
    #[serde(default)]
    resource_access: Option<HashMap<String, RoleAccess>>,
    #[serde(default, alias = "tenant", alias = "tid")]
    tenant_id: Option<String>,
}

impl fmt::Debug for Claims {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Claims")
            .field("subject_present", &!self.sub.is_empty())
            .field("issuer_present", &self.iss.is_some())
            .field("issued_at_present", &self.iat.is_some())
            .field("expires_at_present", &self.exp.is_some())
            .field("token_id_present", &self.jti.is_some())
            .field("scope_present", &self.scope.is_some())
            .field("scope_bytes", &self.scope.as_ref().map_or(0, String::len))
            .field(
                "scope_list_count",
                &self.scopes.as_ref().map_or(0, Vec::len),
            )
            .field("role_count", &self.roles.as_ref().map_or(0, Vec::len))
            .field("realm_access_present", &self.realm_access.is_some())
            .field(
                "resource_access_count",
                &self.resource_access.as_ref().map_or(0, HashMap::len),
            )
            .field("tenant_present", &self.tenant_id.is_some())
            .finish()
    }
}

#[derive(Deserialize)]
struct RoleAccess {
    #[serde(default)]
    roles: Vec<String>,
}

impl fmt::Debug for RoleAccess {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RoleAccess")
            .field("role_count", &self.roles.len())
            .finish()
    }
}

/// Validate JWTs against a single signing key. Constructed from either
/// a symmetric HMAC secret or an asymmetric PEM-encoded public key.
///
/// `validate()` rejects with [`BearerAuthError::Empty`] for an empty
/// token, [`BearerAuthError::Invalid`] for any decode/signature/exp/iss/aud
/// failure (the underlying jsonwebtoken error message is preserved in
/// the variant), and produces
/// [`IdentityAssurance::UserAuthorized`] on success.
pub struct JwtValidator {
    decoding_key: DecodingKey,
    validation: Validation,
    revocation_checker: Option<Arc<dyn TokenRevocationChecker>>,
    require_jti: bool,
}

impl JwtValidator {
    /// Build from an already-constructed `jsonwebtoken` decoding key.
    ///
    /// This is useful for in-process integrations with an auth service that
    /// owns token issuance, such as `rvoip-users-core`.
    pub fn from_decoding_key(decoding_key: DecodingKey, algorithm: Algorithm) -> Self {
        let mut validation = Validation::new(algorithm);
        validation.validate_aud = false;
        Self {
            decoding_key,
            validation,
            revocation_checker: None,
            require_jti: false,
        }
    }

    /// HMAC validator — `secret` is the shared HMAC key bytes. Defaults
    /// to HS256; use [`Self::with_algorithm`] to change.
    pub fn from_hmac_secret(secret: &[u8]) -> Self {
        let mut validation = Validation::new(Algorithm::HS256);
        // jsonwebtoken's default Validation has `validate_exp = true`
        // and a 60s leeway; we keep that. Disable aud/iss by default —
        // callers opt in via with_audience / with_issuer.
        validation.set_audience::<&str>(&[]);
        validation.validate_aud = false;
        Self {
            decoding_key: DecodingKey::from_secret(secret),
            validation,
            revocation_checker: None,
            require_jti: false,
        }
    }

    /// RSA validator from a PEM-encoded public key (`-----BEGIN PUBLIC KEY-----`).
    /// Defaults to RS256.
    pub fn from_rsa_pem(pem: &[u8]) -> Result<Self, BearerAuthError> {
        let key = DecodingKey::from_rsa_pem(pem)
            .map_err(|e| BearerAuthError::Unavailable(format!("invalid RSA PEM: {e}")))?;
        let mut validation = Validation::new(Algorithm::RS256);
        validation.validate_aud = false;
        Ok(Self {
            decoding_key: key,
            validation,
            revocation_checker: None,
            require_jti: false,
        })
    }

    /// EC validator from a PEM-encoded public key. Defaults to ES256.
    pub fn from_ec_pem(pem: &[u8]) -> Result<Self, BearerAuthError> {
        let key = DecodingKey::from_ec_pem(pem)
            .map_err(|e| BearerAuthError::Unavailable(format!("invalid EC PEM: {e}")))?;
        let mut validation = Validation::new(Algorithm::ES256);
        validation.validate_aud = false;
        Ok(Self {
            decoding_key: key,
            validation,
            revocation_checker: None,
            require_jti: false,
        })
    }

    /// Override the signing algorithm (e.g. HS384, RS512). Must be
    /// compatible with the key form passed to the constructor — an
    /// HMAC validator with `with_algorithm(Algorithm::RS256)` will
    /// always reject every token.
    pub fn with_algorithm(mut self, algorithm: Algorithm) -> Self {
        self.validation.algorithms = vec![algorithm];
        self
    }

    /// Reject JWTs whose `jti` appears in a revocation store.
    ///
    /// When configured, tokens without a `jti` claim are rejected because they
    /// cannot participate in revocation checks.
    pub fn with_revocation_checker(mut self, checker: Arc<dyn TokenRevocationChecker>) -> Self {
        self.revocation_checker = Some(checker);
        self
    }

    /// Require a non-empty, bounded JWT `jti` even without a revocation store.
    ///
    /// Production deployments that use token IDs for replay, lease, or audit
    /// correlation should enable this policy. Configuring a revocation checker
    /// already requires `jti` regardless of this setting.
    pub fn with_required_jti(mut self) -> Self {
        self.require_jti = true;
        self
    }

    /// Require the token's `aud` claim to match one of `audiences`.
    /// Tokens without an `aud` (or with a non-matching one) are
    /// rejected as `Invalid`.
    pub fn with_audience<I, S>(mut self, audiences: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let auds: HashSet<String> = audiences
            .into_iter()
            .map(|s| s.as_ref().to_string())
            .collect();
        self.validation
            .set_audience(&auds.into_iter().collect::<Vec<_>>());
        self.validation.validate_aud = true;
        self
    }

    /// Require the token's `iss` claim to match one of `issuers`.
    pub fn with_issuer<I, S>(mut self, issuers: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.validation.set_issuer(
            &issuers
                .into_iter()
                .map(|s| s.as_ref().to_string())
                .collect::<Vec<_>>(),
        );
        self
    }

    /// Build into a `Arc<dyn BearerValidator>` ready for adapter
    /// config. Convenience for the common `UctpQuicConfig::new(...)`
    /// shape that wants an Arc.
    pub fn into_arc(self) -> Arc<dyn BearerValidator> {
        Arc::new(self)
    }
}

#[async_trait]
impl BearerValidator for JwtValidator {
    async fn validate(&self, token: &str) -> Result<IdentityAssurance, BearerAuthError> {
        Ok(self.validate_credential(token).await?.principal.assurance)
    }

    async fn validate_principal(
        &self,
        token: &str,
    ) -> Result<AuthenticatedPrincipal, BearerAuthError> {
        Ok(self.validate_credential(token).await?.principal)
    }

    async fn validate_credential(&self, token: &str) -> Result<ValidatedBearer, BearerAuthError> {
        if token.is_empty() {
            return Err(BearerAuthError::Empty);
        }
        let data = decode::<Claims>(token, &self.decoding_key, &self.validation)
            .map_err(|e| BearerAuthError::Invalid(e.to_string()))?;
        let claims = data.claims;
        let token_id = validate_optional_token_id(claims.jti.clone())?;
        if self.require_jti && token_id.is_none() {
            return Err(BearerAuthError::Invalid(
                "token missing required jti".into(),
            ));
        }
        let issued_at = claims
            .iat
            .map(|iat| unix_time_from_seconds(iat, "iat"))
            .transpose()?;
        let expires_at_system = claims
            .exp
            .map(|exp| unix_time_from_seconds(exp, "exp"))
            .transpose()?;
        let revocation_context = revocation_context_from_claims(
            &claims,
            token_id.as_deref(),
            issued_at,
            expires_at_system,
        );
        check_revocation(
            self.revocation_checker.as_ref(),
            revocation_context.as_ref(),
        )
        .await?;
        let subject = claims.sub.clone();
        let expires_at = claims.exp.map(expiration_from_unix).transpose()?;
        let identity = IdentityId::from_string(subject.clone());
        let scopes = scopes_from_claims(
            claims.scope,
            claims.scopes,
            claims.roles,
            claims.realm_access,
            claims.resource_access,
        );
        let assurance = IdentityAssurance::UserAuthorized {
            identity: identity.clone(),
            user_id: identity,
            scopes: scopes.clone(),
        };
        ValidatedBearer::new(
            AuthenticatedPrincipal {
                subject,
                tenant: claims.tenant_id,
                scopes,
                issuer: claims.iss,
                expires_at,
                method: AuthenticationMethod::Jwt,
                assurance,
            },
            token_id,
            issued_at,
        )
    }
}

fn expiration_from_unix(seconds: u64) -> Result<chrono::DateTime<chrono::Utc>, BearerAuthError> {
    i64::try_from(seconds)
        .ok()
        .and_then(|seconds| chrono::DateTime::from_timestamp(seconds, 0))
        .ok_or_else(|| BearerAuthError::Invalid("token exp is outside the supported range".into()))
}

async fn check_revocation(
    checker: Option<&Arc<dyn TokenRevocationChecker>>,
    context: Option<&TokenRevocationContext>,
) -> Result<(), BearerAuthError> {
    let Some(checker) = checker else {
        return Ok(());
    };
    let Some(context) = context else {
        return Err(BearerAuthError::Invalid(
            "token missing jti for revocation check".into(),
        ));
    };
    match checker.check_token(context).await {
        Ok(TokenRevocationStatus::Active) => Ok(()),
        Ok(TokenRevocationStatus::Revoked) => Err(BearerAuthError::Invalid("token revoked".into())),
        Err(CredentialAuthError::Invalid) | Err(CredentialAuthError::PolicyRejected(_)) => Err(
            BearerAuthError::Invalid("revocation check rejected token".into()),
        ),
        Err(CredentialAuthError::Unavailable(err)) => Err(BearerAuthError::Unavailable(err)),
    }
}

fn revocation_context_from_claims(
    claims: &Claims,
    token_id: Option<&str>,
    issued_at: Option<SystemTime>,
    expires_at: Option<SystemTime>,
) -> Option<TokenRevocationContext> {
    let mut context = TokenRevocationContext::new(token_id?).with_subject(claims.sub.clone());
    if let Some(issuer) = claims.iss.clone() {
        context = context.with_issuer(issuer);
    }
    context = context.with_times(issued_at, expires_at);
    Some(context)
}

fn scopes_from_claims(
    scope: Option<String>,
    scopes: Option<Vec<String>>,
    roles: Option<Vec<String>>,
    realm_access: Option<RoleAccess>,
    resource_access: Option<HashMap<String, RoleAccess>>,
) -> Vec<String> {
    let mut values = Vec::new();
    if let Some(scope) = scope {
        values.extend(scope.split_whitespace().map(str::to_string));
    }
    if let Some(scopes) = scopes {
        for scope in scopes {
            push_unique(&mut values, scope);
        }
    }
    if let Some(roles) = roles {
        for role in roles {
            push_unique(&mut values, format!("role:{role}"));
        }
    }
    if let Some(realm_access) = realm_access {
        for role in realm_access.roles {
            push_unique(&mut values, format!("realm:{role}"));
        }
    }
    if let Some(resource_access) = resource_access {
        for (client, access) in resource_access {
            for role in access.roles {
                push_unique(&mut values, format!("{client}:{role}"));
            }
        }
    }
    values
}

fn push_unique(values: &mut Vec<String>, value: String) {
    if !values.contains(&value) {
        values.push(value);
    }
}

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

    const CANARY: &str = "jwt-claims-malicious-canary\r\nAuthorization: exposed";

    #[test]
    fn decoded_claims_keep_values_out_of_debug() {
        let claims: Claims = serde_json::from_value(serde_json::json!({
            "sub": CANARY,
            "iss": CANARY,
            "iat": 1,
            "exp": 2,
            "jti": CANARY,
            "scope": CANARY,
            "scopes": [CANARY],
            "roles": [CANARY],
            "realm_access": { "roles": [CANARY] },
            "resource_access": { (CANARY): { "roles": [CANARY] } },
            "tenant_id": CANARY,
        }))
        .unwrap();

        for rendered in [
            format!("{claims:?}"),
            format!("{:?}", claims.realm_access.as_ref().unwrap()),
            format!(
                "{:?}",
                claims
                    .resource_access
                    .as_ref()
                    .unwrap()
                    .get(CANARY)
                    .unwrap()
            ),
        ] {
            assert!(!rendered.contains(CANARY), "claim leaked: {rendered}");
        }

        assert_eq!(claims.sub, CANARY);
        assert_eq!(claims.iss.as_deref(), Some(CANARY));
        assert_eq!(claims.jti.as_deref(), Some(CANARY));
        assert_eq!(claims.scope.as_deref(), Some(CANARY));
        assert_eq!(claims.scopes.as_deref(), Some(&[CANARY.to_string()][..]));
        assert_eq!(claims.roles.as_deref(), Some(&[CANARY.to_string()][..]));
        assert_eq!(claims.tenant_id.as_deref(), Some(CANARY));
        assert_eq!(
            claims.realm_access.as_ref().unwrap().roles,
            [CANARY.to_string()]
        );
        assert_eq!(
            claims.resource_access.as_ref().unwrap()[CANARY].roles,
            [CANARY.to_string()]
        );
    }
}