Skip to main content

kz_server/
pipeline.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4use secret_resolvers::{ExposeSecret, Request, SecretResolver};
5use serde::{Deserialize, Serialize};
6use crate::config::{BackendConfig, Bundle, ResolverMode, Resource};
7use crate::error::{Result, ServerError};
8use crate::identity::{Identity, JwtVerifier};
9use crate::policy::{PolicyDecision, PolicyEngine, PolicyInput};
10use crate::security::validate_ref;
11use crate::signing::Signer;
12
13// ---------------------------------------------------------------------------
14// Constants
15// ---------------------------------------------------------------------------
16
17const VAULT_TOKEN_ENV: &str = "VAULT_TOKEN";
18const SIGNING_KEY_ENV: &str = "KEYZERO_SIGNING_KEY_PATH";
19const PROXY_URL_ENV: &str = "KEYZERO_PROXY_URL";
20const DEFAULT_TTL: u64 = 300;
21
22// ---------------------------------------------------------------------------
23// Request / Response types
24// ---------------------------------------------------------------------------
25
26#[derive(Debug, Deserialize)]
27pub struct ResolveRequest {
28    #[serde(rename = "ref")]
29    pub ref_path: Option<String>,
30    pub refs: Option<Vec<String>>,
31    #[serde(default)]
32    pub context: Option<HashMap<String, serde_json::Value>>,
33}
34
35/// Response for /v1/resolve. Always wraps results in a `results` map,
36/// even for single-ref requests, for client consistency.
37#[derive(Debug, Serialize)]
38pub struct ResolveResponse {
39    pub results: HashMap<String, RefResult>,
40}
41
42#[derive(Debug, Serialize)]
43pub struct RefResult {
44    pub allowed: bool,
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub policy: Option<String>,
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub mode: Option<String>,
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub value: Option<String>,
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub token: Option<String>,
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub proxy: Option<String>,
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub ttl: Option<u64>,
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub reason: Option<String>,
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub error: Option<String>,
61}
62
63impl Default for RefResult {
64    fn default() -> Self {
65        Self {
66            allowed: false,
67            policy: None,
68            mode: None,
69            value: None,
70            token: None,
71            proxy: None,
72            ttl: None,
73            reason: None,
74            error: None,
75        }
76    }
77}
78
79impl RefResult {
80    fn denied(policy: &str, reason: &str) -> Self {
81        Self {
82            allowed: false,
83            policy: Some(policy.to_string()),
84            reason: Some(reason.to_string()),
85            ..Default::default()
86        }
87    }
88}
89
90// ---------------------------------------------------------------------------
91// Pipeline
92// ---------------------------------------------------------------------------
93
94pub struct Pipeline {
95    pub(crate) bundle: Bundle,
96    verifier: JwtVerifier,
97    engine: PolicyEngine,
98    resolvers: HashMap<String, Arc<dyn SecretResolver>>,
99    signer: Option<Signer>,
100    proxy_url: Option<String>,
101}
102
103impl Pipeline {
104    /// Create a new pipeline from a bundle configuration.
105    pub async fn new(bundle: Bundle) -> Result<Self> {
106        // 1. JWT verifier
107        let verifier = JwtVerifier::new(bundle.issuers.clone());
108
109        // 2. Policy engine (compile CEL)
110        let engine = PolicyEngine::new(&bundle.policies)?;
111
112        // 3. Resolvers from backends
113        let mut resolvers: HashMap<String, Arc<dyn SecretResolver>> = HashMap::new();
114        for (name, backend) in &bundle.backends {
115            let config_map = backend_to_config(backend);
116            let resolver = secret_resolvers::registry::create_resolver(
117                backend.backend_type.as_resolver_name(),
118                config_map,
119            )
120            .await
121            .map_err(|e| {
122                ServerError::Config(format!("failed to create resolver '{name}': {e}"))
123            })?;
124            resolvers.insert(name.clone(), resolver);
125        }
126
127        // 4. Optional signer
128        let signer = match std::env::var(SIGNING_KEY_ENV) {
129            Ok(path) => {
130                let pem = std::fs::read(&path).map_err(|e| {
131                    ServerError::Config(format!("cannot read signing key at '{path}': {e}"))
132                })?;
133                Some(Signer::new(&pem, "keyzero")?)
134            }
135            Err(_) => None,
136        };
137
138        // 5. Optional proxy URL
139        let proxy_url = std::env::var(PROXY_URL_ENV).ok();
140
141        Ok(Self {
142            bundle,
143            verifier,
144            engine,
145            resolvers,
146            signer,
147            proxy_url,
148        })
149    }
150
151    /// Batch resolve: verify JWT once, resolve each ref independently.
152    pub async fn resolve(
153        &self,
154        token: &str,
155        request: &ResolveRequest,
156    ) -> Result<ResolveResponse> {
157        // Extract refs
158        let refs = match (&request.refs, &request.ref_path) {
159            (Some(refs), _) => refs.clone(),
160            (None, Some(r)) => vec![r.clone()],
161            (None, None) => {
162                return Err(ServerError::Resolution(
163                    "request must contain 'ref' or 'refs'".into(),
164                ))
165            }
166        };
167
168        // Validate all refs upfront
169        for r in &refs {
170            validate_ref(r)?;
171        }
172
173        // Verify JWT once
174        let identity = self.verifier.verify(token).await?;
175
176        let context = request.context.clone().unwrap_or_default();
177
178        // Resolve each ref
179        let mut results = HashMap::new();
180        for ref_path in &refs {
181            let result = self
182                .resolve_single_ref(&identity, ref_path, &context)
183                .await;
184            results.insert(ref_path.clone(), result);
185        }
186
187        Ok(ResolveResponse { results })
188    }
189
190    /// Resolve a single ref (used by MCP fetch tool).
191    /// Returns the secret value and a reference to the matched resource.
192    pub async fn resolve_single(
193        &self,
194        token: &str,
195        ref_path: &str,
196        context: &HashMap<String, serde_json::Value>,
197    ) -> Result<(String, &Resource)> {
198        validate_ref(ref_path)?;
199        let identity = self.verifier.verify(token).await?;
200
201        let resource = self
202            .bundle
203            .match_resource(ref_path)
204            .ok_or_else(|| ServerError::UnknownRef(ref_path.into()))?;
205
206        let input = PolicyInput {
207            identity: &identity,
208            ref_path,
209            context,
210        };
211        match self.engine.evaluate(&input) {
212            PolicyDecision::Allow { .. } => {}
213            PolicyDecision::Deny { policy, reason } => {
214                return Err(ServerError::Resolution(format!(
215                    "denied by policy '{policy}': {reason}"
216                )));
217            }
218        }
219
220        let value = self.resolve_from_backend(ref_path, resource).await?;
221        Ok((value, resource))
222    }
223
224    /// Consume the pipeline and return the resolvers map (for proxy mode).
225    pub fn into_resolvers(self) -> HashMap<String, Arc<dyn SecretResolver>> {
226        self.resolvers
227    }
228
229    /// Borrow the bundle.
230    pub fn bundle(&self) -> &Bundle {
231        &self.bundle
232    }
233
234    // -----------------------------------------------------------------------
235    // Internal helpers
236    // -----------------------------------------------------------------------
237
238    async fn resolve_single_ref(
239        &self,
240        identity: &Identity,
241        ref_path: &str,
242        context: &HashMap<String, serde_json::Value>,
243    ) -> RefResult {
244        // 1. Match resource
245        let resource = match self.bundle.match_resource(ref_path) {
246            Some(r) => r,
247            None => {
248                return RefResult {
249                    error: Some("no resource matches ref".into()),
250                    ..Default::default()
251                }
252            }
253        };
254
255        // 2. Evaluate policy
256        let input = PolicyInput {
257            identity,
258            ref_path,
259            context,
260        };
261        let decision = self.engine.evaluate(&input);
262
263        let policy = match decision {
264            PolicyDecision::Deny { policy, reason } => {
265                return RefResult::denied(&policy, &reason);
266            }
267            PolicyDecision::Allow { policy } => policy,
268        };
269
270        let mut result = RefResult {
271            allowed: true,
272            policy: Some(policy),
273            ..Default::default()
274        };
275
276        match resource.mode {
277            ResolverMode::Direct => {
278                result.mode = Some("direct".into());
279                match self.resolve_from_backend(ref_path, resource).await {
280                    Ok(value) => result.value = Some(value),
281                    Err(e) => result.error = Some(e.to_string()),
282                }
283            }
284            ResolverMode::ShortLived => {
285                result.mode = Some("short_lived".into());
286                let ttl = resource.ttl.unwrap_or(DEFAULT_TTL);
287                match &self.signer {
288                    Some(signer) => match signer.sign(ref_path, &resource.resolver, ttl) {
289                        Ok(token) => {
290                            result.token = Some(token);
291                            result.proxy = self.proxy_url.clone();
292                            result.ttl = Some(ttl);
293                        }
294                        Err(e) => result.error = Some(format!("signing failed: {e}")),
295                    },
296                    None => {
297                        result.error = Some("short-lived mode requires a signing key".into());
298                    }
299                }
300            }
301        }
302
303        result
304    }
305
306    async fn resolve_from_backend(
307        &self,
308        ref_path: &str,
309        resource: &Resource,
310    ) -> Result<String> {
311        let resolver = self.resolvers.get(&resource.resolver).ok_or_else(|| {
312            ServerError::Config(format!(
313                "no backend resolver named '{}'",
314                resource.resolver
315            ))
316        })?;
317
318        let params = build_resolve_params(ref_path, resource);
319        let request = Request::resolve(params);
320        let resolved = resolver.resolve(&request).await.map_err(|e| {
321            ServerError::Resolution(format!("backend '{}' failed: {e}", resource.resolver))
322        })?;
323
324        Ok(resolved.value.expose_secret().to_string())
325    }
326}
327
328// ---------------------------------------------------------------------------
329// Shared resolve-param builder
330// ---------------------------------------------------------------------------
331
332/// Build the parameter map for a secret-resolver `Request::resolve()` call.
333pub fn build_resolve_params(ref_path: &str, resource: &Resource) -> HashMap<String, toml::Value> {
334    let mut params = HashMap::new();
335    params.insert("ref".into(), toml::Value::String(ref_path.into()));
336
337    let optional_fields: &[(&str, Option<&String>)] = &[
338        ("field", resource.field.as_ref()),
339        ("path", resource.path.as_ref()),
340        ("role_arn", resource.role_arn.as_ref()),
341        ("secret_id", resource.secret_id.as_ref()),
342    ];
343    for (key, value) in optional_fields {
344        if let Some(v) = value {
345            params.insert((*key).into(), toml::Value::String((*v).clone()));
346        }
347    }
348    if let Some(duration) = &resource.duration_seconds {
349        params.insert(
350            "duration_seconds".into(),
351            toml::Value::String(duration.to_string()),
352        );
353    }
354
355    params
356}
357
358// ---------------------------------------------------------------------------
359// Backend config helper
360// ---------------------------------------------------------------------------
361
362/// Convert a `BackendConfig` into a config map suitable for
363/// `secret_resolvers::registry::create_resolver`.
364pub fn backend_to_config(backend: &BackendConfig) -> HashMap<String, toml::Value> {
365    let mut m = HashMap::new();
366
367    if let Some(address) = &backend.address {
368        m.insert("address".into(), toml::Value::String(address.clone()));
369    }
370    if let Some(region) = &backend.region {
371        m.insert("region".into(), toml::Value::String(region.clone()));
372    }
373    if let Some(path) = &backend.path {
374        m.insert("path".into(), toml::Value::String(path.clone()));
375    }
376    if let Some(vault) = &backend.vault {
377        m.insert("vault".into(), toml::Value::String(vault.clone()));
378    }
379    if let Some(auth) = &backend.auth {
380        m.insert("auth_method".into(), toml::Value::String(auth.method.clone()));
381        if let Some(role) = &auth.role {
382            m.insert("auth_role".into(), toml::Value::String(role.clone()));
383        }
384    }
385
386    // Inject VAULT_TOKEN from environment if present
387    if let Ok(token) = std::env::var(VAULT_TOKEN_ENV) {
388        m.insert("token".into(), toml::Value::String(token));
389    }
390
391    m
392}