zlayer-types 0.14.0

Shared wire types for the ZLayer platform — API DTOs, OCI image references, and related serde types.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
//! Overlay-network configuration types shared across `ZLayer` crates.
//!
//! [`OverlayMode`] is a per-service data-plane attachment knob. It bundles two
//! independent decisions — the container-attachment topology (per-service Linux
//! bridge vs. one shared node-wide bridge + userspace free-port L4 proxy) and
//! the `WireGuard` transport (the single cluster-wide interface vs. a per-service
//! interface with isolated crypto) — into a single setting.
//!
//! Truth table:
//!
//! | mode      | shared node bridge + free-port proxy? | per-service `WireGuard` transport? | resulting behavior |
//! |-----------|----------------------------------------|------------------------------------|--------------------|
//! | `Auto`      | no  | no  | today's default: veth-per-container on a per-service Linux bridge, carried on the single cluster-wide `WireGuard` interface |
//! | `Dedicated` | no  | yes | veth-per-container on a per-service bridge, with its OWN per-service `WireGuard` transport (isolated crypto) = max isolation |
//! | `Shared`    | yes | no  | NO per-service bridge / NO per-service WG: one shared node-wide bridge for all services + a userspace free-port L4 proxy (`host:FREEPORT` -> `container_ip:port`), carried on the cluster-wide `WireGuard` interface = max sharing |
//! | `Isolated`  | no  | no  | per-service bridge on the cluster-wide `WireGuard` interface (Auto topology), but L3-fenced to its own isolation network (members reach only their own network + node IP + egress) |
//!
//! The real decision surface is the three predicate methods
//! [`OverlayMode::uses_shared_bridge`], [`OverlayMode::uses_per_service_wg`],
//! and [`OverlayMode::uses_isolation_scope`]; consult those rather than matching
//! on variants ad hoc.

use serde::{Deserialize, Serialize};

/// Per-service overlay data-plane attachment knob.
///
/// See the module docs for the full truth table; each variant bundles a
/// container-attachment topology with a `WireGuard` transport choice.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, utoipa::ToSchema)]
#[serde(rename_all = "lowercase")]
pub enum OverlayMode {
    /// Today's default behavior: veth-per-container on a per-service Linux
    /// bridge, carried on the single cluster-wide `WireGuard` interface. No
    /// shared node-wide bridge / free-port proxy and no per-service `WireGuard`
    /// transport.
    #[default]
    Auto,
    /// Max sharing: one shared node-wide bridge for all services plus a
    /// userspace free-port L4 proxy (`host:FREEPORT` -> `container_ip:port`).
    /// No per-service bridge and no per-service `WireGuard`; traffic rides the
    /// cluster-wide `WireGuard` interface.
    Shared,
    /// Max isolation: veth-per-container on a per-service bridge, with its OWN
    /// per-service `WireGuard` transport (isolated crypto context). No shared
    /// node-wide bridge / free-port proxy.
    Dedicated,
    /// Per-service bridge on the cluster-wide `WireGuard` interface (same
    /// topology + transport as [`OverlayMode::Auto`]), but L3-fenced to its own
    /// isolation network: members reach their own network's members plus the
    /// node IP and egress, never other networks' members or arbitrary cluster
    /// overlay IPs. Sugar for "Auto topology auto-fenced to an isolation network
    /// named after the service" — it reuses the same `isolation_network`
    /// membership machinery the named-isolated-networks feature already uses on
    /// every platform. Distinct from [`OverlayMode::Dedicated`], which isolates
    /// the crypto *transport* (its own `WireGuard` device), not the L3 scope.
    Isolated,
}

impl OverlayMode {
    /// Identity resolution: each variant resolves to itself. Retained so
    /// existing `.resolve()` callers keep compiling. `Auto` no longer maps to
    /// `Shared` — `Auto` now denotes today's default behavior (per-service
    /// bridge on the cluster-wide `WireGuard` interface) in its own right.
    #[must_use]
    pub fn resolve(self) -> OverlayMode {
        self
    }

