Skip to main content

engenho_controllers/
attestation.rs

1//! Attestation-gated admission — verify image / artifact signatures
2//! before admission.
3//!
4//! Adapts a pluggable `SignatureVerifier` trait to the
5//! `AdmissionWebhook` trait. Production deployments wire in a
6//! tameshi / cosign / sigstore verifier; the substrate ships a
7//! `FakeSignatureVerifier` for tests + a typed
8//! `TameshiAttestationWebhook` that holds the verifier reference
9//! + opts in to specific kinds (Pods, Jobs, `CronJobs` — anything
10//! that names an image).
11//!
12//! ## Decision rules
13//!
14//! For Put / Patch on a kind that names images (Pod / Job / `CronJob`
15//! / Deployment / `StatefulSet` / `DaemonSet` / `ReplicaSet` via their
16//! `spec.template.spec.containers[].image`), extract every image
17//! reference + ask the verifier. First unsigned image denies with
18//! a typed reason.
19//!
20//! Other kinds + Delete → Allow.
21
22use std::collections::BTreeSet;
23use std::sync::Arc;
24
25use async_trait::async_trait;
26use serde::Serialize;
27use serde_json::Value;
28use thiserror::Error;
29use tokio::sync::Mutex;
30
31use crate::admission::{
32    AdmissionAction, AdmissionDecision, AdmissionError, AdmissionRequest, AdmissionWebhook,
33};
34
35/// Verifier errors.
36#[derive(Debug, Clone, Error)]
37pub enum VerifierError {
38    /// Backend (cosign, tameshi, sigstore) returned an error.
39    #[error("backend: {0}")]
40    Backend(String),
41    /// Image reference malformed.
42    #[error("invalid image ref: {0}")]
43    InvalidRef(String),
44}
45
46engenho_substrate::impl_error_kind! {
47    VerifierError {
48        (Backend(_)) => "backend",
49        (InvalidRef(_)) => "invalid_ref",
50    }
51}
52
53/// What a store says about one path of what an image names.
54#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
55pub struct PathAttestation {
56    /// The path.
57    pub path: String,
58    /// Built on this node, so it has no signature to offer.
59    pub ultimate: bool,
60    /// Its address is a hash of its content, so it proves itself.
61    pub content_addressed: bool,
62    /// The key names its signatures claim.
63    pub claimed: Vec<String>,
64    /// Each known key, `name:base64`, one of its signatures verifies under.
65    pub verified_by: Vec<String>,
66}
67
68/// What a verifier found for one image.
69#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
70pub struct Attestation {
71    /// The keys the store itself trusts, `name:base64`.
72    pub store_keys: Vec<String>,
73    /// Every path the image needs.
74    pub paths: Vec<PathAttestation>,
75}
76
77impl Attestation {
78    /// Whether every path has a signature that verifies.
79    #[must_use]
80    pub fn all_verified(&self) -> bool {
81        !self.paths.is_empty() && self.paths.iter().all(|p| !p.verified_by.is_empty())
82    }
83}
84
85/// Pluggable signature verifier — checks an image / artifact
86/// reference has a valid signature against the verifier's trust
87/// store.
88#[async_trait]
89pub trait SignatureVerifier: Send + Sync {
90    /// Verifier identifier for telemetry.
91    fn name(&self) -> &'static str;
92
93    /// The signature facts of `image_ref`. They are facts, not a verdict: the
94    /// caller decides what they mean.
95    ///
96    /// # Errors
97    /// [`VerifierError::Backend`] on backend failure;
98    /// [`VerifierError::InvalidRef`] on malformed input.
99    async fn attest(&self, image_ref: &str) -> Result<Attestation, VerifierError>;
100
101    /// True if `image_ref` is verifiably signed. False if explicitly
102    /// unsigned. Returns Err for backend failures the caller
103    /// decides how to interpret.
104    ///
105    /// # Errors
106    /// As [`Self::attest`].
107    async fn verify(&self, image_ref: &str) -> Result<bool, VerifierError> {
108        Ok(self.attest(image_ref).await?.all_verified())
109    }
110}
111
112// =================================================================
113// FakeSignatureVerifier — deterministic backend for tests
114// =================================================================
115
116/// In-memory verifier. Holds a set of "signed" image refs; anything
117/// not in the set is unsigned. Records every verify call.
118#[derive(Default, Clone)]
119pub struct FakeSignatureVerifier {
120    inner: Arc<Mutex<FakeVerifierState>>,
121}
122
123#[derive(Default)]
124struct FakeVerifierState {
125    signed: BTreeSet<String>,
126    fail_with: Option<String>,
127    calls: Vec<String>,
128}
129
130impl FakeSignatureVerifier {
131    /// Fresh verifier — everything unsigned.
132    #[must_use]
133    pub fn new() -> Self {
134        Self::default()
135    }
136
137    /// Mark `image` as signed.
138    pub async fn mark_signed(&self, image: impl Into<String>) {
139        self.inner.lock().await.signed.insert(image.into());
140    }
141
142    /// Make the next verify call return `VerifierError::Backend`.
143    pub async fn fail_next(&self, msg: impl Into<String>) {
144        self.inner.lock().await.fail_with = Some(msg.into());
145    }
146
147    /// Snapshot of verify calls.
148    pub async fn calls(&self) -> Vec<String> {
149        self.inner.lock().await.calls.clone()
150    }
151}
152
153#[async_trait]
154impl SignatureVerifier for FakeSignatureVerifier {
155    fn name(&self) -> &'static str {
156        "fake"
157    }
158
159    async fn attest(&self, image_ref: &str) -> Result<Attestation, VerifierError> {
160        let mut state = self.inner.lock().await;
161        state.calls.push(image_ref.to_string());
162        if let Some(msg) = state.fail_with.take() {
163            return Err(VerifierError::Backend(msg));
164        }
165        if image_ref.is_empty() {
166            return Err(VerifierError::InvalidRef("empty".into()));
167        }
168        let verified_by = if state.signed.contains(image_ref) {
169            vec!["fake:key".to_string()]
170        } else {
171            Vec::new()
172        };
173        Ok(Attestation {
174            store_keys: vec!["fake:key".to_string()],
175            paths: vec![PathAttestation {
176                path: image_ref.to_string(),
177                verified_by,
178                ..PathAttestation::default()
179            }],
180        })
181    }
182}
183
184// =================================================================
185// TameshiAttestationWebhook — adapts SignatureVerifier → AdmissionWebhook
186// =================================================================
187
188/// Kinds whose Pod template contains images we should verify.
189fn workload_kinds() -> BTreeSet<&'static str> {
190    [
191        "Pod",
192        "Deployment",
193        "StatefulSet",
194        "DaemonSet",
195        "ReplicaSet",
196        "Job",
197        "CronJob",
198    ]
199    .into_iter()
200    .collect()
201}
202
203/// Webhook backed by a [`SignatureVerifier`].
204pub struct TameshiAttestationWebhook {
205    verifier: Arc<dyn SignatureVerifier>,
206    workload_kinds: BTreeSet<&'static str>,
207}
208
209impl TameshiAttestationWebhook {
210    /// New webhook gating workload kinds (Pod / Deployment /
211    /// `StatefulSet` / Job / `CronJob` / `DaemonSet` / `ReplicaSet`).
212    #[must_use]
213    pub fn new(verifier: Arc<dyn SignatureVerifier>) -> Self {
214        Self {
215            verifier,
216            workload_kinds: workload_kinds(),
217        }
218    }
219
220    /// Pure helper: extract every image reference from a workload
221    /// manifest. Walks `spec.containers[].image` and (for owner-
222    /// resources) `spec.template.spec.containers[].image`. Also
223    /// walks `spec.jobTemplate.spec.template.spec.containers[].image`
224    /// for `CronJob`.
225    #[must_use]
226    pub fn extract_image_refs(value: &Value) -> Vec<String> {
227        let mut refs = Vec::new();
228        fn from_containers(containers: &Value, out: &mut Vec<String>) {
229            if let Some(arr) = containers.as_array() {
230                for c in arr {
231                    if let Some(img) = c.get("image").and_then(|i| i.as_str()) {
232                        out.push(img.to_string());
233                    }
234                }
235            }
236        }
237        // Pod directly: spec.containers[]
238        if let Some(c) = value.get("spec").and_then(|s| s.get("containers")) {
239            from_containers(c, &mut refs);
240        }
241        // Owner: spec.template.spec.containers[]
242        if let Some(c) = value
243            .get("spec")
244            .and_then(|s| s.get("template"))
245            .and_then(|t| t.get("spec"))
246            .and_then(|s| s.get("containers"))
247        {
248            from_containers(c, &mut refs);
249        }
250        // CronJob: spec.jobTemplate.spec.template.spec.containers[]
251        if let Some(c) = value
252            .get("spec")
253            .and_then(|s| s.get("jobTemplate"))
254            .and_then(|jt| jt.get("spec"))
255            .and_then(|s| s.get("template"))
256            .and_then(|t| t.get("spec"))
257            .and_then(|s| s.get("containers"))
258        {
259            from_containers(c, &mut refs);
260        }
261        refs
262    }
263}
264
265#[async_trait]
266impl AdmissionWebhook for TameshiAttestationWebhook {
267    fn name(&self) -> &'static str {
268        "tameshi-attestation"
269    }
270
271    async fn review(
272        &self,
273        request: &AdmissionRequest,
274    ) -> Result<AdmissionDecision, AdmissionError> {
275        if request.action == AdmissionAction::Delete {
276            return Ok(AdmissionDecision::Allow);
277        }
278        if !self.workload_kinds.contains(request.key.kind.as_str()) {
279            return Ok(AdmissionDecision::Allow);
280        }
281        let Some(value) = &request.value else {
282            return Ok(AdmissionDecision::Allow);
283        };
284        let images = Self::extract_image_refs(value);
285        if images.is_empty() {
286            // No images to verify (e.g. patch of unrelated field) → allow.
287            return Ok(AdmissionDecision::Allow);
288        }
289        for image in &images {
290            let signed = self
291                .verifier
292                .verify(image)
293                .await
294                .map_err(|e| AdmissionError::Backend(e.to_string()))?;
295            if !signed {
296                return Ok(AdmissionDecision::Deny(format!(
297                    "image {image} is not signed (verifier={})",
298                    self.verifier.name()
299                )));
300            }
301        }
302        Ok(AdmissionDecision::Allow)
303    }
304}
305
306/// Convenience constructor.
307#[must_use]
308pub fn tameshi_attestation_webhook(
309    verifier: Arc<dyn SignatureVerifier>,
310) -> Arc<dyn AdmissionWebhook> {
311    Arc::new(TameshiAttestationWebhook::new(verifier))
312}
313
314#[cfg(test)]
315mod tests {
316    use super::*;
317    use engenho_store::resource::ResourceKey;
318    use serde_json::json;
319
320    fn pod_req(image: &str) -> AdmissionRequest {
321        AdmissionRequest {
322            action: AdmissionAction::Put,
323            key: ResourceKey::namespaced("", "v1", "Pod", "default", "x"),
324            value: Some(json!({
325                "spec": {"containers": [{"image": image}]}
326            })),
327            current: None,
328            user_info: engenho_types::auth::UserInfo::default(),
329        }
330    }
331
332    fn deployment_req(image: &str) -> AdmissionRequest {
333        AdmissionRequest {
334            action: AdmissionAction::Put,
335            key: ResourceKey::namespaced("apps", "v1", "Deployment", "default", "x"),
336            value: Some(json!({
337                "spec": {
338                    "template": {
339                        "spec": {"containers": [{"image": image}]}
340                    }
341                }
342            })),
343            current: None,
344            user_info: engenho_types::auth::UserInfo::default(),
345        }
346    }
347
348    fn cronjob_req(image: &str) -> AdmissionRequest {
349        AdmissionRequest {
350            action: AdmissionAction::Put,
351            key: ResourceKey::namespaced("batch", "v1", "CronJob", "default", "x"),
352            value: Some(json!({
353                "spec": {
354                    "jobTemplate": {
355                        "spec": {
356                            "template": {
357                                "spec": {"containers": [{"image": image}]}
358                            }
359                        }
360                    }
361                }
362            })),
363            current: None,
364            user_info: engenho_types::auth::UserInfo::default(),
365        }
366    }
367
368    #[tokio::test]
369    async fn signed_image_allowed() {
370        let v = Arc::new(FakeSignatureVerifier::new());
371        v.mark_signed("registry/podinfo:1.0").await;
372        let w = TameshiAttestationWebhook::new(v);
373        let r = w.review(&pod_req("registry/podinfo:1.0")).await.unwrap();
374        assert_eq!(r, AdmissionDecision::Allow);
375    }
376
377    #[tokio::test]
378    async fn unsigned_image_denied() {
379        let v = Arc::new(FakeSignatureVerifier::new());
380        let w = TameshiAttestationWebhook::new(v);
381        let r = w.review(&pod_req("untrusted:latest")).await.unwrap();
382        assert!(
383            matches!(r, AdmissionDecision::Deny(reason) if reason.contains("untrusted:latest"))
384        );
385    }
386
387    #[tokio::test]
388    async fn deployment_walks_template_spec_containers() {
389        let v = Arc::new(FakeSignatureVerifier::new());
390        v.mark_signed("nginx:1.27").await;
391        let w = TameshiAttestationWebhook::new(v.clone());
392        let r = w.review(&deployment_req("nginx:1.27")).await.unwrap();
393        assert_eq!(r, AdmissionDecision::Allow);
394        // Verifier saw the right image.
395        assert!(v.calls().await.contains(&"nginx:1.27".to_string()));
396    }
397
398    #[tokio::test]
399    async fn cronjob_walks_jobtemplate_template_spec_containers() {
400        let v = Arc::new(FakeSignatureVerifier::new());
401        v.mark_signed("alpine:3.20").await;
402        let w = TameshiAttestationWebhook::new(v.clone());
403        let r = w.review(&cronjob_req("alpine:3.20")).await.unwrap();
404        assert_eq!(r, AdmissionDecision::Allow);
405        assert!(v.calls().await.contains(&"alpine:3.20".to_string()));
406    }
407
408    #[tokio::test]
409    async fn non_workload_kind_skips_verification() {
410        let v = Arc::new(FakeSignatureVerifier::new());
411        let w = TameshiAttestationWebhook::new(v.clone());
412        let r = w
413            .review(&AdmissionRequest {
414                action: AdmissionAction::Put,
415                key: ResourceKey::namespaced("", "v1", "ConfigMap", "default", "cm"),
416                value: Some(json!({})),
417                current: None,
418                user_info: engenho_types::auth::UserInfo::default(),
419            })
420            .await
421            .unwrap();
422        assert_eq!(r, AdmissionDecision::Allow);
423        assert!(
424            v.calls().await.is_empty(),
425            "verifier not called for ConfigMap"
426        );
427    }
428
429    #[tokio::test]
430    async fn delete_always_allowed() {
431        let v = Arc::new(FakeSignatureVerifier::new());
432        let w = TameshiAttestationWebhook::new(v.clone());
433        let r = w
434            .review(&AdmissionRequest {
435                action: AdmissionAction::Delete,
436                key: ResourceKey::namespaced("", "v1", "Pod", "default", "x"),
437                value: None,
438                current: None,
439                user_info: engenho_types::auth::UserInfo::default(),
440            })
441            .await
442            .unwrap();
443        assert_eq!(r, AdmissionDecision::Allow);
444        assert!(v.calls().await.is_empty());
445    }
446
447    #[tokio::test]
448    async fn patch_without_images_allowed() {
449        let v = Arc::new(FakeSignatureVerifier::new());
450        let w = TameshiAttestationWebhook::new(v);
451        let r = w
452            .review(&AdmissionRequest {
453                action: AdmissionAction::Patch,
454                key: ResourceKey::namespaced("", "v1", "Pod", "default", "x"),
455                value: Some(json!({"metadata": {"labels": {"new": "label"}}})),
456                current: None,
457                user_info: engenho_types::auth::UserInfo::default(),
458            })
459            .await
460            .unwrap();
461        assert_eq!(r, AdmissionDecision::Allow);
462    }
463
464    #[tokio::test]
465    async fn backend_failure_surfaces_as_admission_error() {
466        let v = Arc::new(FakeSignatureVerifier::new());
467        v.fail_next("verifier down").await;
468        let w = TameshiAttestationWebhook::new(v);
469        let err = w.review(&pod_req("x")).await.unwrap_err();
470        assert_eq!(err.kind(), "backend");
471    }
472
473    #[tokio::test]
474    async fn multiple_containers_all_must_be_signed() {
475        let v = Arc::new(FakeSignatureVerifier::new());
476        v.mark_signed("good:1").await;
477        // "bad:1" intentionally unsigned.
478        let w = TameshiAttestationWebhook::new(v);
479        let req = AdmissionRequest {
480            action: AdmissionAction::Put,
481            key: ResourceKey::namespaced("", "v1", "Pod", "default", "x"),
482            value: Some(json!({
483                "spec": {"containers": [{"image": "good:1"}, {"image": "bad:1"}]}
484            })),
485            current: None,
486            user_info: engenho_types::auth::UserInfo::default(),
487        };
488        let r = w.review(&req).await.unwrap();
489        assert!(matches!(r, AdmissionDecision::Deny(reason) if reason.contains("bad:1")));
490    }
491
492    #[test]
493    fn an_attestation_is_verified_only_when_every_path_is_and_there_is_one() {
494        let path = |key: &[&str]| PathAttestation {
495            verified_by: key.iter().map(ToString::to_string).collect(),
496            ..PathAttestation::default()
497        };
498        let of = |paths| Attestation {
499            store_keys: Vec::new(),
500            paths,
501        };
502        assert!(!of(vec![]).all_verified());
503        assert!(of(vec![path(&["k"])]).all_verified());
504        assert!(!of(vec![path(&["k"]), path(&[])]).all_verified());
505    }
506
507    #[test]
508    fn extract_image_refs_handles_empty_value() {
509        let refs = TameshiAttestationWebhook::extract_image_refs(&json!({}));
510        assert!(refs.is_empty());
511    }
512
513    #[test]
514    fn extract_image_refs_handles_pod_shape() {
515        let refs = TameshiAttestationWebhook::extract_image_refs(&json!({
516            "spec": {"containers": [{"image": "a"}, {"image": "b"}]}
517        }));
518        assert_eq!(refs, vec!["a", "b"]);
519    }
520
521    #[tokio::test]
522    async fn verifier_name_is_stable() {
523        assert_eq!(FakeSignatureVerifier::new().name(), "fake");
524    }
525
526    #[tokio::test]
527    async fn webhook_name_is_stable() {
528        let v = Arc::new(FakeSignatureVerifier::new());
529        let w = TameshiAttestationWebhook::new(v);
530        assert_eq!(w.name(), "tameshi-attestation");
531    }
532
533    #[test]
534    fn verifier_error_kinds_are_stable() {
535        assert_eq!(VerifierError::Backend("x".into()).kind(), "backend");
536        assert_eq!(VerifierError::InvalidRef("x".into()).kind(), "invalid_ref");
537    }
538
539    #[tokio::test]
540    async fn fake_verifier_rejects_empty_ref() {
541        let v = FakeSignatureVerifier::new();
542        let err = v.verify("").await.unwrap_err();
543        assert_eq!(err.kind(), "invalid_ref");
544    }
545}