pdk-token-introspection-lib 1.7.0

PDK Token Introspection Library
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
// Copyright (c) 2026, Salesforce, Inc.,
// All rights reserved.
// For full license text, see the LICENSE.txt file

//! PDK Token Introspection Library
//!
//! Library which provides token introspection functionality for OAuth2 and OpenID Connect
//! token validation policies.
//!
//! ## Primary types
//!
//! - [`TokenValidatorBuilder`]: Builder for creating TokenValidator instances
//! - [`TokenValidator`]: Validator which handles cache, HTTP call, parsing and validation
//! - [`IntrospectionResult`]: Result of a successful token introspection
//! - [`ScopesValidator`]: Validates token scopes
//!
//! ## Example
//!
//! ```rust,ignore
//! use pdk::token_introspection::{TokenValidatorBuilder, ScopesValidator};
//! use pdk::hl::Service;
//!
//! #[entrypoint]
//! async fn configure(
//!     launcher: Launcher,
//!     validator_builder: TokenValidatorBuilder,  // Injected from context
//!     Configuration(config): Configuration,
//! ) -> Result<(), LaunchError> {
//!     let service = Service::new(&config.host, config.port);
//!     let scopes = ScopesValidator::all(vec!["read".into()]);
//!
//!     let validator = validator_builder
//!         .new("token-validator")
//!         .with_path("/introspect")
//!         .with_authorization_value("Basic abc123")
//!         .with_service(service)
//!         .with_scopes_validator(scopes)
//!         .build()?;
//!
//!     launcher.launch(on_request(|req| async {
//!         let token = extract_token(&req)?;
//!         let result = validator.validate(&token).await?;
//!         println!("Client ID: {:?}", result.client_id());
//!     })).await
//! }
//! ```

mod error;
mod introspector;
mod scopes_validator;
mod time_frame;

use error::TokenError;
use pdk_core::log::warn;
use rmp_serde::Serializer;
use serde::{Deserialize, Serialize};

pub use error::{ConfigError, IntrospectionError, ValidationError};
pub use introspector::{
    IntrospectionResult, TokenValidator, TokenValidatorBuildError, TokenValidatorBuilder,
    TokenValidatorBuilderInstance, TokenValidatorConfig,
};
pub use scopes_validator::ScopesValidator;
pub use serde_json::Value;

pub(crate) use time_frame::FixedTimeFrame;

/// Type alias for token properties object
pub type Object = serde_json::Map<String, Value>;

// Client ID token property key.
const CLIENT_ID: &str = "client_id";

// Username token property key.
const USERNAME: &str = "username";

// Active field token property key.
const ACTIVE_FIELD: &str = "active";

/// Common interface for parsed tokens.
pub trait Token {
    fn has_expired(&self, current_time_millis: i64) -> bool;
    fn is_active(&self) -> bool;
    fn scopes(&self) -> &[String];
    fn client_id(&self) -> Option<String>;
    fn username(&self) -> Option<String>;
    fn raw_token_context(&self) -> &str;
    fn properties(&self) -> &Object;
}

/// Represents a parsed token from the introspection response.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "ParsedToken")]
pub enum ParsedToken {
    /// Token with expiration time that can be cached.
    ExpirableToken(ExpirableToken),
    /// Token without expiration (always considered expired for caching).
    OneTimeUseToken(OneTimeUseToken),
}

impl ParsedToken {
    fn as_token(&self) -> &dyn Token {
        match self {
            ParsedToken::ExpirableToken(exp_token) => exp_token,
            ParsedToken::OneTimeUseToken(one_time_token) => one_time_token,
        }
    }

    /// Checks if the token has expired.
    pub fn has_expired(&self, current_time_millis: i64) -> bool {
        self.as_token().has_expired(current_time_millis)
    }

    /// Returns the scopes associated with the token.
    pub fn scopes(&self) -> &[String] {
        self.as_token().scopes()
    }

    /// Returns the client ID if present in token properties.
    #[allow(unused)]
    pub fn client_id(&self) -> Option<String> {
        self.as_token().client_id()
    }

    /// Returns the username if present in token properties.
    #[allow(unused)]
    pub fn username(&self) -> Option<String> {
        self.as_token().username()
    }

