1use crate::formatter::{format as format_source, FormatConfig};
32use crate::parser::ast::Ast;
33use crate::projection::cell::ir::CellIr;
34use crate::projection::cell::lock::sha256_hex;
35use crate::projection::cell::overrides::CellOverrides;
36use crate::projection::sink::ArtifactSink;
37use crate::projection::yaml::to_yaml;
38use serde_json::{json, Map, Value};
39use std::collections::{BTreeMap, BTreeSet};
40
41pub const OPENSHELL_VERSION: &str = "0.1.3";
43pub const PROJECTION_VERSION: &str = "domainforge-openshell/v1";
44pub const SANDBOX_SCHEMA: &str = "domainforge.openshell.sandbox/v1";
45pub const MAPPING_SCHEMA: &str = "domainforge.openshell.mapping/v1";
46pub const LOCK_SCHEMA: &str = "domainforge.openshell.lock/v1";
47
48pub const POLICY_FILE: &str = "policy.yaml";
49pub const SANDBOX_FILE: &str = "sandbox.json";
50pub const MAPPING_FILE: &str = "mapping-report.json";
51pub const LOCK_FILE: &str = "openshell.lock";
52
53const WORKDIR: &str = "/sandbox";
56
57const BASELINE_READ_ONLY: [&str; 11] = [
69 "/app",
70 "/bin",
71 "/dev/urandom",
72 "/etc",
73 "/lib",
74 "/lib64",
75 "/proc",
76 "/sandbox",
77 "/sbin",
78 "/usr",
79 "/var/log",
80];
81
82const BASELINE_READ_WRITE: [&str; 2] = ["/dev/null", "/tmp"];
84
85const EXECUTABLE_DIRS: [&str; 2] = ["/usr/bin", "/usr/local/bin"];
89
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub enum OpenShellProjectionError {
92 Unrepresentable {
94 element: String,
95 requirement: String,
96 reason: String,
97 },
98 Cell(String),
100 Write(String),
102}
103
104impl std::fmt::Display for OpenShellProjectionError {
105 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106 match self {
107 Self::Unrepresentable {
108 element,
109 requirement,
110 reason,
111 } => write!(
112 f,
113 "OSH001 unrepresentable: {element} requires {requirement}: {reason}"
114 ),
115 Self::Cell(message) => write!(f, "OSH002 cell: {message}"),
116 Self::Write(message) => write!(f, "OSH003 write: {message}"),
117 }
118 }
119}
120
121impl std::error::Error for OpenShellProjectionError {}
122
123fn unrepresentable<T>(
124 element: &str,
125 requirement: &str,
126 reason: &str,
127) -> Result<T, OpenShellProjectionError> {
128 Err(OpenShellProjectionError::Unrepresentable {
129 element: element.to_string(),
130 requirement: requirement.to_string(),
131 reason: reason.to_string(),
132 })
133}
134
135struct Mapping {
137 target: String,
138 source: String,
139 class: &'static str,
140 phase: &'static str,
141 note: String,
142}
143
144impl Mapping {
145 fn json(&self) -> Value {
146 json!({
147 "target": self.target,
148 "source": self.source,
149 "class": self.class,
150 "phase": self.phase,
151 "note": self.note,
152 })
153 }
154}
155
156struct Projection {
157 policy: Value,
158 sandbox: Value,
159 mappings: Vec<Mapping>,
160}
161
162fn rule_key(name: &str) -> String {
163 let key: String = name
164 .chars()
165 .map(|c| {
166 if c.is_ascii_alphanumeric() {
167 c.to_ascii_lowercase()
168 } else {
169 '_'
170 }
171 })
172 .collect();
173 format!("cell_{}", key.trim_matches('_'))
175}
176
177fn relocate(element: &str, target: &str) -> Result<String, OpenShellProjectionError> {
178 let valid = target.starts_with('/')
179 && target != "/"
180 && !target.split('/').any(|part| part == ".." || part == ".");
181 if !valid {
182 return unrepresentable(
183 element,
184 &format!("mount target '{target}'"),
185 "the target must be an absolute path without '.' or '..' components, and not '/'",
186 );
187 }
188 Ok(format!("{WORKDIR}{}", target.trim_end_matches('/')))
189}
190
191fn project(ir: &CellIr) -> Result<Projection, OpenShellProjectionError> {
192 let cell = format!("Cell \"{}\"", ir.identity.name);
193 let mut mappings = Vec::new();
194
195 if ir.platform.network_default != "deny" {
196 return unrepresentable(
197 &cell,
198 &format!("network_default '{}'", ir.platform.network_default),
199 "OpenShell denies all egress that no rule allows; a permissive default cannot be expressed",
200 );
201 }
202 if let Some(service) = ir.services.first() {
203 return unrepresentable(
204 &format!("Service \"{}\"", service.name),
205 "a companion service",
206 "an OpenShell sandbox runs one workload; companion services are not supported",
207 );
208 }
209
210 let user = ir.platform.runtime_user.as_str();
213 let run_as = if user == "root" || user == "0" {
214 return unrepresentable(
215 &cell,
216 "runtime_user root",
217 "OpenShell rejects root as the sandbox identity",
218 );
219 } else if user.parse::<u32>().is_ok() {
220 mappings.push(Mapping {
221 target: "policy.yaml#/process".into(),
222 source: ir.identity.cell_id.clone(),
223 class: "enforced",
224 phase: "startup",
225 note: format!("numeric runtime_user {user}"),
226 });
227 user.to_string()
228 } else {
229 mappings.push(Mapping {
230 target: "policy.yaml#/process".into(),
231 source: ir.identity.cell_id.clone(),
232 class: "adapter",
233 phase: "startup",
234 note: format!(
235 "runtime_user '{user}' runs as OpenShell's unprivileged 'sandbox' account; the non-root property is enforced, the account name is not preserved"
236 ),
237 });
238 "sandbox".to_string()
239 };
240
241 let mut read_write: BTreeSet<String> =
243 BASELINE_READ_WRITE.iter().map(|p| p.to_string()).collect();
244 let mut workspaces = Vec::new();
245 for mount in &ir.mounts {
246 let element = format!("Mount \"{}\"", mount.name);
247 if mount.mode != "read-write" {
248 return unrepresentable(
249 &element,
250 &format!("mode '{}'", mount.mode),
251 "OpenShell has no host mounts on its public interface; content reaches a sandbox only by upload into a writable path",
252 );
253 }
254 let path = relocate(&element, &mount.target)?;
255 read_write.insert(path.clone());
256 workspaces.push(json!({
257 "name": mount.name,
258 "source": mount.source,
259 "declared_target": mount.target,
260 "sandbox_path": path,
261 "mode": mount.mode,
262 }));
263 mappings.push(Mapping {
264 target: format!("policy.yaml#/filesystem_policy/read_write/{path}"),
265 source: mount.id.clone(),
266 class: "adapter",
267 phase: "startup",
268 note: format!(
269 "target '{}' is relocated under {WORKDIR}; the host source is uploaded, never mounted",
270 mount.target
271 ),
272 });
273 }
274 for path in BASELINE_READ_ONLY {
275 mappings.push(Mapping {
276 target: format!("policy.yaml#/filesystem_policy/read_only/{path}"),
277 source: format!("profile:{}@{}", ir.profile_id, ir.profile_version),
278 class: "baseline",
279 phase: "startup",
280 note: "read-only system path needed to start a process".into(),
281 });
282 }
283 for path in BASELINE_READ_WRITE {
284 mappings.push(Mapping {
285 target: format!("policy.yaml#/filesystem_policy/read_write/{path}"),
286 source: format!("profile:{}@{}", ir.profile_id, ir.profile_version),
287 class: "baseline",
288 phase: "startup",
289 note: "scratch space inside the sandbox".into(),
290 });
291 }
292 mappings.push(Mapping {
293 target: "policy.yaml#/landlock".into(),
294 source: ir.identity.cell_id.clone(),
295 class: "enforced",
296 phase: "startup",
297 note: "hard_requirement: the sandbox must not start if Landlock is unavailable".into(),
298 });
299
300 let mut binaries: BTreeSet<String> = BTreeSet::new();
303 for name in ir
304 .tools
305 .iter()
306 .map(|t| &t.name)
307 .chain(ir.runtimes.iter().map(|r| &r.name))
308 {
309 for dir in EXECUTABLE_DIRS {
310 binaries.insert(format!("{dir}/{name}"));
311 }
312 }
313 let mut network = Map::new();
314 for flow in &ir.network_flows {
315 let element = format!("NetworkFlow \"{}\"", flow.name);
316 if flow.from_ref != ir.identity.name {
317 return unrepresentable(
318 &element,
319 &format!("source '{}'", flow.from_ref),
320 "an OpenShell policy governs one sandbox; only flows from the Cell itself can be projected",
321 );
322 }
323 if flow.credential.is_some() {
324 return unrepresentable(
325 &element,
326 "a credential",
327 "credential-bound flows need an OpenShell provider profile whose composed rules have been verified; none is projected yet",
328 );
329 }
330 let Some(endpoint) = ir.endpoints.iter().find(|e| e.name == flow.to_ref) else {
331 return Err(OpenShellProjectionError::Cell(format!(
332 "{element} targets undeclared endpoint '{}'",
333 flow.to_ref
334 )));
335 };
336 if endpoint.host.contains('*') {
337 return unrepresentable(
338 &element,
339 "a wildcard host",
340 "wildcard destinations are never projected",
341 );
342 }
343 if binaries.is_empty() {
344 return unrepresentable(
345 &element,
346 "an executable identity",
347 "OpenShell allows egress only to listed binaries and the Cell declares no Tool or Runtime",
348 );
349 }
350
351 let mut rule = Map::new();
352 rule.insert("host".into(), json!(endpoint.host));
353 let default_port = match endpoint.protocol.as_str() {
354 "https" => Some(443),
355 "http" => Some(80),
356 _ => None,
357 };
358 let Some(port) = endpoint.port.or(default_port) else {
359 return unrepresentable(
360 &element,
361 "a port",
362 "the endpoint declares no port and its protocol has no default",
363 );
364 };
365 rule.insert("port".into(), json!(port));
366 match (endpoint.protocol.as_str(), flow.operation.as_str()) {
367 ("https" | "http", "read") => {
368 rule.insert("protocol".into(), json!("rest"));
369 rule.insert("access".into(), json!("read-only"));
370 }
371 ("https" | "http", "write" | "read-write") => {
372 rule.insert("protocol".into(), json!("rest"));
373 rule.insert("access".into(), json!("read-write"));
374 }
375 ("tcp", "connect") => {
376 rule.insert("protocol".into(), json!("tcp"));
377 }
378 ("tcp", operation) => {
379 return unrepresentable(
380 &element,
381 &format!("operation '{operation}' over tcp"),
382 "a raw TCP rule cannot restrict what is sent; declare the operation as 'connect' or use http(s)",
383 );
384 }
385 ("https" | "http", operation) => {
386 return unrepresentable(
387 &element,
388 &format!("operation '{operation}'"),
389 "only 'read' (GET/HEAD/OPTIONS) and 'write' (adds POST/PUT/PATCH) map to OpenShell access presets",
390 );
391 }
392 (protocol, _) => {
393 return unrepresentable(
394 &element,
395 &format!("protocol '{protocol}'"),
396 "only http, https and tcp endpoints are projected",
397 );
398 }
399 }
400 if rule.contains_key("access") {
401 rule.insert("enforcement".into(), json!("enforce"));
402 }
403
404 let key = rule_key(&flow.name);
405 if network.contains_key(&key) {
406 return Err(OpenShellProjectionError::Cell(format!(
407 "{element} collides with another flow on rule key '{key}'"
408 )));
409 }
410 mappings.push(Mapping {
411 target: format!("policy.yaml#/network_policies/{key}"),
412 source: flow.id.clone(),
413 class: "enforced",
414 phase: "live",
415 note: format!(
416 "{} {}:{} for operation '{}', restricted to the Cell's declared executables",
417 endpoint.protocol, endpoint.host, port, flow.operation
418 ),
419 });
420 network.insert(
421 key,
422 json!({
423 "name": flow.name,
424 "endpoints": [Value::Object(rule)],
425 "binaries": binaries.iter().map(|path| json!({ "path": path })).collect::<Vec<_>>(),
426 }),
427 );
428 }
429
430 let policy = json!({
431 "version": 1,
432 "filesystem_policy": {
433 "include_workdir": false,
434 "read_only": BASELINE_READ_ONLY,
435 "read_write": read_write,
436 },
437 "landlock": { "compatibility": "hard_requirement" },
438 "process": { "run_as_user": run_as, "run_as_group": run_as },
439 "network_policies": network,
440 });
441
442 let Ok(vcpus) = u8::try_from(ir.resources.cpu) else {
444 return unrepresentable(
445 &cell,
446 &format!("cpu {}", ir.resources.cpu),
447 "the MicroVM driver accepts at most 255 vCPUs",
448 );
449 };
450 for (field, note) in [
451 ("vcpus", "cpu"),
452 ("mem_mib", "memory_mb"),
453 ("overlay_disk_mib", "disk_mb"),
454 ] {
455 mappings.push(Mapping {
456 target: format!("sandbox.json#/vm_shape/{field}"),
457 source: ir.identity.cell_id.clone(),
458 class: "enforced",
459 phase: "gateway",
460 note: format!(
461 "{note}: set in the gateway's [openshell.drivers.vm] table; the MicroVM driver has no per-sandbox limits"
462 ),
463 });
464 }
465 mappings.push(Mapping {
466 target: "sandbox.json#/exec_timeout_seconds".into(),
467 source: ir.identity.cell_id.clone(),
468 class: "enforced",
469 phase: "exec",
470 note: "timeout_seconds: passed to every exec; OpenShell reports exit 124 on expiry".into(),
471 });
472
473 let mut obligations = vec![json!({
475 "kind": "architecture",
476 "value": ir.platform.architecture,
477 "discharge": "probe `uname -m` in the sandbox and refuse on mismatch",
478 })];
479 for dep in &ir.dependency_sets {
480 obligations.push(json!({
481 "kind": "protected_paths",
482 "source": dep.id,
483 "paths": [dep.manifest, dep.lockfile],
484 "mutation": dep.mutation,
485 "discharge": "apply the mutation decision to any changeset touching these paths before promotion",
486 }));
487 }
488 for policy_ref in &ir.policies {
489 obligations.push(json!({
490 "kind": "policy",
491 "source": policy_ref.id,
492 "name": policy_ref.name,
493 "modality": policy_ref.modality,
494 "discharge": "evaluate through the authority using the model's Rego projection",
495 }));
496 }
497 let image_requirements: Vec<Value> = ir
498 .system_dependencies
499 .iter()
500 .map(|d| json!({ "kind": "system", "name": d.name, "version": d.version }))
501 .chain(
502 ir.runtimes
503 .iter()
504 .map(|r| json!({ "kind": "runtime", "name": r.name, "version": r.version })),
505 )
506 .chain(
507 ir.tools
508 .iter()
509 .map(|t| json!({ "kind": "tool", "name": t.name, "version": t.version })),
510 )
511 .collect();
512 obligations.push(json!({
513 "kind": "image_contents",
514 "requirements": image_requirements,
515 "discharge": "run the evidence probes in the sandbox and refuse on failure; OpenShell does not verify image contents",
516 }));
517
518 let credentials: Vec<Value> = ir
519 .credentials
520 .iter()
521 .map(|c| {
522 json!({
523 "name": c.name,
524 "provider": c.provider,
525 "scope": c.scope,
526 "delivery": c.delivery,
527 "delivered": false,
530 })
531 })
532 .collect();
533
534 let sandbox = json!({
535 "schema": SANDBOX_SCHEMA,
536 "cell_id": ir.identity.cell_id,
537 "openshell_version": OPENSHELL_VERSION,
538 "compute_driver": "vm",
539 "vm_shape": {
540 "vcpus": vcpus,
541 "mem_mib": ir.resources.memory_mb,
542 "overlay_disk_mib": ir.resources.disk_mb,
543 },
544 "container_limits": {
545 "cpu": ir.resources.cpu.to_string(),
546 "memory": format!("{}Mi", ir.resources.memory_mb),
547 "disk": Value::Null,
548 },
549 "exec_timeout_seconds": ir.resources.timeout_seconds,
550 "workdir": WORKDIR,
551 "workspaces": workspaces,
552 "dependency_sets": ir.dependency_sets.iter().map(|d| json!({
553 "name": d.name,
554 "ecosystem": d.ecosystem,
555 "manifest": d.manifest,
556 "lockfile": d.lockfile,
557 "install": d.install,
558 "mutation": d.mutation,
559 })).collect::<Vec<_>>(),
560 "evidence_probes": ir.evidence_probes.iter().map(|p| json!({
561 "id": p.id,
562 "command": p.command,
563 "source": p.source,
564 })).collect::<Vec<_>>(),
565 "credentials": credentials,
566 "obligations": obligations,
567 });
568
569 Ok(Projection {
570 policy,
571 sandbox,
572 mappings,
573 })
574}
575
576fn pretty(value: &Value) -> String {
577 let mut out = serde_json::to_string_pretty(value).expect("JSON values serialize");
578 out.push('\n');
579 out
580}
581
582pub fn emit(
584 ast: &Ast,
585 source: &str,
586 model_ref: &str,
587 created_at: Option<String>,
588 overrides: Option<&CellOverrides>,
589 overrides_source: Option<&str>,
590 sink: &mut ArtifactSink,
591) -> Result<Vec<String>, OpenShellProjectionError> {
592 let created_at = created_at.unwrap_or_else(crate::timefmt::now_rfc3339);
593 let ir = CellIr::build(ast, model_ref, &created_at, overrides)
594 .map_err(OpenShellProjectionError::Cell)?;
595 let projection = project(&ir)?;
596
597 let canonical = format_source(source, FormatConfig::default()).map_err(|e| {
598 OpenShellProjectionError::Cell(format!("failed to canonicalize source: {e}"))
599 })?;
600 let model_hash = format!("sha256:{}", sha256_hex(canonical.as_bytes()));
601
602 let policy_yaml = format!(
603 "# Generated by `domainforge project --format openshell`. Do not edit.\n# Cell: {} ({})\n{}",
604 ir.identity.name,
605 ir.identity.cell_id,
606 to_yaml(&projection.policy)
607 .map_err(|e| OpenShellProjectionError::Write(e.to_string()))?
608 );
609
610 let mut files: BTreeMap<String, String> = BTreeMap::new();
611 files.insert(POLICY_FILE.to_string(), policy_yaml);
612 files.insert(SANDBOX_FILE.to_string(), pretty(&projection.sandbox));
613 files.insert(
614 MAPPING_FILE.to_string(),
615 pretty(&json!({
616 "schema": MAPPING_SCHEMA,
617 "projection": PROJECTION_VERSION,
618 "openshell_version": OPENSHELL_VERSION,
619 "cell_id": ir.identity.cell_id,
620 "classes": {
621 "enforced": "enforced by OpenShell as declared",
622 "adapter": "enforced by OpenShell after an explicit, recorded adaptation",
623 "baseline": "not declared by the Cell; required for any process to run",
624 },
625 "phases": {
626 "startup": "fixed when the sandbox starts",
627 "live": "may be updated on a running sandbox",
628 "gateway": "set in the gateway's driver configuration",
629 "exec": "applied per command",
630 },
631 "rules": projection.mappings.iter().map(Mapping::json).collect::<Vec<_>>(),
632 "obligations": projection.sandbox["obligations"],
633 })),
634 );
635
636 let hashes: Map<String, Value> = files
637 .iter()
638 .map(|(path, content)| {
639 (
640 path.clone(),
641 json!(format!("sha256:{}", sha256_hex(content.as_bytes()))),
642 )
643 })
644 .collect();
645 files.insert(
646 LOCK_FILE.to_string(),
647 pretty(&json!({
648 "schema": LOCK_SCHEMA,
649 "projection": PROJECTION_VERSION,
650 "openshell_version": OPENSHELL_VERSION,
651 "cell_id": ir.identity.cell_id,
652 "created_at": created_at,
653 "model": { "version": ir.identity.model_version, "hash": model_hash },
654 "profile": { "id": ir.profile_id, "version": ir.profile_version },
655 "overrides": {
656 "present": overrides_source.is_some(),
657 "hash": overrides_source.map(|s| format!("sha256:{}", sha256_hex(s.as_bytes()))),
658 },
659 "policy_digest": hashes[POLICY_FILE],
660 "files": hashes,
661 })),
662 );
663
664 for (path, content) in &files {
665 sink.write(path, content)
666 .map_err(OpenShellProjectionError::Write)?;
667 }
668 Ok(files.into_keys().collect())
669}
670
671pub fn project_openshell_in_memory(
673 source: &str,
674 model_ref: &str,
675 created_at: Option<String>,
676 overrides_source: Option<&str>,
677) -> Result<BTreeMap<String, String>, OpenShellProjectionError> {
678 let ast = crate::parser::parse(source)
679 .map_err(|e| OpenShellProjectionError::Cell(format!("parse failed: {e}")))?;
680 let overrides = overrides_source
681 .map(crate::projection::cell::overrides::parse)
682 .transpose()
683 .map_err(OpenShellProjectionError::Cell)?;
684 let mut map = BTreeMap::new();
685 let mut sink = ArtifactSink::Memory {
686 prefix: String::new(),
687 map: &mut map,
688 };
689 emit(
690 &ast,
691 source,
692 model_ref,
693 created_at,
694 overrides.as_ref(),
695 overrides_source,
696 &mut sink,
697 )?;
698 Ok(map)
699}