blueprint-auth 0.2.0-alpha.1

Blueprint HTTP/WS Authentication
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
//! Paseto token generation and validation for short-lived access tokens
//!
//! This module implements secure token generation using PASETO v4 local tokens.
//! Tokens are encrypted with a symmetric key and contain embedded claims including:
//!
//! - Service ID for authorization
//! - Tenant ID with cryptographic binding
//! - Additional headers to inject in requests
//! - Expiration and issuance timestamps
//! - Unique token identifier for tracking
//!
//! # Security
//!
//! - Tokens are encrypted using XChaCha20-Poly1305
//! - Tenant IDs are cryptographically bound to prevent impersonation
//! - Keys are persisted securely with restrictive permissions
//! - Automatic expiration validation

use pasetors::claims::{Claims, ClaimsValidationRules};
use pasetors::keys::SymmetricKey;
use pasetors::token::UntrustedToken;
use pasetors::{Local, version4::V4};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use uuid::Uuid;

use crate::types::ServiceId;

/// Paseto key for symmetric encryption/decryption
#[derive(Clone, Debug)]
pub struct PasetoKey(SymmetricKey<V4>);

impl PasetoKey {
    /// Generate a new random Paseto key
    pub fn generate() -> Self {
        use blueprint_std::rand::RngCore;
        let mut rng = blueprint_std::BlueprintRng::new();
        let mut key_bytes = [0u8; 32];
        rng.fill_bytes(&mut key_bytes);

        let key = SymmetricKey::<V4>::from(&key_bytes).expect("Valid 32-byte key");
        PasetoKey(key)
    }

    /// Create from bytes
    pub fn from_bytes(bytes: [u8; 32]) -> Self {
        let key = SymmetricKey::<V4>::from(&bytes).expect("Valid 32-byte key");
        PasetoKey(key)
    }

    /// Get key as bytes
    pub fn as_bytes(&self) -> Vec<u8> {
        self.0.as_bytes().to_vec()
    }
}

/// Claims embedded in Paseto access tokens
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct AccessTokenClaims {
    /// Service ID this token is for
    pub service_id: ServiceId,
    /// Optional tenant identifier (hashed user ID)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tenant_id: Option<String>,
    /// Cryptographic binding of tenant_id to key_id (hash of key_id + tenant_id)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tenant_binding: Option<String>,
    /// Additional headers to forward to upstream
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub additional_headers: BTreeMap<String, String>,
    /// Token expiration timestamp (seconds since epoch)
    pub expires_at: u64,
    /// Token issued at timestamp (seconds since epoch)
    pub issued_at: u64,
    /// API key ID that was used to generate this token
    pub key_id: String,
    /// Unique token identifier for logging/debugging
    pub jti: String,
    /// Optional scopes granted to this token (blueprint-defined)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scopes: Option<Vec<String>>,
}

impl AccessTokenClaims {
    /// Create new claims with current timestamp
    pub fn new(
        service_id: ServiceId,
        key_id: String,
        ttl: Duration,
        tenant_id: Option<String>,
        additional_headers: BTreeMap<String, String>,
        scopes: Option<Vec<String>>,
    ) -> Self {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        // Create cryptographic binding between key_id and tenant_id
        let tenant_binding = tenant_id.as_ref().map(|tid| {
            use tiny_keccak::{Hasher, Keccak};
            let mut hasher = Keccak::v256();
            hasher.update(key_id.as_bytes());
            hasher.update(b"::tenant::");
            hasher.update(tid.as_bytes());
            let mut output = [0u8; 32];
            hasher.finalize(&mut output);
            hex::encode(output)
        });

        Self {
            service_id,
            tenant_id,
            tenant_binding,
            additional_headers,
            expires_at: now + ttl.as_secs(),
            issued_at: now,
            key_id,
            jti: Uuid::new_v4().to_string(),
            scopes,
        }
    }

    /// Verify tenant binding is valid
    pub fn verify_tenant_binding(&self) -> bool {
        match (&self.tenant_id, &self.tenant_binding) {
            (None, None) => true, // No tenant, no binding required
            (Some(tid), Some(binding)) => {
                // Recompute binding and verify
                use tiny_keccak::{Hasher, Keccak};
                let mut hasher = Keccak::v256();
                hasher.update(self.key_id.as_bytes());
                hasher.update(b"::tenant::");
                hasher.update(tid.as_bytes());
                let mut output = [0u8; 32];
                hasher.finalize(&mut output);
                let expected = hex::encode(output);
                expected == *binding
            }
            _ => false, // Mismatch between tenant_id and binding presence
        }
    }

