kz-server 0.1.0

JWT verification, CEL policies, and HTTP/MCP server for keyzero
Documentation
use crate::config::TagMapping;
use crate::jwt::VerifiedClaims;

/// Maps verified JWT claims to a set of tag strings using rules from the bundle.
///
/// Each tag mapping rule specifies an issuer name and a set of claim patterns.
/// If the issuer name matches the claim's `issuer_name` and all claim patterns
/// match (using glob matching), the mapping's tags are added to the result.
/// Multiple mappings can match, and their tags accumulate.
pub struct TagMapper {
    mappings: Vec<TagMapping>,
}

impl TagMapper {
    /// Create a new `TagMapper` with the given mapping rules.
    pub fn new(mappings: Vec<TagMapping>) -> Self {
        Self { mappings }
    }

    /// Map verified claims to a set of tags based on the configured mappings.
    ///
    /// For each mapping:
    /// 1. Check if the `issuer_name` from the claims matches the mapping's issuer.
    /// 2. For each claim pattern in the mapping, check if the corresponding claim
    ///    value matches the glob pattern.
    /// 3. If all checks pass, add all tags from the mapping to the result.
    pub fn map(&self, claims: &VerifiedClaims) -> Vec<String> {
        let mut tags = Vec::new();

        for mapping in &self.mappings {
            // Check issuer name match
            if mapping.match_rule.issuer != claims.issuer_name {
                continue;
            }

            // Check all claim patterns
            let all_claims_match = mapping.match_rule.claims.iter().all(|(key, pattern)| {
                match claims.claims.get(key) {
                    Some(value) => {
                        let value_str = match value {
                            serde_json::Value::String(s) => s.clone(),
                            other => other.to_string(),
                        };
                        glob_match::glob_match(pattern, &value_str)
                    }
                    None => false,
                }
            });

            if all_claims_match {
                tags.extend(mapping.tags.iter().cloned());
            }
        }

        tags
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::TagMatchRule;
    use std::collections::HashMap;

    fn make_claims(issuer_name: &str, claims: Vec<(&str, &str)>) -> VerifiedClaims {
        let mut claim_map = HashMap::new();
        for (k, v) in claims {
            claim_map.insert(k.to_string(), serde_json::Value::String(v.to_string()));
        }
        VerifiedClaims {
            issuer: "https://token.actions.githubusercontent.com".to_string(),
            issuer_name: issuer_name.to_string(),
            subject: "repo:myorg/my-repo:ref:refs/heads/main".to_string(),
            audience: vec!["kzagent".to_string()],
            claims: claim_map,
        }
    }

    #[test]
    fn test_exact_claim_match() {
        let mappings = vec![TagMapping {
            match_rule: TagMatchRule {
                issuer: "github-actions".to_string(),
                claims: HashMap::from([("repository".to_string(), "myorg/my-repo".to_string())]),
            },
            tags: vec!["team:platform".to_string()],
        }];

        let mapper = TagMapper::new(mappings);
        let claims = make_claims("github-actions", vec![("repository", "myorg/my-repo")]);
        let tags = mapper.map(&claims);
        assert_eq!(tags, vec!["team:platform"]);
    }

    #[test]
    fn test_glob_claim_match() {
        let mappings = vec![TagMapping {
            match_rule: TagMatchRule {
                issuer: "github-actions".to_string(),
                claims: HashMap::from([("repository".to_string(), "myorg/*".to_string())]),
            },
            tags: vec!["team:platform".to_string()],
        }];

        let mapper = TagMapper::new(mappings);
        let claims = make_claims("github-actions", vec![("repository", "myorg/any-repo")]);
        let tags = mapper.map(&claims);
        assert_eq!(tags, vec!["team:platform"]);
    }

    #[test]
    fn test_no_match_returns_empty() {
        let mappings = vec![TagMapping {
            match_rule: TagMatchRule {
                issuer: "github-actions".to_string(),
                claims: HashMap::from([("repository".to_string(), "otherorg/*".to_string())]),
            },
            tags: vec!["team:platform".to_string()],
        }];

        let mapper = TagMapper::new(mappings);
        let claims = make_claims("github-actions", vec![("repository", "myorg/my-repo")]);
        let tags = mapper.map(&claims);
        assert!(tags.is_empty());
    }

    #[test]
    fn test_multiple_mappings_accumulate_tags() {
        let mappings = vec![
            TagMapping {
                match_rule: TagMatchRule {
                    issuer: "github-actions".to_string(),
                    claims: HashMap::from([("repository".to_string(), "myorg/*".to_string())]),
                },
                tags: vec!["team:platform".to_string()],
            },
            TagMapping {
                match_rule: TagMatchRule {
                    issuer: "github-actions".to_string(),
                    claims: HashMap::from([("ref".to_string(), "refs/heads/main".to_string())]),
                },
                tags: vec!["env:prod".to_string()],
            },
        ];

        let mapper = TagMapper::new(mappings);
        let claims = make_claims(
            "github-actions",
            vec![("repository", "myorg/my-repo"), ("ref", "refs/heads/main")],
        );
        let tags = mapper.map(&claims);
        assert_eq!(tags, vec!["team:platform", "env:prod"]);
    }

    #[test]
    fn test_wrong_issuer_no_match() {
        let mappings = vec![TagMapping {
            match_rule: TagMatchRule {
                issuer: "kubernetes".to_string(),
                claims: HashMap::from([("repository".to_string(), "myorg/*".to_string())]),
            },
            tags: vec!["team:platform".to_string()],
        }];

        let mapper = TagMapper::new(mappings);
        let claims = make_claims("github-actions", vec![("repository", "myorg/my-repo")]);
        let tags = mapper.map(&claims);
        assert!(tags.is_empty());
    }
}