    /// Whether this mode uses the shared node-wide bridge plus the userspace
    /// free-port L4 proxy. True only for [`OverlayMode::Shared`].
    #[must_use]
    pub fn uses_shared_bridge(self) -> bool {
        matches!(self, OverlayMode::Shared)
    }

    /// Whether this mode provisions its own per-service `WireGuard` transport
    /// with an isolated crypto context. True only for
    /// [`OverlayMode::Dedicated`].
    #[must_use]
    pub fn uses_per_service_wg(self) -> bool {
        matches!(self, OverlayMode::Dedicated)
    }

    /// Whether this mode is L3-fenced to its own isolation network. True only
    /// for [`OverlayMode::Isolated`]. The fence reuses the platform-neutral
    /// `isolation_network` membership channel; the network is named after the
    /// service.
    #[must_use]
    pub fn uses_isolation_scope(self) -> bool {
        matches!(self, OverlayMode::Isolated)
    }
}

/// Reserved container label naming the isolation network a container must join.
/// Read by every runtime's overlay attach path (via
/// [`crate::overlay::OverlayMode`] + the agent's `resolve_isolation_network`)
/// and by the Windows HCS create path. An explicit value always wins over
/// mode-derived isolation scoping. Canonical definition; per-crate copies in
/// the api/agent crates carry the same string.
pub const ISOLATION_NETWORK_LABEL: &str = "com.zlayer.isolation_network";

/// Per-service overlay configuration, populated from the service spec.
///
/// `parent` names another overlay this one should nest under. In v0.51 only
/// `None` / `Some("cluster")` is honored; any other value triggers a warn-
/// and-fallback (treated as `None`). Future rounds may allow service-of-
/// service nesting.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct OverlayConfig {
    #[serde(default)]
    pub mode: OverlayMode,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent: Option<String>,
}

impl OverlayConfig {
    /// Returns the resolved parent name for v0.51: `None` if the parent is
    /// `None` or `Some("cluster")`; logs a warning and falls back to `None`
    /// for any other value.
    #[must_use]
    pub fn resolved_parent_v0_51(&self) -> Option<&str> {
        match self.parent.as_deref() {
            None | Some("cluster") => None,
            Some(other) => {
                tracing::warn!(
                    parent = other,
                    "OverlayConfig.parent only supports `cluster` (or unset) in v0.51; \
                     service-of-service nesting is reserved for a future round. \
                     Falling back to cluster parent.",
                );
                None
            }
        }
    }
}

/// Egress policy for a workload's outbound connectivity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EgressPolicy {
    /// No outbound network at all.
    None,
    /// Full outbound (DNS/HTTP/HTTPS + arbitrary) — normal containers.
    Full,
}

/// Resolved network-isolation policy for a workload, derived from its
/// `OverlayMode` + `NetworkMode` + optional explicit isolation-network label.
/// Each runtime translates this into its own enforcement (Seatbelt `.sb` ACL,
/// Linux iptables ISO chain, HCN network, …).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NetworkIsolation {
    /// Isolation network name. `None` = flat cluster mesh (reach any overlay peer).
    /// `Some(_)` = fenced to this named network's members only.
    pub scope: Option<String>,
    /// When true, the workload must NOT be granted broad cluster-overlay reach
    /// (isolated/dedicated). When false, it may reach the whole overlay (normal).
    pub fenced: bool,
    /// Whether the workload may reach the daemon/node overlay IP.
    pub allow_host: bool,
    /// Outbound policy.
    pub egress: EgressPolicy,
}