    /// Check if token is expired
    pub fn is_expired(&self) -> bool {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        now >= self.expires_at
    }

    /// Get time until expiration
    pub fn time_to_expiry(&self) -> Option<Duration> {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        if now >= self.expires_at {
            None
        } else {
            Some(Duration::from_secs(self.expires_at - now))
        }
    }
}

/// Paseto token generator and validator
#[derive(Clone, Debug)]
pub struct PasetoTokenManager {
    key: PasetoKey,
    default_ttl: Duration,
}

impl PasetoTokenManager {
    /// Create new token manager with generated key
    pub fn new(default_ttl: Duration) -> Self {
        Self {
            key: PasetoKey::generate(),
            default_ttl,
        }
    }

    /// Create with specific key (for persistence across restarts)
    pub fn with_key(key: PasetoKey, default_ttl: Duration) -> Self {
        Self { key, default_ttl }
    }

    /// Generate a new Paseto access token
    pub fn generate_token(
        &self,
        service_id: ServiceId,
        key_id: String,
        tenant_id: Option<String>,
        additional_headers: BTreeMap<String, String>,
        ttl: Option<Duration>,
        scopes: Option<Vec<String>>,
    ) -> Result<String, PasetoError> {
        let claims = AccessTokenClaims::new(
            service_id,
            key_id,
            ttl.unwrap_or(self.default_ttl),
            tenant_id,
            additional_headers,
            scopes,
        );

        // Create proper PASETO claims with standard fields
        let mut paseto_claims =
            Claims::new().map_err(|e| PasetoError::SerializationError(e.to_string()))?;

        // Add our custom claims as JSON
        let custom_json = serde_json::to_string(&claims)
            .map_err(|e| PasetoError::SerializationError(e.to_string()))?;
        paseto_claims
            .add_additional("data", custom_json)
            .map_err(|e| PasetoError::SerializationError(e.to_string()))?;

        pasetors::local::encrypt(&self.key.0, &paseto_claims, None, None)
            .map_err(|e| PasetoError::EncryptionError(e.to_string()))
    }

    /// Validate and decode a Paseto access token
    pub fn validate_token(&self, token: &str) -> Result<AccessTokenClaims, PasetoError> {
        let untrusted_token = UntrustedToken::<Local, V4>::try_from(token)
            .map_err(|e| PasetoError::DecryptionError(e.to_string()))?;

        // Create basic validation rules (no strict validation for now)
        let validation_rules = ClaimsValidationRules::new();

        let trusted_token =
            pasetors::local::decrypt(&self.key.0, &untrusted_token, &validation_rules, None, None)
                .map_err(|e| PasetoError::DecryptionError(e.to_string()))?;

        // Extract our custom data from the "data" field
        let token_claims = trusted_token.payload_claims().ok_or_else(|| {
            PasetoError::DeserializationError("Failed to parse payload claims".to_string())
        })?;

        let custom_data = token_claims
            .get_claim("data")
            .ok_or_else(|| PasetoError::DeserializationError("Missing data claim".to_string()))?;

        // Get string value from the claim
        let custom_json_str = custom_data.as_str().ok_or_else(|| {
            PasetoError::DeserializationError("Data claim is not a string".to_string())
        })?;

        let claims: AccessTokenClaims = serde_json::from_str(custom_json_str)
            .map_err(|e| PasetoError::DeserializationError(e.to_string()))?;

        if claims.is_expired() {
            return Err(PasetoError::TokenExpired);
        }

        // Verify tenant binding to prevent impersonation
        if !claims.verify_tenant_binding() {
            return Err(PasetoError::InvalidTenantBinding);
        }

        Ok(claims)
    }

    /// Get the encryption key for persistence
    pub fn get_key(&self) -> &PasetoKey {
        &self.key
    }

    /// Get the default TTL
    pub fn default_ttl(&self) -> Duration {
        self.default_ttl
    }
}

#[derive(Debug, thiserror::Error)]
pub enum PasetoError {
    #[error("Token is expired")]
    TokenExpired,

