mxc-sdk 1.2.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use super::primitives::{deserialize_optional_object, NonEmptyString, OptionalField};
use serde::{de, Deserialize, Deserializer};

/// Container lifecycle settings.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Lifecycle {
    /// Whether to destroy the container when execution ends.
    #[serde(default)]
    pub destroy_on_exit: OptionalField<bool>,
    /// Whether to preserve applied policy after execution ends.
    #[serde(default)]
    pub preserve_policy: OptionalField<bool>,
}

/// Telemetry settings.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Telemetry {
    /// Whether telemetry is enabled.
    #[serde(default)]
    pub enabled: OptionalField<bool>,
}

/// Process execution settings.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Process {
    /// The non-empty command line to execute.
    pub command_line: NonEmptyString,
    /// Optional working directory.
    #[serde(default)]
    pub cwd: OptionalField<String>,
    /// Optional environment entries encoded as `KEY=VALUE` strings.
    ///
    /// Omitted gives the backend's default environment; supplied (including as
    /// an empty array) is used verbatim unless `inheritDefaultEnv` is set.
    #[serde(default)]
    pub env: OptionalField<Vec<String>>,
    /// Layer `env` on top of the backend's default environment rather than
    /// replacing it.
    #[serde(default)]
    pub inherit_default_env: OptionalField<bool>,
    /// Optional execution timeout in milliseconds.
    #[serde(default)]
    pub timeout: OptionalField<u32>,
}

/// Filesystem access policy.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Filesystem {
    /// Optional paths granted read-write access.
    #[serde(default)]
    pub readwrite_paths: OptionalField<Vec<String>>,
    /// Optional paths granted read-only access.
    #[serde(default)]
    pub readonly_paths: OptionalField<Vec<String>>,
    /// Optional paths denied access.
    #[serde(default)]
    pub denied_paths: OptionalField<Vec<String>>,
}

/// Fallback settings accepted for 1.x compatibility and ignored.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Fallback {
    /// Accepted for compatibility and ignored.
    #[serde(default)]
    pub allow_dacl_mutation: OptionalField<bool>,
}

string_enum! {
    /// Clipboard access granted to the contained process.
    #[derive(Debug)]
    pub enum UiClipboard {
        /// Deny clipboard reads and writes.
        None => ["none"],
        /// Allow clipboard reads.
        Read => ["read"],
        /// Allow clipboard writes.
        Write => ["write"],
        /// Allow clipboard reads and writes.
        All => ["all"],
    }
}

/// Cross-platform user-interface policy.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Ui {
    /// Whether visible user interface is disabled.
    #[serde(default)]
    pub disable: OptionalField<bool>,
    /// Optional clipboard access level.
    #[serde(default)]
    pub clipboard: OptionalField<UiClipboard>,
    /// Whether keyboard and mouse input injection is allowed.
    #[serde(default)]
    pub injection: OptionalField<bool>,
}

string_enum! {
    /// Isolation level for ProcessContainer desktop resources.
    #[derive(Debug)]
    pub enum ProcessContainerUiIsolation {
        /// Isolate the complete container user-interface environment.
        Container => ["container"],
        /// Isolate desktop resources.
        Desktop => ["desktop"],
        /// Isolate user-interface handles.
        Handles => ["handles"],
        /// Isolate user-interface atoms.
        Atoms => ["atoms"],
    }
}

string_enum! {
    /// System settings for ProcessContainer desktop resources.
    #[derive(Debug)]
    pub enum ProcessContainerUiSystemSettings {
        /// Block system-parameter and display-setting changes.
        None => ["none"],
        /// Block display-setting changes, but not system-parameter changes.
        Parameters => ["parameters"],
        /// Block system-parameter changes, but not display-setting changes.
        Display => ["display"],
        /// Do not block either system-parameter or display-setting changes.
        All => ["all"],
    }
}

/// ProcessContainer-specific user-interface policy.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ProcessContainerUi {
    /// Optional desktop-resource isolation level.
    #[serde(default)]
    pub isolation: OptionalField<ProcessContainerUiIsolation>,
    /// Whether desktop system control is allowed.
    #[serde(default)]
    pub desktop_system_control: OptionalField<bool>,
    /// Optional system-settings access level.
    #[serde(default)]
    pub system_settings: OptionalField<ProcessContainerUiSystemSettings>,
    /// Whether Input Method Editor access is allowed.
    #[serde(default)]
    pub ime: OptionalField<bool>,
}