/// Resolve the effective [`NetworkIsolation`] for a workload.
///
/// Precedence: `NetworkMode` hard cases first (None → no net; Host → full host
/// opt-in), otherwise derive from `OverlayMode`. `auto`/`shared` = Docker-normal
/// (unfenced, reachable). `isolated`/`dedicated` = fenced to their own network
/// (explicit label wins, else the service name). `explicit_isolation_label`
/// comes from the `ISOLATION_NETWORK_LABEL` container label, if present.
#[must_use]
pub fn resolve_network_isolation(
    mode: OverlayMode,
    network_mode_is_none: bool,
    network_mode_is_host: bool,
    service: &str,
    explicit_isolation_label: Option<&str>,
) -> NetworkIsolation {
    if network_mode_is_none {
        return NetworkIsolation {
            scope: None,
            fenced: true,
            allow_host: false,
            egress: EgressPolicy::None,
        };
    }
    if network_mode_is_host {
        return NetworkIsolation {
            scope: None,
            fenced: false,
            allow_host: true,
            egress: EgressPolicy::Full,
        };
    }
    let fenced = mode.uses_isolation_scope() || mode.uses_per_service_wg();
    let scope = if fenced {
        Some(explicit_isolation_label.map_or_else(|| service.to_string(), str::to_string))
    } else {
        explicit_isolation_label.map(str::to_string)
    };
    NetworkIsolation {
        scope,
        fenced,
        allow_host: true,
        egress: EgressPolicy::Full,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn overlay_mode_default_is_auto() {
        assert_eq!(OverlayMode::default(), OverlayMode::Auto);
    }

    #[test]
    fn isolation_network_label_is_canonical() {
        assert_eq!(ISOLATION_NETWORK_LABEL, "com.zlayer.isolation_network");
    }

    #[test]
    fn overlay_mode_resolve() {
        assert_eq!(OverlayMode::Auto.resolve(), OverlayMode::Auto);
        assert_eq!(OverlayMode::Shared.resolve(), OverlayMode::Shared);
        assert_eq!(OverlayMode::Dedicated.resolve(), OverlayMode::Dedicated);
        assert_eq!(OverlayMode::Isolated.resolve(), OverlayMode::Isolated);
    }

    #[test]
    fn overlay_mode_predicates() {
        assert_eq!(
            (
                OverlayMode::Auto.uses_shared_bridge(),
                OverlayMode::Auto.uses_per_service_wg()
            ),
            (false, false)
        );
        assert_eq!(
            (
                OverlayMode::Dedicated.uses_shared_bridge(),
                OverlayMode::Dedicated.uses_per_service_wg()
            ),
            (false, true)
        );
        assert_eq!(
            (
                OverlayMode::Shared.uses_shared_bridge(),
                OverlayMode::Shared.uses_per_service_wg()
            ),
            (true, false)
        );
    }

    #[test]
    fn overlay_mode_isolated_predicates() {
        assert!(OverlayMode::Isolated.uses_isolation_scope());
        assert!(!OverlayMode::Isolated.uses_shared_bridge());
        assert!(!OverlayMode::Isolated.uses_per_service_wg());
        assert!(!OverlayMode::Auto.uses_isolation_scope());
        assert!(!OverlayMode::Shared.uses_isolation_scope());
        assert!(!OverlayMode::Dedicated.uses_isolation_scope());
    }

    #[test]
    fn overlay_mode_serde_lowercase() {
        assert_eq!(
            serde_json::to_string(&OverlayMode::Auto).unwrap(),
            "\"auto\""
        );
        assert_eq!(
            serde_json::to_string(&OverlayMode::Shared).unwrap(),
            "\"shared\""
        );
        assert_eq!(
            serde_json::to_string(&OverlayMode::Dedicated).unwrap(),
            "\"dedicated\""
        );
        assert_eq!(
            serde_json::to_string(&OverlayMode::Isolated).unwrap(),
            "\"isolated\""
        );
        assert_eq!(
            serde_json::from_str::<OverlayMode>("\"shared\"").unwrap(),
            OverlayMode::Shared,
        );
        assert_eq!(
            serde_json::from_str::<OverlayMode>("\"isolated\"").unwrap(),
            OverlayMode::Isolated,
        );
    }

    #[test]
    fn overlay_config_default_is_auto_no_parent() {
        let cfg = OverlayConfig::default();
        assert_eq!(cfg.mode, OverlayMode::Auto);
        assert_eq!(cfg.parent, None);
        assert_eq!(cfg.resolved_parent_v0_51(), None);
    }

    #[test]
    fn overlay_config_cluster_parent_is_none() {
        let cfg = OverlayConfig {
            mode: OverlayMode::Shared,
            parent: Some("cluster".to_string()),
        };
        assert_eq!(cfg.resolved_parent_v0_51(), None);
    }

    #[test]
    fn overlay_config_other_parent_warns_and_returns_none() {
        let cfg = OverlayConfig {
            mode: OverlayMode::Shared,
            parent: Some("svc-other".to_string()),
        };
        assert_eq!(cfg.resolved_parent_v0_51(), None);
    }

    #[test]
    fn resolve_isolation_auto_is_unfenced_full_and_host() {
        let iso = resolve_network_isolation(OverlayMode::Auto, false, false, "svc", None);
        assert_eq!(
            iso,
            NetworkIsolation {
                scope: None,
                fenced: false,
                allow_host: true,
                egress: EgressPolicy::Full,
            }
        );
    }

    #[test]
    fn resolve_isolation_shared_is_unfenced() {
        let iso = resolve_network_isolation(OverlayMode::Shared, false, false, "svc", None);
        assert!(!iso.fenced);
        assert_eq!(iso.scope, None);
        assert_eq!(iso.egress, EgressPolicy::Full);
        assert!(iso.allow_host);
    }

    #[test]
    fn resolve_isolation_isolated_is_fenced_to_service() {
        let iso = resolve_network_isolation(OverlayMode::Isolated, false, false, "svc", None);
        assert!(iso.fenced);
        assert_eq!(iso.scope.as_deref(), Some("svc"));
        assert!(iso.allow_host);
        assert_eq!(iso.egress, EgressPolicy::Full);
    }

    #[test]
    fn resolve_isolation_isolated_explicit_label_overrides_service() {
        let iso =
            resolve_network_isolation(OverlayMode::Isolated, false, false, "svc", Some("netA"));
        assert!(iso.fenced);
        assert_eq!(iso.scope.as_deref(), Some("netA"));
    }

    #[test]
    fn resolve_isolation_dedicated_is_fenced() {
        let iso = resolve_network_isolation(OverlayMode::Dedicated, false, false, "svc", None);
        assert!(iso.fenced);
        assert_eq!(iso.scope.as_deref(), Some("svc"));
        assert_eq!(iso.egress, EgressPolicy::Full);
    }

    #[test]
    fn resolve_isolation_unfenced_label_still_sets_scope() {
        // An explicit label on an unfenced (auto) workload still names a scope,
        // but the workload is not fenced.
        let iso = resolve_network_isolation(OverlayMode::Auto, false, false, "svc", Some("netA"));
        assert!(!iso.fenced);
        assert_eq!(iso.scope.as_deref(), Some("netA"));
    }

    #[test]
    fn resolve_isolation_network_none_has_no_net() {
        let iso = resolve_network_isolation(OverlayMode::Auto, true, false, "svc", Some("netA"));
        assert_eq!(
            iso,
            NetworkIsolation {
                scope: None,
                fenced: true,
                allow_host: false,
                egress: EgressPolicy::None,
            }
        );
    }

    #[test]
    fn resolve_isolation_network_host_is_unfenced_full() {
        // Host mode wins over an isolated overlay mode: full host opt-in.
        let iso =
            resolve_network_isolation(OverlayMode::Isolated, false, true, "svc", Some("netA"));
        assert_eq!(
            iso,
            NetworkIsolation {
                scope: None,
                fenced: false,
                allow_host: true,
                egress: EgressPolicy::Full,
            }
        );
    }
}