Skip to main content

engenho_controllers/
cluster_ip.rs

1//! Service `ClusterIP` (VIP) allocator + the defaulting admission webhook
2//! that stamps an allocated VIP onto a Service at create time.
3//!
4//! ## The gap this closes
5//!
6//! Before this module a Service stored in engenho kept whatever
7//! `spec.clusterIP` the operator supplied — and `kubectl get svc`
8//! reported `clusterIP: None` for the common case (operator supplies no
9//! IP). Nothing ALLOCATED a virtual IP. `ServiceRoutingController`
10//! (`service_router.rs`) already computes VIP→pod routing rules, the DNS
11//! controller already answers `*.svc → clusterIP`, and the
12//! `EndpointsController` already resolves selectors → pod IPs — every
13//! one of them keyed on a `ClusterIP` that nothing produced. This module
14//! is the producer.
15//!
16//! ## Shape (★★ TYPED-SPEC + INTERPRETER TRIPLET — Environment trait)
17//!
18//! The allocator core ([`ClusterIpAllocator`]) is a PURE typed value over
19//! a parsed CIDR — no I/O, fully unit-testable. The defaulting webhook
20//! ([`ClusterIpDefaultingWebhook`]) is an [`AdmissionWebhook`] whose ONE
21//! side effect — "what VIPs are currently held by live Services?" — is
22//! abstracted behind the [`ServiceIpSource`] trait (production: read the
23//! store; test: a static list). That seam is also what makes the
24//! allocation **restart-persistent + collision-free by construction**:
25//! every allocation reseeds the in-use set from the live Service set, so
26//! a freshly-restarted process recomputes the held VIPs from the durable
27//! store rather than from a lost in-memory counter. The Services are the
28//! ledger; the one addition is the short-lived set of VIPs this process has
29//! granted to creates that have not committed yet, held under one lock so
30//! concurrent creates (Helm creates a chart's Services in parallel) cannot
31//! all draw the same lowest free VIP. A grant leaves that set when its
32//! Service appears in the store, or after [`GRANT_TTL`] if it never does.
33//!
34//! ## Rules (upstream parity)
35//!
36//!   * `type: ClusterIP` (the default) + `clusterIP` unset/"" ⇒ allocate
37//!     a free VIP from the configured `service_cidr`, write it onto
38//!     `spec.clusterIP` AND `spec.clusterIPs[0]`.
39//!   * `clusterIP: "None"` (headless) ⇒ left untouched. No VIP.
40//!   * `type: ExternalName` ⇒ left untouched. No VIP.
41//!   * `clusterIP` already a concrete IP (operator pinned it) ⇒ left
42//!     untouched (honored as-is; the in-use set already accounts for it
43//!     on the next allocation because it's a live Service).
44//!   * Pool exhaustion ⇒ a typed [`Deny`] (NOT a silent unallocated
45//!     Service) — the operator sees the exhaustion, never a half-built
46//!     object.
47//!
48//! [`Deny`]: crate::admission::AdmissionDecision::Deny
49
50use std::collections::{BTreeMap, BTreeSet};
51use std::sync::Arc;
52use std::time::{Duration, Instant};
53
54use async_trait::async_trait;
55use engenho_config::parse_ipv4_cidr;
56use engenho_store::StoreMesh;
57use serde_json::Value;
58use thiserror::Error;
59
60use crate::admission::{
61    AdmissionAction, AdmissionDecision, AdmissionError, AdmissionRequest, AdmissionWebhook,
62};
63
64// ═══════════════════════════════════════════════════════════════════════════
65//  Errors.
66// ═══════════════════════════════════════════════════════════════════════════
67
68/// A typed failure from the allocator. No silent wrong answers.
69#[derive(Debug, Clone, Error, PartialEq, Eq)]
70pub enum AllocatorError {
71    /// The configured `service_cidr` is not a parseable IPv4 CIDR.
72    #[error("invalid service CIDR: {0}")]
73    InvalidCidr(String),
74    /// Every assignable VIP in the CIDR is already held by a live
75    /// Service — the pool is exhausted.
76    #[error("service CIDR {cidr} is exhausted ({held} VIPs in use)")]
77    PoolExhausted {
78        /// The configured CIDR.
79        cidr: String,
80        /// How many VIPs are currently held.
81        held: usize,
82    },
83}
84
85engenho_substrate::impl_error_kind! {
86    AllocatorError {
87        (InvalidCidr(_)) => "invalid_cidr",
88        { PoolExhausted { .. } } => "pool_exhausted",
89    }
90}
91
92// ═══════════════════════════════════════════════════════════════════════════
93//  The pure allocator core.
94// ═══════════════════════════════════════════════════════════════════════════
95
96/// A typed `ClusterIP` allocator over one IPv4 service CIDR.
97///
98/// PURE — holds the parsed CIDR bounds + an in-use VIP set. Construct it,
99/// seed the in-use set from the live Service VIPs ([`Self::reserve`]),
100/// then [`Self::allocate`] / [`Self::release`]. Collision-freedom is a
101/// property of the in-use set: `allocate` never returns a held VIP and
102/// inserts what it returns.
103#[derive(Clone, Debug)]
104pub struct ClusterIpAllocator {
105    /// The original CIDR string (for error messages).
106    cidr: String,
107    /// Network base address as a u32 (host order).
108    base: u32,
109    /// First assignable host VIP (base + 1 — the network address itself
110    /// is skipped per upstream convention).
111    first: u32,
112    /// Last assignable host VIP (broadcast - 1 for non-/31,/32; for /31
113    /// and /32 the whole range is assignable).
114    last: u32,
115    /// VIPs currently held — the collision-free invariant lives here.
116    in_use: BTreeSet<u32>,
117}
118
119impl ClusterIpAllocator {
120    /// Construct an allocator over `cidr` (e.g. `10.96.0.0/12`).
121    ///
122    /// # Errors
123    /// [`AllocatorError::InvalidCidr`] when `cidr` is not a parseable
124    /// IPv4 CIDR.
125    pub fn new(cidr: &str) -> Result<Self, AllocatorError> {
126        let (base, prefix) = parse_ipv4_cidr(cidr).map_err(AllocatorError::InvalidCidr)?;
127        // Host bits = 32 - prefix. The assignable host range is
128        // (network+1)..=(broadcast-1) for the common case; for a /31 or
129        // /32 the whole block is assignable (no separate net/broadcast).
130        let host_bits = 32 - u32::from(prefix);
131        let (first, last) = if prefix >= 31 {
132            // /32 → single address; /31 → two addresses, both usable.
133            let size = if host_bits == 0 { 1 } else { 2 };
134            (base, base.saturating_add(size - 1))
135        } else {
136            let block_size = 1u64 << host_bits;
137            let broadcast = u64::from(base) + block_size - 1;
138            // Skip the network address (base) and the broadcast. The
139            // last assignable host (broadcast - 1) is in-range by
140            // construction (block_size >= 4 for prefix <= 30), so the
141            // truncating cast back to u32 is exact.
142            let last = u32::try_from(broadcast - 1).unwrap_or(u32::MAX);
143            (base + 1, last)
144        };
145        Ok(Self {
146            cidr: cidr.to_string(),
147            base,
148            first,
149            last,
150            in_use: BTreeSet::new(),
151        })
152    }
153
154    /// Mark `ip` as in-use if it falls within this CIDR. Out-of-range or
155    /// unparseable IPs are ignored (a live Service may carry a VIP from a
156    /// different range after a CIDR reconfiguration; it's simply not
157    /// drawn from this pool). Returns `true` iff the IP was reserved.
158    pub fn reserve(&mut self, ip: &str) -> bool {
159        match ip_to_u32(ip) {
160            Some(v) if v >= self.base && v <= self.last => self.in_use.insert(v),
161            _ => false,
162        }
163    }
164
165    /// Release `ip` back to the pool (reclaim on Service delete).
166    pub fn release(&mut self, ip: &str) {
167        if let Some(v) = ip_to_u32(ip) {
168            self.in_use.remove(&v);
169        }
170    }
171
172    /// Allocate the next free VIP, marking it in-use. Deterministic:
173    /// always the lowest free assignable VIP, so the same in-use set
174    /// yields the same allocation order (stable tests + diffs).
175    ///
176    /// # Errors
177    /// [`AllocatorError::PoolExhausted`] when no assignable VIP is free.
178    pub fn allocate(&mut self) -> Result<String, AllocatorError> {
179        let mut candidate = self.first;
180        while candidate <= self.last {
181            if !self.in_use.contains(&candidate) {
182                self.in_use.insert(candidate);
183                return Ok(u32_to_ip(candidate));
184            }
185            // Guard the u32 add at the top of the range.
186            if candidate == u32::MAX {
187                break;
188            }
189            candidate += 1;
190        }
191        Err(AllocatorError::PoolExhausted {
192            cidr: self.cidr.clone(),
193            held: self.in_use.len(),
194        })
195    }
196
197    /// Count of currently-held VIPs.
198    #[must_use]
199    pub fn held(&self) -> usize {
200        self.in_use.len()
201    }
202
203    /// True iff `ip` is currently held.
204    #[must_use]
205    pub fn is_held(&self, ip: &str) -> bool {
206        ip_to_u32(ip).is_some_and(|v| self.in_use.contains(&v))
207    }
208}
209
210/// Parse a dotted-quad IPv4 into a host-order u32. `None` on malformed.
211fn ip_to_u32(ip: &str) -> Option<u32> {
212    let octets: Vec<&str> = ip.split('.').collect();
213    if octets.len() != 4 {
214        return None;
215    }
216    let mut v: u32 = 0;
217    for oct in octets {
218        let byte: u8 = oct.parse().ok()?;
219        v = (v << 8) | u32::from(byte);
220    }
221    Some(v)
222}
223
224/// Render a host-order u32 as a dotted-quad IPv4 string. Built from typed
225/// octets (no `format!()` of address structure — the four octets ARE the
226/// typed pieces; `format!` of the `{}.{}.{}.{}` shape is the canonical
227/// dotted-quad serializer, ★★ TYPED EMISSION allows it as the value's
228/// render surface).
229fn u32_to_ip(v: u32) -> String {
230    format!(
231        "{}.{}.{}.{}",
232        (v >> 24) & 0xff,
233        (v >> 16) & 0xff,
234        (v >> 8) & 0xff,
235        v & 0xff
236    )
237}
238
239// ═══════════════════════════════════════════════════════════════════════════
240//  Service classification — what kind of Service is this?
241// ═══════════════════════════════════════════════════════════════════════════
242
243/// How a Service relates to VIP allocation.
244#[derive(Clone, Copy, Debug, PartialEq, Eq)]
245pub enum ServiceVipDisposition {
246    /// `type: ClusterIP` (or unset) with `clusterIP` unset/"" ⇒ allocate.
247    NeedsAllocation,
248    /// `clusterIP: "None"` (headless) ⇒ leave untouched.
249    Headless,
250    /// `type: ExternalName` ⇒ leave untouched.
251    ExternalName,
252    /// `clusterIP` is already a concrete IP ⇒ honored as-is.
253    AlreadyAssigned,
254}
255
256/// Classify a Service object by its VIP disposition. Pure.
257#[must_use]
258pub fn classify_service(svc: &Value) -> ServiceVipDisposition {
259    let spec = svc.get("spec");
260    let svc_type = spec
261        .and_then(|s| s.get("type"))
262        .and_then(Value::as_str)
263        .unwrap_or("ClusterIP");
264    if svc_type == "ExternalName" {
265        return ServiceVipDisposition::ExternalName;
266    }
267    let cluster_ip = spec
268        .and_then(|s| s.get("clusterIP"))
269        .and_then(Value::as_str);
270    match cluster_ip {
271        Some("None") => ServiceVipDisposition::Headless,
272        None | Some("") => ServiceVipDisposition::NeedsAllocation,
273        Some(_concrete) => ServiceVipDisposition::AlreadyAssigned,
274    }
275}
276
277// ═══════════════════════════════════════════════════════════════════════════
278//  The Environment seam (restart-persistence + collision-freedom).
279// ═══════════════════════════════════════════════════════════════════════════
280
281/// Source of the VIPs currently held by live Services. Production reads
282/// the store; tests pass a static list. The webhook reseeds the
283/// allocator from this on EVERY allocation, so the durable Service set is
284/// the single source of truth — no separate allocation ledger, and a
285/// restarted process recomputes the held set rather than losing a counter.
286#[async_trait]
287pub trait ServiceIpSource: Send + Sync {
288    /// Every `spec.clusterIP` (+ `spec.clusterIPs`) string currently held
289    /// by a live Service. Headless ("None") and empty values are caller-
290    /// filtered, so this may include "None"/"" — the allocator's
291    /// [`ClusterIpAllocator::reserve`] ignores anything not a real VIP in
292    /// range.
293    async fn held_cluster_ips(&self) -> Vec<String>;
294}
295
296/// Production [`ServiceIpSource`] — reads `spec.clusterIP` +
297/// `spec.clusterIPs` off every live Service in the store.
298pub struct StoreServiceIpSource {
299    store: Arc<StoreMesh>,
300}
301
302impl StoreServiceIpSource {
303    /// New source over `store`.
304    #[must_use]
305    pub fn new(store: Arc<StoreMesh>) -> Self {
306        Self { store }
307    }
308}
309
310#[async_trait]
311impl ServiceIpSource for StoreServiceIpSource {
312    async fn held_cluster_ips(&self) -> Vec<String> {
313        let services = self.store.list("", "v1", "Service", None).await;
314        let mut ips = Vec::new();
315        for (_key, svc) in services {
316            if let Some(ip) = svc
317                .get("spec")
318                .and_then(|s| s.get("clusterIP"))
319                .and_then(Value::as_str)
320            {
321                ips.push(ip.to_string());
322            }
323            if let Some(arr) = svc
324                .get("spec")
325                .and_then(|s| s.get("clusterIPs"))
326                .and_then(Value::as_array)
327            {
328                for v in arr {
329                    if let Some(ip) = v.as_str() {
330                        ips.push(ip.to_string());
331                    }
332                }
333            }
334        }
335        ips
336    }
337}
338
339// ═══════════════════════════════════════════════════════════════════════════
340//  The defaulting admission webhook.
341// ═══════════════════════════════════════════════════════════════════════════
342
343/// A defaulting [`AdmissionWebhook`] that allocates a `ClusterIP` for a
344/// Service on create.
345///
346/// Fires on Put of a `v1/Service` (CREATE). It (1) reseeds a fresh
347/// [`ClusterIpAllocator`] from the live Service VIPs, (2) classifies the
348/// proposed Service, (3) for `NeedsAllocation` allocates a free VIP and
349/// returns [`AdmissionDecision::Mutate`] with `spec.clusterIP` +
350/// `spec.clusterIPs` set. Headless / `ExternalName` / already-assigned
351/// Services + every non-Service kind pass through unchanged
352/// ([`AdmissionDecision::Allow`]). Pool exhaustion is a typed
353/// [`AdmissionDecision::Deny`].
354pub struct ClusterIpDefaultingWebhook {
355    /// The configured service CIDR.
356    cidr: String,
357    /// The live-VIP source (reseeded per allocation).
358    source: Arc<dyn ServiceIpSource>,
359    /// VIPs handed out and not yet seen on a stored Service, with when.
360    /// Reviews run under this lock, so two creates in flight at once
361    /// cannot both draw the lowest free VIP before either commits.
362    granted: tokio::sync::Mutex<BTreeMap<String, Instant>>,
363    /// How long a grant holds its VIP without appearing in the store.
364    grant_ttl: Duration,
365}
366
367const GRANT_TTL: Duration = Duration::from_secs(120);
368
369impl ClusterIpDefaultingWebhook {
370    /// New webhook over `cidr` reading live VIPs from `source`.
371    #[must_use]
372    pub fn new(cidr: impl Into<String>, source: Arc<dyn ServiceIpSource>) -> Self {
373        Self {
374            cidr: cidr.into(),
375            source,
376            granted: tokio::sync::Mutex::new(BTreeMap::new()),
377            grant_ttl: GRANT_TTL,
378        }
379    }
380
381    /// The same webhook with grants held for `ttl` instead of
382    /// [`GRANT_TTL`].
383    #[must_use]
384    pub fn with_grant_ttl(mut self, ttl: Duration) -> Self {
385        self.grant_ttl = ttl;
386        self
387    }
388
389    /// Whether `key` names a core/v1 Service.
390    fn is_service(key: &engenho_store::resource::ResourceKey) -> bool {
391        key.group.is_empty() && key.version == "v1" && key.kind == "Service"
392    }
393}
394
395#[async_trait]
396impl AdmissionWebhook for ClusterIpDefaultingWebhook {
397    fn name(&self) -> &'static str {
398        "cluster-ip-allocator"
399    }
400
401    async fn review(
402        &self,
403        request: &AdmissionRequest,
404    ) -> Result<AdmissionDecision, AdmissionError> {
405        // Only CREATE of a Service is in scope; everything else passes.
406        if request.action != AdmissionAction::Put || !Self::is_service(&request.key) {
407            return Ok(AdmissionDecision::Allow);
408        }
409        let Some(svc) = &request.value else {
410            return Ok(AdmissionDecision::Allow);
411        };
412
413        match classify_service(svc) {
414            ServiceVipDisposition::NeedsAllocation => {}
415            // Headless / ExternalName / already-pinned: untouched.
416            _ => return Ok(AdmissionDecision::Allow),
417        }
418
419        // Build a fresh allocator + reseed it from the live Service VIPs.
420        // This is the restart-persistence + collision-freedom step: the
421        // durable Service set is the ledger.
422        let mut allocator = match ClusterIpAllocator::new(&self.cidr) {
423            Ok(a) => a,
424            Err(e) => {
425                // A misconfigured CIDR is a typed backend error — the
426                // chain's FailClosed/FailOpen mode governs it, never a
427                // silent unallocated Service.
428                return Err(AdmissionError::Backend(e.to_string()));
429            }
430        };
431        let mut granted = self.granted.lock().await;
432        let held: BTreeSet<String> = self.source.held_cluster_ips().await.into_iter().collect();
433        granted.retain(|ip, at| !held.contains(ip) && at.elapsed() < self.grant_ttl);
434        for ip in held.iter().chain(granted.keys()) {
435            allocator.reserve(ip);
436        }
437
438        let vip = match allocator.allocate() {
439            Ok(ip) => ip,
440            Err(e) => {
441                // Pool exhausted → Deny (the operator sees it). NOT a
442                // silently unallocated Service.
443                return Ok(AdmissionDecision::Deny(e.to_string()));
444            }
445        };
446        granted.insert(vip.clone(), Instant::now());
447        drop(granted);
448
449        // Stamp the VIP onto a clone of the proposed object: spec.clusterIP
450        // (legacy single) + spec.clusterIPs[0] (dual-stack-aware list).
451        let mut mutated = svc.clone();
452        let spec = mutated.as_object_mut().and_then(|o| {
453            o.entry("spec")
454                .or_insert_with(|| Value::Object(Default::default()))
455                .as_object_mut()
456        });
457        let Some(spec) = spec else {
458            // A non-object spec is malformed — surface it, don't paper over.
459            return Ok(AdmissionDecision::Deny(
460                "Service has a non-object spec; cannot assign clusterIP".to_string(),
461            ));
462        };
463        spec.insert("clusterIP".to_string(), Value::String(vip.clone()));
464        spec.insert(
465            "clusterIPs".to_string(),
466            Value::Array(vec![Value::String(vip)]),
467        );
468        Ok(AdmissionDecision::Mutate(mutated))
469    }
470}
471
472/// A static [`ServiceIpSource`] for tests — a fixed list of held VIPs.
473#[derive(Clone, Default)]
474pub struct StaticServiceIpSource {
475    ips: Vec<String>,
476}
477
478impl StaticServiceIpSource {
479    /// New source holding `ips`.
480    #[must_use]
481    pub fn new(ips: Vec<String>) -> Self {
482        Self { ips }
483    }
484}
485
486#[async_trait]
487impl ServiceIpSource for StaticServiceIpSource {
488    async fn held_cluster_ips(&self) -> Vec<String> {
489        self.ips.clone()
490    }
491}
492
493#[cfg(test)]
494mod tests {
495    use super::*;
496    use engenho_store::resource::ResourceKey;
497    use serde_json::json;
498
499    // ── allocator core ───────────────────────────────────────────────
500
501    #[test]
502    fn allocate_starts_at_first_host() {
503        let mut a = ClusterIpAllocator::new("10.96.0.0/12").unwrap();
504        // Network address 10.96.0.0 is skipped; first host is 10.96.0.1.
505        assert_eq!(a.allocate().unwrap(), "10.96.0.1");
506    }
507
508    #[test]
509    fn two_allocations_are_distinct_and_sequential() {
510        let mut a = ClusterIpAllocator::new("10.96.0.0/12").unwrap();
511        let v1 = a.allocate().unwrap();
512        let v2 = a.allocate().unwrap();
513        assert_ne!(v1, v2, "collision-free");
514        assert_eq!(v1, "10.96.0.1");
515        assert_eq!(v2, "10.96.0.2");
516    }
517
518    #[test]
519    fn reserve_skips_held_vips() {
520        let mut a = ClusterIpAllocator::new("10.96.0.0/12").unwrap();
521        a.reserve("10.96.0.1");
522        a.reserve("10.96.0.2");
523        // Next free is .3.
524        assert_eq!(a.allocate().unwrap(), "10.96.0.3");
525    }
526
527    #[test]
528    fn release_returns_vip_to_pool() {
529        let mut a = ClusterIpAllocator::new("10.96.0.0/12").unwrap();
530        let v1 = a.allocate().unwrap(); // .1
531        assert_eq!(a.held(), 1);
532        a.release(&v1);
533        assert_eq!(a.held(), 0);
534        // Re-allocates the freed VIP (lowest free).
535        assert_eq!(a.allocate().unwrap(), "10.96.0.1");
536    }
537
538    #[test]
539    fn reserve_ignores_out_of_range_and_non_vip() {
540        let mut a = ClusterIpAllocator::new("10.96.0.0/24").unwrap();
541        assert!(!a.reserve("None"));
542        assert!(!a.reserve(""));
543        assert!(!a.reserve("192.168.1.1")); // out of CIDR
544        assert!(!a.reserve("not-an-ip"));
545        assert_eq!(a.held(), 0);
546    }
547
548    #[test]
549    fn small_cidr_exhausts_with_typed_error() {
550        // /30 → 4 addresses; .0 net + .3 broadcast skipped ⇒ 2 assignable.
551        let mut a = ClusterIpAllocator::new("10.0.0.0/30").unwrap();
552        assert_eq!(a.allocate().unwrap(), "10.0.0.1");
553        assert_eq!(a.allocate().unwrap(), "10.0.0.2");
554        let err = a.allocate().unwrap_err();
555        assert_eq!(err.kind(), "pool_exhausted");
556    }
557
558    #[test]
559    fn invalid_cidr_is_typed_error() {
560        let err = ClusterIpAllocator::new("nonsense").unwrap_err();
561        assert_eq!(err.kind(), "invalid_cidr");
562    }
563
564    #[test]
565    fn allocation_survives_restart_via_reseed() {
566        // Simulate a restart: process 1 allocates two VIPs, they land on
567        // live Services. Process 2 (fresh allocator) reseeds from those
568        // live VIPs → never re-hands them out.
569        let mut p1 = ClusterIpAllocator::new("10.96.0.0/16").unwrap();
570        let held1 = p1.allocate().unwrap(); // .0.1
571        let held2 = p1.allocate().unwrap(); // .0.2
572
573        // Fresh allocator after "restart" — no in-memory counter survives.
574        let mut p2 = ClusterIpAllocator::new("10.96.0.0/16").unwrap();
575        p2.reserve(&held1);
576        p2.reserve(&held2);
577        let next = p2.allocate().unwrap();
578        assert_ne!(next, held1);
579        assert_ne!(next, held2);
580        assert_eq!(next, "10.96.0.3", "recomputes from the durable set");
581    }
582
583    // ── classification ───────────────────────────────────────────────
584
585    #[test]
586    fn classify_default_service_needs_allocation() {
587        let svc = json!({"spec": {"ports": [{"port": 80}]}});
588        assert_eq!(
589            classify_service(&svc),
590            ServiceVipDisposition::NeedsAllocation
591        );
592        let svc2 = json!({"spec": {"type": "ClusterIP", "clusterIP": ""}});
593        assert_eq!(
594            classify_service(&svc2),
595            ServiceVipDisposition::NeedsAllocation
596        );
597    }
598
599    #[test]
600    fn classify_headless_service() {
601        let svc = json!({"spec": {"clusterIP": "None"}});
602        assert_eq!(classify_service(&svc), ServiceVipDisposition::Headless);
603    }
604
605    #[test]
606    fn classify_external_name_service() {
607        let svc = json!({"spec": {"type": "ExternalName", "externalName": "db.example.com"}});
608        assert_eq!(classify_service(&svc), ServiceVipDisposition::ExternalName);
609    }
610
611    #[test]
612    fn classify_already_assigned() {
613        let svc = json!({"spec": {"clusterIP": "10.96.5.5"}});
614        assert_eq!(
615            classify_service(&svc),
616            ServiceVipDisposition::AlreadyAssigned
617        );
618    }
619
620    // ── defaulting webhook ───────────────────────────────────────────
621
622    fn svc_request(svc: Value) -> AdmissionRequest {
623        AdmissionRequest {
624            action: AdmissionAction::Put,
625            key: ResourceKey::namespaced("", "v1", "Service", "default", "podinfo"),
626            value: Some(svc),
627            current: None,
628            user_info: engenho_types::auth::UserInfo::default(),
629        }
630    }
631
632    #[tokio::test]
633    async fn webhook_allocates_vip_for_default_service() {
634        let source = Arc::new(StaticServiceIpSource::new(vec![]));
635        let wh = ClusterIpDefaultingWebhook::new("10.96.0.0/12", source);
636        let req = svc_request(json!({
637            "kind": "Service", "apiVersion": "v1",
638            "metadata": {"name": "podinfo"},
639            "spec": {"selector": {"app": "podinfo"}, "ports": [{"port": 80}]}
640        }));
641        match wh.review(&req).await.unwrap() {
642            AdmissionDecision::Mutate(v) => {
643                let ip = v["spec"]["clusterIP"].as_str().unwrap();
644                assert_eq!(ip, "10.96.0.1");
645                // clusterIPs[0] mirrors clusterIP (dual-stack-aware list).
646                assert_eq!(v["spec"]["clusterIPs"][0], "10.96.0.1");
647            }
648            other => panic!("expected Mutate, got {other:?}"),
649        }
650    }
651
652    #[tokio::test]
653    async fn webhook_skips_held_vips_collision_free() {
654        // Two live Services already hold .1 and .2; the new Service gets .3.
655        let source = Arc::new(StaticServiceIpSource::new(vec![
656            "10.96.0.1".into(),
657            "10.96.0.2".into(),
658        ]));
659        let wh = ClusterIpDefaultingWebhook::new("10.96.0.0/12", source);
660        let req = svc_request(json!({
661            "kind": "Service", "apiVersion": "v1",
662            "metadata": {"name": "new"}, "spec": {"ports": [{"port": 80}]}
663        }));
664        match wh.review(&req).await.unwrap() {
665            AdmissionDecision::Mutate(v) => {
666                assert_eq!(v["spec"]["clusterIP"], "10.96.0.3");
667            }
668            other => panic!("expected Mutate, got {other:?}"),
669        }
670    }
671
672    #[tokio::test]
673    async fn webhook_leaves_headless_untouched() {
674        let source = Arc::new(StaticServiceIpSource::new(vec![]));
675        let wh = ClusterIpDefaultingWebhook::new("10.96.0.0/12", source);
676        let req = svc_request(json!({
677            "kind": "Service", "apiVersion": "v1",
678            "metadata": {"name": "headless"},
679            "spec": {"clusterIP": "None", "selector": {"app": "x"}}
680        }));
681        // Headless → Allow (unchanged); clusterIP stays None.
682        assert!(matches!(
683            wh.review(&req).await.unwrap(),
684            AdmissionDecision::Allow
685        ));
686    }
687
688    #[tokio::test]
689    async fn webhook_leaves_external_name_untouched() {
690        let source = Arc::new(StaticServiceIpSource::new(vec![]));
691        let wh = ClusterIpDefaultingWebhook::new("10.96.0.0/12", source);
692        let req = svc_request(json!({
693            "kind": "Service", "apiVersion": "v1",
694            "metadata": {"name": "ext"},
695            "spec": {"type": "ExternalName", "externalName": "db.example.com"}
696        }));
697        assert!(matches!(
698            wh.review(&req).await.unwrap(),
699            AdmissionDecision::Allow
700        ));
701    }
702
703    #[tokio::test]
704    async fn webhook_honors_operator_pinned_clusterip() {
705        let source = Arc::new(StaticServiceIpSource::new(vec![]));
706        let wh = ClusterIpDefaultingWebhook::new("10.96.0.0/12", source);
707        let req = svc_request(json!({
708            "kind": "Service", "apiVersion": "v1",
709            "metadata": {"name": "pinned"},
710            "spec": {"clusterIP": "10.96.7.7", "ports": [{"port": 80}]}
711        }));
712        // Already-assigned → Allow (honored as-is, never reallocated).
713        assert!(matches!(
714            wh.review(&req).await.unwrap(),
715            AdmissionDecision::Allow
716        ));
717    }
718
719    #[tokio::test]
720    async fn webhook_ignores_non_service_kinds() {
721        let source = Arc::new(StaticServiceIpSource::new(vec![]));
722        let wh = ClusterIpDefaultingWebhook::new("10.96.0.0/12", source);
723        let req = AdmissionRequest {
724            action: AdmissionAction::Put,
725            key: ResourceKey::namespaced("", "v1", "Pod", "default", "p"),
726            value: Some(json!({"kind": "Pod"})),
727            current: None,
728            user_info: engenho_types::auth::UserInfo::default(),
729        };
730        assert!(matches!(
731            wh.review(&req).await.unwrap(),
732            AdmissionDecision::Allow
733        ));
734    }
735
736    #[tokio::test]
737    async fn webhook_denies_on_pool_exhaustion() {
738        // A /30 with both assignable VIPs already held → Deny (not silent).
739        let source = Arc::new(StaticServiceIpSource::new(vec![
740            "10.0.0.1".into(),
741            "10.0.0.2".into(),
742        ]));
743        let wh = ClusterIpDefaultingWebhook::new("10.0.0.0/30", source);
744        let req = svc_request(json!({
745            "kind": "Service", "apiVersion": "v1",
746            "metadata": {"name": "doomed"}, "spec": {"ports": [{"port": 80}]}
747        }));
748        match wh.review(&req).await.unwrap() {
749            AdmissionDecision::Deny(reason) => assert!(reason.contains("exhausted")),
750            other => panic!("expected Deny, got {other:?}"),
751        }
752    }
753
754    #[tokio::test]
755    async fn webhook_restart_persistence_via_store_reseed() {
756        // The webhook reseeds from the source on EVERY call. Simulate a
757        // restart by constructing a NEW webhook over a source reporting the
758        // VIPs that landed on live Services — it never re-hands them out.
759        let live_after_restart = Arc::new(StaticServiceIpSource::new(vec![
760            "10.96.0.1".into(),
761            "10.96.0.2".into(),
762            "10.96.0.3".into(),
763        ]));
764        let wh = ClusterIpDefaultingWebhook::new("10.96.0.0/12", live_after_restart);
765        let req = svc_request(json!({
766            "kind": "Service", "apiVersion": "v1",
767            "metadata": {"name": "post-restart"}, "spec": {"ports": [{"port": 80}]}
768        }));
769        match wh.review(&req).await.unwrap() {
770            AdmissionDecision::Mutate(v) => {
771                assert_eq!(v["spec"]["clusterIP"], "10.96.0.4");
772            }
773            other => panic!("expected Mutate, got {other:?}"),
774        }
775    }
776
777    fn vip_of(decision: AdmissionDecision) -> String {
778        match decision {
779            AdmissionDecision::Mutate(v) => v["spec"]["clusterIP"].as_str().unwrap().to_string(),
780            other => panic!("expected Mutate, got {other:?}"),
781        }
782    }
783
784    #[tokio::test]
785    async fn concurrent_creates_never_share_a_vip_before_any_of_them_commits() {
786        let source = Arc::new(StaticServiceIpSource::new(vec![]));
787        let wh = Arc::new(ClusterIpDefaultingWebhook::new("10.97.0.0/16", source));
788        let reviews = ["grafana", "kube-state-metrics", "operator"].map(|name| {
789            let wh = wh.clone();
790            tokio::spawn(async move {
791                let req = svc_request(json!({
792                    "kind": "Service", "apiVersion": "v1",
793                    "metadata": {"name": name}, "spec": {"ports": [{"port": 80}]}
794                }));
795                vip_of(wh.review(&req).await.unwrap())
796            })
797        });
798        let mut vips = BTreeSet::new();
799        for r in reviews {
800            vips.insert(r.await.unwrap());
801        }
802        assert_eq!(vips.len(), 3, "{vips:?}");
803    }
804
805    #[tokio::test]
806    async fn a_grant_that_never_committed_returns_to_the_pool_after_its_ttl() {
807        let source = Arc::new(StaticServiceIpSource::new(vec![]));
808        let wh = ClusterIpDefaultingWebhook::new("10.97.0.0/16", source)
809            .with_grant_ttl(std::time::Duration::ZERO);
810        let req = svc_request(json!({
811            "kind": "Service", "apiVersion": "v1",
812            "metadata": {"name": "a"}, "spec": {"ports": [{"port": 80}]}
813        }));
814        assert_eq!(vip_of(wh.review(&req).await.unwrap()), "10.97.0.1");
815        assert_eq!(vip_of(wh.review(&req).await.unwrap()), "10.97.0.1");
816    }
817
818    #[test]
819    fn u32_ip_roundtrip() {
820        assert_eq!(u32_to_ip(ip_to_u32("10.96.0.1").unwrap()), "10.96.0.1");
821        assert_eq!(
822            u32_to_ip(ip_to_u32("255.255.255.255").unwrap()),
823            "255.255.255.255"
824        );
825        assert_eq!(u32_to_ip(0), "0.0.0.0");
826    }
827}