string_enum! {
    /// Mode for capture denials
    #[derive(Debug)]
    pub enum CaptureDenialsMode {
        /// Access stays **denied** and the denial is recorded. Deny-by-default containment is preserved; this is the safe default.
        Block => ["block"],
        /// Access is **allowed** and recorded (audit mode). This relaxes deny-by-default for the run, so it is a security-sensitive choice and the runner emits a security warning.
        Allow => ["allow"],
    }
}

/// Windows denial-capture settings.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct CaptureDenials {
    /// How each ungranted access is handled while it is recorded.
    #[serde(default)]
    pub mode: OptionalField<CaptureDenialsMode>,
    /// Optional destination for the generated denial report.
    #[serde(default)]
    pub output_path: OptionalField<String>,
    /// Whether to retain the sealed ETL trace after analysis. Retained traces
    /// can contain sensitive resource paths and identifiers. When any later
    /// capture starts, MXC may delete retained traces that are 7 or more days
    /// old; move a trace elsewhere to keep it longer.
    #[serde(default)]
    pub retain_etl: OptionalField<bool>,
}

/// An AppContainer capability name supplied by the caller.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProcessContainerCapability(String);

const RESERVED_CAPABILITIES: &[&str] = &["learningModeLogging", "permissiveLearningMode"];

impl ProcessContainerCapability {
    /// Creates a validated capability name.
    ///
    /// Commas are rejected because BaseContainer uses them as its wire
    /// delimiter. Learning-mode capabilities are reserved for MXC's dedicated
    /// learning-mode and denial-capture controls.
    pub fn new(value: String) -> Result<Self, String> {
        if value.contains(',') {
            return Err(
                "capability must not contain a comma; provide multiple capabilities as separate array entries, for example [\"internetClient\", \"privateNetworkClientServer\"]"
                    .to_string(),
            );
        }
        if RESERVED_CAPABILITIES
            .iter()
            .any(|reserved| value.eq_ignore_ascii_case(reserved))
        {
            return Err(
                "learningModeLogging and permissiveLearningMode are reserved; use learningMode, --audit, or captureDenials instead"
                    .to_string(),
            );
        }
        Ok(Self(value))
    }

    /// Returns the validated capability name.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the wrapper and returns the validated capability name.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl<'de> Deserialize<'de> for ProcessContainerCapability {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::new(value).map_err(de::Error::custom)
    }
}

#[cfg(feature = "schema-gen")]
fn ascii_case_insensitive_literal(value: &str) -> String {
    let mut pattern = String::with_capacity(value.len() * 4);
    for character in value.chars() {
        if character.is_ascii_alphabetic() {
            pattern.push('[');
            pattern.push(character.to_ascii_lowercase());
            pattern.push(character.to_ascii_uppercase());
            pattern.push(']');
        } else {
            if r"\.^$|?*+()[]{}".contains(character) {
                pattern.push('\\');
            }
            pattern.push(character);
        }
    }
    pattern
}

#[cfg(feature = "schema-gen")]
fn capability_schema_pattern() -> String {
    let reserved = RESERVED_CAPABILITIES
        .iter()
        .map(|value| ascii_case_insensitive_literal(value))
        .collect::<Vec<_>>()
        .join("|");
    format!(r"^(?![\s\S]*,)(?!(?:{reserved})$)[\s\S]*$")
}

#[cfg(feature = "schema-gen")]
impl schemars::JsonSchema for ProcessContainerCapability {
    fn schema_name() -> String {
        "ProcessContainerCapability".to_string()
    }

    fn json_schema(_generator: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
        use schemars::schema::{InstanceType, Schema, SchemaObject, SingleOrVec, StringValidation};

        Schema::Object(SchemaObject {
            instance_type: Some(SingleOrVec::Single(Box::new(InstanceType::String))),
            string: Some(Box::new(StringValidation {
                pattern: Some(capability_schema_pattern()),
                ..Default::default()
            })),
            ..Default::default()
        })
    }
}

