Compare commits

...

1 Commits

Author SHA1 Message Date
Yuval Kohavi
0a397c63ae
initial claim mapping 2026-03-24 10:00:56 -04:00
6 changed files with 347 additions and 27 deletions

View File

@ -57,6 +57,8 @@ pub enum JwkError {
algorithm: AlgorithmParameters,
key_id: String,
},
#[error("invalid claim mapper {0:?}")]
InvalidClaimMapper(cel::Error),
}
#[derive(Clone)]
@ -69,6 +71,7 @@ pub struct Jwt {
pub struct Provider {
issuer: String,
keys: HashMap<String, Jwk>,
claim_mappings: HashMap<String, Arc<cel::Expression>>,
}
// TODO: can we give anything useful here?
@ -99,10 +102,12 @@ impl serde::Serialize for Provider {
pub struct Serde<'a> {
issuer: &'a str,
keys: Vec<&'a str>,
claim_mappings: &'a HashMap<String, Arc<cel::Expression>>,
}
Serde {
issuer: &self.issuer,
keys: self.keys.keys().map(|x| x.as_str()).collect::<Vec<_>>(),
claim_mappings: &self.claim_mappings,
}
.serialize(serializer)
}
@ -133,6 +138,7 @@ pub enum LocalJwtConfig {
jwks: serdes::FileInlineOrRemote,
#[serde(default)]
jwt_validation_options: JWTValidationOptions,
claims_mapping: Option<HashMap<String, String>>,
},
}
@ -145,6 +151,7 @@ pub struct ProviderConfig {
pub jwks: serdes::FileInlineOrRemote,
#[serde(default)]
pub jwt_validation_options: JWTValidationOptions,
pub claims_mapping: Option<HashMap<String, String>>,
}
#[apply(schema_enum!)]
@ -225,6 +232,7 @@ impl LocalJwtConfig {
audiences,
jwks,
jwt_validation_options,
claims_mapping,
} => (
mode,
vec![ProviderConfig {
@ -232,6 +240,7 @@ impl LocalJwtConfig {
audiences,
jwks,
jwt_validation_options,
claims_mapping,
}],
),
};
@ -243,7 +252,13 @@ impl LocalJwtConfig {
.load::<JwkSet>(client.clone())
.await
.map_err(JwkError::JwkLoadError)?;
let provider = Provider::from_jwks(jwks, pc.issuer, pc.audiences, pc.jwt_validation_options)?;
let provider = Provider::from_jwks(
jwks,
pc.issuer,
pc.audiences,
pc.jwt_validation_options,
pc.claims_mapping.as_ref(),
)?;
providers.push(provider);
}
Ok(Jwt { mode, providers })
@ -256,6 +271,7 @@ impl Provider {
issuer: String,
audiences: Option<Vec<String>>,
jwt_validation_options: JWTValidationOptions,
claim_mapping: Option<&HashMap<String, String>>,
) -> Result<Provider, JwkError> {
warn_unsupported_claims(&jwt_validation_options.required_claims);
@ -331,8 +347,16 @@ impl Provider {
},
);
}
Ok(Provider { issuer, keys })
let claim_mappings: Result<HashMap<String, _>, _> = claim_mapping
.unwrap_or(&HashMap::new())
.iter()
.map(|(k, v)| cel::Expression::new_strict(v).map(|v| (k.clone(), Arc::new(v))))
.collect();
Ok(Provider {
issuer,
keys,
claim_mappings: claim_mappings.map_err(|e| JwkError::InvalidClaimMapper(e))?,
})
}
}
@ -406,8 +430,8 @@ impl Jwt {
// Otherwise with no, don't attempt to authenticate.
return Ok(());
};
let claims = match self.validate_claims(bearer.token()) {
Ok(claims) => claims,
let (provider, mut claims) = match self.validate_claims(bearer.token()) {
Ok(provider_and_claims) => provider_and_claims,
Err(e) if self.mode == Mode::Permissive => {
debug!("token verification failed ({e}), continue due to permissive mode");
return Ok(());
@ -421,12 +445,47 @@ impl Jwt {
};
// Remove the token.
req.headers_mut().remove(http::header::AUTHORIZATION);
// add the claim mappings
for (claim, expr) in &provider.claim_mappings {
let res = {
// The reason we need to create a new executor in each iteration, is because the
// claim mapping expressions is borrowed by the executor, so for us to insert new values to it,
// the executor needs to be end before we can insert the result of the execution to the claims.
// As creating a new executor is cheap, this should be ok.
let mut exec = cel::Executor::new_request(req);
exec.jwt = cel::ExtensionOrDirect::Direct(Some(&claims));
exec.eval(expr.as_ref()).map(|v| Self::cel_to_json(v))
};
let value = match res {
Ok(value) => value,
Err(e) => {
debug!(%claim, ?e, "failed to evaluate claim mapping expression, default to null");
serde_json::Value::Null
},
};
debug!(%claim, ?value, "mapped claim to request extension");
claims.inner.insert(claim.clone(), value);
}
// Insert the claims into extensions so we can reference it later
req.extensions_mut().insert(claims);
Ok(())
}
pub fn validate_claims(&self, token: &str) -> Result<Claims, TokenError> {
fn cel_to_json(value: cel::Value) -> serde_json::Value {
match value {
// for now, only support string cel outputs. we shouldn't need more complex outputs for claim mapping, and this keeps things simple for now
cel::Value::String(s) => serde_json::Value::String(s.to_string()),
_ => {
debug!(
?value,
"unsupported CEL value type for claim mapping, default to null"
);
serde_json::Value::Null
},
}
}
fn validate_claims(&self, token: &str) -> Result<(&Provider, Claims), TokenError> {
let header = decode_header(token).map_err(|error| {
debug!(?error, "Received token with invalid header.");
@ -439,10 +498,10 @@ impl Jwt {
})?;
// Search for the key across all providers
let key = self
let (provider, key) = self
.providers
.iter()
.find_map(|provider| provider.keys.get(kid))
.find_map(|provider| provider.keys.get(kid).map(|key| (provider, key)))
.ok_or_else(|| {
debug!(%kid, "Token refers to an unknown key.");
@ -460,6 +519,6 @@ impl Jwt {
inner: decoded_token.claims,
jwt: SecretString::new(token.into()),
};
Ok(claims)
Ok((provider, claims))
}
}

View File

@ -1,4 +1,4 @@
use std::collections::HashSet;
use std::collections::{HashMap, HashSet};
use super::{JWTValidationOptions, Jwt, LocalJwtConfig, Mode, Provider, TokenError};
use crate::telemetry::log::MetricsConfig;
@ -153,6 +153,7 @@ pub fn test_azure_jwks() {
"https://login.microsoftonline.com/test/v2.0".to_string(),
Some(vec!["test-aud".to_string()]),
JWTValidationOptions::default(),
None,
)
.unwrap();
assert_eq!(
@ -182,6 +183,7 @@ pub fn test_basic_jwks() {
"https://example.com".to_string(),
Some(vec!["test-aud".to_string()]),
JWTValidationOptions::default(),
None,
)
.unwrap();
assert_eq!(
@ -215,6 +217,7 @@ fn setup_test_jwt() -> (Jwt, &'static str, &'static str, &'static str) {
issuer.to_string(),
Some(vec![allowed_aud.to_string()]),
JWTValidationOptions::default(),
None,
)
.unwrap();
// Test-only: allow synthetic tokens without a real signature
@ -307,7 +310,8 @@ pub fn test_jwt_rejections_table() {
Expected::Iss => assert!(matches!(e.kind(), ErrorKind::InvalidIssuer), "{name}"),
Expected::Exp => assert!(matches!(e.kind(), ErrorKind::ExpiredSignature), "{name}"),
},
other => panic!("{name}: expected Invalid(..), got {:?}", other),
Err(e) => panic!("{name}: expected Invalid(..), got {:?}", e),
Ok(_) => panic!("{name}: expected Invalid(..), got Ok(..)"),
}
}
@ -551,6 +555,7 @@ fn setup_test_multi_jwt() -> (Jwt, ProviderInfo, ProviderInfo) {
issuer1.to_string(),
Some(vec![aud1.to_string()]),
JWTValidationOptions::default(),
None,
)
.unwrap();
#[allow(deprecated)]
@ -568,6 +573,7 @@ fn setup_test_multi_jwt() -> (Jwt, ProviderInfo, ProviderInfo) {
issuer2.to_string(),
Some(vec![aud2.to_string()]),
JWTValidationOptions::default(),
None,
)
.unwrap();
#[allow(deprecated)]
@ -662,6 +668,7 @@ pub fn test_empty_required_claims_accepts_token_without_exp() {
issuer.to_string(),
Some(vec![aud.to_string()]),
jwt_validation_options,
None,
)
.unwrap();
@ -687,7 +694,7 @@ pub fn test_empty_required_claims_accepts_token_without_exp() {
"empty required_claims should accept tokens without exp claim"
);
let claims = result.unwrap();
let (_, claims) = result.unwrap();
assert_eq!(
claims.inner.get("sub"),
Some(&serde_json::Value::String("test-user".to_string()))
@ -720,6 +727,7 @@ pub fn test_default_required_claims_rejects_token_without_exp() {
issuer.to_string(),
Some(vec![aud.to_string()]),
JWTValidationOptions::default(),
None,
)
.unwrap();
@ -776,6 +784,7 @@ pub fn test_empty_required_claims_still_rejects_expired_tokens() {
issuer.to_string(),
Some(vec![aud.to_string()]),
jwt_validation_options,
None,
)
.unwrap();
@ -832,6 +841,7 @@ pub fn test_required_claims_with_nbf_rejects_missing_nbf() {
issuer.to_string(),
Some(vec![aud.to_string()]),
jwt_validation_options,
None,
)
.unwrap();
@ -863,3 +873,141 @@ pub fn test_required_claims_with_nbf_rejects_missing_nbf() {
"required_claims with nbf should reject tokens missing nbf claim"
);
}
#[test]
pub fn test_provider_from_jwks_compiles_claim_mappings() {
let jwks = json!({
"keys": [
{
"use": "sig",
"kty": "EC",
"kid": "mapping-kid",
"crv": "P-256",
"alg": "ES256",
"x": "XZHF8Em5LbpqfgewAalpSEH4Ka2I2xjcxxUt2j6-lCo",
"y": "g3DFz45A7EOUMgmsNXatrXw1t-PG5xsbkxUs851RxSE"
}
]
});
let jwks = serde_json::from_value(jwks).unwrap();
let claim_mapping = HashMap::from([(
"mappedIssuer".to_string(),
"jwt.iss".to_string(),
)]);
let provider = Provider::from_jwks(
jwks,
"https://mapping-idp.example.com".to_string(),
Some(vec!["mapping-aud".to_string()]),
JWTValidationOptions::default(),
Some(&claim_mapping),
)
.unwrap();
assert!(provider.claim_mappings.contains_key("mappedIssuer"));
}
#[test]
pub fn test_provider_from_jwks_rejects_invalid_claim_mapping_expression() {
let jwks = json!({
"keys": [
{
"use": "sig",
"kty": "EC",
"kid": "mapping-kid-invalid",
"crv": "P-256",
"alg": "ES256",
"x": "XZHF8Em5LbpqfgewAalpSEH4Ka2I2xjcxxUt2j6-lCo",
"y": "g3DFz45A7EOUMgmsNXatrXw1t-PG5xsbkxUs851RxSE"
}
]
});
let jwks = serde_json::from_value(jwks).unwrap();
let claim_mapping = HashMap::from([("bad".to_string(), "jwt.".to_string())]);
let provider = Provider::from_jwks(
jwks,
"https://mapping-idp.example.com".to_string(),
Some(vec!["mapping-aud".to_string()]),
JWTValidationOptions::default(),
Some(&claim_mapping),
);
assert!(matches!(provider, Err(super::JwkError::InvalidClaimMapper(_))));
}
#[tokio::test]
pub async fn test_apply_inserts_claim_from_claim_mapping() {
use std::time::{SystemTime, UNIX_EPOCH};
let jwks = json!({
"keys": [
{
"use": "sig",
"kty": "EC",
"kid": "mapping-apply-kid",
"crv": "P-256",
"alg": "ES256",
"x": "XZHF8Em5LbpqfgewAalpSEH4Ka2I2xjcxxUt2j6-lCo",
"y": "g3DFz45A7EOUMgmsNXatrXw1t-PG5xsbkxUs851RxSE"
}
]
});
let jwks = serde_json::from_value(jwks).unwrap();
let issuer = "https://mapped-claim-idp.example.com";
let aud = "mapped-claim-aud";
let kid = "mapping-apply-kid";
let claim_mapping = HashMap::from([(
"issuerAlias".to_string(),
"jwt.iss".to_string(),
)]);
let mut provider = Provider::from_jwks(
jwks,
issuer.to_string(),
Some(vec![aud.to_string()]),
JWTValidationOptions::default(),
Some(&claim_mapping),
)
.unwrap();
#[allow(deprecated)]
{
provider
.keys
.get_mut(kid)
.unwrap()
.validation
.insecure_disable_signature_validation();
}
let jwt = Jwt {
mode: Mode::Strict,
providers: vec![provider],
};
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let token = build_unsigned_token(kid, issuer, aud, now + 600);
let mut req = crate::http::Request::new(crate::http::Body::empty());
req.headers_mut().insert(
crate::http::header::AUTHORIZATION,
crate::http::HeaderValue::from_str(&format!("Bearer {token}")).unwrap(),
);
let mut log = make_min_req_log();
let res = jwt.apply(Some(&mut log), &mut req).await;
assert!(res.is_ok());
let claims = req.extensions().get::<super::Claims>().unwrap();
assert_eq!(
claims.inner.get("issuerAlias"),
Some(&serde_json::Value::String(issuer.to_string()))
);
}

View File

@ -2165,6 +2165,7 @@ impl LocalMcpAuthentication {
audiences: Some(self.audiences.clone()),
jwks,
jwt_validation_options: self.jwt_validation_options.clone(),
claims_mapping: None,
})
}

View File

@ -220,13 +220,18 @@ impl TryFrom<&proto::agent::backend_policy_spec::McpAuthentication> for McpAuthe
required_claims: vo.required_claims.iter().cloned().collect(),
})
.unwrap_or_default();
let jwt_provider =
http::jwt::Provider::from_jwks(jwk_set, m.issuer.clone(), audiences, jwt_validation_options)
.map_err(|e| {
ProtoError::Generic(format!(
"failed to create JWT provider for MCP Authentication: {e}"
))
})?;
let jwt_provider = http::jwt::Provider::from_jwks(
jwk_set,
m.issuer.clone(),
audiences,
jwt_validation_options,
None,
)
.map_err(|e| {
ProtoError::Generic(format!(
"failed to create JWT provider for MCP Authentication: {e}"
))
})?;
let mode = match proto::agent::backend_policy_spec::mcp_authentication::Mode::try_from(m.mode)
.map_err(|_| ProtoError::EnumParse("invalid JWT mode".to_string()))?
@ -1415,6 +1420,7 @@ impl TryFrom<&proto::agent::TrafficPolicySpec> for TrafficPolicy {
p.issuer.clone(),
audiences,
jwt_validation_options,
p.claim_mapping.as_ref().map(|x| &x.mapping),
)
.map_err(|e| ProtoError::Generic(format!("failed to create JWT config: {e}")))
})
@ -2414,4 +2420,98 @@ mod tests {
assert!(path.contains("qualifier=v1"));
Ok(())
}
#[test]
fn test_jwt_claim_mapping_xds_conversion_accepts_valid_mapping() -> Result<(), ProtoError> {
let jwks = json!({
"keys": [
{
"use": "sig",
"kty": "EC",
"kid": "jwt-claim-map-kid",
"crv": "P-256",
"alg": "ES256",
"x": "XZHF8Em5LbpqfgewAalpSEH4Ka2I2xjcxxUt2j6-lCo",
"y": "g3DFz45A7EOUMgmsNXatrXw1t-PG5xsbkxUs851RxSE"
}
]
});
let spec = proto::agent::TrafficPolicySpec {
phase: proto::agent::traffic_policy_spec::PolicyPhase::Route as i32,
kind: Some(proto::agent::traffic_policy_spec::Kind::Jwt(
proto::agent::traffic_policy_spec::Jwt {
mode: proto::agent::traffic_policy_spec::jwt::Mode::Strict as i32,
providers: vec![proto::agent::traffic_policy_spec::JwtProvider {
issuer: "https://issuer.example.com".to_string(),
audiences: vec!["aud-1".to_string()],
jwks_source: Some(
proto::agent::traffic_policy_spec::jwt_provider::JwksSource::Inline(
jwks.to_string(),
),
),
jwt_validation_options: None,
claim_mapping: Some(proto::agent::traffic_policy_spec::ClaimMapping {
mapping: [("issuerAlias".to_string(), "jwt.iss".to_string())]
.into_iter()
.collect(),
}),
}],
},
)),
};
let policy = TrafficPolicy::try_from(&spec)?;
assert!(matches!(policy, TrafficPolicy::JwtAuth(_)));
Ok(())
}
#[test]
fn test_jwt_claim_mapping_xds_conversion_rejects_invalid_mapping() {
let jwks = json!({
"keys": [
{
"use": "sig",
"kty": "EC",
"kid": "jwt-claim-map-kid-invalid",
"crv": "P-256",
"alg": "ES256",
"x": "XZHF8Em5LbpqfgewAalpSEH4Ka2I2xjcxxUt2j6-lCo",
"y": "g3DFz45A7EOUMgmsNXatrXw1t-PG5xsbkxUs851RxSE"
}
]
});
let spec = proto::agent::TrafficPolicySpec {
phase: proto::agent::traffic_policy_spec::PolicyPhase::Route as i32,
kind: Some(proto::agent::traffic_policy_spec::Kind::Jwt(
proto::agent::traffic_policy_spec::Jwt {
mode: proto::agent::traffic_policy_spec::jwt::Mode::Strict as i32,
providers: vec![proto::agent::traffic_policy_spec::JwtProvider {
issuer: "https://issuer.example.com".to_string(),
audiences: vec!["aud-1".to_string()],
jwks_source: Some(
proto::agent::traffic_policy_spec::jwt_provider::JwksSource::Inline(
jwks.to_string(),
),
),
jwt_validation_options: None,
claim_mapping: Some(proto::agent::traffic_policy_spec::ClaimMapping {
mapping: [("bad".to_string(), "jwt.".to_string())]
.into_iter()
.collect(),
}),
}],
},
)),
};
let err = TrafficPolicy::try_from(&spec).unwrap_err();
assert!(
err
.to_string()
.contains("failed to create JWT config"),
"unexpected error: {err}"
);
}
}

