1use std::collections::BTreeMap;
30use std::sync::Arc;
31
32use async_trait::async_trait;
33use engenho_store::resource::ResourceKey;
34use serde_json::Value;
35use thiserror::Error;
36use tokio::sync::Mutex;
37
38#[derive(Clone, Debug, PartialEq, Eq)]
40pub enum AdmissionDecision {
41 Allow,
43 Mutate(Value),
45 Deny(String),
47}
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum AdmissionAction {
53 Put,
55 Patch,
57 Delete,
59}
60
61#[derive(Clone, Debug)]
63pub struct AdmissionRequest {
64 pub action: AdmissionAction,
66 pub key: ResourceKey,
68 pub value: Option<Value>,
70 pub current: Option<Value>,
72 pub user_info: engenho_types::auth::UserInfo,
80}
81
82#[derive(Debug, Clone, Error)]
84pub enum AdmissionError {
85 #[error("backend: {0}")]
87 Backend(String),
88}
89
90engenho_substrate::impl_error_kind! {
91 AdmissionError {
92 (Backend(_)) => "backend",
93 }
94}
95
96#[async_trait]
98pub trait AdmissionWebhook: Send + Sync {
99 fn name(&self) -> &'static str;
101
102 async fn review(&self, request: &AdmissionRequest)
109 -> Result<AdmissionDecision, AdmissionError>;
110}
111
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
118pub enum AdmissionMode {
119 FailOpen,
122 FailClosed,
125}
126
127pub struct AdmissionChain {
130 hooks: Vec<Arc<dyn AdmissionWebhook>>,
131 mode: AdmissionMode,
132}
133
134impl AdmissionChain {
135 #[must_use]
137 pub fn new(hooks: Vec<Arc<dyn AdmissionWebhook>>, mode: AdmissionMode) -> Self {
138 Self { hooks, mode }
139 }
140
141 pub async fn review(&self, mut request: AdmissionRequest) -> AdmissionDecision {
144 for hook in &self.hooks {
145 let decision = match hook.review(&request).await {
146 Ok(d) => d,
147 Err(_) => match self.mode {
148 AdmissionMode::FailOpen => AdmissionDecision::Allow,
149 AdmissionMode::FailClosed => {
150 return AdmissionDecision::Deny(format!(
151 "{}: backend failure (fail-closed)",
152 hook.name()
153 ));
154 }
155 },
156 };
157 match decision {
158 AdmissionDecision::Allow => continue,
159 AdmissionDecision::Mutate(new) => {
160 request.value = Some(new);
161 }
162 AdmissionDecision::Deny(reason) => {
163 return AdmissionDecision::Deny(format!("{}: {reason}", hook.name()));
164 }
165 }
166 }
167 match request.value {
170 Some(v) => AdmissionDecision::Mutate(v),
171 None => AdmissionDecision::Allow,
172 }
173 }
174
175 #[must_use]
177 pub fn len(&self) -> usize {
178 self.hooks.len()
179 }
180
181 #[must_use]
183 pub fn is_empty(&self) -> bool {
184 self.hooks.is_empty()
185 }
186}
187
188#[derive(Clone, Default)]
194pub struct FakeAdmissionWebhook {
195 inner: Arc<Mutex<FakeAdmissionState>>,
196 backend_name: &'static str,
197}
198
199#[derive(Default)]
200struct FakeAdmissionState {
201 decisions: BTreeMap<String, AdmissionDecision>,
202 fail_with: Option<String>,
203 call_log: Vec<(AdmissionAction, String)>,
204 last_user_info: Option<engenho_types::auth::UserInfo>,
208}
209
210impl FakeAdmissionWebhook {
211 #[must_use]
213 pub fn new(name: &'static str) -> Self {
214 Self {
215 inner: Arc::new(Mutex::new(FakeAdmissionState::default())),
216 backend_name: name,
217 }
218 }
219
220 pub async fn set_decision(&self, key: &str, d: AdmissionDecision) {
222 self.inner.lock().await.decisions.insert(key.to_string(), d);
223 }
224
225 pub async fn fail_next(&self, msg: impl Into<String>) {
227 self.inner.lock().await.fail_with = Some(msg.into());
228 }
229
230 pub async fn calls(&self) -> Vec<(AdmissionAction, String)> {
232 self.inner.lock().await.call_log.clone()
233 }
234
235 pub async fn last_user_info(&self) -> Option<engenho_types::auth::UserInfo> {
239 self.inner.lock().await.last_user_info.clone()
240 }
241}
242
243#[async_trait]
244impl AdmissionWebhook for FakeAdmissionWebhook {
245 fn name(&self) -> &'static str {
246 self.backend_name
247 }
248
249 async fn review(
250 &self,
251 request: &AdmissionRequest,
252 ) -> Result<AdmissionDecision, AdmissionError> {
253 let mut state = self.inner.lock().await;
254 state.call_log.push((request.action, request.key.label()));
255 state.last_user_info = Some(request.user_info.clone());
256 if let Some(msg) = state.fail_with.take() {
257 return Err(AdmissionError::Backend(msg));
258 }
259 Ok(state
260 .decisions
261 .get(&request.key.label())
262 .cloned()
263 .unwrap_or(AdmissionDecision::Allow))
264 }
265}
266
267#[cfg(test)]
268mod tests {
269 use super::*;
270 use serde_json::json;
271
272 fn req(action: AdmissionAction, name: &str, value: Value) -> AdmissionRequest {
273 AdmissionRequest {
274 action,
275 key: ResourceKey::namespaced("", "v1", "Pod", "default", name),
276 value: Some(value),
277 current: None,
278 user_info: engenho_types::auth::UserInfo::default(),
279 }
280 }
281
282 fn label_for(name: &str) -> String {
283 ResourceKey::namespaced("", "v1", "Pod", "default", name).label()
284 }
285
286 #[tokio::test]
287 async fn allow_passes_through_unchanged() {
288 let hook = Arc::new(FakeAdmissionWebhook::new("test"));
289 let chain = AdmissionChain::new(vec![hook], AdmissionMode::FailClosed);
290 let r = chain
291 .review(req(AdmissionAction::Put, "x", json!({"spec": {}})))
292 .await;
293 assert!(matches!(r, AdmissionDecision::Mutate(_)));
295 }
296
297 #[tokio::test]
298 async fn deny_short_circuits_chain() {
299 let h1 = Arc::new(FakeAdmissionWebhook::new("h1"));
300 let h2 = Arc::new(FakeAdmissionWebhook::new("h2"));
301 h1.set_decision(&label_for("x"), AdmissionDecision::Deny("no".into()))
302 .await;
303 let chain = AdmissionChain::new(vec![h1.clone(), h2.clone()], AdmissionMode::FailClosed);
304 let r = chain
305 .review(req(AdmissionAction::Put, "x", json!({})))
306 .await;
307 assert!(
308 matches!(r, AdmissionDecision::Deny(reason) if reason.contains("h1") && reason.contains("no"))
309 );
310 assert_eq!(h2.calls().await.len(), 0);
312 }
313
314 #[tokio::test]
315 async fn mutate_feeds_forward() {
316 let h1 = Arc::new(FakeAdmissionWebhook::new("defaulter"));
317 let h2 = Arc::new(FakeAdmissionWebhook::new("validator"));
318 h1.set_decision(
319 &label_for("x"),
320 AdmissionDecision::Mutate(json!({"spec": {"replicas": 3}})),
321 )
322 .await;
323 let chain = AdmissionChain::new(vec![h1.clone(), h2.clone()], AdmissionMode::FailClosed);
325 let r = chain
326 .review(req(AdmissionAction::Put, "x", json!({"spec": {}})))
327 .await;
328 match r {
329 AdmissionDecision::Mutate(v) => {
330 assert_eq!(v.get("spec").unwrap().get("replicas").unwrap(), 3);
331 }
332 other => panic!("expected Mutate, got {other:?}"),
333 }
334 assert_eq!(h2.calls().await.len(), 1);
335 }
336
337 #[tokio::test]
338 async fn fail_open_treats_error_as_allow() {
339 let h1 = Arc::new(FakeAdmissionWebhook::new("h1"));
340 h1.fail_next("oops").await;
341 let chain = AdmissionChain::new(vec![h1], AdmissionMode::FailOpen);
342 let r = chain
343 .review(req(AdmissionAction::Put, "x", json!({})))
344 .await;
345 assert!(matches!(r, AdmissionDecision::Mutate(_)));
347 }
348
349 #[tokio::test]
350 async fn fail_closed_treats_error_as_deny() {
351 let h1 = Arc::new(FakeAdmissionWebhook::new("compliance"));
352 h1.fail_next("oops").await;
353 let chain = AdmissionChain::new(vec![h1], AdmissionMode::FailClosed);
354 let r = chain
355 .review(req(AdmissionAction::Put, "x", json!({})))
356 .await;
357 match r {
358 AdmissionDecision::Deny(reason) => {
359 assert!(reason.contains("compliance"));
360 assert!(reason.contains("fail-closed"));
361 }
362 other => panic!("expected Deny, got {other:?}"),
363 }
364 }
365
366 #[tokio::test]
367 async fn empty_chain_allows_anything() {
368 let chain = AdmissionChain::new(vec![], AdmissionMode::FailClosed);
369 let r = chain
370 .review(req(AdmissionAction::Put, "x", json!({})))
371 .await;
372 assert!(matches!(r, AdmissionDecision::Mutate(_)));
373 }
374
375 #[tokio::test]
376 async fn chain_metadata_helpers() {
377 let h1 = Arc::new(FakeAdmissionWebhook::new("a"));
378 let h2 = Arc::new(FakeAdmissionWebhook::new("b"));
379 let chain = AdmissionChain::new(vec![h1, h2], AdmissionMode::FailOpen);
380 assert_eq!(chain.len(), 2);
381 assert!(!chain.is_empty());
382 let empty = AdmissionChain::new(vec![], AdmissionMode::FailOpen);
383 assert!(empty.is_empty());
384 }
385
386 #[test]
387 fn admission_error_kind_is_stable() {
388 assert_eq!(AdmissionError::Backend("x".into()).kind(), "backend");
389 }
390
391 #[tokio::test]
392 async fn webhook_observes_threaded_user_info() {
393 let hook = Arc::new(FakeAdmissionWebhook::new("observer"));
398 let chain = AdmissionChain::new(vec![hook.clone()], AdmissionMode::FailClosed);
399 let mut request = req(AdmissionAction::Put, "x", json!({}));
400 request.user_info = engenho_types::auth::UserInfo::admin();
401 let _ = chain.review(request).await;
402 let observed = hook.last_user_info().await.expect("a review ran");
403 assert_eq!(observed.username, "engenho-admin");
404 assert!(observed.groups.iter().any(|g| g == "system:masters"));
405 }
406
407 #[tokio::test]
408 async fn default_request_carries_empty_user_info() {
409 let hook = Arc::new(FakeAdmissionWebhook::new("observer"));
412 let chain = AdmissionChain::new(vec![hook.clone()], AdmissionMode::FailClosed);
413 let _ = chain
414 .review(req(AdmissionAction::Put, "x", json!({})))
415 .await;
416 let observed = hook.last_user_info().await.expect("a review ran");
417 assert_eq!(observed, engenho_types::auth::UserInfo::default());
418 }
419}