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 /// Enforce typed Windows named-pipe local-IPC endpoints.
189 NetworkWindowsNamedPipeRules,
190 /// Start from all inherited environment variables.
191 EnvironmentAll,
192 /// Start from a backend-selected core environment.
193 EnvironmentCore,
194 /// Start from an empty environment.
195 EnvironmentNone,
196 /// Apply environment include and exclude filters.
197 EnvironmentFilters,
198 /// Apply environment set and remove overrides.
199 EnvironmentOverrides,
200}
201
202/// Common failures at the portable backend contract boundary.
203#[derive(Debug, Error, Clone, PartialEq, Eq)]
204pub enum BackendContractError {
205 /// The backend cannot safely enforce one required capability.
206 #[error("backend cannot safely enforce required capability: {capability}")]
207 UnsupportedCapability {
208 /// The missing capability.
209 capability: BackendCapability,
210 },
211 /// The command and composed sandbox were built from different environment
212 /// specifications.
213 #[error("command environment does not match the composed requested environment")]
214 CommandEnvironmentMismatch,
215 /// The backend could not construct a safe runtime path context.
216 #[error("invalid backend runtime context: {source}")]
217 InvalidRuntimeContext {
218 /// The composition failure raised while narrowing the runtime context.
219 #[source]
220 source: CompositionError,
221 },
222 /// The backend could not construct the selected environment base.
223 #[error("environment preparation failed: {source}")]
224 EnvironmentPreparation {
225 /// The composition failure raised while applying the environment.
226 #[source]
227 source: CompositionError,
228 },
229 /// The effective filesystem policy rejected a backend query.
230 #[error("filesystem policy evaluation failed: {source}")]
231 FilesystemEvaluation {
232 /// The composition failure raised while evaluating filesystem access.
233 #[source]
234 source: CompositionError,
235 },
236 /// The command's working directory is outside the effective filesystem
237 /// policy.
238 #[error("working directory {path:?} is denied by the effective filesystem policy")]
239 WorkingDirectoryDenied {
240 /// The denied working directory.
241 path: PathBuf,
242 },
243 /// A relative working directory had no runtime current directory.
244 #[error("relative working directory {path:?} requires a runtime current directory")]
245 WorkingDirectoryResolution {
246 /// The unresolved relative working directory.
247 path: PathBuf,
248 },
249 /// The command omitted a working directory and the runtime did not supply
250 /// the directory that would otherwise be inherited by the child.
251 #[error("runtime current directory is required for backend preflight")]
252 MissingRuntimeCurrentDirectory,
253 /// The effective network policy rejected a backend query.
254 #[error("network policy evaluation failed: {source}")]
255 NetworkEvaluation {
256 /// The composition failure raised while evaluating network access.
257 #[source]
258 source: CompositionError,
259 },
260 /// A prepared handoff was used with a different backend instance than the
261 /// one whose capabilities were checked.
262 #[error("prepared backend request belongs to a different backend instance")]
263 BackendIdentityMismatch,
264 /// A prepared handoff was used after its backend changed capabilities.
265 #[error("backend capabilities changed after request preparation")]
266 BackendCapabilitiesMismatch,
267}
268
269/// The capability-discovery contract implemented by a native backend.
270///
271/// Implementations advertise only capabilities they can enforce. Call
272/// [`BackendRequest::prepare_for`] to run the common preflight; native
273/// backends cannot replace that check with a broader capability set. Process
274/// launch, platform I/O, and backend-specific errors remain outside this
275/// trait. Prepared accessors reject a changed capability snapshot with a typed
276/// error. The identity and capability checks do not prove that operating-system
277/// enforcement exists.
278pub trait SandboxBackend {
279 /// Returns the stable identity of this backend enforcement instance.
280 ///
281 /// The same reference must be returned for the lifetime of the backend.
282 /// Two instances may return the same identity only when they share the
283 /// same enforcement state and capability contract.
284 fn identity(&self) -> &BackendIdentity;
285
286 /// Returns the capabilities this backend can enforce safely.
287 fn capabilities(&self) -> BackendCapabilities;
288}