Repository navigation
Expand file tree
/
Copy pathconfig.rs
More file actions
1305 lines (1217 loc) · 53 KB
/
Copy pathconfig.rs
File metadata and controls
1305 lines (1217 loc) · 53 KB
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
use std::net::{IpAddr, Ipv4Addr};
use std::num::{NonZeroI64, NonZeroU64};
use std::path::PathBuf;
use openshell_core::{AppArmorProfile, ImagePullPolicy};
/// Default Podman bridge network name.
pub const DEFAULT_NETWORK_NAME: &str = "openshell";
pub const MACOS_PODMAN_MACHINE_HOST_GATEWAY_IP: &str = "192.168.127.254";
/// Default Podman stop timeout in seconds (SIGTERM → SIGKILL).
pub const DEFAULT_PODMAN_STOP_TIMEOUT_SECS: u32 = 45;
/// Translate the shared pull-policy vocabulary to the Podman libpod API.
#[must_use]
pub const fn podman_image_pull_policy(policy: ImagePullPolicy) -> &'static str {
match policy {
ImagePullPolicy::Always => "always",
ImagePullPolicy::IfNotPresent => "missing",
ImagePullPolicy::Never => "never",
ImagePullPolicy::Newer => "newer",
}
}
#[derive(Clone, serde::Serialize, serde::Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct PodmanComputeConfig {
/// Permit caller-supplied driver JSON. Does not waive resource admission.
pub allow_driver_config: bool,
/// Operator-owned external attachment approval policy.
pub resource_admission: openshell_core::resource_admission::ResourceAdmissionConfig,
/// Podman API Unix socket. When unset, use the socket selected by
/// gateway auto-detection.
pub socket_path: Option<PathBuf>,
/// Default OCI image for sandboxes.
pub default_image: String,
/// Image pull policy for sandbox images.
pub image_pull_policy: ImagePullPolicy,
/// Gateway gRPC endpoint the sandbox connects back to.
///
/// When empty, the driver selects loopback on Linux or
/// `host.containers.internal` with Podman Machine, using `gateway_port`.
pub grpc_endpoint: String,
/// Port the gateway server is actually listening on.
///
/// Used by the driver's auto-detection fallback when `grpc_endpoint`
/// is empty. The server must set this to `config.bind_address.port()`
/// so the correct port is used even when `--port` differs from the
/// default. Defaults to [`openshell_core::config::DEFAULT_SERVER_PORT`].
pub gateway_port: u16,
/// Unix socket path the in-container supervisor bridges relay traffic to.
pub ssh_socket_path: String,
/// Name of the Podman bridge network used for driver-managed resources.
pub network_name: String,
/// Trusted supervisor-side destination for sandbox host-gateway aliases.
///
/// Empty uses supervisor loopback on Linux and gvproxy's host-loopback IP
/// with Podman Machine. The resolved address is pinned into the protected
/// runtime descriptor; sandbox policy DNS never trusts workload resolver
/// state for `host.openshell.internal`.
pub host_gateway_ip: String,
/// Container stop timeout in seconds (SIGTERM → SIGKILL).
pub stop_timeout_secs: u32,
/// OCI image containing the statically linked `openshell-sandbox` binary.
/// The driver extracts the binary from this image into a verified host
/// cache and mounts it read-only into each sandbox container.
pub sandbox_runtime_image: String,
/// OCI image containing the dynamically linked `openshell-supervisor` binary.
pub supervisor_image: String,
/// Host path to the CA certificate for sandbox mTLS.
///
/// When all three TLS paths (`guest_tls_ca`, `guest_tls_cert`,
/// `guest_tls_key`) are set, the driver bind-mounts them into sandbox
/// containers and switches the auto-detected endpoint from `http://`
/// to `https://`.
pub guest_tls_ca: Option<PathBuf>,
/// Host path to the client certificate for sandbox mTLS.
pub guest_tls_cert: Option<PathBuf>,
/// Host path to the client private key for sandbox mTLS.
pub guest_tls_key: Option<PathBuf>,
/// Container cgroup PID limit for Podman-managed sandboxes.
///
/// Omit the field to use `OpenShell`'s 2048-process sandbox limit. Explicit
/// zero is invalid.
#[serde(
default = "openshell_core::config::default_sandbox_pids_limit",
skip_serializing_if = "Option::is_none"
)]
pub sandbox_pids_limit: Option<NonZeroI64>,
/// Allow sandbox requests to attach host bind mounts through
/// `template.driver_config`.
#[serde(default)]
pub enable_bind_mounts: bool,
/// Host path to a SPIFFE Workload API Unix socket exposed to sandbox
/// supervisors for provider token exchange client assertions.
pub provider_spiffe_workload_api_socket: Option<PathBuf>,
/// `AppArmor` confinement requested for the workload container. Omission
/// sends no override and preserves Podman's runtime-selected profile.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub app_armor_profile: Option<AppArmorProfile>,
/// Health check interval in seconds for supervisor containers.
///
/// Podman runs the health check command at this interval to determine
/// container readiness. Lower values detect readiness faster but
/// increase process churn (each check spawns a conmon subprocess).
/// Omit the field to disable health checks entirely. Explicit zero is
/// invalid.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub health_check_interval_secs: Option<NonZeroU64>,
/// Corporate forward proxy URL passed to the in-container supervisor
/// (e.g. `http://proxy.corp.com:8080` or `https://proxy.corp.com:3130`).
///
/// The supervisor chains policy-approved TLS tunnels through this proxy
/// with HTTP CONNECT instead of dialing upstream destinations directly.
/// `http://` and `https://` proxy URLs in explicit `scheme://host:port`
/// form (scheme and port required) are supported; for an `https://` proxy
/// the supervisor wraps the proxy connection in TLS, verifying the proxy
/// certificate against the built-in and system roots plus the optional
/// [`proxy_ca_bundle`](Self::proxy_ca_bundle). This is an operator-owned
/// egress boundary delivered on the supervisor's command line, so
/// sandbox/template environment cannot override it, and the conventional
/// `HTTPS_PROXY` variables are not used.
pub https_proxy: Option<String>,
/// Comma-separated `NO_PROXY` list passed alongside the proxy URL (e.g.
/// `*.svc.cluster.local,10.0.0.0/8`). Destinations matching an entry are
/// dialed directly instead of through the corporate proxy. Entries take
/// an optional `:port` qualifier that limits them to that destination
/// port, and IP/CIDR entries also match hostnames through their
/// validated DNS resolution.
pub no_proxy: Option<String>,
/// Path (on the gateway host) to a file containing the corporate proxy
/// credentials as `user:pass`.
///
/// Credentials must be supplied through this file, never embedded in the
/// proxy URL: an inline `user:pass@` in `https_proxy` is
/// rejected at startup because it would leak into `gateway.toml` and
/// container metadata. The gateway reads this file at sandbox-create time
/// and delivers it to the supervisor through a root-only secret mount.
pub proxy_auth_file: Option<String>,
/// Explicit acknowledgement that proxy credentials are sent in cleartext.
///
/// `Proxy-Authorization: Basic` is base64, not encryption, and the
/// connection to an `http://` corporate proxy is plain TCP, so anyone on
/// the network path between the sandbox host and the proxy can recover
/// the credential. Setting `proxy_auth_file` therefore requires
/// `proxy_auth_allow_insecure = true`; without it the configuration is
/// rejected at startup. Set it only when the path to the proxy is a
/// trusted network segment.
pub proxy_auth_allow_insecure: Option<bool>,
/// Send the destination *hostname* in CONNECT requests to the corporate
/// proxy instead of a validated IP.
///
/// By default the supervisor CONNECTs to an address that already passed
/// SSRF and `allowed_ips` validation, so the proxy performs no DNS
/// resolution and the tunnel stays bound to the validated answer. Set
/// this to `true` only when the proxy's ACLs filter on hostnames and
/// reject IP CONNECT targets: the proxy then resolves the name itself,
/// so a name that resolves differently at the proxy (split-horizon DNS,
/// rebinding) can reach destinations the sandbox policy never approved,
/// and the proxy's own ACLs become the effective egress control. Prefer
/// pointing the gateway host at the corporate resolver so validated-IP
/// CONNECT works in split-horizon networks.
pub proxy_connect_by_hostname: Option<bool>,
/// Path (on the gateway host) to a PEM CA bundle trusted for the corporate
/// proxy.
///
/// A CA certificate is not secret, so the gateway bind-mounts this file
/// read-only into the sandbox (at
/// [`PROXY_CA_MOUNT_PATH`](openshell_core::driver_utils::PROXY_CA_MOUNT_PATH))
/// and passes its path to the supervisor via `--upstream-proxy-ca-bundle`.
/// The supervisor trusts it for the TLS handshake with an `https://`
/// proxy and, because a TLS-intercepting proxy re-signs tunneled server
/// certificates with the same CA, folds it into the sandbox trust bundle
/// and upstream verification. Only meaningful with `https_proxy` set; the
/// bundle must exist and contain at least one certificate.
pub proxy_ca_bundle: Option<String>,
/// User namespace mode for sandbox containers (e.g. `auto`, `private`).
/// When unset, containers use the default user namespace.
pub userns: Option<String>,
/// Explicit UID mappings for `userns = "private"`.
/// Each entry is `"container_id:host_id:size"`.
#[serde(default)]
pub uidmap: Vec<String>,
/// Explicit GID mappings for `userns = "private"`.
/// Each entry is `"container_id:host_id:size"`.
#[serde(default)]
pub gidmap: Vec<String>,
}
/// Parse a single `"container_id:host_id:size"` mapping entry.
///
/// Returns `(container_id, host_id, size)` on success.
pub fn parse_id_map_entry(
field: &str,
entry: &str,
) -> Result<(u32, u32, u32), crate::client::PodmanApiError> {
let parts: Vec<&str> = entry.split(':').collect();
if parts.len() != 3 {
return Err(crate::client::PodmanApiError::InvalidInput(format!(
"{field} entry '{entry}' must be 'container_id:host_id:size'",
)));
}
let container_id: u32 = parts[0].parse().map_err(|_| {
crate::client::PodmanApiError::InvalidInput(format!(
"{field} entry '{entry}': container_id must be a non-negative integer",
))
})?;
let host_id: u32 = parts[1].parse().map_err(|_| {
crate::client::PodmanApiError::InvalidInput(format!(
"{field} entry '{entry}': host_id must be a non-negative integer",
))
})?;
let size: u32 = parts[2].parse().map_err(|_| {
crate::client::PodmanApiError::InvalidInput(format!(
"{field} entry '{entry}': size must be a non-negative integer",
))
})?;
if size == 0 {
return Err(crate::client::PodmanApiError::InvalidInput(format!(
"{field} entry '{entry}': size must be greater than 0",
)));
}
Ok((container_id, host_id, size))
}
impl PodmanComputeConfig {
/// Validate and normalize startup configuration without connecting to Podman.
pub fn validate_configuration(&mut self) -> Result<(), crate::client::PodmanApiError> {
self.resource_admission
.validate()
.map_err(crate::client::PodmanApiError::InvalidInput)?;
self.validate_tls_config()?;
self.validate_runtime_limits()?;
self.validate_host_gateway_ip()?;
self.validate_proxy_config()?;
self.validate_app_armor_profile()?;
if let Some(socket) = self.provider_spiffe_workload_api_socket.as_deref() {
let raw = socket.to_str().ok_or_else(|| {
crate::client::PodmanApiError::InvalidInput(
"provider_spiffe_workload_api_socket must be valid UTF-8".to_string(),
)
})?;
// Preserve pass-through support for an explicitly configured
// container-reachable Workload API TCP endpoint.
if !raw.starts_with("tcp:") {
openshell_core::driver_utils::validate_provider_spiffe_unix_socket(socket)
.map_err(crate::client::PodmanApiError::InvalidInput)?;
}
}
self.canonicalize_userns()?;
self.validate_userns_mappings()
}
/// Returns `true` when all three TLS paths are configured.
#[must_use]
pub fn tls_enabled(&self) -> bool {
self.guest_tls_ca.is_some() && self.guest_tls_cert.is_some() && self.guest_tls_key.is_some()
}
/// Validate TLS configuration consistency.
///
/// Returns `Ok(())` when either all three TLS paths are set (full mTLS)
/// or none are set (plaintext). Returns an error naming the missing
/// fields when only a subset is provided — this prevents silent
/// fallback to plaintext when an operator partially configures mTLS.
pub fn validate_tls_config(&self) -> Result<(), crate::client::PodmanApiError> {
let has_ca = self.guest_tls_ca.is_some();
let has_cert = self.guest_tls_cert.is_some();
let has_key = self.guest_tls_key.is_some();
// All set or none set — both are valid.
if (has_ca && has_cert && has_key) || (!has_ca && !has_cert && !has_key) {
return Ok(());
}
let mut missing = Vec::new();
if !has_ca {
missing.push("--podman-tls-ca / OPENSHELL_PODMAN_TLS_CA");
}
if !has_cert {
missing.push("--podman-tls-cert / OPENSHELL_PODMAN_TLS_CERT");
}
if !has_key {
missing.push("--podman-tls-key / OPENSHELL_PODMAN_TLS_KEY");
}
Err(crate::client::PodmanApiError::InvalidInput(format!(
"Partial TLS configuration: all three TLS paths must be provided together. \
Missing: {}",
missing.join(", ")
)))
}
/// Validate runtime resource-limit configuration.
pub fn validate_runtime_limits(&self) -> Result<(), crate::client::PodmanApiError> {
if self.sandbox_pids_limit.is_some_and(|limit| limit.get() < 0) {
return Err(crate::client::PodmanApiError::InvalidInput(
"sandbox_pids_limit must be positive when set".to_string(),
));
}
Ok(())
}
/// Validate optional corporate proxy configuration.
///
/// Shares validation semantics with the in-container supervisor through
/// [`openshell_core::driver_utils::parse_upstream_proxy_url`], so a value
/// accepted here can never be rejected by the supervisor at sandbox
/// startup (or vice versa). The supervisor supports `http://` and
/// `https://` forward proxies, so other schemes (SOCKS, etc.) are rejected
/// at config time instead of failing inside every sandbox. Credentials
/// must be supplied through `proxy_auth_file`; an inline `user:pass@` in
/// the URL is rejected because it would otherwise be stored in
/// `gateway.toml` and exposed in container metadata.
pub fn validate_proxy_config(&self) -> Result<(), crate::client::PodmanApiError> {
// Keep the Podman-only CA-bundle behaviour below, but delegate the
// shared URL, bypass-list, credential-file, and acknowledgement
// contract to openshell-core so Docker and VM cannot drift.
openshell_core::UpstreamProxyConfig {
https_proxy: self.https_proxy.clone(),
no_proxy: self.no_proxy.clone(),
proxy_auth_file: self.proxy_auth_file.as_ref().map(PathBuf::from),
proxy_auth_allow_insecure: self.proxy_auth_allow_insecure,
proxy_connect_by_hostname: self.proxy_connect_by_hostname,
}
.validate()
.map_err(crate::client::PodmanApiError::InvalidInput)?;
if let Some(path) = self.proxy_ca_bundle.as_deref() {
if path.trim().is_empty() {
return Err(crate::client::PodmanApiError::InvalidInput(
"proxy_ca_bundle must not be empty when set".to_string(),
));
}
if self.https_proxy.is_none() {
return Err(crate::client::PodmanApiError::InvalidInput(
"proxy_ca_bundle is set but no https_proxy is configured".to_string(),
));
}
}
Ok(())
}
/// Validate and canonicalize the optional `userns` mode.
///
/// Supported modes: `auto` (with optional params, e.g. `auto:size=65536`),
/// `host`, `keep-id` (with optional params), `no-map` (alias `nomap`),
/// and `private` (requires explicit `uidmap`/`gidmap`).
/// Modes that don't accept parameters (`host`, `no-map`, `private`) are
/// rejected when a colon-separated suffix is present.
///
/// On success, `self.userns` is rewritten with the canonical lowercase
/// mode string so downstream code can rely on exact matches.
pub fn canonicalize_userns(&mut self) -> Result<(), crate::client::PodmanApiError> {
let Some(mode) = self.userns.as_deref() else {
return Ok(());
};
let (base, has_params) = mode
.split_once(':')
.map_or((mode, false), |(b, _)| (b, true));
let canonical = match base.to_ascii_lowercase().as_str() {
"auto" => "auto",
"host" => "host",
"keep-id" => "keep-id",
"nomap" | "no-map" => "no-map",
"private" => "private",
_ => {
return Err(crate::client::PodmanApiError::InvalidInput(format!(
"unsupported userns mode '{mode}'; \
supported modes: auto, host, keep-id, no-map, private",
)));
}
};
if has_params {
match canonical {
"auto" | "keep-id" => {}
_ => {
return Err(crate::client::PodmanApiError::InvalidInput(format!(
"userns mode '{canonical}' does not accept parameters",
)));
}
}
}
self.userns = Some(if has_params {
let params = mode.split_once(':').unwrap().1;
format!("{canonical}:{params}")
} else {
canonical.to_string()
});
Ok(())
}
/// Validate `uidmap`/`gidmap` consistency with the userns mode.
///
/// `private` requires at least one entry in both `uidmap` and `gidmap`;
/// other modes (or no userns) reject non-empty mappings. Each entry must
/// be `"container_id:host_id:size"` with `size > 0`.
pub fn validate_userns_mappings(&self) -> Result<(), crate::client::PodmanApiError> {
let is_private = self
.userns
.as_deref()
.is_some_and(|m| m.eq_ignore_ascii_case("private"));
if is_private {
if self.uidmap.is_empty() || self.gidmap.is_empty() {
return Err(crate::client::PodmanApiError::InvalidInput(
"userns mode 'private' requires at least one entry in both \
uidmap and gidmap"
.to_string(),
));
}
} else if !self.uidmap.is_empty() || !self.gidmap.is_empty() {
return Err(crate::client::PodmanApiError::InvalidInput(
"uidmap/gidmap are only valid with userns = \"private\"".to_string(),
));
}
for (field, entries) in [("uidmap", &self.uidmap), ("gidmap", &self.gidmap)] {
for entry in entries {
parse_id_map_entry(field, entry)?;
}
}
Ok(())
}
/// Validate optional host gateway override.
/// Validate `AppArmor` syntax before contacting the runtime. Drivers check
/// runtime availability after querying their backend.
pub fn validate_app_armor_profile(&self) -> Result<(), crate::client::PodmanApiError> {
if matches!(self.app_armor_profile, Some(AppArmorProfile::Localhost(ref name)) if name.is_empty())
{
return Err(crate::client::PodmanApiError::InvalidInput(
"app_armor_profile Localhost profile must not be empty".to_string(),
));
}
Ok(())
}
pub fn validate_host_gateway_ip(&self) -> Result<(), crate::client::PodmanApiError> {
self.resolved_host_gateway_ip().map(|_| ())
}
/// Resolve the trusted supervisor-side destination for host-gateway aliases.
pub fn resolved_host_gateway_ip(&self) -> Result<IpAddr, crate::client::PodmanApiError> {
let trimmed = self.host_gateway_ip.trim();
let address = if trimmed.is_empty() {
#[cfg(target_os = "macos")]
{
MACOS_PODMAN_MACHINE_HOST_GATEWAY_IP
.parse::<IpAddr>()
.expect("Podman Machine host gateway constant must be an IP address")
}
#[cfg(not(target_os = "macos"))]
{
IpAddr::V4(Ipv4Addr::LOCALHOST)
}
} else {
trimmed.parse::<IpAddr>().map_err(|err| {
crate::client::PodmanApiError::InvalidInput(format!(
"invalid host_gateway_ip value '{trimmed}': {err}"
))
})?
};
let normalized = match address {
IpAddr::V6(ip) => ip.to_ipv4_mapped().map_or(address, IpAddr::V4),
IpAddr::V4(_) => address,
};
if address.is_unspecified()
|| address.is_multicast()
|| normalized == IpAddr::V4(Ipv4Addr::BROADCAST)
|| normalized == IpAddr::V4(Ipv4Addr::new(169, 254, 169, 254))
{
return Err(crate::client::PodmanApiError::InvalidInput(format!(
"invalid host_gateway_ip value '{address}': address is not a safe concrete host destination"
)));
}
Ok(address)
}
/// Resolve the default host gateway override for the current platform.
#[must_use]
pub fn default_host_gateway_ip() -> String {
#[cfg(target_os = "macos")]
{
MACOS_PODMAN_MACHINE_HOST_GATEWAY_IP.to_string()
}
#[cfg(not(target_os = "macos"))]
{
String::new()
}
}
}
impl Default for PodmanComputeConfig {
fn default() -> Self {
Self {
socket_path: None,
allow_driver_config: false,
resource_admission:
openshell_core::resource_admission::ResourceAdmissionConfig::default(),
default_image: openshell_core::image::default_sandbox_image(),
image_pull_policy: ImagePullPolicy::default(),
grpc_endpoint: String::new(),
gateway_port: openshell_core::config::DEFAULT_SERVER_PORT,
ssh_socket_path: openshell_core::container_paths::SSH_SOCKET_PATH.to_string(),
network_name: DEFAULT_NETWORK_NAME.to_string(),
host_gateway_ip: Self::default_host_gateway_ip(),
stop_timeout_secs: DEFAULT_PODMAN_STOP_TIMEOUT_SECS,
sandbox_runtime_image: openshell_core::config::default_sandbox_runtime_image(),
supervisor_image: openshell_core::config::default_supervisor_image(),
guest_tls_ca: None,
guest_tls_cert: None,
guest_tls_key: None,
sandbox_pids_limit: openshell_core::config::default_sandbox_pids_limit(),
enable_bind_mounts: false,
provider_spiffe_workload_api_socket: None,
app_armor_profile: None,
health_check_interval_secs: None,
https_proxy: None,
no_proxy: None,
proxy_auth_file: None,
proxy_auth_allow_insecure: None,
proxy_connect_by_hostname: None,
proxy_ca_bundle: None,
userns: None,
uidmap: Vec::new(),
gidmap: Vec::new(),
}
}
}
impl std::fmt::Debug for PodmanComputeConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PodmanComputeConfig")
.field("socket_path", &self.socket_path)
.field("default_image", &self.default_image)
.field("image_pull_policy", &self.image_pull_policy)
.field("grpc_endpoint", &self.grpc_endpoint)
.field("gateway_port", &self.gateway_port)
.field("ssh_socket_path", &self.ssh_socket_path)
.field("network_name", &self.network_name)
.field("host_gateway_ip", &self.host_gateway_ip)
.field("stop_timeout_secs", &self.stop_timeout_secs)
.field("sandbox_runtime_image", &self.sandbox_runtime_image)
.field("supervisor_image", &self.supervisor_image)
.field("guest_tls_ca", &self.guest_tls_ca)
.field("guest_tls_cert", &self.guest_tls_cert)
.field("guest_tls_key", &self.guest_tls_key)
.field("sandbox_pids_limit", &self.sandbox_pids_limit)
.field("enable_bind_mounts", &self.enable_bind_mounts)
.field(
"provider_spiffe_workload_api_socket",
&self.provider_spiffe_workload_api_socket,
)
.field("app_armor_profile", &self.app_armor_profile)
.field(
"health_check_interval_secs",
&self.health_check_interval_secs,
)
// Proxy URLs may embed credentials in userinfo; log presence only.
.field("https_proxy", &self.https_proxy.is_some())
.field("no_proxy", &self.no_proxy)
.field("proxy_auth_file", &self.proxy_auth_file.is_some())
.field("proxy_auth_allow_insecure", &self.proxy_auth_allow_insecure)
.field("proxy_connect_by_hostname", &self.proxy_connect_by_hostname)
.field("proxy_ca_bundle", &self.proxy_ca_bundle)
.field("userns", &self.userns)
.field("uidmap", &self.uidmap)
.field("gidmap", &self.gidmap)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shared_image_pull_policies_map_to_podman_vocabulary() {
for (policy, expected) in [
(ImagePullPolicy::Always, "always"),
(ImagePullPolicy::IfNotPresent, "missing"),
(ImagePullPolicy::Never, "never"),
(ImagePullPolicy::Newer, "newer"),
] {
assert_eq!(podman_image_pull_policy(policy), expected);
}
}
#[test]
fn config_uses_canonical_ssh_socket_path_name() {
let config: PodmanComputeConfig =
serde_json::from_value(serde_json::json!({ "ssh_socket_path": "/run/test.sock" }))
.unwrap();
assert_eq!(config.ssh_socket_path, "/run/test.sock");
let serialized = serde_json::to_value(config).unwrap();
assert_eq!(serialized["ssh_socket_path"], "/run/test.sock");
assert!(serialized.get("sandbox_ssh_socket_path").is_none());
}
#[test]
fn config_rejects_legacy_sandbox_ssh_socket_path() {
let error = serde_json::from_value::<PodmanComputeConfig>(serde_json::json!({
"sandbox_ssh_socket_path": "/run/test.sock"
}))
.expect_err("legacy sandbox_ssh_socket_path must be rejected");
assert!(error.to_string().contains("sandbox_ssh_socket_path"));
}
#[test]
fn default_config_disables_health_checks() {
assert_eq!(
PodmanComputeConfig::default().health_check_interval_secs,
None
);
}
#[test]
fn omitted_apparmor_profile_preserves_runtime_default() {
let config: PodmanComputeConfig = serde_json::from_value(serde_json::json!({}))
.expect("omitted AppArmor profile should deserialize");
assert_eq!(config.app_armor_profile, None);
let serialized = serde_json::to_value(config).expect("config should serialize");
assert!(serialized.get("app_armor_profile").is_none());
}
#[test]
fn explicit_apparmor_profiles_round_trip() {
for value in [
"RuntimeDefault",
"Unconfined",
"Localhost/openshell-supervisor",
] {
let config: PodmanComputeConfig = serde_json::from_value(serde_json::json!({
"app_armor_profile": value,
}))
.expect("explicit AppArmor profile should deserialize");
let serialized = serde_json::to_value(config).expect("config should serialize");
assert_eq!(serialized["app_armor_profile"], value);
}
}
#[test]
fn default_config_sets_podman_stop_timeout() {
let cfg = PodmanComputeConfig::default();
assert_eq!(cfg.stop_timeout_secs, DEFAULT_PODMAN_STOP_TIMEOUT_SECS);
}
#[test]
fn default_config_sets_driver_owned_pids_limit() {
let cfg = PodmanComputeConfig::default();
assert_eq!(
cfg.sandbox_pids_limit.map(NonZeroI64::get),
Some(openshell_core::config::DEFAULT_SANDBOX_PIDS_LIMIT)
);
assert!(!cfg.enable_bind_mounts);
}
#[test]
fn omitted_pids_limit_uses_driver_owned_default() {
let cfg: PodmanComputeConfig = serde_json::from_value(serde_json::json!({}))
.expect("default Podman config should deserialize");
assert_eq!(
cfg.sandbox_pids_limit.map(NonZeroI64::get),
Some(openshell_core::config::DEFAULT_SANDBOX_PIDS_LIMIT)
);
}
#[test]
#[cfg(target_os = "macos")]
fn default_config_uses_gvproxy_host_gateway_ip_on_macos() {
let cfg = PodmanComputeConfig::default();
assert_eq!(cfg.host_gateway_ip, MACOS_PODMAN_MACHINE_HOST_GATEWAY_IP);
assert!(cfg.validate_host_gateway_ip().is_ok());
assert_eq!(
cfg.resolved_host_gateway_ip().unwrap(),
MACOS_PODMAN_MACHINE_HOST_GATEWAY_IP
.parse::<IpAddr>()
.unwrap()
);
}
#[test]
#[cfg(not(target_os = "macos"))]
fn default_config_leaves_host_gateway_ip_empty_off_macos() {
let cfg = PodmanComputeConfig::default();
assert!(cfg.host_gateway_ip.is_empty());
assert!(cfg.validate_host_gateway_ip().is_ok());
assert_eq!(
cfg.resolved_host_gateway_ip().unwrap(),
IpAddr::V4(Ipv4Addr::LOCALHOST)
);
}
#[test]
fn host_gateway_ip_validation_rejects_invalid_values() {
let cfg = PodmanComputeConfig {
host_gateway_ip: "not-an-ip".to_string(),
..PodmanComputeConfig::default()
};
let err = cfg.validate_host_gateway_ip().unwrap_err();
assert!(err.to_string().contains("host_gateway_ip"));
}
#[test]
fn host_gateway_ip_resolution_preserves_explicit_address() {
let cfg = PodmanComputeConfig {
host_gateway_ip: "192.168.127.254".to_string(),
..PodmanComputeConfig::default()
};
assert_eq!(
cfg.resolved_host_gateway_ip().unwrap(),
"192.168.127.254".parse::<IpAddr>().unwrap()
);
}
#[test]
fn host_gateway_ip_validation_rejects_unsafe_destinations() {
for address in ["0.0.0.0", "224.0.0.1", "255.255.255.255", "169.254.169.254"] {
let cfg = PodmanComputeConfig {
host_gateway_ip: address.to_string(),
..PodmanComputeConfig::default()
};
let error = cfg.validate_host_gateway_ip().unwrap_err();
assert!(
error.to_string().contains("safe concrete host destination"),
"unexpected validation error for {address}: {error}"
);
}
}
#[test]
fn runtime_limit_rejects_invalid_pids_limits() {
let zero = serde_json::from_value::<PodmanComputeConfig>(serde_json::json!({
"sandbox_pids_limit": 0
}))
.expect_err("zero PID limit must be rejected");
assert!(zero.to_string().contains("invalid value: integer `0`"));
let negative: PodmanComputeConfig = serde_json::from_value(serde_json::json!({
"sandbox_pids_limit": -1
}))
.expect("nonzero integer deserializes before semantic validation");
let error = negative.validate_runtime_limits().unwrap_err();
assert!(error.to_string().contains("must be positive"));
}
#[test]
fn health_check_interval_rejects_zero() {
let error = serde_json::from_value::<PodmanComputeConfig>(serde_json::json!({
"health_check_interval_secs": 0
}))
.expect_err("zero health-check interval must be rejected");
assert!(error.to_string().contains("invalid value: integer `0`"));
}
// ── Proxy config validation ───────────────────────────────────────
#[test]
fn validate_proxy_config_accepts_unset_http_and_https() {
assert!(
PodmanComputeConfig::default()
.validate_proxy_config()
.is_ok()
);
let cfg = PodmanComputeConfig {
https_proxy: Some("http://proxy.corp.com:8080".to_string()),
no_proxy: Some("*.svc.cluster.local".to_string()),
..PodmanComputeConfig::default()
};
assert!(cfg.validate_proxy_config().is_ok());
// An https:// proxy URL is now supported (scheme and port required).
let cfg = PodmanComputeConfig {
https_proxy: Some("https://proxy.corp.com:3130".to_string()),
..PodmanComputeConfig::default()
};
assert!(cfg.validate_proxy_config().is_ok());
}
#[test]
fn validate_proxy_config_rejects_socks_schemes() {
// http:// and https:// are supported; only other schemes are rejected.
for url in ["socks5://proxy:1080", "ftp://proxy:21"] {
let cfg = PodmanComputeConfig {
https_proxy: Some(url.to_string()),
..PodmanComputeConfig::default()
};
let err = cfg.validate_proxy_config().unwrap_err();
assert!(
err.to_string().contains("unsupported proxy scheme"),
"{url}: {err}"
);
}
}
#[test]
fn validate_proxy_config_accepts_ca_bundle_with_proxy() {
let cfg = PodmanComputeConfig {
https_proxy: Some("https://proxy.corp.com:3130".to_string()),
proxy_ca_bundle: Some("/etc/openshell/proxy-ca.pem".to_string()),
..PodmanComputeConfig::default()
};
assert!(cfg.validate_proxy_config().is_ok());
// A CA bundle is also valid with an http:// proxy: a TLS-intercepting
// proxy reached over plain HTTP still re-signs upstream certificates.
let cfg = PodmanComputeConfig {
https_proxy: Some("http://proxy.corp.com:8080".to_string()),
proxy_ca_bundle: Some("/etc/openshell/proxy-ca.pem".to_string()),
..PodmanComputeConfig::default()
};
assert!(cfg.validate_proxy_config().is_ok());
}
#[test]
fn validate_proxy_config_rejects_ca_bundle_without_proxy() {
let cfg = PodmanComputeConfig {
proxy_ca_bundle: Some("/etc/openshell/proxy-ca.pem".to_string()),
..PodmanComputeConfig::default()
};
let err = cfg.validate_proxy_config().unwrap_err();
assert!(err.to_string().contains("proxy_ca_bundle"), "{err}");
assert!(err.to_string().contains("no https_proxy"), "{err}");
}
#[test]
fn validate_proxy_config_rejects_empty_ca_bundle() {
let cfg = PodmanComputeConfig {
https_proxy: Some("https://proxy.corp.com:3130".to_string()),
proxy_ca_bundle: Some(" ".to_string()),
..PodmanComputeConfig::default()
};
let err = cfg.validate_proxy_config().unwrap_err();
assert!(err.to_string().contains("proxy_ca_bundle"), "{err}");
}
#[test]
fn validate_proxy_config_rejects_url_components() {
for url in [
"http://proxy.corp.com:8080/path",
"http://proxy.corp.com:8080?x=1",
"http://proxy.corp.com:8080#frag",
] {
let cfg = PodmanComputeConfig {
https_proxy: Some(url.to_string()),
..PodmanComputeConfig::default()
};
let err = cfg.validate_proxy_config().unwrap_err();
assert!(
err.to_string().contains("scheme://host:port"),
"{url}: {err}"
);
}
}
#[test]
fn validate_proxy_config_rejects_zero_port() {
let cfg = PodmanComputeConfig {
https_proxy: Some("http://proxy.corp.com:0".to_string()),
..PodmanComputeConfig::default()
};
let err = cfg.validate_proxy_config().unwrap_err();
assert!(err.to_string().contains("port must not be 0"), "{err}");
}
#[test]
fn validate_proxy_config_rejects_missing_scheme_or_port() {
// A scheme-less value (previously normalized to http://) and a
// port-less value (previously defaulted to 80) are both rejected so
// gateway.toml matches the documented http://host:port grammar.
for url in ["proxy.corp.com:8080", "http://proxy.corp.com"] {
let cfg = PodmanComputeConfig {
https_proxy: Some(url.to_string()),
..PodmanComputeConfig::default()
};
let err = cfg.validate_proxy_config().unwrap_err();
assert!(err.to_string().contains("explicit"), "{url}: {err}");
}
}
#[test]
fn validate_proxy_config_rejects_empty_value() {
let cfg = PodmanComputeConfig {
https_proxy: Some(" ".to_string()),
..PodmanComputeConfig::default()
};
let err = cfg.validate_proxy_config().unwrap_err();
assert!(err.to_string().contains("https_proxy"), "{err}");
}
#[test]
fn validate_proxy_config_rejects_empty_no_proxy() {
let cfg = PodmanComputeConfig {
https_proxy: Some("http://proxy.corp.com:8080".to_string()),
no_proxy: Some(" ".to_string()),
..PodmanComputeConfig::default()
};
let err = cfg.validate_proxy_config().unwrap_err();
assert!(err.to_string().contains("no_proxy"), "{err}");
}
#[test]
fn validate_proxy_config_rejects_no_proxy_without_proxy() {
let cfg = PodmanComputeConfig {
no_proxy: Some("*.svc.cluster.local".to_string()),
..PodmanComputeConfig::default()
};
let err = cfg.validate_proxy_config().unwrap_err();
assert!(err.to_string().contains("no_proxy"), "{err}");
}
#[test]
fn validate_proxy_config_rejects_inline_credentials() {
for url in [
"http://user:[email protected]:8080",
"http://[email protected]:8080",
] {
let cfg = PodmanComputeConfig {
https_proxy: Some(url.to_string()),
..PodmanComputeConfig::default()
};
let err = cfg.validate_proxy_config().unwrap_err();
assert!(
err.to_string().contains("proxy_auth_file"),
"{url} should be rejected and point at proxy_auth_file: {err}"
);
}
}
#[test]
fn validate_proxy_config_accepts_auth_file_with_proxy_and_acknowledgement() {
let cfg = PodmanComputeConfig {
https_proxy: Some("http://proxy.corp.com:8080".to_string()),
proxy_auth_file: Some("/etc/openshell/secrets/proxy-auth".to_string()),
proxy_auth_allow_insecure: Some(true),
..PodmanComputeConfig::default()
};
assert!(cfg.validate_proxy_config().is_ok());
}
#[test]
fn validate_proxy_config_rejects_auth_file_without_insecure_acknowledgement() {
// Basic auth over the plain-TCP proxy connection is readable on the
// network path; sending it must be an explicit operator decision.
for allow in [None, Some(false)] {
let cfg = PodmanComputeConfig {
https_proxy: Some("http://proxy.corp.com:8080".to_string()),
proxy_auth_file: Some("/etc/openshell/secrets/proxy-auth".to_string()),
proxy_auth_allow_insecure: allow,
..PodmanComputeConfig::default()
};
let err = cfg.validate_proxy_config().unwrap_err();
assert!(
err.to_string().contains("proxy_auth_allow_insecure"),
"{allow:?}: {err}"
);
assert!(err.to_string().contains("cleartext"), "{allow:?}: {err}");
}
}
#[test]
fn validate_proxy_config_accepts_auth_file_without_acknowledgement_for_https_proxy() {
let cfg = PodmanComputeConfig {
https_proxy: Some("https://proxy.corp.com:3130".to_string()),
proxy_auth_file: Some("/etc/openshell/secrets/proxy-auth".to_string()),
..PodmanComputeConfig::default()
};
assert!(cfg.validate_proxy_config().is_ok());
}
#[test]
fn validate_proxy_config_accepts_connect_by_hostname_with_proxy() {
for by_hostname in [Some(true), Some(false)] {
let cfg = PodmanComputeConfig {
https_proxy: Some("http://proxy.corp.com:8080".to_string()),
proxy_connect_by_hostname: by_hostname,
..PodmanComputeConfig::default()
};
assert!(cfg.validate_proxy_config().is_ok(), "{by_hostname:?}");
}
}
#[test]
fn validate_proxy_config_rejects_connect_by_hostname_without_proxy() {
let cfg = PodmanComputeConfig {
proxy_connect_by_hostname: Some(true),
..PodmanComputeConfig::default()
};
let err = cfg.validate_proxy_config().unwrap_err();
assert!(err.to_string().contains("no https_proxy"), "{err}");
}
#[test]
fn validate_proxy_config_rejects_acknowledgement_without_auth_file() {
for allow in [Some(true), Some(false)] {