/// ProcessContainer-specific settings.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ProcessContainer {
    /// Whether least-privilege mode is enabled.
    #[serde(default)]
    pub least_privilege: OptionalField<bool>,
    /// Optional learning-mode (deny-and-record)
    #[serde(default)]
    pub learning_mode: OptionalField<bool>,
    /// Optional AppContainer capability names. Each entry must contain one
    /// name; commas are rejected because BaseContainer uses them as its wire
    /// delimiter. `learningModeLogging` and `permissiveLearningMode` are
    /// reserved; use `learningMode`, `--audit`, or `captureDenials` instead.
    #[serde(default)]
    pub capabilities: OptionalField<Vec<ProcessContainerCapability>>,
    /// Optional capture-denials policy.
    #[serde(default)]
    pub capture_denials: OptionalField<CaptureDenials>,
    /// Optional ProcessContainer-specific user-interface policy.
    #[serde(default)]
    pub ui: OptionalField<ProcessContainerUi>,
    /// Optional ProcessContainer-specific filesystem policy.
    #[serde(default)]
    pub filesystem: OptionalField<ProcessContainerFilesystem>,
    /// Optional ProcessContainer-specific network settings.
    #[serde(default)]
    pub network: OptionalField<ProcessContainerNetwork>,
}

/// ProcessContainer-specific filesystem policy.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ProcessContainerFilesystem {
    /// Optional paths that may be queried or enumerated without granting file-content reads.
    #[serde(default)]
    pub enumerate_paths: OptionalField<Vec<String>>,
}

/// ProcessContainer-specific network settings.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ProcessContainerNetwork {
    /// Optional loopback peer the contained process may reach in addition to
    /// the configured runtime proxy. Requires `runtimeConfig.networkProxy`.
    #[serde(default)]
    pub allowed_proxy_peer: OptionalField<String>,
}

/// Runtime configuration supplied alongside the sandbox policy.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RuntimeConfig {
    /// Optional HTTP/S proxy URL. Host-process backends require a localhost
    /// endpoint; WSLc requires an endpoint routable from its container and
    /// inherits the provisioned networking mode on exec.
    #[serde(default)]
    pub network_proxy: OptionalField<String>,
}

/// Linux LXC distribution settings.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Lxc {
    /// The Linux distribution name.
    pub distribution: String,
    /// The distribution release.
    pub release: String,
}

/// macOS Seatbelt backend settings.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Seatbelt {
    /// Optional override of the generated sandbox profile.
    #[serde(default)]
    pub profile_override: OptionalField<String>,
    /// Allows all Mach lookups and registrations, IOKit user clients, and
    /// POSIX shared memory, plus writes to the system temp folders. This
    /// includes system services that can make network requests for the sandbox.
    /// Deprecated: use the `custom*` Mach, IOKit, and shared memory lists.
    #[serde(default)]
    pub gui_access: OptionalField<bool>,
    /// Whether the contained process may allocate nested pseudo-terminals.
    #[serde(default)]
    pub nested_pty: OptionalField<bool>,
    /// Whether macOS Keychain access is allowed.
    #[serde(default)]
    pub keychain_access: OptionalField<bool>,
    /// Additional Mach service global names the process may resolve.
    /// Deprecated: use `customMachLookups.allow`.
    #[serde(default)]
    pub extra_mach_lookups: OptionalField<Vec<String>>,
    /// IOKit user-client classes the process may open. When present, this
    /// replaces guiAccess's IOKit grant.
    #[serde(default, deserialize_with = "deserialize_optional_object")]
    pub custom_io_kits: OptionalField<SeatbeltCustomRules>,
    /// Mach service names the process may register. Each present scope
    /// (`global` or `local`) replaces guiAccess's registration grant for it.
    #[serde(default, deserialize_with = "deserialize_optional_object")]
    pub custom_mach_registers: OptionalField<SeatbeltCustomMachRegisters>,
    /// Mach service global names the process may resolve. When present, this
    /// replaces guiAccess's Mach lookup grant.
    #[serde(default, deserialize_with = "deserialize_optional_object")]
    pub custom_mach_lookups: OptionalField<SeatbeltCustomRules>,
    /// POSIX shared memory names the process may use. When present, this
    /// replaces guiAccess's shared memory grant.
    #[serde(default, deserialize_with = "deserialize_optional_object")]
    pub custom_posix_shm: OptionalField<SeatbeltCustomPosixShm>,
    /// Records sandbox denials to a JSON report.
    #[serde(default, deserialize_with = "deserialize_optional_object")]
    pub capture_denials: OptionalField<SeatbeltCaptureDenials>,
}