    /// Returns the raw JSON response from the introspection server.
    pub fn raw_token_context(&self) -> &str {
        self.as_token().raw_token_context()
    }

    /// Returns the token properties as a JSON object.
    pub fn properties(&self) -> &Object {
        self.as_token().properties()
    }

    /// Deserializes a token from MessagePack binary format.
    pub(crate) fn from_binary(raw_data: Vec<u8>) -> Result<Self, TokenError> {
        let parsed_token: ParsedToken =
            rmp_serde::decode::from_slice(&raw_data).map_err(|err| {
                warn!("Error deserializing token: {err:?}");
                TokenError::BinaryDeserializeError {
                    msg: err.to_string(),
                }
            })?;

        Ok(parsed_token)
    }

    /// Serializes the token to MessagePack binary format.
    pub(crate) fn to_binary(&self) -> Result<Vec<u8>, TokenError> {
        let mut raw_data = Vec::new();
        self.serialize(&mut Serializer::new(&mut raw_data))
            .map_err(|err| {
                warn!("Error serializing Token to binary: {err:?}");
                TokenError::BinarySerializeError {
                    msg: err.to_string(),
                }
            })?;
        Ok(raw_data)
    }
}

/// Token with expiration time that can be cached.
#[derive(Clone, Serialize, Deserialize)]
pub struct ExpirableToken {
    /// Raw token context.
    raw_token_context: String,
    /// Token properties.
    properties: Object,
    /// Token expiration.
    expiration: FixedTimeFrame,
    /// Token is active.
    is_active: bool,
    /// Token scopes.
    scopes: Vec<String>,
}

impl Eq for ExpirableToken {}

impl PartialEq for ExpirableToken {
    fn eq(&self, other: &Self) -> bool {
        self.properties == other.properties
            && self.expiration == other.expiration
            && self.is_active == other.is_active
            && self.scopes == other.scopes
    }
}

impl std::fmt::Debug for ExpirableToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ExpirableToken")
            .field("properties", &self.properties)
            .field("expiration", &self.expiration)
            .field("is_active", &self.is_active)
            .field("scopes", &self.scopes)
            .finish()
    }
}

impl ExpirableToken {
    /// Creates a new expirable token.
    pub fn new(
        raw_token_context: String,
        properties: Object,
        expiration: FixedTimeFrame,
        scopes: Vec<String>,
    ) -> Self {
        let is_active = properties
            .get(ACTIVE_FIELD)
            .and_then(|v| v.as_bool())
            .unwrap_or(true);

        ExpirableToken {
            raw_token_context,
            properties,
            expiration,
            is_active,
            scopes,
        }
    }
}

impl Token for ExpirableToken {
    fn has_expired(&self, current_time_millis: i64) -> bool {
        self.expiration.has_finished(current_time_millis) || self.expiration.in_millis() == 0
    }

    fn is_active(&self) -> bool {
        self.is_active
    }

    fn scopes(&self) -> &[String] {
        self.scopes.as_ref()
    }

    fn properties(&self) -> &Object {
        &self.properties
    }

    fn client_id(&self) -> Option<String> {
        self.properties().get(CLIENT_ID)?.as_str().map(String::from)
    }

    fn username(&self) -> Option<String> {
        self.properties().get(USERNAME)?.as_str().map(String::from)
    }

    fn raw_token_context(&self) -> &str {
        &self.raw_token_context
    }
}

/// Token without expiration time (always considered expired).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OneTimeUseToken {
    /// Raw token context.
    raw_token_context: String,
    /// Token properties.
    properties: Object,
    /// Token is active.
    is_active: bool,
    /// Token scopes.
    scopes: Vec<String>,
}

impl Eq for OneTimeUseToken {}

impl OneTimeUseToken {
    /// Creates a new one time use token.
    pub fn new(raw_token_context: String, properties: Object, scopes: Vec<String>) -> Self {
        let is_active = properties
            .get(ACTIVE_FIELD)
            .and_then(|v| v.as_bool())
            .unwrap_or(true);
        OneTimeUseToken {
            raw_token_context,
            properties,
            is_active,
            scopes,
        }
    }
}

impl Token for OneTimeUseToken {
    fn has_expired(&self, _current_time_millis: i64) -> bool {
        true
    }

    fn is_active(&self) -> bool {
        self.is_active
    }

