kz-server 0.2.0

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

/// Convert a JSON value to a string, avoiding extra quotes for string values.
pub(crate) fn json_value_to_string(v: &serde_json::Value) -> String {
    match v {
        serde_json::Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

/// 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 = json_value_to_string(value);
                        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_name: issuer_name.to_string(),
            claims: claim_map,
        }
    }

    fn make_mapping(issuer: &str, claims: &[(&str, &str)], tags: &[&str]) -> TagMapping {
        TagMapping {
            match_rule: TagMatchRule {
                issuer: issuer.to_string(),
                claims: claims.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),
            },
            tags: tags.iter().map(|t| t.to_string()).collect(),
        }
    }

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

    #[test]
    fn test_glob_claim_match() {
        let mapper = TagMapper::new(vec![
            make_mapping("github-actions", &[("repository", "myorg/*")], &["team:platform"]),
        ]);
        let tags = mapper.map(&make_claims("github-actions", vec![("repository", "myorg/any-repo")]));
        assert_eq!(tags, vec!["team:platform"]);
    }

    #[test]
    fn test_no_match_returns_empty() {
        let mapper = TagMapper::new(vec![
            make_mapping("github-actions", &[("repository", "otherorg/*")], &["team:platform"]),
        ]);
        let tags = mapper.map(&make_claims("github-actions", vec![("repository", "myorg/my-repo")]));
        assert!(tags.is_empty());
    }

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

    #[test]
    fn test_wrong_issuer_no_match() {
        let mapper = TagMapper::new(vec![
            make_mapping("kubernetes", &[("repository", "myorg/*")], &["team:platform"]),
        ]);
        let tags = mapper.map(&make_claims("github-actions", vec![("repository", "myorg/my-repo")]));
        assert!(tags.is_empty());
    }
}