    #[error("Invalid tenant binding - possible impersonation attempt")]
    InvalidTenantBinding,

    #[error("Encryption error: {0}")]
    EncryptionError(String),

    #[error("Decryption error: {0}")]
    DecryptionError(String),

    #[error("Serialization error: {0}")]
    SerializationError(String),

    #[error("Deserialization error: {0}")]
    DeserializationError(String),
}

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

    #[test]
    fn test_paseto_key_generation() {
        let key1 = PasetoKey::generate();
        let key2 = PasetoKey::generate();

        // Keys should be different
        assert_ne!(key1.0, key2.0);

        // Should be 32 bytes
        assert_eq!(key1.as_bytes().len(), 32);
    }

    #[test]
    fn test_access_token_claims_creation() {
        let service_id = ServiceId::new(1);
        let key_id = "ak_test123".to_string();
        let ttl = Duration::from_secs(900); // 15 minutes
        let tenant_id = Some("tenant123".to_string());
        let mut headers = BTreeMap::new();
        headers.insert("X-Custom".to_string(), "value".to_string());

        let claims = AccessTokenClaims::new(
            service_id,
            key_id.clone(),
            ttl,
            tenant_id.clone(),
            headers.clone(),
            None,
        );

        assert_eq!(claims.service_id, service_id);
        assert_eq!(claims.key_id, key_id);
        assert_eq!(claims.tenant_id, tenant_id);
        assert_eq!(claims.additional_headers, headers);
        assert!(!claims.is_expired());
        assert!(claims.time_to_expiry().is_some());
        assert!(!claims.jti.is_empty());
    }

    #[test]
    fn test_token_expiration() {
        let claims = AccessTokenClaims {
            service_id: ServiceId::new(1),
            tenant_id: None,
            tenant_binding: None,
            additional_headers: BTreeMap::new(),
            expires_at: 1, // Very old timestamp
            issued_at: 1,
            key_id: "ak_test".to_string(),
            jti: Uuid::new_v4().to_string(),
            scopes: None,
        };

        assert!(claims.is_expired());
        assert!(claims.time_to_expiry().is_none());
    }

    #[test]
    fn test_token_generation_and_validation() {
        let manager = PasetoTokenManager::new(Duration::from_secs(900));
        let service_id = ServiceId::new(1);
        let key_id = "ak_test123".to_string();
        let tenant_id = Some("tenant123".to_string());
        let mut headers = BTreeMap::new();
        headers.insert("X-Custom".to_string(), "value".to_string());

        // Generate token
        let token = manager
            .generate_token(
                service_id,
                key_id.clone(),
                tenant_id.clone(),
                headers.clone(),
                None,
                None,
            )
            .expect("Should generate token");

        // Token should start with v4.local.
        assert!(token.starts_with("v4.local."));

        // Validate token
        let claims = manager
            .validate_token(&token)
            .expect("Should validate token");

        assert_eq!(claims.service_id, service_id);
        assert_eq!(claims.key_id, key_id);
        assert_eq!(claims.tenant_id, tenant_id);
        assert_eq!(claims.additional_headers, headers);
        assert!(!claims.is_expired());
    }

    #[test]
    fn test_token_validation_with_different_key() {
        let manager1 = PasetoTokenManager::new(Duration::from_secs(900));
        let manager2 = PasetoTokenManager::new(Duration::from_secs(900));

        let token = manager1
            .generate_token(
                ServiceId::new(1),
                "ak_test".to_string(),
                None,
                BTreeMap::new(),
                None,
                None,
            )
            .expect("Should generate token");

        // Should fail with different key
        let result = manager2.validate_token(&token);
        assert!(result.is_err());
        assert!(matches!(result, Err(PasetoError::DecryptionError(_))));
    }

    #[test]
    fn test_expired_token_validation() {
        let manager = PasetoTokenManager::new(Duration::from_millis(1));

        let token = manager
            .generate_token(
                ServiceId::new(1),
                "ak_test".to_string(),
                None,
                BTreeMap::new(),
                None,
                None,
            )
            .expect("Should generate token");

        // Wait for token to expire
        thread::sleep(Duration::from_millis(10));

        let result = manager.validate_token(&token);
        assert!(result.is_err());
        assert!(matches!(result, Err(PasetoError::TokenExpired)));
    }
}