Skip to main content

agent_tools_interface/core/
jwt.rs

1//! JWT-based authentication for ATI.
2//!
3//! ES256-signed JWTs carry identity + scopes + expiry in a single tamper-proof
4//! credential. The orchestrator signs with a private key; the proxy validates
5//! with the corresponding public key (served via JWKS).
6//!
7//! Supports ES256 (recommended) and HS256 (simpler, for single-machine setups).
8
9use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, TokenData, Validation};
10use serde::{Deserialize, Serialize};
11use std::collections::HashMap;
12use thiserror::Error;
13
14#[derive(Error, Debug)]
15pub enum JwtError {
16    #[error("JWT encoding failed: {0}")]
17    Encode(#[from] jsonwebtoken::errors::Error),
18    #[error("Invalid PEM key: {0}")]
19    InvalidKey(String),
20    #[error("No encoding key configured (private key required for issuance)")]
21    NoEncodingKey,
22    #[error("No decoding key configured (public key required for validation)")]
23    NoDecodingKey,
24    #[error("Base64 decode error: {0}")]
25    Base64(String),
26}
27
28/// Configuration for JWT validation and (optionally) issuance.
29#[derive(Clone)]
30pub struct JwtConfig {
31    /// Public key for validation.
32    pub decoding_key: DecodingKey,
33    /// Private key for issuance (only on orchestrator).
34    pub encoding_key: Option<EncodingKey>,
35    /// Signing algorithm (ES256 or HS256).
36    pub algorithm: Algorithm,
37    /// Expected `iss` claim (optional — skipped if None).
38    pub required_issuer: Option<String>,
39    /// Expected `aud` claim.
40    pub required_audience: String,
41    /// Clock skew tolerance in seconds.
42    pub leeway_secs: u64,
43    /// Raw public key PEM bytes (for JWKS endpoint).
44    pub public_key_pem: Option<Vec<u8>>,
45}
46
47impl std::fmt::Debug for JwtConfig {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        f.debug_struct("JwtConfig")
50            .field("algorithm", &self.algorithm)
51            .field("required_issuer", &self.required_issuer)
52            .field("required_audience", &self.required_audience)
53            .field("leeway_secs", &self.leeway_secs)
54            .field("has_encoding_key", &self.encoding_key.is_some())
55            .finish()
56    }
57}
58
59/// ATI-specific namespace in JWT claims.
60#[derive(Debug, Clone, Serialize, Deserialize)]
61pub struct AtiNamespace {
62    /// Claims schema version.
63    pub v: u8,
64    /// Per-tool-pattern rate limits (e.g. {"tool:github__*": "10/hour"}).
65    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
66    pub rate: HashMap<String, String>,
67}
68
69/// JWT claims per RFC 9068.
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct TokenClaims {
72    /// Issuer (who signed this token).
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub iss: Option<String>,
75    /// Subject (agent identity).
76    pub sub: String,
77    /// Audience (target service, e.g. "ati-proxy").
78    pub aud: String,
79    /// Issued-at timestamp (Unix seconds).
80    pub iat: u64,
81    /// Expiry timestamp (Unix seconds).
82    pub exp: u64,
83    /// Unique token ID (UUID) for replay detection.
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub jti: Option<String>,
86    /// Space-delimited scopes per RFC 9068 §2.2.3.
87    pub scope: String,
88    /// ATI-specific claims namespace.
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub ati: Option<AtiNamespace>,
91}
92
93impl TokenClaims {
94    /// Parse the space-delimited scope string into a Vec.
95    pub fn scopes(&self) -> Vec<String> {
96        self.scope.split_whitespace().map(String::from).collect()
97    }
98}
99
100/// Validate a JWT token string and return the claims.
101pub fn validate(token: &str, config: &JwtConfig) -> Result<TokenClaims, JwtError> {
102    let mut validation = Validation::new(config.algorithm);
103    validation.set_audience(&[&config.required_audience]);
104    validation.leeway = config.leeway_secs;
105
106    if let Some(ref issuer) = config.required_issuer {
107        validation.set_issuer(&[issuer]);
108    } else {
109        // Don't require issuer validation if not configured
110        validation.set_required_spec_claims(&["exp", "sub", "aud"]);
111    }
112
113    let token_data: TokenData<TokenClaims> =
114        jsonwebtoken::decode(token, &config.decoding_key, &validation)?;
115
116    Ok(token_data.claims)
117}
118
119/// Issue (sign) a JWT token from claims.
120pub fn issue(claims: &TokenClaims, config: &JwtConfig) -> Result<String, JwtError> {
121    let encoding_key = config
122        .encoding_key
123        .as_ref()
124        .ok_or(JwtError::NoEncodingKey)?;
125
126    let header = Header::new(config.algorithm);
127    let token = jsonwebtoken::encode(&header, claims, encoding_key)?;
128    Ok(token)
129}
130
131/// Decode a JWT without verifying the signature (for inspection only).
132pub fn inspect(token: &str) -> Result<TokenClaims, JwtError> {
133    let mut validation = Validation::default();
134    validation.insecure_disable_signature_validation();
135    validation.validate_aud = false;
136    validation.validate_exp = false;
137    validation.set_required_spec_claims::<&str>(&[]);
138
139    // Use a dummy key since we're not validating
140    let key = DecodingKey::from_secret(b"unused");
141    let token_data: TokenData<TokenClaims> = jsonwebtoken::decode(token, &key, &validation)?;
142
143    Ok(token_data.claims)
144}
145
146/// Load an ES256 or RS256 public key from PEM bytes.
147pub fn load_public_key_pem(pem: &[u8], alg: Algorithm) -> Result<DecodingKey, JwtError> {
148    match alg {
149        Algorithm::ES256 | Algorithm::ES384 => {
150            DecodingKey::from_ec_pem(pem).map_err(|e| JwtError::InvalidKey(e.to_string()))
151        }
152        Algorithm::RS256 | Algorithm::RS384 | Algorithm::RS512 => {
153            DecodingKey::from_rsa_pem(pem).map_err(|e| JwtError::InvalidKey(e.to_string()))
154        }
155        _ => Err(JwtError::InvalidKey(format!(
156            "Unsupported algorithm for PEM: {alg:?}"
157        ))),
158    }
159}
160
161/// Load an ES256 or RS256 private key from PEM bytes.
162pub fn load_private_key_pem(pem: &[u8], alg: Algorithm) -> Result<EncodingKey, JwtError> {
163    match alg {
164        Algorithm::ES256 | Algorithm::ES384 => {
165            EncodingKey::from_ec_pem(pem).map_err(|e| JwtError::InvalidKey(e.to_string()))
166        }
167        Algorithm::RS256 | Algorithm::RS384 | Algorithm::RS512 => {
168            EncodingKey::from_rsa_pem(pem).map_err(|e| JwtError::InvalidKey(e.to_string()))
169        }
170        _ => Err(JwtError::InvalidKey(format!(
171            "Unsupported algorithm for PEM: {alg:?}"
172        ))),
173    }
174}
175
176/// Create a JwtConfig from an HS256 shared secret.
177pub fn config_from_secret(secret: &[u8], issuer: Option<String>, audience: String) -> JwtConfig {
178    JwtConfig {
179        decoding_key: DecodingKey::from_secret(secret),
180        encoding_key: Some(EncodingKey::from_secret(secret)),
181        algorithm: Algorithm::HS256,
182        required_issuer: issuer,
183        required_audience: audience,
184        leeway_secs: 60,
185        public_key_pem: None,
186    }
187}
188
189/// Create a JwtConfig from PEM key files.
190pub fn config_from_pem(
191    public_pem: &[u8],
192    private_pem: Option<&[u8]>,
193    alg: Algorithm,
194    issuer: Option<String>,
195    audience: String,
196) -> Result<JwtConfig, JwtError> {
197    let decoding_key = load_public_key_pem(public_pem, alg)?;
198    let encoding_key = match private_pem {
199        Some(pem) => Some(load_private_key_pem(pem, alg)?),
200        None => None,
201    };
202
203    Ok(JwtConfig {
204        decoding_key,
205        encoding_key,
206        algorithm: alg,
207        required_issuer: issuer,
208        required_audience: audience,
209        leeway_secs: 60,
210        public_key_pem: Some(public_pem.to_vec()),
211    })
212}
213
214/// Generate a JWKS JSON object from a public key PEM.
215/// Returns the JWKS `keys` array suitable for `/.well-known/jwks.json`.
216pub fn public_key_to_jwks(
217    pem: &[u8],
218    alg: Algorithm,
219    kid: &str,
220) -> Result<serde_json::Value, JwtError> {
221    // Parse the PEM to extract the raw key bytes
222    let pem_str = std::str::from_utf8(pem).map_err(|e| JwtError::InvalidKey(e.to_string()))?;
223
224    // Extract base64 content between PEM headers
225    let key_type = match alg {
226        Algorithm::ES256 | Algorithm::ES384 => "EC",
227        Algorithm::RS256 | Algorithm::RS384 | Algorithm::RS512 => "RSA",
228        _ => {
229            return Err(JwtError::InvalidKey(
230                "Unsupported algorithm for JWKS".into(),
231            ))
232        }
233    };
234
235    let alg_str = match alg {
236        Algorithm::ES256 => "ES256",
237        Algorithm::ES384 => "ES384",
238        Algorithm::RS256 => "RS256",
239        Algorithm::RS384 => "RS384",
240        Algorithm::RS512 => "RS512",
241        _ => "unknown",
242    };
243
244    // For JWKS, we encode the full DER of the public key as x5c or use raw coordinates.
245    // Simpler approach: encode the entire PEM-decoded DER as a base64url x5c entry.
246    let der_b64: String = pem_str
247        .lines()
248        .filter(|line| !line.starts_with("-----"))
249        .collect::<Vec<_>>()
250        .join("");
251
252    let jwk = serde_json::json!({
253        "kty": key_type,
254        "use": "sig",
255        "alg": alg_str,
256        "kid": kid,
257        "x5c": [der_b64],
258    });
259
260    Ok(serde_json::json!({
261        "keys": [jwk]
262    }))
263}
264
265/// Build a JwtConfig from environment variables.
266///
267/// Priority:
268/// 1. `ATI_JWT_PUBLIC_KEY` (PEM file) → ES256
269/// 2. `ATI_JWT_SECRET` (hex string) → HS256
270/// 3. Neither → None (JWT disabled)
271pub fn config_from_env() -> Result<Option<JwtConfig>, JwtError> {
272    let issuer = std::env::var("ATI_JWT_ISSUER").ok();
273    let audience = std::env::var("ATI_JWT_AUDIENCE").unwrap_or_else(|_| "ati-proxy".to_string());
274
275    // Try ES256 first
276    if let Ok(pub_key_path) = std::env::var("ATI_JWT_PUBLIC_KEY") {
277        let public_pem = std::fs::read(&pub_key_path)
278            .map_err(|e| JwtError::InvalidKey(format!("Cannot read {pub_key_path}: {e}")))?;
279
280        let private_pem = std::env::var("ATI_JWT_PRIVATE_KEY")
281            .ok()
282            .and_then(|path| std::fs::read(&path).ok());
283
284        let mut config = config_from_pem(
285            &public_pem,
286            private_pem.as_deref(),
287            Algorithm::ES256,
288            issuer,
289            audience,
290        )?;
291
292        // Store raw PEM for JWKS endpoint
293        config.public_key_pem = Some(public_pem);
294
295        return Ok(Some(config));
296    }
297
298    // Try HS256 fallback
299    if let Ok(secret_hex) = std::env::var("ATI_JWT_SECRET") {
300        let secret_bytes = hex::decode(&secret_hex)
301            .map_err(|e| JwtError::InvalidKey(format!("ATI_JWT_SECRET is not valid hex: {e}")))?;
302
303        return Ok(Some(config_from_secret(&secret_bytes, issuer, audience)));
304    }
305
306    Ok(None)
307}
308
309/// Get the current Unix timestamp.
310pub fn now_secs() -> u64 {
311    std::time::SystemTime::now()
312        .duration_since(std::time::UNIX_EPOCH)
313        .unwrap_or_default()
314        .as_secs()
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320
321    fn hs256_config() -> JwtConfig {
322        config_from_secret(
323            b"test-secret-key-32-bytes-long!!!",
324            None,
325            "ati-proxy".into(),
326        )
327    }
328
329    fn hs256_config_with_issuer() -> JwtConfig {
330        config_from_secret(
331            b"test-secret-key-32-bytes-long!!!",
332            Some("ati-orchestrator".into()),
333            "ati-proxy".into(),
334        )
335    }
336
337    fn make_claims(scope: &str) -> TokenClaims {
338        let now = now_secs();
339        TokenClaims {
340            iss: Some("ati-orchestrator".into()),
341            sub: "agent-7".into(),
342            aud: "ati-proxy".into(),
343            iat: now,
344            exp: now + 1800,
345            jti: Some(uuid::Uuid::new_v4().to_string()),
346            scope: scope.into(),
347            ati: Some(AtiNamespace { v: 1, rate: HashMap::new() }),
348        }
349    }
350
351    #[test]
352    fn test_hs256_round_trip() {
353        let config = hs256_config();
354        let claims = make_claims("tool:web_search tool:github__*");
355
356        let token = issue(&claims, &config).unwrap();
357        let decoded = validate(&token, &config).unwrap();
358
359        assert_eq!(decoded.sub, "agent-7");
360        assert_eq!(decoded.aud, "ati-proxy");
361        assert_eq!(decoded.scope, "tool:web_search tool:github__*");
362        assert_eq!(decoded.scopes(), vec!["tool:web_search", "tool:github__*"]);
363        assert_eq!(decoded.iss, Some("ati-orchestrator".into()));
364    }
365
366    #[test]
367    fn test_expired_token_rejected() {
368        let config = hs256_config();
369        let mut claims = make_claims("tool:web_search");
370        claims.exp = 1; // Expired long ago
371
372        let token = issue(&claims, &config).unwrap();
373        let result = validate(&token, &config);
374        assert!(result.is_err());
375    }
376
377    #[test]
378    fn test_wrong_secret_rejected() {
379        let config1 = hs256_config();
380        let config2 =
381            config_from_secret(b"different-secret-key-32-bytes!!", None, "ati-proxy".into());
382
383        let claims = make_claims("tool:web_search");
384        let token = issue(&claims, &config1).unwrap();
385        let result = validate(&token, &config2);
386        assert!(result.is_err());
387    }
388
389    #[test]
390    fn test_wrong_audience_rejected() {
391        let config = hs256_config();
392        let mut claims = make_claims("tool:web_search");
393        claims.aud = "wrong-audience".into();
394
395        let token = issue(&claims, &config).unwrap();
396        let result = validate(&token, &config);
397        assert!(result.is_err());
398    }
399
400    #[test]
401    fn test_wrong_issuer_rejected() {
402        let config = hs256_config_with_issuer();
403        let mut claims = make_claims("tool:web_search");
404        claims.iss = Some("evil-orchestrator".into());
405
406        let token = issue(&claims, &config).unwrap();
407        let result = validate(&token, &config);
408        assert!(result.is_err());
409    }
410
411    #[test]
412    fn test_tampered_payload_rejected() {
413        let config = hs256_config();
414        let claims = make_claims("tool:web_search");
415        let token = issue(&claims, &config).unwrap();
416
417        // Tamper with the payload: change a character in the middle section
418        let parts: Vec<&str> = token.split('.').collect();
419        assert_eq!(parts.len(), 3);
420        let mut tampered_payload = parts[1].to_string();
421        // Flip a character
422        if tampered_payload.ends_with('A') {
423            tampered_payload.push('B');
424        } else {
425            tampered_payload.push('A');
426        }
427        let tampered = format!("{}.{}.{}", parts[0], tampered_payload, parts[2]);
428
429        let result = validate(&tampered, &config);
430        assert!(result.is_err());
431    }
432
433    #[test]
434    fn test_malformed_token_rejected() {
435        let config = hs256_config();
436        let result = validate("not.a.jwt.token.at.all", &config);
437        assert!(result.is_err());
438
439        let result = validate("", &config);
440        assert!(result.is_err());
441
442        let result = validate("just-a-string", &config);
443        assert!(result.is_err());
444    }
445
446    #[test]
447    fn test_inspect_decodes_without_key() {
448        let config = hs256_config();
449        let claims = make_claims("tool:web_search skill:research-*");
450        let token = issue(&claims, &config).unwrap();
451
452        let decoded = inspect(&token).unwrap();
453        assert_eq!(decoded.sub, "agent-7");
454        assert_eq!(decoded.scope, "tool:web_search skill:research-*");
455    }
456
457    #[test]
458    fn test_scope_parsing() {
459        let claims = make_claims("tool:web_search tool:github__* skill:research-* help");
460        let scopes = claims.scopes();
461        assert_eq!(
462            scopes,
463            vec![
464                "tool:web_search",
465                "tool:github__*",
466                "skill:research-*",
467                "help"
468            ]
469        );
470    }
471
472    #[test]
473    fn test_empty_scope() {
474        let claims = make_claims("");
475        assert!(claims.scopes().is_empty());
476    }
477
478    #[test]
479    fn test_single_scope() {
480        let claims = make_claims("*");
481        assert_eq!(claims.scopes(), vec!["*"]);
482    }
483
484    #[test]
485    fn test_no_encoding_key_fails() {
486        let config = JwtConfig {
487            decoding_key: DecodingKey::from_secret(b"test"),
488            encoding_key: None,
489            algorithm: Algorithm::HS256,
490            required_issuer: None,
491            required_audience: "ati-proxy".into(),
492            leeway_secs: 60,
493            public_key_pem: None,
494        };
495
496        let claims = make_claims("tool:web_search");
497        let result = issue(&claims, &config);
498        assert!(result.is_err());
499    }
500
501    #[test]
502    fn test_issuer_not_required_when_none() {
503        let config = hs256_config(); // No required_issuer
504        let mut claims = make_claims("tool:web_search");
505        claims.iss = None;
506
507        let token = issue(&claims, &config).unwrap();
508        let decoded = validate(&token, &config).unwrap();
509        assert_eq!(decoded.iss, None);
510    }
511
512    #[test]
513    fn test_jti_preserved() {
514        let config = hs256_config();
515        let claims = make_claims("tool:web_search");
516        let jti = claims.jti.clone();
517
518        let token = issue(&claims, &config).unwrap();
519        let decoded = validate(&token, &config).unwrap();
520        assert_eq!(decoded.jti, jti);
521    }
522
523    #[test]
524    fn test_ati_namespace_preserved() {
525        let config = hs256_config();
526        let claims = make_claims("tool:web_search");
527
528        let token = issue(&claims, &config).unwrap();
529        let decoded = validate(&token, &config).unwrap();
530        assert!(decoded.ati.is_some());
531        assert_eq!(decoded.ati.unwrap().v, 1);
532    }
533}