string_enum! {
    /// Access for names that no `allow` or `deny` entry matches.
    #[derive(Debug)]
    pub enum SeatbeltCustomDefault {
        /// Allow every name not denied. Use only for compatibility.
        Allow => ["allow"],
        /// Deny unlisted names. MXC's built-in grants and enabled settings
        /// still apply.
        Deny => ["deny"],
    }
}

string_enum! {
    /// Access to a POSIX shared memory name. Each level includes the ones
    /// before it.
    #[derive(Debug)]
    pub enum SeatbeltPosixShmAccess {
        /// No access.
        Deny => ["deny"],
        /// Open and read existing regions.
        Read => ["read"],
        /// Also write existing regions.
        ReadWrite => ["readWrite"],
        /// Also create regions.
        Create => ["create"],
        /// Also delete regions.
        Own => ["own"],
    }
}

/// Allow and deny lists for one kind of Seatbelt name. An entry ending in `*`
/// matches every name with that prefix. `deny` entries win over `allow`.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SeatbeltCustomRules {
    /// Access for unlisted names. Defaults to `deny`.
    #[serde(default)]
    pub default: OptionalField<SeatbeltCustomDefault>,
    /// Names to allow.
    #[serde(default)]
    pub allow: OptionalField<Vec<String>>,
    /// Names to deny, including names MXC allows by default.
    #[serde(default)]
    pub deny: OptionalField<Vec<String>>,
}

/// Mach service registration rules, by name scope.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SeatbeltCustomMachRegisters {
    /// Names registered with launchd, visible to other processes.
    #[serde(default, deserialize_with = "deserialize_optional_object")]
    pub global: OptionalField<SeatbeltCustomRules>,
    /// Per-process names, shown as `(per-pid)` in denial reports.
    #[serde(default, deserialize_with = "deserialize_optional_object")]
    pub local: OptionalField<SeatbeltCustomRules>,
}

/// POSIX shared memory rules, by access. An entry ending in `*` matches every
/// name with that prefix. Each listed name gets exactly its list's access; a
/// longer entry wins over a shorter prefix. `deny` entries win over every
/// other list.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SeatbeltCustomPosixShm {
    /// Access for unlisted names. Defaults to `deny`.
    #[serde(default)]
    pub default: OptionalField<SeatbeltPosixShmAccess>,
    /// Names the process may only read.
    #[serde(default)]
    pub read: OptionalField<Vec<String>>,
    /// Existing names the process may read and write.
    #[serde(default)]
    pub read_write: OptionalField<Vec<String>>,
    /// Names the process may read, write, and create.
    #[serde(default)]
    pub create: OptionalField<Vec<String>>,
    /// Names the process may read, write, create, and delete.
    #[serde(default)]
    pub own: OptionalField<Vec<String>>,
    /// Names to deny.
    #[serde(default)]
    pub deny: OptionalField<Vec<String>>,
}

/// macOS Seatbelt denial-capture settings.
#[derive(Debug, serde::Deserialize)]
#[cfg_attr(feature = "schema-gen", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SeatbeltCaptureDenials {
    /// How each ungranted access is handled while it is recorded.
    #[serde(default)]
    pub mode: OptionalField<CaptureDenialsMode>,
    /// Optional absolute file path for the denial report; may start with `~/`.
    #[serde(default)]
    pub output_path: OptionalField<String>,
    /// Whether to keep the run's raw `log stream` lines as `.seatbelt.log`
    /// next to the report. The trace can contain sensitive paths; callers are
    /// responsible for deleting it.
    #[serde(default)]
    pub retain_etl: OptionalField<bool>,
}