Skip to main content

kz_server/
config.rs

1use std::collections::HashMap;
2use std::path::Path;
3
4use serde::Deserialize;
5
6use crate::error::{Result, ServerError};
7
8// ---------------------------------------------------------------------------
9// Top-level bundle
10// ---------------------------------------------------------------------------
11
12#[derive(Debug, Clone, Deserialize)]
13pub struct Bundle {
14    pub version: String,
15    #[serde(default)]
16    pub issuers: Vec<Issuer>,
17    #[serde(default)]
18    pub policies: Vec<Policy>,
19    #[serde(default)]
20    pub resources: Vec<Resource>,
21    #[serde(default)]
22    pub backends: HashMap<String, BackendConfig>,
23}
24
25impl Bundle {
26    /// Load a bundle from a YAML file on disk.
27    pub fn load(path: &Path) -> Result<Self> {
28        let content = std::fs::read_to_string(path)
29            .map_err(|e| ServerError::Config(format!("cannot read bundle file: {e}")))?;
30        let bundle: Bundle = serde_yaml::from_str(&content)
31            .map_err(|e| ServerError::Config(format!("cannot parse bundle YAML: {e}")))?;
32        Ok(bundle)
33    }
34
35    /// Return the most-specific matching resource for `ref_path`.
36    ///
37    /// Priority:
38    /// 1. Exact match (`ref_pattern == ref_path`) wins immediately.
39    /// 2. Glob matches — highest specificity (longest literal prefix) wins.
40    /// 3. Tie-breaker: first defined in the bundle.
41    pub fn match_resource(&self, ref_path: &str) -> Option<&Resource> {
42        // 1. Exact match
43        if let Some(r) = self.resources.iter().find(|r| r.ref_pattern == ref_path) {
44            return Some(r);
45        }
46
47        // 2. Glob matches — pick highest specificity, first-defined on tie
48        self.resources
49            .iter()
50            .filter(|r| r.is_glob() && glob_match::glob_match(&r.ref_pattern, ref_path))
51            .max_by_key(|r| r.specificity())
52    }
53}
54
55// ---------------------------------------------------------------------------
56// Issuer
57// ---------------------------------------------------------------------------
58
59#[derive(Debug, Clone, Deserialize)]
60pub struct Issuer {
61    pub name: String,
62    #[serde(rename = "type", default)]
63    pub issuer_type: IssuerType,
64    pub issuer_url: String,
65    pub jwks_url: Option<String>,
66    pub audience: Option<String>,
67    pub static_keys: Option<Vec<StaticKey>>,
68    /// Claim field overrides; merged on top of the built-in profile.
69    pub map: Option<HashMap<String, String>>,
70}
71
72impl Issuer {
73    /// Returns the effective claim map: built-in profile merged with any
74    /// user-supplied overrides from `map`.
75    pub fn effective_map(&self) -> HashMap<String, String> {
76        let mut m = self.issuer_type.default_map();
77        if let Some(overrides) = &self.map {
78            m.extend(overrides.iter().map(|(k, v)| (k.clone(), v.clone())));
79        }
80        m
81    }
82}
83
84// ---------------------------------------------------------------------------
85// IssuerType
86// ---------------------------------------------------------------------------
87
88#[derive(Debug, Clone, Deserialize, Default)]
89#[serde(rename_all = "kebab-case")]
90pub enum IssuerType {
91    GithubActions,
92    Kubernetes,
93    Gcp,
94    Aws,
95    #[default]
96    Custom,
97}
98
99const GITHUB_ACTIONS_MAP: &[(&str, &str)] = &[
100    ("org", "repository_owner"),
101    ("service", "repository"),
102    ("env", "environment"),
103    ("action", "workflow"),
104    ("branch", "ref"),
105    ("actor", "actor"),
106];
107
108const KUBERNETES_MAP: &[(&str, &str)] = &[
109    ("org", "namespace"),
110    ("service", "serviceaccount"),
111];
112
113const GCP_MAP: &[(&str, &str)] = &[
114    ("org", "project_id"),
115    ("service", "email"),
116];
117
118const AWS_MAP: &[(&str, &str)] = &[
119    ("org", "account_id"),
120    ("service", "arn"),
121];
122
123impl IssuerType {
124    /// Returns the built-in claim-mapping profile for this issuer type.
125    /// Keys are canonical identity field names; values are JWT claim names.
126    pub fn default_map(&self) -> HashMap<String, String> {
127        let pairs: &[(&str, &str)] = match self {
128            IssuerType::GithubActions => GITHUB_ACTIONS_MAP,
129            IssuerType::Kubernetes => KUBERNETES_MAP,
130            IssuerType::Gcp => GCP_MAP,
131            IssuerType::Aws => AWS_MAP,
132            IssuerType::Custom => &[],
133        };
134
135        pairs
136            .iter()
137            .map(|(k, v)| (k.to_string(), v.to_string()))
138            .collect()
139    }
140}
141
142// ---------------------------------------------------------------------------
143// StaticKey
144// ---------------------------------------------------------------------------
145
146#[derive(Debug, Clone, Deserialize)]
147pub struct StaticKey {
148    pub kid: String,
149    pub alg: String,
150    pub pem: String,
151}
152
153// ---------------------------------------------------------------------------
154// Policy / Effect
155// ---------------------------------------------------------------------------
156
157#[derive(Debug, Clone, Deserialize)]
158pub struct Policy {
159    pub name: String,
160    pub description: Option<String>,
161    pub rule: String,
162    pub effect: Effect,
163}
164
165#[derive(Debug, Clone, Deserialize, PartialEq)]
166#[serde(rename_all = "snake_case")]
167pub enum Effect {
168    Allow,
169    Deny,
170}
171
172// ---------------------------------------------------------------------------
173// Resource / ResolverMode
174// ---------------------------------------------------------------------------
175
176#[derive(Debug, Clone, Deserialize)]
177pub struct Resource {
178    #[serde(rename = "ref")]
179    pub ref_pattern: String,
180    pub resolver: String,
181    #[serde(default)]
182    pub mode: ResolverMode,
183    pub credential_location: Option<String>,
184    pub ttl: Option<u64>,
185    pub path: Option<String>,
186    pub field: Option<String>,
187    pub role_arn: Option<String>,
188    pub duration_seconds: Option<u64>,
189    pub secret_id: Option<String>,
190}
191
192impl Resource {
193    /// Length of the literal prefix before the first glob character.
194    pub fn specificity(&self) -> usize {
195        self.ref_pattern
196            .find(|c| c == '*' || c == '?' || c == '[')
197            .unwrap_or(self.ref_pattern.len())
198    }
199
200    /// Returns `true` if `ref_pattern` contains any glob metacharacter.
201    pub fn is_glob(&self) -> bool {
202        self.ref_pattern
203            .contains(|c| c == '*' || c == '?' || c == '[')
204    }
205}
206
207#[derive(Debug, Clone, Deserialize, PartialEq, Default)]
208#[serde(rename_all = "snake_case")]
209pub enum ResolverMode {
210    #[default]
211    Direct,
212    ShortLived,
213}
214
215// ---------------------------------------------------------------------------
216// BackendConfig / BackendType / BackendAuth
217// ---------------------------------------------------------------------------
218
219#[derive(Debug, Clone, Deserialize)]
220pub struct BackendConfig {
221    #[serde(rename = "type")]
222    pub backend_type: BackendType,
223    pub address: Option<String>,
224    pub auth: Option<BackendAuth>,
225    pub region: Option<String>,
226    pub path: Option<String>,
227    pub vault: Option<String>,
228}
229
230#[derive(Debug, Clone, Deserialize)]
231#[serde(rename_all = "snake_case")]
232pub enum BackendType {
233    EnvFile,
234    HashicorpVault,
235    AwsSecretsManager,
236    AwsSts,
237    #[serde(rename = "1password_cli")]
238    OnepasswordCli,
239}
240
241impl BackendType {
242    /// Maps to the secret-resolvers crate resolver name.
243    pub fn as_resolver_name(&self) -> &'static str {
244        match self {
245            BackendType::EnvFile => "env_file",
246            BackendType::HashicorpVault => "hashicorp",
247            BackendType::AwsSecretsManager => "aws",
248            BackendType::AwsSts => "aws_sts",
249            BackendType::OnepasswordCli => "1password",
250        }
251    }
252}
253
254#[derive(Debug, Clone, Deserialize)]
255pub struct BackendAuth {
256    pub method: String,
257    pub role: Option<String>,
258}