View File

@ -151,6 +151,7 @@ policies:
providers:
- issuer: agentgateway.dev
keys: []
claim_mappings: {}
phase: gateway
- key: listener/1
name: ~

View File

@ -665,6 +665,13 @@ message TrafficPolicySpec {
repeated string allow = 1;
repeated string deny = 2;
}
message ClaimMapping {
// Mapping between a name and a CEL expression to extract the claim value from the token.
// the name will be appear as a JWT claim for purposes of policy.
map<string, string> mapping = 1;
}
message JWTProvider {
// JWT issuer that must match the 'iss' claim
string issuer = 1;
@ -680,18 +687,22 @@ message TrafficPolicySpec {
// JWT validation options controlling which claims must be present.
JWTValidationOptions jwt_validation_options = 4;
// These map jwt claims to internal metadata fields that can be used in later policies.
ClaimMapping claim_mapping = 5;
}
// JWT authentication configuration
message JWT {
// Validation mode for JWT authentication
enum Mode {
// Default mode - if a token exists, validate it
OPTIONAL = 0;
// A valid token must be present
STRICT = 1;
// Requests are never rejected (useful for claims in later steps)
PERMISSIVE = 2;
}
enum Mode {
// Default mode - if a token exists, validate it
OPTIONAL = 0;
// A valid token must be present
STRICT = 1;
// Requests are never rejected (useful for claims in later steps)
PERMISSIVE = 2;
}
// How the JWT validation should behave
Mode mode = 1;