    fn scopes(&self) -> &[String] {
        self.scopes.as_ref()
    }

    fn client_id(&self) -> Option<String> {
        self.properties().get(CLIENT_ID)?.as_str().map(String::from)
    }

    fn username(&self) -> Option<String> {
        self.properties().get(USERNAME)?.as_str().map(String::from)
    }

    fn raw_token_context(&self) -> &str {
        &self.raw_token_context
    }

    fn properties(&self) -> &Object {
        &self.properties
    }
}

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

    fn create_properties(active: bool, client_id: Option<&str>) -> Object {
        let mut props = Object::new();
        props.insert("active".to_string(), serde_json::json!(active));
        if let Some(id) = client_id {
            props.insert("client_id".to_string(), serde_json::json!(id));
        }
        props
    }

    #[test]
    fn expirable_token_not_expired_when_in_range() {
        let token = ExpirableToken::new(
            "{}".to_string(),
            create_properties(true, None),
            FixedTimeFrame::new(1000, 5000),
            vec![],
        );
        // In range -> not expired
        assert!(!token.has_expired(3000));
        // Out of range -> expired (proves distinction)
        assert!(token.has_expired(7000));
    }

    #[test]
    fn expirable_token_expired_when_past_end() {
        let token = ExpirableToken::new(
            "{}".to_string(),
            create_properties(true, None),
            FixedTimeFrame::new(1000, 5000),
            vec![],
        );

        assert!(token.has_expired(7000));
        assert!(!token.has_expired(3000));
    }

    #[test]
    fn expirable_token_expired_when_zero_duration() {
        let token = ExpirableToken::new(
            "{}".to_string(),
            create_properties(true, None),
            FixedTimeFrame::new(1000, 0),
            vec![],
        );

        assert!(token.has_expired(1000));

        let token_with_duration = ExpirableToken::new(
            "{}".to_string(),
            create_properties(true, None),
            FixedTimeFrame::new(1000, 5000),
            vec![],
        );
        assert!(!token_with_duration.has_expired(3000));
    }

    #[test]
    fn expirable_token_reads_active_from_properties() {
        let active_token = ExpirableToken::new(
            "{}".to_string(),
            create_properties(true, None),
            FixedTimeFrame::new(0, 1000),
            vec![],
        );
        let inactive_token = ExpirableToken::new(
            "{}".to_string(),
            create_properties(false, None),
            FixedTimeFrame::new(0, 1000),
            vec![],
        );

        assert!(active_token.is_active());
        assert!(!inactive_token.is_active());
    }

    #[test]
    fn one_time_use_token_always_expired() {
        let token = OneTimeUseToken::new("{}".to_string(), create_properties(true, None), vec![]);
        // Always expired regardless of time
        assert!(token.has_expired(0));
        assert!(token.has_expired(i64::MAX));
        // ExpirableToken behaves differently
        let expirable = ExpirableToken::new(
            "{}".to_string(),
            create_properties(true, None),
            FixedTimeFrame::new(0, i64::MAX),
            vec![],
        );
        assert!(!expirable.has_expired(1000));
    }

    #[test]
    fn token_extracts_client_id() {
        let token_with_id = ExpirableToken::new(
            "{}".to_string(),
            create_properties(true, Some("my-client")),
            FixedTimeFrame::new(0, 1000),
            vec![],
        );
        let token_without_id = ExpirableToken::new(
            "{}".to_string(),
            create_properties(true, None),
            FixedTimeFrame::new(0, 1000),
            vec![],
        );

        assert_eq!(token_with_id.client_id(), Some("my-client".to_string()));
        assert_eq!(token_without_id.client_id(), None);
    }

    #[test]
    fn parsed_token_serialization_roundtrip() {
        let token = ParsedToken::ExpirableToken(ExpirableToken::new(
            r#"{"active":true}"#.to_string(),
            create_properties(true, Some("test")),
            FixedTimeFrame::new(1000, 5000),
            vec!["read".to_string()],
        ));

        let binary = token.to_binary().unwrap();
        let restored = ParsedToken::from_binary(binary).unwrap();

        assert_eq!(token, restored);
        // Invalid binary fails
        assert!(ParsedToken::from_binary(vec![0, 1, 2, 3]).is_err());
    }
}