-
Notifications
You must be signed in to change notification settings - Fork 640
Expand file tree
/
Copy pathlib.rs
More file actions
2139 lines (1936 loc) · 76 KB
/
lib.rs
File metadata and controls
2139 lines (1936 loc) · 76 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
//! OpenShell Sandbox library.
//!
//! This crate provides process sandboxing and monitoring capabilities.
pub mod bypass_monitor;
mod child_env;
pub mod denial_aggregator;
mod grpc_client;
mod identity;
pub mod l7;
pub mod log_push;
pub mod mechanistic_mapper;
pub mod opa;
mod policy;
mod process;
pub mod procfs;
pub mod proxy;
mod sandbox;
mod secrets;
mod ssh;
use miette::{IntoDiagnostic, Result};
#[cfg(target_os = "linux")]
use std::collections::HashSet;
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
#[cfg(target_os = "linux")]
use std::sync::{LazyLock, Mutex};
use std::time::Duration;
use tokio::time::timeout;
use tracing::{debug, error, info, trace, warn};
use crate::identity::BinaryIdentityCache;
use crate::l7::tls::{
CertCache, ProxyTlsState, SandboxCa, build_upstream_client_config, write_ca_files,
};
use crate::opa::OpaEngine;
use crate::policy::{NetworkMode, NetworkPolicy, ProxyPolicy, SandboxPolicy};
use crate::proxy::ProxyHandle;
#[cfg(target_os = "linux")]
use crate::sandbox::linux::netns::NetworkNamespace;
use crate::secrets::SecretResolver;
pub use process::{ProcessHandle, ProcessStatus};
/// Default interval (seconds) for re-fetching the inference route bundle from
/// the gateway in cluster mode. Override at runtime with the
/// `OPENSHELL_ROUTE_REFRESH_INTERVAL_SECS` environment variable.
/// File-based routes (`--inference-routes`) are loaded once at startup and never
/// refreshed.
const DEFAULT_ROUTE_REFRESH_INTERVAL_SECS: u64 = 5;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum InferenceRouteSource {
File,
Cluster,
None,
}
fn infer_route_source(
sandbox_id: Option<&str>,
openshell_endpoint: Option<&str>,
inference_routes: Option<&str>,
) -> InferenceRouteSource {
if inference_routes.is_some() {
InferenceRouteSource::File
} else if sandbox_id.is_some() && openshell_endpoint.is_some() {
InferenceRouteSource::Cluster
} else {
InferenceRouteSource::None
}
}
fn disable_inference_on_empty_routes(source: InferenceRouteSource) -> bool {
!matches!(source, InferenceRouteSource::Cluster)
}
fn route_refresh_interval_secs() -> u64 {
match std::env::var("OPENSHELL_ROUTE_REFRESH_INTERVAL_SECS") {
Ok(value) => match value.parse::<u64>() {
Ok(interval) if interval > 0 => interval,
Ok(_) => {
warn!(
default_interval_secs = DEFAULT_ROUTE_REFRESH_INTERVAL_SECS,
"Ignoring zero route refresh interval"
);
DEFAULT_ROUTE_REFRESH_INTERVAL_SECS
}
Err(error) => {
warn!(
interval = %value,
error = %error,
default_interval_secs = DEFAULT_ROUTE_REFRESH_INTERVAL_SECS,
"Ignoring invalid route refresh interval"
);
DEFAULT_ROUTE_REFRESH_INTERVAL_SECS
}
},
Err(_) => DEFAULT_ROUTE_REFRESH_INTERVAL_SECS,
}
}
#[cfg(target_os = "linux")]
static MANAGED_CHILDREN: LazyLock<Mutex<HashSet<i32>>> =
LazyLock::new(|| Mutex::new(HashSet::new()));
#[cfg(target_os = "linux")]
pub(crate) fn register_managed_child(pid: u32) {
let Ok(pid) = i32::try_from(pid) else {
return;
};
if pid <= 0 {
return;
}
if let Ok(mut children) = MANAGED_CHILDREN.lock() {
children.insert(pid);
}
}
#[cfg(target_os = "linux")]
pub(crate) fn unregister_managed_child(pid: u32) {
let Ok(pid) = i32::try_from(pid) else {
return;
};
if pid <= 0 {
return;
}
if let Ok(mut children) = MANAGED_CHILDREN.lock() {
children.remove(&pid);
}
}
#[cfg(target_os = "linux")]
fn is_managed_child(pid: i32) -> bool {
MANAGED_CHILDREN
.lock()
.is_ok_and(|children| children.contains(&pid))
}
/// Run a command in the sandbox.
///
/// # Errors
///
/// Returns an error if the command fails to start or encounters a fatal error.
#[allow(clippy::too_many_arguments, clippy::similar_names)]
pub async fn run_sandbox(
command: Vec<String>,
workdir: Option<String>,
timeout_secs: u64,
interactive: bool,
sandbox_id: Option<String>,
sandbox: Option<String>,
openshell_endpoint: Option<String>,
policy_rules: Option<String>,
policy_data: Option<String>,
ssh_listen_addr: Option<String>,
ssh_handshake_secret: Option<String>,
ssh_handshake_skew_secs: u64,
_health_check: bool,
_health_port: u16,
inference_routes: Option<String>,
) -> Result<i32> {
let (program, args) = command
.split_first()
.ok_or_else(|| miette::miette!("No command specified"))?;
// Load policy and initialize OPA engine
let openshell_endpoint_for_proxy = openshell_endpoint.clone();
let sandbox_name_for_agg = sandbox.clone();
let (policy, opa_engine, retained_proto) = load_policy(
sandbox_id.clone(),
sandbox,
openshell_endpoint.clone(),
policy_rules,
policy_data,
)
.await?;
// Validate that the required "sandbox" user exists in this image.
// All sandbox images must include this user for privilege dropping.
#[cfg(unix)]
validate_sandbox_user(&policy)?;
// Fetch provider environment variables from the server.
// This is done after loading the policy so the sandbox can still start
// even if provider env fetch fails (graceful degradation).
let provider_env = if let (Some(id), Some(endpoint)) = (&sandbox_id, &openshell_endpoint) {
match grpc_client::fetch_provider_environment(endpoint, id).await {
Ok(env) => {
info!(env_count = env.len(), "Fetched provider environment");
env
}
Err(e) => {
warn!(error = %e, "Failed to fetch provider environment, continuing without");
std::collections::HashMap::new()
}
}
} else {
std::collections::HashMap::new()
};
let (provider_env, secret_resolver) = SecretResolver::from_provider_env(provider_env);
let secret_resolver = secret_resolver.map(Arc::new);
// Create identity cache for SHA256 TOFU when OPA is active
let identity_cache = opa_engine
.as_ref()
.map(|_| Arc::new(BinaryIdentityCache::new()));
// Prepare filesystem: create and chown read_write directories
prepare_filesystem(&policy)?;
// Generate ephemeral CA and TLS state for HTTPS L7 inspection.
// The CA cert is written to disk so sandbox processes can trust it.
let (tls_state, ca_file_paths) = if matches!(policy.network.mode, NetworkMode::Proxy) {
match SandboxCa::generate() {
Ok(ca) => {
let tls_dir = std::path::Path::new("/etc/openshell-tls");
match write_ca_files(&ca, tls_dir) {
Ok(paths) => {
// /etc/openshell-tls is subsumed by the /etc baseline
// path injected by enrich_*_baseline_paths(), so no
// explicit Landlock entry is needed here.
let upstream_config = build_upstream_client_config();
let cert_cache = CertCache::new(ca);
let state = Arc::new(ProxyTlsState::new(cert_cache, upstream_config));
info!("TLS termination enabled: ephemeral CA generated");
(Some(state), Some(paths))
}
Err(e) => {
tracing::warn!(
error = %e,
"Failed to write CA files, TLS termination disabled"
);
(None, None)
}
}
}
Err(e) => {
tracing::warn!(
error = %e,
"Failed to generate ephemeral CA, TLS termination disabled"
);
(None, None)
}
}
} else {
(None, None)
};
// Create network namespace for proxy mode (Linux only)
// This must be created before the proxy AND SSH server so that SSH
// sessions can enter the namespace for network isolation.
#[cfg(target_os = "linux")]
let netns = if matches!(policy.network.mode, NetworkMode::Proxy) {
match NetworkNamespace::create() {
Ok(ns) => {
// Install bypass detection rules (iptables LOG + REJECT).
// This provides fast-fail UX and diagnostic logging for direct
// connection attempts that bypass the HTTP CONNECT proxy.
let proxy_port = policy
.network
.proxy
.as_ref()
.and_then(|p| p.http_addr)
.map_or(3128, |addr| addr.port());
if let Err(e) = ns.install_bypass_rules(proxy_port) {
warn!(
error = %e,
"Failed to install bypass detection rules (non-fatal)"
);
}
Some(ns)
}
Err(e) => {
return Err(miette::miette!(
"Network namespace creation failed and proxy mode requires isolation. \
Ensure CAP_NET_ADMIN and CAP_SYS_ADMIN are available and iproute2 is installed. \
Error: {e}"
));
}
}
} else {
None
};
// On non-Linux, network namespace isolation is not supported
#[cfg(not(target_os = "linux"))]
#[allow(clippy::no_effect_underscore_binding)]
let _netns: Option<()> = None;
// Shared PID: set after process spawn so the proxy can look up
// the entrypoint process's /proc/net/tcp for identity binding.
let entrypoint_pid = Arc::new(AtomicU32::new(0));
let (_proxy, denial_rx, bypass_denial_tx) = if matches!(policy.network.mode, NetworkMode::Proxy)
{
let proxy_policy = policy.network.proxy.as_ref().ok_or_else(|| {
miette::miette!("Network mode is set to proxy but no proxy configuration was provided")
})?;
let engine = opa_engine.clone().ok_or_else(|| {
miette::miette!("Proxy mode requires an OPA engine (--rego-policy and --rego-data)")
})?;
let cache = identity_cache.clone().ok_or_else(|| {
miette::miette!("Proxy mode requires an identity cache (OPA engine must be configured)")
})?;
// If we have a network namespace, bind to the veth host IP so sandboxed
// processes can reach the proxy via TCP.
#[cfg(target_os = "linux")]
let bind_addr = netns.as_ref().map(|ns| {
let port = proxy_policy.http_addr.map_or(3128, |addr| addr.port());
SocketAddr::new(ns.host_ip(), port)
});
#[cfg(not(target_os = "linux"))]
let bind_addr: Option<SocketAddr> = None;
// Build inference context for local routing of intercepted inference calls.
let inference_ctx = build_inference_context(
sandbox_id.as_deref(),
openshell_endpoint_for_proxy.as_deref(),
inference_routes.as_deref(),
)
.await?;
// Create denial aggregator channel if in gRPC mode (sandbox_id present).
// Clone the sender for the bypass monitor before passing to the proxy.
let (denial_tx, denial_rx, bypass_denial_tx) = if sandbox_id.is_some() {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
let bypass_tx = tx.clone();
(Some(tx), Some(rx), Some(bypass_tx))
} else {
(None, None, None)
};
let proxy_handle = ProxyHandle::start_with_bind_addr(
proxy_policy,
bind_addr,
engine,
cache,
entrypoint_pid.clone(),
tls_state,
inference_ctx,
secret_resolver.clone(),
denial_tx,
)
.await?;
(Some(proxy_handle), denial_rx, bypass_denial_tx)
} else {
(None, None, None)
};
// Spawn bypass detection monitor (Linux only, proxy mode only).
// Reads /dev/kmsg for iptables LOG entries and emits structured
// tracing events for direct connection attempts that bypass the proxy.
#[cfg(target_os = "linux")]
let _bypass_monitor = if netns.is_some() {
bypass_monitor::spawn(
netns.as_ref().expect("netns is Some").name().to_string(),
entrypoint_pid.clone(),
bypass_denial_tx,
)
} else {
None
};
// On non-Linux, bypass_denial_tx is unused (no /dev/kmsg).
#[cfg(not(target_os = "linux"))]
drop(bypass_denial_tx);
// Compute the proxy URL and netns fd for SSH sessions.
// SSH shell processes need both to enforce network policy:
// - netns_fd: enter the network namespace via setns() so all traffic
// goes through the veth pair (hard enforcement, non-bypassable)
// - proxy_url: set proxy env vars so cooperative tools route through the
// CONNECT proxy; this also opts Node.js into honoring those vars
#[cfg(target_os = "linux")]
let ssh_netns_fd = netns.as_ref().and_then(NetworkNamespace::ns_fd);
#[cfg(not(target_os = "linux"))]
let ssh_netns_fd: Option<i32> = None;
let ssh_proxy_url = if matches!(policy.network.mode, NetworkMode::Proxy) {
#[cfg(target_os = "linux")]
{
netns.as_ref().map(|ns| {
let port = policy
.network
.proxy
.as_ref()
.and_then(|p| p.http_addr)
.map_or(3128, |addr| addr.port());
format!("http://{}:{port}", ns.host_ip())
})
}
#[cfg(not(target_os = "linux"))]
{
policy
.network
.proxy
.as_ref()
.and_then(|p| p.http_addr)
.map(|addr| format!("http://{addr}"))
}
} else {
None
};
// Zombie reaper — openshell-sandbox may run as PID 1 in containers and
// must reap orphaned grandchildren (e.g. background daemons started by
// coding agents) to prevent zombie accumulation.
//
// Use waitid(..., WNOWAIT) so we can inspect exited children before
// actually reaping them. This avoids racing explicit `child.wait()` calls
// for managed children (entrypoint and SSH session processes).
#[cfg(target_os = "linux")]
tokio::spawn(async {
use nix::sys::wait::{Id, WaitPidFlag, WaitStatus, waitid, waitpid};
use tokio::signal::unix::{SignalKind, signal};
use tokio::time::MissedTickBehavior;
let mut sigchld = match signal(SignalKind::child()) {
Ok(s) => s,
Err(e) => {
tracing::warn!(error = %e, "Failed to register SIGCHLD handler for zombie reaping");
return;
}
};
let mut retry = tokio::time::interval(Duration::from_secs(5));
retry.set_missed_tick_behavior(MissedTickBehavior::Skip);
loop {
tokio::select! {
_ = sigchld.recv() => {}
_ = retry.tick() => {}
}
loop {
let status = match waitid(
Id::All,
WaitPidFlag::WEXITED | WaitPidFlag::WNOHANG | WaitPidFlag::WNOWAIT,
) {
Ok(WaitStatus::StillAlive) | Err(nix::errno::Errno::ECHILD) => break,
Ok(status) => status,
Err(nix::errno::Errno::EINTR) => continue,
Err(e) => {
tracing::debug!(error = %e, "waitid error during zombie reaping");
break;
}
};
let Some(pid) = status.pid() else {
break;
};
if is_managed_child(pid.as_raw()) {
// Let the explicit waiter own this child status.
break;
}
match waitpid(pid, Some(WaitPidFlag::WNOHANG)) {
Ok(WaitStatus::StillAlive) | Err(nix::errno::Errno::ECHILD) => {}
Ok(reaped) => {
tracing::debug!(?reaped, "Reaped orphaned child process");
}
Err(nix::errno::Errno::EINTR) => {}
Err(e) => {
tracing::debug!(error = %e, "waitpid error during orphan reap");
break;
}
}
}
}
});
if let Some(listen_addr) = ssh_listen_addr {
let addr: SocketAddr = listen_addr.parse().into_diagnostic()?;
let policy_clone = policy.clone();
let workdir_clone = workdir.clone();
let secret = ssh_handshake_secret
.filter(|s| !s.is_empty())
.ok_or_else(|| {
miette::miette!(
"OPENSHELL_SSH_HANDSHAKE_SECRET is required when SSH is enabled.\n\
Set --ssh-handshake-secret or the OPENSHELL_SSH_HANDSHAKE_SECRET env var."
)
})?;
let proxy_url = ssh_proxy_url;
let netns_fd = ssh_netns_fd;
let ca_paths = ca_file_paths.clone();
let provider_env_clone = provider_env.clone();
let (ssh_ready_tx, ssh_ready_rx) = tokio::sync::oneshot::channel();
tokio::spawn(async move {
if let Err(err) = ssh::run_ssh_server(
addr,
ssh_ready_tx,
policy_clone,
workdir_clone,
secret,
ssh_handshake_skew_secs,
netns_fd,
proxy_url,
ca_paths,
provider_env_clone,
)
.await
{
tracing::error!(error = %err, "SSH server failed");
}
});
// Wait for the SSH server to bind its socket before spawning the
// entrypoint process. This prevents exec requests from racing against
// SSH server startup when Kubernetes marks the pod Ready.
match timeout(Duration::from_secs(10), ssh_ready_rx).await {
Ok(Ok(Ok(()))) => {
info!("SSH server is ready to accept connections");
}
Ok(Ok(Err(err))) => {
return Err(err.context("SSH server failed during startup"));
}
Ok(Err(_)) => {
return Err(miette::miette!(
"SSH server task panicked before signaling ready"
));
}
Err(_) => {
return Err(miette::miette!(
"SSH server did not start within 10 seconds"
));
}
}
}
#[cfg(target_os = "linux")]
let mut handle = ProcessHandle::spawn(
program,
args,
workdir.as_deref(),
interactive,
&policy,
netns.as_ref(),
ca_file_paths.as_ref(),
&provider_env,
)?;
#[cfg(not(target_os = "linux"))]
let mut handle = ProcessHandle::spawn(
program,
args,
workdir.as_deref(),
interactive,
&policy,
ca_file_paths.as_ref(),
&provider_env,
)?;
// Store the entrypoint PID so the proxy can resolve TCP peer identity
entrypoint_pid.store(handle.pid(), Ordering::Release);
info!(pid = handle.pid(), "Process started");
// Resolve policy binary symlinks now that the container filesystem is
// accessible via /proc/<pid>/root/. This expands symlinks like
// /usr/bin/python3 → /usr/bin/python3.11 in the OPA policy data so that
// either path matches at evaluation time.
//
// If /proc/<pid>/root/ is inaccessible (restricted ptrace, rootless
// container, etc.), resolve_binary_in_container logs a warning per binary
// and falls back to literal path matching. The reload itself still
// succeeds — only the symlink expansion is skipped.
if let (Some(engine), Some(proto)) = (&opa_engine, &retained_proto) {
let pid = handle.pid();
if let Err(e) = engine.reload_from_proto_with_pid(proto, pid) {
warn!(
error = %e,
"Failed to rebuild OPA engine with symlink resolution (non-fatal, \
falling back to literal path matching)"
);
} else {
info!(
pid = pid,
"Policy binary symlink resolution attempted via container filesystem \
(check logs above for per-binary results)"
);
}
}
// Spawn background policy poll task (gRPC mode only).
if let (Some(id), Some(endpoint), Some(engine)) =
(&sandbox_id, &openshell_endpoint, &opa_engine)
{
let poll_id = id.clone();
let poll_endpoint = endpoint.clone();
let poll_engine = engine.clone();
let poll_pid = entrypoint_pid.clone();
let poll_interval_secs: u64 = std::env::var("OPENSHELL_POLICY_POLL_INTERVAL_SECS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10);
tokio::spawn(async move {
if let Err(e) = run_policy_poll_loop(
&poll_endpoint,
&poll_id,
&poll_engine,
&poll_pid,
poll_interval_secs,
)
.await
{
warn!(error = %e, "Policy poll loop exited with error");
}
});
// Spawn denial aggregator (gRPC mode only, when proxy is active).
if let Some(rx) = denial_rx {
// SubmitPolicyAnalysis resolves by sandbox *name*, not UUID.
let agg_name = sandbox_name_for_agg.clone().unwrap_or_else(|| id.clone());
let agg_endpoint = endpoint.clone();
let flush_interval_secs: u64 = std::env::var("OPENSHELL_DENIAL_FLUSH_INTERVAL_SECS")
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(10);
let aggregator = denial_aggregator::DenialAggregator::new(rx, flush_interval_secs);
tokio::spawn(async move {
aggregator
.run(|summaries| {
let endpoint = agg_endpoint.clone();
let sandbox_name = agg_name.clone();
async move {
if let Err(e) =
flush_proposals_to_gateway(&endpoint, &sandbox_name, summaries)
.await
{
warn!(error = %e, "Failed to flush denial summaries to gateway");
}
}
})
.await;
});
}
}
// Wait for process with optional timeout
let result = if timeout_secs > 0 {
if let Ok(result) = timeout(Duration::from_secs(timeout_secs), handle.wait()).await {
result
} else {
error!("Process timed out, killing");
handle.kill()?;
return Ok(124); // Standard timeout exit code
}
} else {
handle.wait().await
};
let status = result.into_diagnostic()?;
info!(exit_code = status.code(), "Process exited");
Ok(status.code())
}
/// Build an inference context for local routing, if route sources are available.
///
/// Route sources (in priority order):
/// 1. Inference routes file (standalone mode) — always takes precedence
/// 2. Cluster bundle (fetched from gateway via gRPC)
///
/// If both a routes file and cluster credentials are provided, the routes file
/// wins and the cluster bundle is not fetched.
///
/// Returns `None` if neither source is configured (inference routing disabled).
async fn build_inference_context(
sandbox_id: Option<&str>,
openshell_endpoint: Option<&str>,
inference_routes: Option<&str>,
) -> Result<Option<Arc<proxy::InferenceContext>>> {
use openshell_router::Router;
use openshell_router::config::RouterConfig;
let source = infer_route_source(sandbox_id, openshell_endpoint, inference_routes);
// Captured during the initial cluster bundle fetch so the background refresh
// loop can skip no-op updates from the very first tick.
let mut initial_revision: Option<String> = None;
let routes = match source {
InferenceRouteSource::File => {
let Some(path) = inference_routes else {
return Ok(None);
};
// Standalone mode: load routes from file (fail-fast on errors)
if sandbox_id.is_some() {
info!(
inference_routes = %path,
"Inference routes file takes precedence over cluster bundle"
);
}
info!(inference_routes = %path, "Loading inference routes from file");
let config = RouterConfig::load_from_file(std::path::Path::new(path))
.map_err(|e| miette::miette!("failed to load inference routes {path}: {e}"))?;
config
.resolve_routes()
.map_err(|e| miette::miette!("failed to resolve routes from {path}: {e}"))?
}
InferenceRouteSource::Cluster => {
let (Some(_id), Some(endpoint)) = (sandbox_id, openshell_endpoint) else {
return Ok(None);
};
// Cluster mode: fetch bundle from gateway
info!(endpoint = %endpoint, "Fetching inference route bundle from gateway");
match grpc_client::fetch_inference_bundle(endpoint).await {
Ok(bundle) => {
initial_revision = Some(bundle.revision.clone());
info!(
route_count = bundle.routes.len(),
revision = %bundle.revision,
"Loaded inference route bundle"
);
bundle_to_resolved_routes(&bundle)
}
Err(e) => {
// Distinguish expected "not configured" states from server errors.
// gRPC PermissionDenied/NotFound means inference bundle is unavailable
// for this sandbox — skip gracefully. Other errors are unexpected.
let msg = e.to_string();
if msg.contains("permission denied") || msg.contains("not found") {
info!(error = %e, "Inference bundle unavailable, routing disabled");
return Ok(None);
}
warn!(error = %e, "Failed to fetch inference bundle, inference routing disabled");
return Ok(None);
}
}
}
InferenceRouteSource::None => {
// No route source — inference routing is not configured
return Ok(None);
}
};
if routes.is_empty() && disable_inference_on_empty_routes(source) {
info!("No usable inference routes, inference routing disabled");
return Ok(None);
}
if routes.is_empty() {
info!("Inference route bundle is empty; keeping routing enabled and waiting for refresh");
}
info!(
route_count = routes.len(),
"Inference routing enabled with local execution"
);
// Partition routes by name into user-facing and system caches.
let (user_routes, system_routes) = partition_routes(routes);
let router =
Router::new().map_err(|e| miette::miette!("failed to initialize inference router: {e}"))?;
let patterns = l7::inference::default_patterns();
let ctx = Arc::new(proxy::InferenceContext::new(
patterns,
router,
user_routes,
system_routes,
));
// Spawn background route cache refresh for cluster mode at startup so
// request handling never depends on control-plane latency.
if matches!(source, InferenceRouteSource::Cluster)
&& let (Some(_id), Some(endpoint)) = (sandbox_id, openshell_endpoint)
{
spawn_route_refresh(
ctx.route_cache(),
ctx.system_route_cache(),
endpoint.to_string(),
route_refresh_interval_secs(),
initial_revision,
);
}
Ok(Some(ctx))
}
/// Route name for the sandbox system inference route.
const SANDBOX_SYSTEM_ROUTE_NAME: &str = "sandbox-system";
/// Split resolved routes into user-facing and system caches by route name.
///
/// Routes named `"sandbox-system"` go to the system cache; everything else
/// (including `"inference.local"` and empty names) goes to the user cache.
fn partition_routes(
routes: Vec<openshell_router::config::ResolvedRoute>,
) -> (
Vec<openshell_router::config::ResolvedRoute>,
Vec<openshell_router::config::ResolvedRoute>,
) {
let mut user = Vec::new();
let mut system = Vec::new();
for r in routes {
if r.name == SANDBOX_SYSTEM_ROUTE_NAME {
system.push(r);
} else {
user.push(r);
}
}
(user, system)
}
/// Convert a proto bundle response into resolved routes for the router.
pub(crate) fn bundle_to_resolved_routes(
bundle: &openshell_core::proto::GetInferenceBundleResponse,
) -> Vec<openshell_router::config::ResolvedRoute> {
bundle
.routes
.iter()
.map(|r| {
let (auth, default_headers) =
openshell_core::inference::auth_for_provider_type(&r.provider_type);
let timeout = if r.timeout_secs == 0 {
openshell_router::config::DEFAULT_ROUTE_TIMEOUT
} else {
Duration::from_secs(r.timeout_secs)
};
openshell_router::config::ResolvedRoute {
name: r.name.clone(),
endpoint: r.base_url.clone(),
model: r.model_id.clone(),
api_key: r.api_key.clone(),
protocols: r.protocols.clone(),
auth,
default_headers,
timeout,
}
})
.collect()
}
/// Spawn a background task that periodically refreshes both route caches from the gateway.
///
/// The loop uses the bundle `revision` hash to avoid unnecessary cache writes
/// when routes haven't changed. `initial_revision` is the revision captured
/// during the startup fetch in [`build_inference_context`] so the first refresh
/// cycle can already skip a no-op update.
pub(crate) fn spawn_route_refresh(
user_cache: Arc<tokio::sync::RwLock<Vec<openshell_router::config::ResolvedRoute>>>,
system_cache: Arc<tokio::sync::RwLock<Vec<openshell_router::config::ResolvedRoute>>>,
endpoint: String,
interval_secs: u64,
initial_revision: Option<String>,
) {
tokio::spawn(async move {
use tokio::time::{MissedTickBehavior, interval};
let mut current_revision = initial_revision;
let mut tick = interval(Duration::from_secs(interval_secs));
tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
loop {
tick.tick().await;
match grpc_client::fetch_inference_bundle(&endpoint).await {
Ok(bundle) => {
if current_revision.as_deref() == Some(&bundle.revision) {
trace!(revision = %bundle.revision, "Inference bundle unchanged");
continue;
}
let routes = bundle_to_resolved_routes(&bundle);
let (user_routes, system_routes) = partition_routes(routes);
info!(
user_route_count = user_routes.len(),
system_route_count = system_routes.len(),
revision = %bundle.revision,
"Inference routes updated"
);
current_revision = Some(bundle.revision);
*user_cache.write().await = user_routes;
*system_cache.write().await = system_routes;
}
Err(e) => {
warn!(error = %e, "Failed to refresh inference route cache, keeping stale routes");
}
}
}
});
}
// ============================================================================
// Baseline filesystem path enrichment
// ============================================================================
/// Minimum read-only paths required for a proxy-mode sandbox child process to
/// function: dynamic linker, shared libraries, DNS resolution, CA certs,
/// Python venv, openshell logs, process info, and random bytes.
///
/// `/proc` and `/dev/urandom` are included here for the same reasons they
/// appear in `restrictive_default_policy()`: virtually every process needs
/// them. Before the Landlock per-path fix (#677) these were effectively free
/// because a missing path silently disabled the entire ruleset; now they must
/// be explicit.
const PROXY_BASELINE_READ_ONLY: &[&str] = &[
"/usr",
"/lib",
"/etc",
"/app",
"/var/log",
"/proc",
"/dev/urandom",
];
/// Minimum read-write paths required for a proxy-mode sandbox child process:
/// user working directory and temporary files.
const PROXY_BASELINE_READ_WRITE: &[&str] = &["/sandbox", "/tmp"];
/// GPU read-only paths.
///
/// `/run/nvidia-persistenced`: NVML tries to connect to the persistenced
/// socket at init time. If the directory exists but Landlock denies traversal
/// (EACCES vs ECONNREFUSED), NVML returns `NVML_ERROR_INSUFFICIENT_PERMISSIONS`
/// even though the daemon is optional. Only read/traversal access is needed.
const GPU_BASELINE_READ_ONLY: &[&str] = &["/run/nvidia-persistenced"];
/// GPU read-write paths (static).
///
/// `/dev/nvidiactl`, `/dev/nvidia-uvm`, `/dev/nvidia-uvm-tools`,
/// `/dev/nvidia-modeset`: control and UVM devices injected by CDI.
/// Landlock restricts `open(2)` on device files even when DAC allows it;
/// these need read-write because NVML/CUDA opens them with `O_RDWR`.
///
/// `/proc`: CUDA writes to `/proc/<pid>/task/<tid>/comm` during `cuInit()`
/// to set thread names. Without write access, `cuInit()` returns error 304.
/// Must use `/proc` (not `/proc/self/task`) because Landlock rules bind to
/// inodes and child processes have different procfs inodes than the parent.
///
/// Per-GPU device files (`/dev/nvidia0`, …) are enumerated at runtime by
/// `enumerate_gpu_device_nodes()` since the count varies.
const GPU_BASELINE_READ_WRITE: &[&str] = &[
"/dev/nvidiactl",
"/dev/nvidia-uvm",
"/dev/nvidia-uvm-tools",
"/dev/nvidia-modeset",
"/proc",
];
/// Returns true if GPU devices are present in the container.
fn has_gpu_devices() -> bool {
std::path::Path::new("/dev/nvidiactl").exists()
}
/// Enumerate per-GPU device nodes (`/dev/nvidia0`, `/dev/nvidia1`, …).
fn enumerate_gpu_device_nodes() -> Vec<String> {
let mut paths = Vec::new();
if let Ok(entries) = std::fs::read_dir("/dev") {
for entry in entries.flatten() {
let name = entry.file_name();
let name = name.to_string_lossy();
if let Some(suffix) = name.strip_prefix("nvidia") {
if suffix.is_empty() || !suffix.chars().all(|c| c.is_ascii_digit()) {
continue;
}
paths.push(entry.path().to_string_lossy().into_owned());
}
}
}
paths
}
/// Collect all baseline paths for enrichment: proxy defaults + GPU (if present).
/// Returns `(read_only, read_write)` as owned `String` vecs.
fn baseline_enrichment_paths() -> (Vec<String>, Vec<String>) {
let mut ro: Vec<String> = PROXY_BASELINE_READ_ONLY
.iter()
.map(|&s| s.to_string())
.collect();
let mut rw: Vec<String> = PROXY_BASELINE_READ_WRITE
.iter()
.map(|&s| s.to_string())
.collect();
if has_gpu_devices() {
ro.extend(GPU_BASELINE_READ_ONLY.iter().map(|&s| s.to_string()));
rw.extend(GPU_BASELINE_READ_WRITE.iter().map(|&s| s.to_string()));