cageforge_backend_api/model.rs
1// SPDX-License-Identifier: Apache-2.0
2
3use std::collections::BTreeSet;
4use std::marker::PhantomData;
5use std::path::PathBuf;
6use std::sync::Arc;
7
8use cageforge_command::CommandRequest;
9use cageforge_policy_compose::{CompositionError, EffectivePathContext, EffectiveSandbox};
10use thiserror::Error;
11
12/// A portable command and effective policy submitted for backend preflight.
13///
14/// The request borrows the already validated values. It cannot be constructed
15/// from a raw [`cageforge_policy::SandboxPolicy`], which keeps composition a
16/// mandatory boundary for native execution.
17#[derive(Debug, Clone, Copy)]
18pub struct BackendRequest<'a> {
19 pub(super) command: &'a CommandRequest,
20 pub(super) sandbox: &'a EffectiveSandbox,
21}
22
23/// The capabilities advertised by one backend.
24///
25/// The set is deterministic so missing-capability diagnostics and tests are
26/// stable across platforms. Use named builders rather than positional
27/// booleans when constructing it.
28#[derive(Debug, Clone, Default, PartialEq, Eq)]
29pub struct BackendCapabilities {
30 pub(crate) capabilities: BTreeSet<BackendCapability>,
31}
32
33/// A request that passed backend capability preflight.
34///
35/// This type is still portable and contains no process handle. Native backend
36/// code may lower it to an OS-specific launch request after applying the
37/// filesystem, network, environment, and lifecycle contracts.
38///
39/// The `B` type parameter is a type-level binding to the backend whose
40/// capabilities were checked during preparation. The handoff also stores a
41/// runtime [`BackendIdentity`], so every accessor verifies the exact backend
42/// instance that was checked. Native lowering should accept
43/// `PreparedBackendRequest<'_, Self>` and pass the same backend instance to its
44/// accessors.
45///
46/// ```compile_fail
47/// use cageforge_backend_api::{
48/// BackendCapabilities, BackendIdentity, PreparedBackendRequest, SandboxBackend,
49/// };
50///
51/// struct LinuxBackend(BackendIdentity);
52/// struct WindowsBackend(BackendIdentity);
53///
54/// impl SandboxBackend for LinuxBackend {
55/// fn identity(&self) -> &BackendIdentity {
56/// &self.0
57/// }
58///
59/// fn capabilities(&self) -> BackendCapabilities {
60/// BackendCapabilities::new()
61/// }
62/// }
63///
64/// impl SandboxBackend for WindowsBackend {
65/// fn identity(&self) -> &BackendIdentity {
66/// &self.0
67/// }
68///
69/// fn capabilities(&self) -> BackendCapabilities {
70/// BackendCapabilities::new()
71/// }
72/// }
73///
74/// fn take_linux<'a>(_: PreparedBackendRequest<'a, LinuxBackend>) {}
75///
76/// fn pass_windows_to_linux<'a>(prepared: PreparedBackendRequest<'a, WindowsBackend>) {
77/// take_linux(prepared);
78/// }
79/// ```
80pub struct PreparedBackendRequest<'a, B: SandboxBackend> {
81 pub(super) request: BackendRequest<'a>,
82 pub(super) path_context: EffectivePathContext,
83 pub(super) working_directory: PathBuf,
84 pub(super) capabilities: BackendCapabilities,
85 pub(super) backend_identity: BackendIdentity,
86 pub(super) backend: PhantomData<fn() -> B>,
87}
88
89/// Identity of one backend enforcement instance.
90///
91/// A backend must store one identity for the lifetime of its enforcement
92/// state and return a reference to it from [`SandboxBackend::identity`]. Two
93/// backend instances may share an identity only when they intentionally share
94/// the same capability and enforcement state. This is an identity token, not
95/// proof that operating-system enforcement exists.
96///
97/// This type intentionally has no [`Default`] implementation. Every identity
98/// must be created explicitly with [`Self::new`], because a default value
99/// would be a fresh identity rather than a shared backend boundary.
100///
101/// ```compile_fail
102/// use cageforge_backend_api::BackendIdentity;
103/// let _ = BackendIdentity::default();
104/// ```
105#[derive(Clone)]
106pub struct BackendIdentity(pub(super) Arc<()>);
107
108/// One capability that a native backend may advertise.
109///
110/// A capability means that the backend can enforce the corresponding
111/// effective request safely. It is not a hint that the backend can parse the
112/// value. Backends must not advertise a capability whose enforcement would be
113/// best-effort or silently incomplete. `Ord` is used only for deterministic
114/// capability-set iteration and diagnostics; it is not an enforcement
115/// precedence.
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
117pub enum BackendCapability {
118 /// Execute a validated command request.
119 CommandExecution,
120 /// Resolve and enforce the effective working directory, including the
121 /// runtime directory inherited when the command has no explicit cwd.
122 WorkingDirectory,
123 /// Inherit a standard stream from the launcher.
124 StdioInherit,
125 /// Connect a standard stream to the platform null device.
126 StdioNull,
127 /// Create a pipe for a standard stream.
128 StdioPipe,
129 /// Apply the backend's default timeout policy.
130 TimeoutBackendDefault,
131 /// Apply an explicit timeout duration.
132 TimeoutLimit,
133 /// Run without an automatic timeout.
134 TimeoutDisabled,
135 /// Enforce a restricted filesystem policy.
136 FilesystemRestricted,
137 /// Run without a local filesystem boundary.
138 FilesystemUnrestricted,
139 /// Delegate filesystem enforcement to an external owner.
140 FilesystemExternal,
141 /// Enforce concrete and symbolic filesystem scopes, including workspace
142 /// roots required by workspace-relative selectors and globs.
143 FilesystemScopes,
144 /// Enforce native absolute filesystem scopes and absolute globs.
145 FilesystemAbsoluteScopes,
146 /// Resolve filesystem scopes and globs against runtime workspace roots.
147 FilesystemWorkspaceScopes,
148 /// Resolve filesystem scopes against caller-supplied system roots.
149 FilesystemRootScopes,
150 /// Resolve filesystem scopes against the platform-minimal paths.
151 FilesystemMinimalScopes,
152 /// Resolve filesystem scopes against the platform temporary directory.
153 FilesystemTmpdirScopes,
154 /// Resolve filesystem scopes against the platform's conventional
155 /// temporary path supplied by the runtime context.
156 FilesystemConventionalTemporaryScopes,
157 /// Enforce filesystem deny globs.
158 FilesystemGlobs,
159 /// Expand filesystem globs with the requested scan-depth semantics.
160 FilesystemGlobScanDepth,
161 /// Enforce read-only subpaths below writable scopes.
162 FilesystemReadOnlySubpaths,
163 /// Enforce the error-or-skip behavior for missing concrete filesystem
164 /// scopes.
165 FilesystemMissingPathBehavior,
166 /// Enforce protected relative paths such as the default `.git` path.
167 FilesystemProtectedPaths,
168 /// Disable outbound networking.
169 NetworkDisabled,
170 /// Enforce local outbound networking.
171 NetworkEnabled,
172 /// Delegate network enforcement to an external owner.
173 NetworkExternal,
174 /// Enforce domain rules and domain defaults.
175 NetworkDomainRules,
176 /// Enforce the policy for non-public and special-purpose addresses.
177 NetworkLocalAddressRestrictions,
178 /// Resolve once and authorize the exact address used for a connection.
179 NetworkResolvedTargets,
180 /// Prevent pathname local-IPC endpoint access while retaining
181 /// process-local IPC.
182 NetworkLocalIpcIsolation,
183 /// Enforce per-path local-IPC endpoint allow rules.
184 NetworkLocalIpcRules,
185 /// Enforce explicit pathname local-IPC deny rules when the default is
186 /// otherwise allow-all.
187 NetworkLocalIpcDenyRules,
188 /// Start from all inherited environment variables.
189 EnvironmentAll,
190 /// Start from a backend-selected core environment.
191 EnvironmentCore,
192 /// Start from an empty environment.
193 EnvironmentNone,
194 /// Apply environment include and exclude filters.
195 EnvironmentFilters,
196 /// Apply environment set and remove overrides.
197 EnvironmentOverrides,
198}
199
200/// Common failures at the portable backend contract boundary.
201#[derive(Debug, Error, Clone, PartialEq, Eq)]
202pub enum BackendContractError {
203 /// The backend cannot safely enforce one required capability.
204 #[error("backend cannot safely enforce required capability: {capability}")]
205 UnsupportedCapability {
206 /// The missing capability.
207 capability: BackendCapability,
208 },
209 /// The command and composed sandbox were built from different environment
210 /// specifications.
211 #[error("command environment does not match the composed requested environment")]
212 CommandEnvironmentMismatch,
213 /// The backend could not construct a safe runtime path context.
214 #[error("invalid backend runtime context: {source}")]
215 InvalidRuntimeContext {
216 /// The composition failure raised while narrowing the runtime context.
217 #[source]
218 source: CompositionError,
219 },
220 /// The backend could not construct the selected environment base.
221 #[error("environment preparation failed: {source}")]
222 EnvironmentPreparation {
223 /// The composition failure raised while applying the environment.
224 #[source]
225 source: CompositionError,
226 },
227 /// The effective filesystem policy rejected a backend query.
228 #[error("filesystem policy evaluation failed: {source}")]
229 FilesystemEvaluation {
230 /// The composition failure raised while evaluating filesystem access.
231 #[source]
232 source: CompositionError,
233 },
234 /// The command's working directory is outside the effective filesystem
235 /// policy.
236 #[error("working directory {path:?} is denied by the effective filesystem policy")]
237 WorkingDirectoryDenied {
238 /// The denied working directory.
239 path: PathBuf,
240 },
241 /// A relative working directory had no runtime current directory.
242 #[error("relative working directory {path:?} requires a runtime current directory")]
243 WorkingDirectoryResolution {
244 /// The unresolved relative working directory.
245 path: PathBuf,
246 },
247 /// The command omitted a working directory and the runtime did not supply
248 /// the directory that would otherwise be inherited by the child.
249 #[error("runtime current directory is required for backend preflight")]
250 MissingRuntimeCurrentDirectory,
251 /// The effective network policy rejected a backend query.
252 #[error("network policy evaluation failed: {source}")]
253 NetworkEvaluation {
254 /// The composition failure raised while evaluating network access.
255 #[source]
256 source: CompositionError,
257 },
258 /// A prepared handoff was used with a different backend instance than the
259 /// one whose capabilities were checked.
260 #[error("prepared backend request belongs to a different backend instance")]
261 BackendIdentityMismatch,
262 /// A prepared handoff was used after its backend changed capabilities.
263 #[error("backend capabilities changed after request preparation")]
264 BackendCapabilitiesMismatch,
265}
266
267/// The capability-discovery contract implemented by a native backend.
268///
269/// Implementations advertise only capabilities they can enforce. Call
270/// [`BackendRequest::prepare_for`] to run the common preflight; native
271/// backends cannot replace that check with a broader capability set. Process
272/// launch, platform I/O, and backend-specific errors remain outside this
273/// trait. Prepared accessors reject a changed capability snapshot with a typed
274/// error. The identity and capability checks do not prove that operating-system
275/// enforcement exists.
276pub trait SandboxBackend {
277 /// Returns the stable identity of this backend enforcement instance.
278 ///
279 /// The same reference must be returned for the lifetime of the backend.
280 /// Two instances may return the same identity only when they share the
281 /// same enforcement state and capability contract.
282 fn identity(&self) -> &BackendIdentity;
283
284 /// Returns the capabilities this backend can enforce safely.
285 fn capabilities(&self) -> BackendCapabilities;
286}