Repository navigation
Expand file tree
/
Copy pathopenshell.rs
More file actions
3602 lines (3491 loc) · 137 KB
/
Copy pathopenshell.rs
File metadata and controls
3602 lines (3491 loc) · 137 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
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::fs;
use std::path::Path;
use crate::Error;
use crate::domain;
use crate::fleet;
use crate::identity::sha256_hex;
use crate::json::Value;
use crate::run;
use crate::state::{files, secure};
use crate::text::{Text, trim};
pub const OPENSHELL_DOCTOR_USAGE: &str = "Use roster doctor --openshell [--opt-in] [--approve-live] [--runtime PATH] [--prover PATH] [--gateway URL] [--policy PATH] [--provider ID].";
const MAX_POLICY_PATHS: usize = 256;
const MAX_PATH_BYTES: usize = 4096;
const MAX_CANDIDATE_FILE_BYTES: u64 = 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpenShellNetworkRule {
pub name: String,
pub host: String,
pub port: u16,
pub protocol: String,
pub methods: Vec<String>,
pub binaries: Vec<String>,
pub access: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpenShellPolicySpec {
pub read_only_files: Vec<String>,
pub read_write_files: Vec<String>,
pub run_as_user: String,
pub run_as_group: String,
pub landlock_compatibility: String,
pub network_rules: Vec<OpenShellNetworkRule>,
}
impl Default for OpenShellPolicySpec {
fn default() -> Self {
Self {
read_only_files: Vec::new(),
read_write_files: Vec::new(),
run_as_user: "1500".to_owned(),
run_as_group: "1500".to_owned(),
landlock_compatibility: "hard_requirement".to_owned(),
network_rules: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpenShellPolicy {
pub version: u32,
pub include_workdir: bool,
pub read_only: Vec<String>,
pub read_write: Vec<String>,
pub landlock_compatibility: String,
pub run_as_user: String,
pub run_as_group: String,
pub network_rules: Vec<OpenShellNetworkRule>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpenShellProviderProfile {
pub id: String,
pub display_name: String,
pub model: String,
pub endpoint_host: String,
pub endpoint_port: u16,
pub endpoint_scheme: String,
pub base_url: String,
pub credential_env: Option<String>,
pub binaries: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpenShellDoctorOptions {
pub opt_in: bool,
pub approve_live: bool,
pub runtime_path: Option<String>,
pub prover_path: Option<String>,
pub gateway_url: Option<String>,
pub policy_path: Option<String>,
pub provider_id: Option<String>,
pub landlock_state: String,
pub is_tty: Option<bool>,
}
impl Default for OpenShellDoctorOptions {
fn default() -> Self {
Self {
opt_in: false,
approve_live: false,
runtime_path: None,
prover_path: None,
gateway_url: None,
policy_path: None,
provider_id: None,
landlock_state: "unknown".to_owned(),
is_tty: None,
}
}
}
fn validate_process_identity(value: &str, field: &str) -> Result<String, Error> {
let trimmed = value.trim();
if trimmed == "sandbox" {
return Ok(trimmed.to_owned());
}
let parsed = trimmed.parse::<u32>().map_err(|_| {
Error::type_error(format!(
"OpenShell {field} must be 'sandbox' or a non-root numeric ID (1..=4294967294)"
))
})?;
if parsed == 0 || parsed == u32::MAX {
return Err(Error::type_error(format!(
"OpenShell {field} rejects root (0) and reserved UID/GID 4294967295"
)));
}
Ok(parsed.to_string())
}
fn is_protected_write_surface(relative: &str) -> bool {
let trimmed = relative.trim_start_matches('/');
let lower = trimmed.to_ascii_lowercase();
if crate::planning::forbidden_write(trimmed) || crate::execution::policy::managed(trimmed) {
return true;
}
let segments = lower.split('/').collect::<Vec<_>>();
let first = segments.first().copied().unwrap_or("");
if matches!(
first,
".github" | "vendor" | ".git" | ".roster" | ".roster-state" | "agent-policy.yml"
) {
return true;
}
segments.iter().any(|seg| {
matches!(
*seg,
".git" | ".roster" | ".roster-state" | "agent-policy.yml" | ".env"
) || seg.starts_with(".env.")
|| seg.ends_with(".env")
|| seg.ends_with(".pem")
|| seg.ends_with(".key")
})
}
fn is_secret_read_surface(relative: &str) -> bool {
let trimmed = relative.trim_start_matches('/');
let lower = trimmed.to_ascii_lowercase();
if crate::planning::forbidden_read(trimmed) {
return true;
}
lower.split('/').any(|seg| {
matches!(seg, ".git" | ".roster" | ".roster-state" | ".env")
|| seg.starts_with(".env.")
|| seg.ends_with(".env")
|| seg.ends_with(".pem")
|| seg.ends_with(".key")
})
}
fn validate_posix_binary_path(bin: &str) -> Result<String, Error> {
if !bin.starts_with('/')
|| bin.len() > MAX_PATH_BYTES
|| bin.contains('\\')
|| bin
.bytes()
.any(|b| matches!(b, 0..=32 | 127 | b':' | b'#' | b'"' | b'\''))
{
return Err(Error::type_error(format!(
"OpenShell binary path must be a single-line absolute POSIX path without whitespace or metacharacters: {bin}"
)));
}
let segments = bin.trim_start_matches('/').split('/').collect::<Vec<_>>();
if segments
.iter()
.any(|seg| seg.is_empty() || *seg == "." || *seg == "..")
{
return Err(Error::type_error(format!(
"OpenShell binary path must not contain empty, '.' or '..' segments: {bin}"
)));
}
Ok(format!("/{}", segments.join("/")))
}
fn normalize_sandbox_path(raw: &str, writable: bool) -> Result<String, Error> {
if raw.is_empty()
|| raw.len() > MAX_PATH_BYTES
|| raw.bytes().any(|b| matches!(b, 0..=31 | 127))
|| raw.contains('\\')
{
return Err(Error::type_error(
"OpenShell policy path must be a bounded POSIX path without control characters",
));
}
if raw == "/" {
if writable {
return Err(Error::type_error(
"OpenShell filesystem_policy.read_write cannot contain '/'",
));
}
return Err(Error::type_error(
"OpenShell policy must not grant whole-root '/' read access",
));
}
let segments = raw
.trim_start_matches('/')
.split('/')
.collect::<Vec<&str>>();
if segments
.iter()
.any(|seg| seg.is_empty() || *seg == "." || *seg == "..")
{
return Err(Error::type_error(
"OpenShell policy path must not contain empty, '.' or '..' segments",
));
}
let normalized_rel = segments.join("/");
if writable && is_protected_write_surface(&normalized_rel) {
return Err(Error::new(
"PolicyViolation",
format!("OpenShell read_write denies protected surface: {normalized_rel}"),
)
.coded("ROSTER_OPENSHELL_PROTECTED_SURFACE"));
}
if !writable && is_secret_read_surface(&normalized_rel) {
return Err(Error::new(
"PolicyViolation",
format!("OpenShell read_only denies private/secret surface: {normalized_rel}"),
)
.coded("ROSTER_OPENSHELL_SECRET_SURFACE"));
}
if raw.starts_with('/') {
let allowed_system = ["/usr/", "/lib/", "/lib64/", "/bin/", "/etc/", "/tmp/"]
.iter()
.any(|prefix| raw.starts_with(prefix) || raw == &prefix[..prefix.len() - 1]);
let allowed_sandbox = raw.starts_with("/sandbox/workspace/");
if !allowed_system && !allowed_sandbox {
return Err(Error::type_error(format!(
"OpenShell absolute path must reside under /sandbox/workspace or baseline system dirs: {raw}"
)));
}
if writable && !allowed_sandbox && !raw.starts_with("/tmp") {
return Err(Error::type_error(format!(
"OpenShell read_write absolute path must reside under /sandbox/workspace or /tmp: {raw}"
)));
}
if allowed_sandbox {
let ws_rel = raw.trim_start_matches("/sandbox/workspace/");
if writable && is_protected_write_surface(ws_rel) {
return Err(Error::new(
"PolicyViolation",
format!("OpenShell read_write denies protected surface: {ws_rel}"),
)
.coded("ROSTER_OPENSHELL_PROTECTED_SURFACE"));
}
if !writable && is_secret_read_surface(ws_rel) {
return Err(Error::new(
"PolicyViolation",
format!("OpenShell read_only denies private/secret surface: {ws_rel}"),
)
.coded("ROSTER_OPENSHELL_SECRET_SURFACE"));
}
}
Ok(raw.to_owned())
} else {
Ok(format!("/sandbox/workspace/{normalized_rel}"))
}
}
pub(crate) fn is_forbidden_metadata_host(host: &str) -> bool {
let lower = host
.trim()
.trim_matches(|c| c == '[' || c == ']')
.trim_end_matches('.')
.to_ascii_lowercase();
lower == "169.254.169.254"
|| lower == "::ffff:169.254.169.254"
|| lower == "0:0:0:0:0:ffff:a9fe:a9fe"
|| lower == "metadata.google.internal"
|| lower == "metadata"
|| lower == "100.100.100.200"
|| lower == "fd00:ec2::254"
}
fn validate_network_rule(rule: &OpenShellNetworkRule) -> Result<OpenShellNetworkRule, Error> {
let name = rule.name.trim();
if name.is_empty()
|| name.starts_with("_provider_")
|| !name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'))
{
return Err(Error::type_error(
"OpenShell network rule name must be alphanumeric/hyphen/underscore and must not start with '_provider_'",
));
}
let host = rule.host.trim();
if host.is_empty()
|| host
.bytes()
.any(|b| matches!(b, 0..=32 | 127 | b'/' | b'\\' | b'#' | b'"' | b'\''))
{
return Err(Error::type_error(
"OpenShell network rule host must be a valid hostname or IP",
));
}
if is_forbidden_metadata_host(host) {
return Err(Error::new(
"PolicyViolation",
format!("OpenShell network rule denies cloud metadata endpoint: {host}"),
)
.coded("ROSTER_OPENSHELL_METADATA_DENIED"));
}
if rule.port == 0 {
return Err(Error::type_error(
"OpenShell network rule port must be 1..=65535",
));
}
if !matches!(rule.protocol.as_str(), "rest" | "https" | "http") {
return Err(Error::type_error(
"OpenShell network rule protocol must be rest, https, or http",
));
}
if !matches!(rule.access.as_str(), "read-only" | "read-write") {
return Err(Error::type_error(
"OpenShell network rule access must be read-only or read-write",
));
}
if rule.methods.is_empty() {
return Err(Error::type_error(
"OpenShell network rule must declare at least one HTTP method",
));
}
let mut normalized_methods = Vec::new();
for method in &rule.methods {
let m = method.trim();
if !matches!(
m,
"GET" | "HEAD" | "OPTIONS" | "POST" | "PUT" | "PATCH" | "DELETE"
) {
return Err(Error::type_error(format!(
"Unsupported OpenShell HTTP method: {method}"
)));
}
if rule.access == "read-only" && !matches!(m, "GET" | "HEAD" | "OPTIONS") {
return Err(Error::type_error(format!(
"OpenShell read-only network rule cannot grant mutating HTTP method {m}"
)));
}
if !normalized_methods.iter().any(|existing| existing == m) {
normalized_methods.push(m.to_owned());
}
}
if rule.binaries.is_empty() {
return Err(Error::type_error(
"OpenShell network rule must bind at least one binary path",
));
}
let mut normalized_binaries = Vec::new();
for binary in &rule.binaries {
let valid_bin = validate_posix_binary_path(binary)?;
if !normalized_binaries.contains(&valid_bin) {
normalized_binaries.push(valid_bin);
}
}
Ok(OpenShellNetworkRule {
name: name.to_owned(),
host: host.to_owned(),
port: rule.port,
protocol: rule.protocol.clone(),
methods: normalized_methods,
binaries: normalized_binaries,
access: rule.access.clone(),
})
}
pub fn compile_task_policy(spec: &OpenShellPolicySpec) -> Result<OpenShellPolicy, Error> {
if spec.landlock_compatibility != "hard_requirement" {
return Err(Error::new(
"PolicyViolation",
"Roster requires OpenShell landlock.compatibility to be 'hard_requirement'",
)
.coded("ROSTER_OPENSHELL_LANDLOCK_REQUIRED"));
}
let run_as_user = validate_process_identity(&spec.run_as_user, "run_as_user")?;
let run_as_group = validate_process_identity(&spec.run_as_group, "run_as_group")?;
let mut read_only = BTreeSet::new();
for path in ["/usr", "/lib", "/bin", "/etc"] {
read_only.insert(path.to_owned());
}
for path in &spec.read_only_files {
read_only.insert(normalize_sandbox_path(path, false)?);
}
let mut read_write = BTreeSet::new();
read_write.insert("/tmp".to_owned());
for path in &spec.read_write_files {
let normalized = normalize_sandbox_path(path, true)?;
read_only.remove(&normalized);
read_write.insert(normalized);
}
if read_only.len() + read_write.len() > MAX_POLICY_PATHS {
return Err(Error::type_error(
"OpenShell filesystem_policy cannot exceed 256 total paths",
));
}
let mut seen_rules = HashSet::new();
let mut network_rules = Vec::new();
for rule in &spec.network_rules {
let validated = validate_network_rule(rule)?;
if !seen_rules.insert(validated.name.clone()) {
return Err(Error::type_error(
"OpenShell network_policies rule names must be unique",
));
}
network_rules.push(validated);
}
Ok(OpenShellPolicy {
version: 1,
include_workdir: false,
read_only: read_only.into_iter().collect(),
read_write: read_write.into_iter().collect(),
landlock_compatibility: spec.landlock_compatibility.clone(),
run_as_user,
run_as_group,
network_rules,
})
}
impl OpenShellPolicy {
pub fn to_yaml(&self) -> String {
let mut out = String::from(
"version: 1\nfilesystem_policy:\n include_workdir: false\n read_only:\n",
);
for path in &self.read_only {
out.push_str(&format!(" - {path}\n"));
}
out.push_str(" read_write:\n");
for path in &self.read_write {
out.push_str(&format!(" - {path}\n"));
}
out.push_str(&format!(
"landlock:\n compatibility: {}\nprocess:\n run_as_user: \"{}\"\n run_as_group: \"{}\"\n",
self.landlock_compatibility, self.run_as_user, self.run_as_group
));
if self.network_rules.is_empty() {
out.push_str("network_policies: {}\n");
} else {
out.push_str("network_policies:\n");
for rule in &self.network_rules {
out.push_str(&format!(
" {}:\n name: {}\n endpoints:\n - host: {}\n port: {}\n protocol: {}\n enforcement: enforce\n access: {}\n binaries:\n",
rule.name,
rule.name,
rule.host,
rule.port,
rule.protocol,
rule.access,
));
for bin in &rule.binaries {
out.push_str(&format!(" - path: {bin}\n"));
}
}
}
out
}
pub fn as_value(&self) -> Value {
Value::object(vec![
("version", Value::Number(f64::from(self.version))),
(
"filesystem_policy",
Value::object(vec![
("include_workdir", Value::Boolean(self.include_workdir)),
(
"read_only",
Value::Array(self.read_only.iter().map(|s| Value::string(s)).collect()),
),
(
"read_write",
Value::Array(self.read_write.iter().map(|s| Value::string(s)).collect()),
),
]),
),
(
"landlock",
Value::object(vec![(
"compatibility",
Value::string(&self.landlock_compatibility),
)]),
),
(
"process",
Value::object(vec![
("run_as_user", Value::string(&self.run_as_user)),
("run_as_group", Value::string(&self.run_as_group)),
]),
),
(
"network_policies",
Value::Array(
self.network_rules
.iter()
.map(|r| {
Value::object(vec![
("name", Value::string(&r.name)),
("host", Value::string(&r.host)),
("port", Value::Number(f64::from(r.port))),
("protocol", Value::string(&r.protocol)),
("access", Value::string(&r.access)),
(
"methods",
Value::Array(
r.methods.iter().map(|m| Value::string(m)).collect(),
),
),
(
"binaries",
Value::Array(
r.binaries.iter().map(|b| Value::string(b)).collect(),
),
),
])
})
.collect(),
),
),
])
}
pub fn digest(&self) -> String {
sha256_hex(self.to_yaml().as_bytes())
}
}
pub fn compile_fleet_provider_profile(
profile: &Value,
binaries: &[String],
) -> Result<OpenShellProviderProfile, Error> {
let validated = fleet::validate_profile(profile)?;
let val = validated.as_value();
let id = val
.get("id")
.and_then(Value::as_string)
.ok_or_else(|| Error::type_error("Fleet profile id is required"))?
.to_utf8()?;
let model = val
.get("model")
.and_then(Value::as_string)
.ok_or_else(|| Error::type_error("Fleet profile model is required"))?
.to_utf8()?;
let raw_base = val
.get("base_url")
.and_then(Value::as_string)
.ok_or_else(|| Error::type_error("Fleet profile base_url is required"))?;
let parsed_url = crate::config::base_url(raw_base, "fleet base_url")?;
let raw_host = parsed_url
.host_str()
.ok_or_else(|| Error::type_error("Fleet base_url must include a host"))?;
if is_forbidden_metadata_host(raw_host) {
return Err(Error::new(
"PolicyViolation",
format!("OpenShell provider profile denies cloud metadata endpoint: {raw_host}"),
)
.coded("ROSTER_OPENSHELL_METADATA_DENIED"));
}
let mapped_host = match raw_host {
"127.0.0.1" | "localhost" | "[::1]" | "::1" => "host.openshell.internal".to_owned(),
other => other.to_owned(),
};
let port = parsed_url.port_or_known_default().unwrap_or(80);
let scheme = parsed_url.scheme().to_owned();
let path = parsed_url.path().trim_end_matches('/');
let default_port = (scheme == "http" && port == 80) || (scheme == "https" && port == 443);
let routed_base_url = if default_port {
format!("{scheme}://{mapped_host}{path}")
} else {
format!("{scheme}://{mapped_host}:{port}{path}")
};
let credential_env = match val.get("api_key_env").and_then(Value::as_string) {
Some(secret_name) => {
let env_str = secret_name.to_utf8()?;
let upper = env_str.to_ascii_uppercase();
if upper.starts_with("GITHUB_APP_")
|| upper.starts_with("OPENSHELL_")
|| matches!(
upper.as_str(),
"OPENAI_BASE_URL"
| "ROSTER_MODEL"
| "HOME"
| "TMPDIR"
| "NO_COLOR"
| "GIT_TERMINAL_PROMPT"
)
{
return Err(Error::new(
"PolicyViolation",
format!(
"OpenShell provider profile rejects reserved or GitHub App credential env: {env_str}"
),
)
.coded("ROSTER_OPENSHELL_RESERVED_CREDENTIAL"));
}
Some(env_str)
}
None => None,
};
if binaries.is_empty() {
return Err(Error::type_error(
"OpenShell provider profile requires at least one allowed binary path",
));
}
let mut normalized_bins = Vec::new();
for bin in binaries {
let valid_bin = validate_posix_binary_path(bin)?;
if !normalized_bins.contains(&valid_bin) {
normalized_bins.push(valid_bin);
}
}
Ok(OpenShellProviderProfile {
id: format!("roster-{id}"),
display_name: format!("Roster Fleet {id} ({model})"),
model,
endpoint_host: mapped_host,
endpoint_port: port,
endpoint_scheme: scheme,
base_url: routed_base_url,
credential_env,
binaries: normalized_bins,
})
}
impl OpenShellProviderProfile {
pub fn to_yaml(&self) -> String {
let mut out = format!(
"id: {}\ndisplay_name: \"{}\"\ncategory: inference\ninference_capable: true\n",
self.id, self.display_name
);
match &self.credential_env {
Some(env_name) => {
out.push_str(&format!(
"credentials:\n - name: {env_name}\n env_var: {env_name}\n placeholder_only: true\n"
));
}
None => out.push_str("credentials: []\n"),
}
out.push_str(&format!(
"endpoints:\n - host: {}\n port: {}\n protocol: rest\n access: read-write\n enforcement: enforce\nbinaries:\n",
self.endpoint_host, self.endpoint_port
));
for bin in &self.binaries {
out.push_str(&format!(" - {bin}\n"));
}
out
}
pub fn as_value(&self) -> Value {
Value::object(vec![
("id", Value::string(&self.id)),
("display_name", Value::string(&self.display_name)),
("category", Value::string("inference")),
("inference_capable", Value::Boolean(true)),
("model", Value::string(&self.model)),
("base_url", Value::string(&self.base_url)),
("endpoint_host", Value::string(&self.endpoint_host)),
(
"endpoint_port",
Value::Number(f64::from(self.endpoint_port)),
),
(
"credential_env",
self.credential_env
.as_deref()
.map_or(Value::Null, Value::string),
),
(
"binaries",
Value::Array(self.binaries.iter().map(|b| Value::string(b)).collect()),
),
])
}
}
pub fn openshell_launch_environment(
gateway_url: &str,
provider: &OpenShellProviderProfile,
) -> Result<Value, Error> {
let gw_text = Text::from(gateway_url);
let parsed_gw = crate::config::base_url(&gw_text, "OpenShell gateway URL")?;
if let Some(gw_host) = parsed_gw.host_str() {
if is_forbidden_metadata_host(gw_host) {
return Err(Error::new(
"PolicyViolation",
format!("OpenShell gateway URL denies cloud metadata endpoint: {gw_host}"),
)
.coded("ROSTER_OPENSHELL_METADATA_DENIED"));
}
}
if is_forbidden_metadata_host(&provider.endpoint_host) {
return Err(Error::new(
"PolicyViolation",
format!(
"OpenShell provider endpoint denies cloud metadata host: {}",
provider.endpoint_host
),
)
.coded("ROSTER_OPENSHELL_METADATA_DENIED"));
}
let mut entries = vec![
("OPENSHELL_TELEMETRY_ENABLED", Value::string("false")),
(
"OPENSHELL_GATEWAY_URL",
Value::string(parsed_gw.as_str().trim_end_matches('/')),
),
("OPENSHELL_PROVIDER_ID", Value::string(&provider.id)),
("OPENAI_BASE_URL", Value::string(&provider.base_url)),
("ROSTER_MODEL", Value::string(&provider.model)),
("HOME", Value::string("/sandbox/home")),
("TMPDIR", Value::string("/tmp")),
("NO_COLOR", Value::string("1")),
("GIT_TERMINAL_PROMPT", Value::string("0")),
];
if let Some(env_var) = &provider.credential_env {
let upper = env_var.to_ascii_uppercase();
if upper.starts_with("GITHUB_APP_")
|| upper.starts_with("OPENSHELL_")
|| matches!(
upper.as_str(),
"OPENAI_BASE_URL"
| "ROSTER_MODEL"
| "HOME"
| "TMPDIR"
| "NO_COLOR"
| "GIT_TERMINAL_PROMPT"
)
{
return Err(Error::new(
"PolicyViolation",
format!("OpenShell launch environment rejects reserved credential env: {env_var}"),
)
.coded("ROSTER_OPENSHELL_RESERVED_CREDENTIAL"));
}
entries.push((
env_var.as_str(),
Value::string("OPENSHELL_SUPERVISOR_PLACEHOLDER"),
));
} else {
entries.push(("OPENAI_API_KEY", Value::string("unused")));
}
Ok(Value::object(entries))
}
pub fn prove_openshell_policy_boundary(
candidate: &OpenShellPolicy,
boundary: &OpenShellPolicy,
) -> Result<Value, Error> {
let mut findings = Vec::new();
if candidate.version != 1 || boundary.version != 1 {
findings.push(Value::string("Policy version must be 1."));
}
if candidate.include_workdir || boundary.include_workdir {
findings.push(Value::string(
"Policy enables include_workdir; explicit path allow-lists are required.",
));
}
if candidate.landlock_compatibility != "hard_requirement"
|| boundary.landlock_compatibility != "hard_requirement"
{
findings.push(Value::string(
"Policy weakens Landlock compatibility from hard_requirement.",
));
}
let cand_user = validate_process_identity(&candidate.run_as_user, "candidate.run_as_user").ok();
let cand_group =
validate_process_identity(&candidate.run_as_group, "candidate.run_as_group").ok();
let bound_user = validate_process_identity(&boundary.run_as_user, "boundary.run_as_user").ok();
let bound_group =
validate_process_identity(&boundary.run_as_group, "boundary.run_as_group").ok();
if cand_user.is_none()
|| cand_group.is_none()
|| bound_user.is_none()
|| bound_group.is_none()
|| cand_user != bound_user
|| cand_group != bound_group
{
findings.push(Value::string(
"Candidate or boundary policy has invalid or mismatched non-root UID/GID identity.",
));
}
if candidate.read_only.len() + candidate.read_write.len() > MAX_POLICY_PATHS
|| boundary.read_only.len() + boundary.read_write.len() > MAX_POLICY_PATHS
{
findings.push(Value::string(
"Policy filesystem path count exceeds 256 limit.",
));
}
let mut bound_rw = Vec::new();
for raw in &boundary.read_write {
match normalize_sandbox_path(raw, true) {
Ok(norm) => bound_rw.push(norm),
Err(err) => findings.push(Value::string(&format!(
"Invalid boundary read_write path '{raw}': {}",
err.message
))),
}
}
let mut bound_ro = Vec::new();
for raw in &boundary.read_only {
match normalize_sandbox_path(raw, false) {
Ok(norm) => bound_ro.push(norm),
Err(err) => findings.push(Value::string(&format!(
"Invalid boundary read_only path '{raw}': {}",
err.message
))),
}
}
for raw in &candidate.read_write {
match normalize_sandbox_path(raw, true) {
Ok(path) => {
let covered = bound_rw
.iter()
.any(|allowed| &path == allowed || path.starts_with(&format!("{allowed}/")));
if !covered {
findings.push(Value::string(&format!(
"Candidate policy expands read_write outside boundary: {path}"
)));
}
}
Err(err) => findings.push(Value::string(&format!(
"Invalid candidate read_write path '{raw}': {}",
err.message
))),
}
}
for raw in &candidate.read_only {
match normalize_sandbox_path(raw, false) {
Ok(path) => {
let covered = bound_ro
.iter()
.chain(bound_rw.iter())
.any(|allowed| &path == allowed || path.starts_with(&format!("{allowed}/")));
if !covered {
findings.push(Value::string(&format!(
"Candidate policy expands read_only outside boundary: {path}"
)));
}
}
Err(err) => findings.push(Value::string(&format!(
"Invalid candidate read_only path '{raw}': {}",
err.message
))),
}
}
let mut valid_boundary_rules = Vec::new();
for b_rule in &boundary.network_rules {
match validate_network_rule(b_rule) {
Ok(valid) => valid_boundary_rules.push(valid),
Err(err) => findings.push(Value::string(&format!(
"Invalid boundary network rule '{}': {}",
b_rule.name, err.message
))),
}
}
for raw_rule in &candidate.network_rules {
let rule = match validate_network_rule(raw_rule) {
Ok(valid) => valid,
Err(err) => {
findings.push(Value::string(&format!(
"Invalid candidate network rule '{}': {}",
raw_rule.name, err.message
)));
continue;
}
};
let matching = valid_boundary_rules
.iter()
.filter(|b| b.host == rule.host && b.port == rule.port && b.protocol == rule.protocol)
.collect::<Vec<_>>();
if matching.is_empty() {
findings.push(Value::string(&format!(
"Candidate network rule adds unapproved endpoint {}:{} ({})",
rule.host, rule.port, rule.name
)));
continue;
}
let covered_by_any = matching.iter().any(|bound| {
let access_ok = !(rule.access == "read-write" && bound.access != "read-write");
let methods_ok = rule.methods.iter().all(|m| bound.methods.contains(m));
let bins_ok = rule.binaries.iter().all(|b| bound.binaries.contains(b));
access_ok && methods_ok && bins_ok
});
if !covered_by_any {
findings.push(Value::string(&format!(
"Candidate network rule '{}' widens access, methods, or binaries beyond boundary rules for {}:{}",
rule.name, rule.host, rule.port
)));
}
}
let verified = findings.is_empty();
Ok(Value::object(vec![
("verified", Value::Boolean(verified)),
("candidateDigest", Value::string(&candidate.digest())),
("boundaryDigest", Value::string(&boundary.digest())),
("findings", Value::Array(findings)),
]))
}
pub fn compile_active_llm_provider_profile(
config: &Value,
fleet_catalog: Option<&fleet::Fleet>,
binaries: &[String],
) -> Result<OpenShellProviderProfile, Error> {
let llm = config
.get("llm")
.ok_or_else(|| Error::type_error("Configuration is missing llm section"))?;
let wanted_id = llm
.get("fleet_profile")
.or_else(|| llm.get("profile"))
.and_then(Value::as_string)
.and_then(|t| t.to_utf8().ok())
.filter(|s| !s.trim().is_empty());
let base_url = llm
.get("base_url")
.and_then(Value::as_string)
.and_then(|t| t.to_utf8().ok())
.unwrap_or_default();
let model = llm
.get("model")
.and_then(Value::as_string)
.and_then(|t| t.to_utf8().ok())
.unwrap_or_default();
if let Some(catalog) = fleet_catalog {
if let Some(ref wid) = wanted_id {
if let Some(found) = catalog.profiles().iter().find(|p| {
p.as_value()
.get("id")
.and_then(Value::as_string)
.and_then(|t| t.to_utf8().ok())
.is_some_and(|id| id == *wid)
}) {
return compile_fleet_provider_profile(found.as_value(), binaries);
}
}
if !base_url.is_empty() && !model.is_empty() {
if let Some(found) = catalog.profiles().iter().find(|p| {
let pv = p.as_value();
let b = pv
.get("base_url")
.and_then(Value::as_string)
.and_then(|t| t.to_utf8().ok())
.unwrap_or_default();
let m = pv
.get("model")
.and_then(Value::as_string)
.and_then(|t| t.to_utf8().ok())
.unwrap_or_default();
b.trim_end_matches('/')
.eq_ignore_ascii_case(base_url.trim_end_matches('/'))
&& m == model
}) {
return compile_fleet_provider_profile(found.as_value(), binaries);
}
}
}
let effective_base = if base_url.trim().is_empty() {
"http://127.0.0.1:8000/v1".to_owned()
} else {
base_url
};
let effective_model = if model.trim().is_empty() || !run::is_model_id(&model) {
"qwen3.8-27b".to_owned()
} else {
model
};
let profile_id = wanted_id
.filter(|id| fleet::validate_id(Some(&Value::string(id))).is_ok())
.unwrap_or_else(|| "active-llm".to_owned());
let context_max = domain::safe_integer(llm.get("context_max"))
.filter(|&n| n >= 1024)
.unwrap_or(65_536);
let mut synthesized = vec![
("id", Value::string(&profile_id)),
("base_url", Value::string(&effective_base)),
("model", Value::string(&effective_model)),
("provider", Value::string("vllm")),
("context_max", Value::Number(context_max as f64)),
("concurrency", Value::Number(1.0)),
("hardware", Value::string("host-configured")),
("notes", Value::string("synthesized from active llm config")),
];
if let Some(api_key_env) = llm
.get("api_key_env")
.and_then(Value::as_string)
.and_then(|t| t.to_utf8().ok())
.filter(|s| !s.trim().is_empty())
{
synthesized.push(("api_key_env", Value::string(&api_key_env)));