Repository navigation
Expand file tree
/
Copy pathcontainer.rs
More file actions
3349 lines (3051 loc) · 122 KB
/
Copy pathcontainer.rs
File metadata and controls
3349 lines (3051 loc) · 122 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
//! Container spec construction for the Podman driver.
use crate::config::PodmanComputeConfig;
use openshell_core::ComputeDriverError;
use openshell_core::driver_mounts::SelinuxLabel;
#[cfg(test)]
use openshell_core::gpu::{driver_gpu_requirements, validate_specific_gpu_device_request};
use openshell_core::proto::compute::v1::{DriverSandbox, DriverSandboxTemplate};
use openshell_core::proto_struct::deserialize_optional_non_empty_string_list;
use openshell_core::{driver_mounts, proto_struct};
use serde::Serialize;
use serde_json::Value;
use std::collections::{BTreeMap, HashSet};
use std::path::Path;
/// Returns `true` when `SELinux` is enabled (enforcing or permissive).
///
/// Checks whether selinuxfs is mounted, matching Podman's own detection
/// logic. Bind-mount relabeling (the `z` mount option) is needed in both
/// enforcing and permissive modes: enforcing blocks access outright, while
/// permissive floods the audit log with AVC denials that mask real issues.
///
/// On non-`SELinux` systems (Ubuntu, macOS, Alpine) the directory does not
/// exist and this returns `false`, leaving mount options unchanged.
#[cfg(target_os = "linux")]
fn is_selinux_enabled() -> bool {
Path::new("/sys/fs/selinux").is_dir()
}
#[cfg(not(target_os = "linux"))]
fn is_selinux_enabled() -> bool {
false
}
pub use openshell_core::driver_utils::{
LABEL_SANDBOX_ID, LABEL_SANDBOX_NAME, LABEL_SANDBOX_NAMESPACE, LABEL_SANDBOX_WORKSPACE,
};
/// Label applied to all managed containers.
pub const LABEL_MANAGED: &str = "openshell.managed";
/// Label filter string for list/event queries.
pub const LABEL_MANAGED_FILTER: &str = "openshell.managed=true";
/// Container name prefix to avoid collisions with user containers.
const CONTAINER_PREFIX: &str = "openshell-";
/// Volume name prefix.
const VOLUME_PREFIX: &str = "openshell-sandbox-";
/// Secret name prefix for per-sandbox gateway JWTs.
const TOKEN_SECRET_PREFIX: &str = "openshell-token-";
const PROXY_AUTH_SECRET_PREFIX: &str = "openshell-proxy-auth-";
const TLS_CA_SECRET_PREFIX: &str = "openshell-tls-ca-";
const TLS_CERT_SECRET_PREFIX: &str = "openshell-tls-cert-";
const TLS_KEY_SECRET_PREFIX: &str = "openshell-tls-key-";
/// Container-side mount paths for client TLS materials and the sandbox token.
const TLS_CA_MOUNT_PATH: &str = openshell_core::driver_utils::TLS_CA_MOUNT_PATH;
const TLS_CERT_MOUNT_PATH: &str = openshell_core::driver_utils::TLS_CERT_MOUNT_PATH;
const TLS_KEY_MOUNT_PATH: &str = openshell_core::driver_utils::TLS_KEY_MOUNT_PATH;
const SANDBOX_TOKEN_MOUNT_PATH: &str = openshell_core::driver_utils::SANDBOX_TOKEN_MOUNT_PATH;
const UPSTREAM_PROXY_AUTH_MOUNT_PATH: &str =
openshell_core::driver_utils::UPSTREAM_PROXY_AUTH_MOUNT_PATH;
const PROXY_CA_MOUNT_PATH: &str = openshell_core::driver_utils::PROXY_CA_MOUNT_PATH;
const PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR: &str =
openshell_core::driver_utils::PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR;
/// Directory inside sandbox containers where the supervisor binary is mounted.
const SUPERVISOR_MOUNT_DIR: &str = openshell_core::driver_utils::SUPERVISOR_CONTAINER_DIR;
/// Full path to the supervisor binary inside sandbox containers.
const SUPERVISOR_BINARY_PATH: &str = openshell_core::driver_utils::SUPERVISOR_CONTAINER_BINARY;
#[derive(Debug, Clone, Default, serde::Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct PodmanSandboxDriverConfig {
#[serde(
default,
deserialize_with = "deserialize_optional_non_empty_string_list"
)]
pub cdi_devices: Option<Vec<String>>,
mounts: Vec<PodmanDriverMountConfig>,
}
impl PodmanSandboxDriverConfig {
pub fn from_sandbox(sandbox: &DriverSandbox) -> Result<Self, ComputeDriverError> {
let Some(template) = sandbox
.spec
.as_ref()
.and_then(|spec| spec.template.as_ref())
else {
return Ok(Self::default());
};
Self::from_template(template)
}
pub fn from_template(template: &DriverSandboxTemplate) -> Result<Self, ComputeDriverError> {
let Some(config) = template.driver_config.as_ref() else {
return Ok(Self::default());
};
serde_json::from_value(proto_struct::struct_to_json_value(config)).map_err(|err| {
ComputeDriverError::InvalidArgument(format!("invalid podman driver_config: {err}"))
})
}
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
enum PodmanDriverMountConfig {
Bind {
source: String,
target: String,
#[serde(default = "default_true")]
read_only: bool,
#[serde(default)]
selinux_label: Option<SelinuxLabel>,
},
Volume {
source: String,
target: String,
#[serde(default = "default_true")]
read_only: bool,
#[serde(default)]
subpath: Option<String>,
},
Tmpfs {
target: String,
#[serde(default)]
options: Vec<String>,
#[serde(default)]
size_bytes: Option<f64>,
#[serde(default)]
mode: Option<f64>,
},
Image {
source: String,
target: String,
#[serde(default = "default_true")]
read_only: bool,
#[serde(default)]
subpath: Option<String>,
},
}
fn default_true() -> bool {
true
}
/// Build a Podman container name from the sandbox workspace, name, and ID.
///
/// Format: `openshell-{workspace}--{name}-{id}`
#[must_use]
pub fn container_name(workspace: &str, name: &str, id: &str) -> String {
format!("{CONTAINER_PREFIX}{workspace}--{name}-{id}")
}
/// Build the workspace volume name from the sandbox ID.
#[must_use]
pub fn volume_name(sandbox_id: &str) -> String {
format!("{VOLUME_PREFIX}{sandbox_id}-workspace")
}
/// Build the per-sandbox Podman secret name for the gateway JWT.
#[must_use]
pub fn token_secret_name(sandbox_id: &str) -> String {
format!("{TOKEN_SECRET_PREFIX}{sandbox_id}")
}
/// Build the per-sandbox Podman secret name for the corporate proxy credentials.
#[must_use]
pub fn proxy_auth_secret_name(sandbox_id: &str) -> String {
format!("{PROXY_AUTH_SECRET_PREFIX}{sandbox_id}")
}
/// Build per-sandbox Podman secret names for TLS CA, cert, and key.
#[must_use]
pub fn tls_secret_names(sandbox_id: &str) -> [String; 3] {
[
format!("{TLS_CA_SECRET_PREFIX}{sandbox_id}"),
format!("{TLS_CERT_SECRET_PREFIX}{sandbox_id}"),
format!("{TLS_KEY_SECRET_PREFIX}{sandbox_id}"),
]
}
/// Truncate a container ID to 12 characters (standard short form).
#[must_use]
pub fn short_id(id: &str) -> String {
id.chars().take(12).collect()
}
// ---------------------------------------------------------------------------
// Typed container spec structs for the Podman libpod create API.
// ---------------------------------------------------------------------------
#[derive(Serialize)]
struct ContainerSpec {
name: String,
image: String,
labels: BTreeMap<String, String>,
env: BTreeMap<String, String>,
volumes: Vec<NamedVolume>,
image_volumes: Vec<ImageVolume>,
hostname: String,
/// Overrides the image's ENTRYPOINT. In Podman's libpod API, `command`
/// only overrides CMD (appended as args to the entrypoint). We must set
/// `entrypoint` explicitly so the supervisor binary runs directly,
/// regardless of what ENTRYPOINT the sandbox image defines.
entrypoint: Vec<String>,
command: Vec<String>,
user: String,
cap_drop: Vec<String>,
cap_add: Vec<String>,
no_new_privileges: bool,
seccomp_profile_path: String,
image_pull_policy: String,
healthconfig: HealthConfig,
resource_limits: ResourceLimits,
/// Env-type secrets: map of `ENV_VAR_NAME → secret_name`.
/// Podman's libpod `SpecGenerator` uses `secret_env` (a flat map) for
/// environment-variable injection, distinct from `secrets` which only
/// handles file-mounted secrets under `/run/secrets/`.
secret_env: BTreeMap<String, String>,
/// File-mounted Podman secrets.
secrets: Vec<SecretMount>,
stop_timeout: u32,
/// Extra /etc/hosts entries. Used to inject `host.containers.internal`
/// via Podman's `host-gateway` magic so sandbox containers can reach
/// the gateway server running on the host in rootless mode.
hostadd: Vec<String>,
/// Search domains written to `/etc/resolv.conf` by Podman.
dns_search: Vec<String>,
/// Resolver options written to `/etc/resolv.conf` by Podman.
dns_option: Vec<String>,
netns: NetNS,
// Matches libpod's network spec format, which is `{name: {opts}}` where
// empty opts is a unit struct rather than `()`. Keep as a map so JSON
// serialization matches the API exactly.
#[allow(clippy::zero_sized_map_values)]
networks: BTreeMap<String, NetworkAttachment>,
#[serde(skip_serializing_if = "Option::is_none")]
devices: Option<Vec<LinuxDevice>>,
/// Extra mounts for the libpod `SpecGenerator` (e.g. tmpfs entries).
mounts: Vec<Mount>,
/// Port mappings from host to container. Using `host_port=0` requests an
/// ephemeral port, readable back from the inspect response.
portmappings: Vec<PortMapping>,
/// User namespace mode override (e.g. `auto`).
#[serde(skip_serializing_if = "Option::is_none")]
userns: Option<UserNS>,
/// UID/GID mapping options. Required for `userns = "auto"` — the Podman
/// API needs `AutoUserNs: true` alongside the namespace mode.
#[serde(skip_serializing_if = "Option::is_none")]
idmappings: Option<IDMappings>,
}
/// A port mapping entry for the libpod `SpecGenerator`.
#[derive(Serialize)]
struct PortMapping {
host_port: u16,
container_port: u16,
protocol: String,
}
/// A mount entry for the libpod container create API `mounts` field.
///
/// Unlike `volumes` (named Podman volumes) or `image_volumes` (OCI image
/// mounts resolved at the libpod layer), these mounts are passed to the
/// libpod `SpecGenerator` and support arbitrary mount types (e.g. tmpfs).
/// Field names must be lowercase to match the libpod JSON schema.
#[derive(Serialize)]
struct Mount {
#[serde(rename = "type")]
kind: String,
source: String,
destination: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
options: Vec<String>,
}
/// A Podman image volume for the libpod container create API.
///
/// Image volumes mount an OCI image's filesystem into a container without
/// running it. Podman resolves these at the libpod layer before generating
/// the OCI runtime spec, unlike `mounts` which are passed directly to the
/// OCI runtime (crun/runc).
#[derive(Serialize)]
struct ImageVolume {
source: String,
destination: String,
rw: bool,
}
#[derive(Serialize)]
struct NamedVolume {
name: String,
dest: String,
options: Vec<String>,
}
#[derive(Default)]
struct PodmanUserMounts {
volumes: Vec<NamedVolume>,
image_volumes: Vec<ImageVolume>,
mounts: Vec<Mount>,
}
#[derive(Serialize)]
struct HealthConfig {
test: Vec<String>,
#[serde(rename = "Interval")]
interval: u64,
#[serde(rename = "Timeout")]
timeout: u64,
#[serde(rename = "Retries")]
retries: u32,
#[serde(rename = "StartPeriod")]
start_period: u64,
}
#[derive(Serialize)]
struct SecretMount {
source: String,
target: String,
uid: u32,
gid: u32,
mode: u32,
}
#[derive(Serialize)]
struct ResourceLimits {
cpu: CpuLimits,
memory: MemoryLimits,
#[serde(rename = "PidsLimit", skip_serializing_if = "Option::is_none")]
pids_limit: Option<i64>,
}
#[derive(Serialize)]
struct CpuLimits {
quota: u64,
period: u64,
}
#[derive(Serialize)]
struct MemoryLimits {
limit: u64,
}
#[derive(Serialize)]
struct NetNS {
nsmode: String,
}
#[derive(Serialize)]
struct UserNS {
nsmode: String,
#[serde(skip_serializing_if = "Option::is_none")]
value: Option<String>,
}
#[derive(Serialize)]
struct IDMap {
container_id: u32,
host_id: u32,
size: u32,
}
#[derive(Serialize)]
struct IDMappings {
#[serde(rename = "HostUIDMapping")]
host_uid_mapping: bool,
#[serde(rename = "HostGIDMapping")]
host_gid_mapping: bool,
#[serde(rename = "AutoUserNs")]
auto_user_ns: bool,
#[serde(rename = "UIDMap", skip_serializing_if = "Vec::is_empty")]
uid_map: Vec<IDMap>,
#[serde(rename = "GIDMap", skip_serializing_if = "Vec::is_empty")]
gid_map: Vec<IDMap>,
}
fn parse_id_maps(entries: &[String]) -> Result<Vec<IDMap>, ComputeDriverError> {
entries
.iter()
.map(|entry| {
let (cid, hid, size) = crate::config::parse_id_map_entry("idmap", entry)
.map_err(|err| ComputeDriverError::Precondition(err.to_string()))?;
Ok(IDMap {
container_id: cid,
host_id: hid,
size,
})
})
.collect()
}
#[derive(Serialize)]
struct NetworkAttachment {}
#[derive(Serialize)]
struct LinuxDevice {
path: String,
}
/// Default limits: 2 CPU cores (200000µs quota / 100000µs period), 4 GiB memory.
const DEFAULT_CPU_QUOTA: u64 = 200_000;
const DEFAULT_CPU_PERIOD: u64 = 100_000;
const DEFAULT_MEMORY_LIMIT: u64 = 4_294_967_296; // 4 GiB
/// Resolve the OCI image reference for a sandbox, using the template image
/// if provided, otherwise the driver's default image.
#[must_use]
pub fn resolve_image<'a>(sandbox: &'a DriverSandbox, config: &'a PodmanComputeConfig) -> &'a str {
let spec = sandbox.spec.as_ref();
let template = spec.and_then(|s| s.template.as_ref());
template
.map(|t| t.image.as_str())
.filter(|s| !s.is_empty())
.unwrap_or(&config.default_image)
}
/// Merge environment variables from user spec/template with required driver vars.
///
/// User-supplied vars are inserted first so that the required driver
/// vars always win -- preventing spec/template overrides of security-
/// critical values like `OPENSHELL_ENDPOINT` or `OPENSHELL_SANDBOX_ID`.
/// Build the corporate upstream-proxy command-line arguments passed to the
/// supervisor.
///
/// This operator-owned egress boundary travels on argv, which sandbox
/// spec/template environment and image `ENV` cannot influence. Credentials
/// are never on argv — only the root-only mount path is passed; the
/// supervisor reads the secret from the mount.
fn upstream_proxy_cli_args(config: &PodmanComputeConfig) -> Vec<String> {
let mut args = Vec::new();
if let Some(url) = &config.https_proxy {
args.push("--upstream-proxy".to_string());
args.push(url.clone());
}
if let Some(list) = &config.no_proxy {
args.push("--upstream-no-proxy".to_string());
args.push(list.clone());
}
if config.proxy_auth_file.is_some() {
args.push("--upstream-proxy-auth-file".to_string());
args.push(UPSTREAM_PROXY_AUTH_MOUNT_PATH.to_string());
}
// Config validation guarantees the acknowledgement is `true` whenever an
// auth file is configured; the supervisor independently refuses
// credentials without it.
if config.proxy_auth_allow_insecure == Some(true) {
args.push("--upstream-proxy-auth-allow-insecure".to_string());
}
// Absent means the default validated-IP CONNECT binding; only the
// explicit hostname opt-in is passed through.
if config.proxy_connect_by_hostname == Some(true) {
args.push("--upstream-proxy-connect-by-hostname".to_string());
}
// A CA certificate is not secret, so the host PEM is bind-mounted
// read-only and the container-side mount path is passed on argv.
if config.proxy_ca_bundle.is_some() {
args.push("--upstream-proxy-ca-bundle".to_string());
args.push(PROXY_CA_MOUNT_PATH.to_string());
}
args
}
fn build_env(
sandbox: &DriverSandbox,
config: &PodmanComputeConfig,
image: &str,
oci_user: &str,
) -> BTreeMap<String, String> {
let spec = sandbox.spec.as_ref();
let template = spec.and_then(|s| s.template.as_ref());
let mut env: BTreeMap<String, String> = BTreeMap::new();
// 1. User-supplied environment (lowest priority).
// Template vars first, then spec overwrites (spec is user-specified).
let mut user_env: BTreeMap<String, String> = BTreeMap::new();
if let Some(t) = template {
for (k, v) in &t.environment {
user_env.insert(k.clone(), v.clone());
}
}
if let Some(s) = spec {
if !s.log_level.is_empty() {
env.insert(
openshell_core::sandbox_env::LOG_LEVEL.into(),
s.log_level.clone(),
);
}
for (k, v) in &s.environment {
user_env.insert(k.clone(), v.clone());
}
}
env.extend(user_env.clone());
if !user_env.is_empty()
&& let Ok(json) = serde_json::to_string(&user_env)
{
env.insert(openshell_core::sandbox_env::USER_ENVIRONMENT.into(), json);
}
// 2. Required driver vars (highest priority -- always overwrite).
// The operator's corporate egress proxy settings are not environment
// variables: they travel on the supervisor's argv (see
// `upstream_proxy_cli_args`), which sandbox spec/template environment
// and image ENV cannot influence.
env.insert(
openshell_core::sandbox_env::SANDBOX.into(),
sandbox.name.clone(),
);
env.insert(
openshell_core::sandbox_env::SANDBOX_ID.into(),
sandbox.id.clone(),
);
env.insert(
openshell_core::sandbox_env::ENDPOINT.into(),
config.grpc_endpoint.clone(),
);
env.insert(
openshell_core::sandbox_env::SSH_SOCKET_PATH.into(),
config.sandbox_ssh_socket_path.clone(),
);
env.insert("OPENSHELL_CONTAINER_IMAGE".into(), image.to_string());
let main_process = openshell_core::sandbox_env::MainProcessConfig::encode_driver_spec(spec)
.expect("main process config serialization cannot fail");
env.insert(
openshell_core::sandbox_env::MAIN_PROCESS_SPEC.into(),
main_process,
);
env.insert(
openshell_core::sandbox_env::TELEMETRY_ENABLED.into(),
openshell_core::telemetry::enabled_env_value().into(),
);
// Runtime capabilities are driver-owned. Override image/user input with
// only the substrate that this driver configures for the supervisor.
env.insert(
openshell_core::sandbox_env::NETWORK_RUNTIME_CAPABILITIES.into(),
openshell_core::sandbox_env::POLICY_DNS_TRANSPARENT_TCP_CAPABILITY.into(),
);
// 3. TLS client cert paths (when mTLS is enabled). These point to
// the container-side mount paths where the cert files are
// bind-mounted from the host.
if config.tls_enabled() {
env.insert(
openshell_core::sandbox_env::TLS_CA.into(),
TLS_CA_MOUNT_PATH.into(),
);
env.insert(
openshell_core::sandbox_env::TLS_CERT.into(),
TLS_CERT_MOUNT_PATH.into(),
);
env.insert(
openshell_core::sandbox_env::TLS_KEY.into(),
TLS_KEY_MOUNT_PATH.into(),
);
}
if let Some(socket_path) = provider_spiffe_workload_api_socket_env_value(config) {
env.insert(
openshell_core::sandbox_env::PROVIDER_SPIFFE_WORKLOAD_API_SOCKET.into(),
socket_path,
);
}
env.remove(openshell_core::sandbox_env::SANDBOX_TOKEN);
env.remove(openshell_core::sandbox_env::SANDBOX_TOKEN_FILE);
// Prevent user-supplied environment from overriding the TLS server name
// the supervisor verifies — a sandbox user who can redirect the gateway
// hostname could otherwise present a certificate for a name they control
// and intercept the sandbox JWT.
env.remove(openshell_core::sandbox_env::GATEWAY_TLS_SERVER_NAME);
env.insert(
openshell_core::sandbox_env::OCI_IMAGE_USER.into(),
oci_user.to_string(),
);
env.insert(
openshell_core::sandbox_env::SANDBOX_UID.into(),
String::new(),
);
env.insert(
openshell_core::sandbox_env::SANDBOX_GID.into(),
String::new(),
);
// 4. Gateway-minted sandbox JWT. Keep the raw bearer out of container
// metadata; the supervisor reads it from a driver-owned bind mount.
if let Some(s) = spec
&& !s.sandbox_token.is_empty()
{
env.insert(
openshell_core::sandbox_env::SANDBOX_TOKEN_FILE.into(),
SANDBOX_TOKEN_MOUNT_PATH.into(),
);
}
env
}
/// Merge labels from the sandbox template with required managed labels.
///
/// User-supplied labels are inserted first so that the managed labels
/// always win -- preventing template overrides of internal tracking labels.
fn build_labels(sandbox: &DriverSandbox) -> BTreeMap<String, String> {
let template = sandbox.spec.as_ref().and_then(|s| s.template.as_ref());
let mut labels: BTreeMap<String, String> = BTreeMap::new();
if let Some(t) = template {
for (k, v) in &t.labels {
labels.insert(k.clone(), v.clone());
}
}
// Managed labels (highest priority -- always overwrite).
labels.insert(LABEL_SANDBOX_ID.into(), sandbox.id.clone());
labels.insert(LABEL_SANDBOX_NAME.into(), sandbox.name.clone());
labels.insert(LABEL_SANDBOX_NAMESPACE.into(), sandbox.namespace.clone());
labels.insert(LABEL_SANDBOX_WORKSPACE.into(), sandbox.workspace.clone());
labels.insert(LABEL_MANAGED.into(), "true".into());
labels
}
/// Parse resource limits from the sandbox template, falling back to defaults.
fn build_resource_limits(sandbox: &DriverSandbox, config: &PodmanComputeConfig) -> ResourceLimits {
let resources = sandbox
.spec
.as_ref()
.and_then(|s| s.template.as_ref())
.and_then(|t| t.resources.as_ref());
let cpu_micros = resources
.filter(|r| !r.cpu_limit.is_empty())
.and_then(|r| parse_cpu_to_microseconds(&r.cpu_limit))
.unwrap_or(DEFAULT_CPU_QUOTA);
let mem_bytes = resources
.filter(|r| !r.memory_limit.is_empty())
.and_then(|r| parse_memory_to_bytes(&r.memory_limit))
.unwrap_or(DEFAULT_MEMORY_LIMIT);
ResourceLimits {
cpu: CpuLimits {
quota: cpu_micros,
period: DEFAULT_CPU_PERIOD,
},
memory: MemoryLimits { limit: mem_bytes },
pids_limit: podman_pids_limit(config.sandbox_pids_limit),
}
}
fn podman_pids_limit(value: i64) -> Option<i64> {
if value > 0 { Some(value) } else { None }
}
pub fn podman_driver_volume_mount_sources(
sandbox: &DriverSandbox,
enable_bind_mounts: bool,
) -> Result<Vec<String>, String> {
let template = sandbox
.spec
.as_ref()
.and_then(|spec| spec.template.as_ref());
let Some(template) = template else {
return Ok(Vec::new());
};
let config = podman_driver_config(template, enable_bind_mounts)?;
Ok(config
.mounts
.into_iter()
.filter_map(|mount| match mount {
PodmanDriverMountConfig::Volume { source, .. } => Some(source),
_ => None,
})
.collect())
}
pub fn podman_driver_image_mount_sources(
sandbox: &DriverSandbox,
enable_bind_mounts: bool,
) -> Result<Vec<String>, String> {
let template = sandbox
.spec
.as_ref()
.and_then(|spec| spec.template.as_ref());
let Some(template) = template else {
return Ok(Vec::new());
};
let config = podman_driver_config(template, enable_bind_mounts)?;
Ok(config
.mounts
.into_iter()
.filter_map(|mount| match mount {
PodmanDriverMountConfig::Image { source, .. } => Some(source),
_ => None,
})
.collect())
}
fn podman_user_mounts(
sandbox: &DriverSandbox,
enable_bind_mounts: bool,
) -> Result<PodmanUserMounts, String> {
let template = sandbox
.spec
.as_ref()
.and_then(|spec| spec.template.as_ref());
let Some(template) = template else {
return Ok(PodmanUserMounts::default());
};
let config = podman_driver_config(template, enable_bind_mounts)?;
let mut result = PodmanUserMounts::default();
for mount in config.mounts {
match mount {
PodmanDriverMountConfig::Bind {
source,
target,
read_only,
selinux_label,
} => {
let mut options = vec![
if read_only { "ro" } else { "rw" }.to_string(),
"rbind".to_string(),
];
match selinux_label {
Some(SelinuxLabel::Shared) => options.push("z".to_string()),
Some(SelinuxLabel::Private) => options.push("Z".to_string()),
None => {}
}
driver_mounts::validate_absolute_mount_source(&source, "bind source")?;
driver_mounts::validate_container_mount_target(&target)?;
result.mounts.push(Mount {
kind: "bind".into(),
source,
destination: driver_mounts::normalize_mount_target(&target),
options,
});
}
PodmanDriverMountConfig::Volume {
source,
target,
read_only,
subpath,
} => {
reject_subpath(subpath.as_deref(), "podman volume mounts")?;
driver_mounts::validate_mount_source(&source, "volume source")?;
driver_mounts::validate_container_mount_target(&target)?;
result.volumes.push(NamedVolume {
name: source,
dest: target,
options: vec![if read_only { "ro" } else { "rw" }.to_string()],
});
}
PodmanDriverMountConfig::Tmpfs {
target,
options,
size_bytes,
mode,
} => {
let mut options = validate_tmpfs_options(&options)?;
if options.is_empty() {
options.push("rw".to_string());
}
if let Some(size_bytes) =
validate_optional_positive_integral_i64(size_bytes, "tmpfs size_bytes")?
{
options.push(format!("size={size_bytes}"));
}
if let Some(mode) = validate_optional_nonnegative_integral_i64(mode, "tmpfs mode")?
{
options.push(format!("mode={mode:o}"));
}
driver_mounts::validate_container_mount_target(&target)?;
result.mounts.push(Mount {
kind: "tmpfs".into(),
source: "tmpfs".into(),
destination: target,
options,
});
}
PodmanDriverMountConfig::Image {
source,
target,
read_only,
subpath,
} => {
reject_subpath(subpath.as_deref(), "podman image mounts")?;
driver_mounts::validate_mount_source(&source, "image source")?;
driver_mounts::validate_container_mount_target(&target)?;
result.image_volumes.push(ImageVolume {
source,
destination: target,
rw: !read_only,
});
}
}
}
Ok(result)
}
fn podman_driver_config(
template: &DriverSandboxTemplate,
enable_bind_mounts: bool,
) -> Result<PodmanSandboxDriverConfig, String> {
let Some(config) = template.driver_config.as_ref() else {
return Ok(PodmanSandboxDriverConfig::default());
};
let json = Value::Object(proto_struct::struct_to_json_object(config));
let config: PodmanSandboxDriverConfig = serde_json::from_value(json)
.map_err(|err| format!("invalid podman driver_config: {err}"))?;
validate_podman_driver_mounts(&config.mounts, enable_bind_mounts)?;
Ok(config)
}
fn validate_podman_driver_mounts(
mounts: &[PodmanDriverMountConfig],
enable_bind_mounts: bool,
) -> Result<(), String> {
let mut targets = HashSet::new();
for mount in mounts {
let target = match mount {
PodmanDriverMountConfig::Bind { source, target, .. } => {
if !enable_bind_mounts {
return Err(
"podman bind mounts require enable_bind_mounts = true in [openshell.drivers.podman]"
.to_string(),
);
}
driver_mounts::validate_absolute_mount_source(source, "bind source")?;
target
}
PodmanDriverMountConfig::Volume {
source,
target,
subpath,
..
} => {
driver_mounts::validate_mount_source(source, "volume source")?;
reject_subpath(subpath.as_deref(), "podman volume mounts")?;
target
}
PodmanDriverMountConfig::Tmpfs {
target,
options,
size_bytes,
mode,
} => {
validate_tmpfs_options(options)?;
validate_optional_positive_integral_i64(*size_bytes, "tmpfs size_bytes")?;
validate_optional_nonnegative_integral_i64(*mode, "tmpfs mode")?;
target
}
PodmanDriverMountConfig::Image {
source,
target,
subpath,
..
} => {
driver_mounts::validate_mount_source(source, "image source")?;
reject_subpath(subpath.as_deref(), "podman image mounts")?;
target
}
};
driver_mounts::validate_container_mount_target(target)?;
let normalized_target = driver_mounts::normalize_mount_target(target);
if !targets.insert(normalized_target.clone()) {
return Err(format!(
"duplicate podman driver_config mount target '{normalized_target}'"
));
}
}
Ok(())
}
fn reject_subpath(subpath: Option<&str>, mount_type: &str) -> Result<(), String> {
let Some(subpath) = subpath else {
return Ok(());
};
driver_mounts::validate_mount_subpath(subpath)?;
Err(format!("{mount_type} do not support subpath"))
}
fn validate_optional_positive_integral_i64(
value: Option<f64>,
field: &str,
) -> Result<Option<i64>, String> {
let Some(value) = validate_optional_integral_i64(value, field)? else {
return Ok(None);
};
if value <= 0 {
return Err(format!("{field} must be positive"));
}
Ok(Some(value))
}
fn validate_optional_nonnegative_integral_i64(
value: Option<f64>,
field: &str,
) -> Result<Option<i64>, String> {
let Some(value) = validate_optional_integral_i64(value, field)? else {
return Ok(None);
};
if value < 0 {
return Err(format!("{field} must be zero or greater"));
}
Ok(Some(value))
}
fn validate_optional_integral_i64(value: Option<f64>, field: &str) -> Result<Option<i64>, String> {
let Some(value) = value else {
return Ok(None);
};
if !value.is_finite() || value.fract() != 0.0 {
return Err(format!("{field} must be an integer"));
}
value
.to_string()
.parse::<i64>()
.map(Some)
.map_err(|_| format!("{field} must be representable as an i64"))
}
fn validate_tmpfs_options(options: &[String]) -> Result<Vec<String>, String> {
options
.iter()
.map(|option| {
let option = option.trim();
if option.is_empty() {
return Err("tmpfs options must not contain empty values".to_string());
}
Ok(option.to_string())
})
.collect()
}
/// Build the Podman container creation JSON spec.
#[cfg(test)]
#[must_use]
pub fn build_container_spec(sandbox: &DriverSandbox, config: &PodmanComputeConfig) -> Value {
try_build_container_spec_with_token(sandbox, config, None)
.expect("container spec should be valid")
}
#[cfg(test)]
#[must_use]
pub fn build_container_spec_with_token(
sandbox: &DriverSandbox,
config: &PodmanComputeConfig,
token_secret_name: Option<&str>,
) -> Value {
try_build_container_spec_with_token(sandbox, config, token_secret_name)
.expect("container spec should be valid")
}
#[cfg(test)]
pub fn try_build_container_spec_with_token(
sandbox: &DriverSandbox,
config: &PodmanComputeConfig,
token_secret_name: Option<&str>,
) -> Result<Value, ComputeDriverError> {
let driver_config = PodmanSandboxDriverConfig::from_sandbox(sandbox)?;
let gpu_requirements = sandbox
.spec
.as_ref()
.and_then(|spec| driver_gpu_requirements(spec.resource_requirements.as_ref()));
let cdi_devices = if let Some(cdi_devices) = driver_config.cdi_devices.as_ref() {
validate_specific_gpu_device_request(
gpu_requirements,
cdi_devices,
"driver_config.cdi_devices",
)
.map_err(ComputeDriverError::InvalidArgument)?;
Some(cdi_devices.as_slice())
} else {
None
};
build_container_spec_with_token_and_gpu_devices(sandbox, config, token_secret_name, cdi_devices)
}
#[cfg(test)]
pub fn build_container_spec_with_token_and_gpu_devices(
sandbox: &DriverSandbox,
config: &PodmanComputeConfig,
token_secret_name: Option<&str>,
gpu_device_ids: Option<&[String]>,
) -> Result<Value, ComputeDriverError> {
let image = resolve_image(sandbox, config);
build_container_spec_for_image(
sandbox,
config,
token_secret_name,
gpu_device_ids,
image,