mxc-sdk 1.1.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Diagnostic configuration for MXC real-time logging.
//!
//! ## Environment variables
//! - `MXC_DIAG_CONSOLE=1` — enable diagnostic console (named pipe)

use std::env;

use crate::mxc_common::models::ExecutionRequest;

use windows::Win32::Foundation::CloseHandle;
use windows::Win32::Security::{GetTokenInformation, TokenUser, TOKEN_QUERY, TOKEN_USER};
use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};

const ENV_CONSOLE: &str = "MXC_DIAG_CONSOLE";
const ENV_PIPE_TOKEN: &str = "MXC_DIAG_PIPE_TOKEN";
const PIPE_NAME_PREFIX: &str = r"\\.\pipe\mxc-diagnostics";

/// Build the per-user, per-session diagnostic pipe name.
pub fn diagnostic_pipe_name() -> String {
    let suffix = diagnostic_pipe_token()
        .map(|token| format!("-{token}"))
        .unwrap_or_default();
    match current_user_sid() {
        Some(sid) => format!("{PIPE_NAME_PREFIX}-{sid}{suffix}"),
        None => format!("{PIPE_NAME_PREFIX}{suffix}"),
    }
}

/// Return the caller-provided per-session pipe token when it has sufficient
/// entropy for a pipe name.
pub fn diagnostic_pipe_token() -> Option<String> {
    let token = env::var(ENV_PIPE_TOKEN).ok()?;
    if !is_valid_pipe_token(&token) {
        return None;
    }
    Some(token)
}

fn is_valid_pipe_token(token: &str) -> bool {
    token.len() >= 32
        && token
            .bytes()
            .all(|byte| byte.is_ascii_hexdigit() || byte == b'-')
        && has_sufficient_entropy(token)
}

/// Approximate Shannon entropy (bits per hex character) over the token's
/// non-separator bytes, rejecting low-entropy patterns that a simple
/// "at least 4 distinct bytes" check would let through — e.g. `"abcd"`
/// repeated eight times has exactly 4 distinct bytes (enough to pass a bare
/// distinct-count check) but only 2 bits of entropy per character, far short
/// of what a real random token carries.
fn has_sufficient_entropy(token: &str) -> bool {
    let mut counts = [0u32; 256];
    let mut total = 0u32;
    for byte in token.bytes().filter(|byte| *byte != b'-') {
        counts[byte as usize] += 1;
        total += 1;
    }
    if total == 0 {
        return false;
    }
    let entropy: f64 = counts
        .iter()
        .filter(|&&count| count > 0)
        .map(|&count| {
            let p = f64::from(count) / f64::from(total);
            -p * p.log2()
        })
        .sum();
    // A uniformly random hex token carries up to 4 bits/char (log2(16)).
    // Require at least 3 bits/char: comfortably above what any low-period
    // repeating pattern can produce (a period-4 repeat tops out at 2
    // bits/char) while still accepting real random tokens.
    const MIN_BITS_PER_CHAR: f64 = 3.0;
    entropy >= MIN_BITS_PER_CHAR
}

/// Retrieve the SID string for the current process token's user.
pub fn current_user_sid() -> Option<String> {
    use crate::mxc_common::string_util::sid_to_string;
    use windows::Win32::Foundation::HANDLE;

    let mut token = HANDLE::default();
    // SAFETY: GetCurrentProcess returns a pseudo-handle always valid.
    // OpenProcessToken with TOKEN_QUERY is safe on a valid process handle.
    unsafe {
        OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token).ok()?;
    }

    let mut buf = vec![0u8; 256];
    let mut returned: u32 = 0;
    // SAFETY: token is valid (from OpenProcessToken above); buf is large enough for TOKEN_USER.
    let ok = unsafe {
        GetTokenInformation(
            token,
            TokenUser,
            Some(buf.as_mut_ptr().cast()),
            buf.len() as u32,
            &mut returned,
        )
    };

    if ok.is_err() {
        unsafe {
            let _ = CloseHandle(token);
        }
        return None;
    }

    // SAFETY: GetTokenInformation succeeded with TokenUser, so buf contains a valid TOKEN_USER.
    let token_user = unsafe { &*(buf.as_ptr() as *const TOKEN_USER) };
    let sid_str = unsafe { sid_to_string(token_user.User.Sid.0) };

    unsafe {
        let _ = CloseHandle(token);
    }

    sid_str
}

/// Maximum number of characters to include from `script_code` in diagnostic output.
const SCRIPT_CODE_TRUNCATE_LEN: usize = 200;

/// Resolved diagnostic configuration.
#[derive(Debug, Clone)]
pub struct DiagnosticConfig {
    /// Whether to send log messages to the shared diagnostic console via named pipe.
    pub console_enabled: bool,
}

impl DiagnosticConfig {
    /// Returns true if any diagnostic sink is enabled.
    pub fn any_enabled(&self) -> bool {
        self.console_enabled
    }

    /// Read diagnostic settings from environment variables.
    pub fn from_environment() -> Self {
        let console_enabled = env_bool(ENV_CONSOLE).unwrap_or(false);

        Self { console_enabled }
    }

    /// Check whether learning mode should be force-injected.
    ///
    /// When the diagnostic console is enabled (`MXC_DIAG_CONSOLE=1`), the
    /// `learningModeLogging` capability is automatically injected into the
    /// container policy so that access-check ETW events are captured.
    pub fn force_learning_mode() -> bool {
        env_bool(ENV_CONSOLE).unwrap_or(false)
    }
}

/// Produce a redacted JSON representation of an `ExecutionRequest` suitable for diagnostic logging.
///
/// - Environment variable values are replaced with `<redacted>`.
/// - `script_code` is truncated to `SCRIPT_CODE_TRUNCATE_LEN` characters.
/// - `network_proxy` (which is `#[serde(skip)]`) is logged separately.
pub fn redacted_request_json(request: &ExecutionRequest) -> String {
    // Build a redacted copy for serialization.
    let mut redacted = request.clone();

    // Redact env values: keep keys, replace values. `None` (no environment
    // supplied) is preserved as `None` so the dump distinguishes it from an
    // explicitly empty environment.
    redacted.env = redacted.env.map(|entries| {
        entries
            .iter()
            .map(|entry| {
                if let Some(pos) = entry.find('=') {
                    format!("{}=<redacted>", &entry[..pos])
                } else {
                    entry.clone()
                }
            })
            .collect()
    });

    // Truncate script_code.
    if redacted.script_code.len() > SCRIPT_CODE_TRUNCATE_LEN {
        let total_len = redacted.script_code.len();
        redacted.script_code.truncate(SCRIPT_CODE_TRUNCATE_LEN);
        redacted
            .script_code
            .push_str(&format!("... ({total_len} chars total)"));
    }

    // Serialize the redacted request.
    let json = serde_json::to_string_pretty(&redacted)
        .unwrap_or_else(|e| format!("{{\"error\": \"failed to serialize request: {e}\"}}"));

    // Append network_proxy info (skipped by serde).
    let proxy_info = match request.policy.network_proxy.address.as_ref() {
        Some(address) => format!(
            "\n[network_proxy: enabled, address={}]",
            crate::mxc_common::proxy_env::redact_proxy_url(&address.to_url())
        ),
        None => "\n[network_proxy: disabled]".to_string(),
    };

    format!("{json}{proxy_info}")
}

/// Parse caller-supplied raw config JSON and redact secret-bearing fields
/// (same closed set of markers as `crate::mxc_common::config_deserialize`'s error-path
/// redaction, e.g. `token`, `secret`, and whole `user` credential bundles)
/// before it is safe to write to a diagnostic sink.
///
/// This must run *before* any policy validation: an `IsolationSession`
/// one-shot request's credential bundle is only rejected by the runner after
/// the request has already been parsed and logged, so the raw text emitted
/// here cannot rely on downstream validation having stripped it first.
///
/// If the text fails to parse as JSON, a placeholder is returned instead of
/// the raw text, since malformed input cannot be proven free of embedded
/// credentials.
pub fn redact_raw_config_json(raw: &str) -> String {
    match serde_json::from_str::<serde_json::Value>(raw) {
        Ok(mut value) => {
            redact_secret_fields(&mut value);
            serde_json::to_string_pretty(&value)
                .unwrap_or_else(|_| "<unable to re-serialize redacted config>".to_string())
        }
        Err(_) => "<unparsable JSON config, omitted from diagnostics>".to_string(),
    }
}

/// Recursively blank JSON object values whose key is secret-bearing (see
/// `crate::mxc_common::config_deserialize::is_secret_path_field`). Over-redaction fails
/// safe: e.g. blanking the whole `user` object (rather than only `upn`/
/// `wamToken` within it) never leaks a credential.
fn redact_secret_fields(value: &mut serde_json::Value) {
    let mut path = Vec::new();
    redact_secret_fields_at_path(value, &mut path);
}

fn redact_secret_fields_at_path(value: &mut serde_json::Value, path: &mut Vec<String>) {
    match value {
        serde_json::Value::Object(map) => {
            for (key, entry) in map.iter_mut() {
                let key_lower = key.to_ascii_lowercase();
                if crate::mxc_common::config_deserialize::is_secret_path_field(&key_lower) {
                    *entry = serde_json::Value::String("<redacted>".to_string());
                } else if key_lower == "env" {
                    redact_environment_values(entry);
                } else if (key_lower == "networkproxy"
                    && path.last().is_some_and(|parent| parent == "runtimeconfig"))
                    || (key_lower == "url" && path.iter().any(|parent| parent == "proxy"))
                {
                    if let serde_json::Value::String(url) = entry {
                        *url = crate::mxc_common::proxy_env::redact_proxy_url(url);
                    } else {
                        *entry = serde_json::Value::String("<redacted>".to_string());
                    }
                } else {
                    // Reuse one mutable path stack across the whole
                    // recursion instead of cloning it at every key: push the
                    // current key before descending, pop it on the way back
                    // out, so allocation cost no longer grows with both JSON
                    // size and nesting depth.
                    path.push(key_lower);
                    redact_secret_fields_at_path(entry, path);
                    path.pop();
                }
            }
        }
        serde_json::Value::Array(items) => {
            for item in items.iter_mut() {
                redact_secret_fields_at_path(item, path);
            }
        }
        _ => {}
    }
}

fn redact_environment_values(value: &mut serde_json::Value) {
    match value {
        serde_json::Value::Array(items) => {
            for item in items {
                if let serde_json::Value::String(entry) = item {
                    if let Some(separator) = entry.find('=') {
                        entry.truncate(separator);
                        entry.push_str("=<redacted>");
                    }
                }
            }
        }
        other => redact_secret_fields_at_path(other, &mut Vec::new()),
    }
}

/// Get the parent process name and PID (e.g. `"node.exe:67890"`).
///
/// Returns `"unknown"` if the parent PID cannot be determined, or
/// `"?:<pid>"` if the parent process name cannot be resolved.
pub fn get_parent_process_info() -> String {
    use crate::mxc_common::process_util::{parent_process_id, process_image_path, OwnedHandle};
    use windows::Win32::System::Threading::{OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION};

    let ppid = match parent_process_id() {
        Ok(pid) => pid,
        Err(_) => return "unknown".to_string(),
    };

    // SAFETY: The returned handle is checked and immediately wrapped for owned cleanup.
    let exe_name = match unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, ppid) } {
        Ok(handle) => {
            let handle = OwnedHandle::new(handle);
            process_image_path(handle.get())
                .ok()
                .and_then(|path| {
                    path.file_name()
                        .map(|name| name.to_string_lossy().into_owned())
                })
                .unwrap_or_else(|| "?".to_string())
        }
        Err(_) => "?".to_string(),
    };

    format!("{exe_name}:{ppid}")
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Read a boolean from an environment variable ("1" or "true" = true).
fn env_bool(name: &str) -> Option<bool> {
    env::var(name)
        .ok()
        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mxc_common::models::{ProxyAddress, ProxyConfig};

    #[test]
    fn redacted_request_hides_env_values() {
        let request = ExecutionRequest {
            env: Some(vec![
                "PATH=C:\\Windows".to_string(),
                "SECRET_TOKEN=abc123".to_string(),
            ]),
            ..Default::default()
        };
        let json = redacted_request_json(&request);
        assert!(json.contains("PATH=<redacted>"));
        assert!(json.contains("SECRET_TOKEN=<redacted>"));
        assert!(!json.contains("abc123"));
        assert!(!json.contains("C:\\\\Windows"));
    }

    #[test]
    fn redacted_request_truncates_script_code() {
        let request = ExecutionRequest {
            script_code: "x".repeat(500),
            ..Default::default()
        };
        let json = redacted_request_json(&request);
        assert!(json.contains("500 chars total"));
        assert!(!json.contains(&"x".repeat(500)));
    }

    #[test]
    fn redacted_request_shows_proxy_info() {
        let mut request = ExecutionRequest::default();
        request.policy.network_proxy = ProxyConfig {
            address: Some(ProxyAddress::new("127.0.0.1".to_string(), 8080)),
        };
        let json = redacted_request_json(&request);
        assert!(json.contains("network_proxy: enabled"));
        assert!(json.contains("http://127.0.0.1:8080"));
    }

    #[test]
    fn redacted_request_shows_proxy_disabled() {
        let request = ExecutionRequest::default();
        let json = redacted_request_json(&request);
        assert!(json.contains("network_proxy: disabled"));
    }

    #[test]
    fn runtime_proxy_credentials_are_redacted_in_diagnostics() {
        let url = format!("http://user:{}@localhost:8080", "pass");
        let mut request = ExecutionRequest::default();
        request.policy.network_proxy = ProxyConfig {
            address: Some(ProxyAddress::from_url(&url, "localhost".to_string(), 8080)),
        };
        let redacted = redacted_request_json(&request);
        assert!(!redacted.contains(&url));
        assert!(redacted.contains("http://***@localhost:8080"));

        let raw = serde_json::json!({"runtimeConfig": {"networkProxy": url}}).to_string();
        let redacted = redact_raw_config_json(&raw);
        assert!(!redacted.contains(&url));
        assert!(redacted.contains("http://***@localhost:8080"));
    }

    #[test]
    fn non_string_proxy_values_in_comments_are_redacted() {
        for proxy_value in [
            serde_json::json!({"password": "diagnostic-canary"}),
            serde_json::json!([{"password": "diagnostic-canary"}]),
        ] {
            let raw = serde_json::json!({
                "_comment": {
                    "runtimeConfig": {"networkProxy": proxy_value.clone()},
                    "proxy": {"url": proxy_value}
                }
            })
            .to_string();
            let redacted = redact_raw_config_json(&raw);
            assert!(!redacted.contains("diagnostic-canary"));

            let parsed: serde_json::Value = serde_json::from_str(&redacted).unwrap();
            assert_eq!(
                parsed["_comment"]["runtimeConfig"]["networkProxy"],
                "<redacted>"
            );
            assert_eq!(parsed["_comment"]["proxy"]["url"], "<redacted>");
        }
    }

    #[test]
    fn redact_raw_config_json_hides_isolation_session_user_bundle() {
        let raw = r#"{
            "process": {"commandLine": "echo hi"},
            "containment": "isolation_session",
            "experimental": {
                "isolationSession": {
                    "user": {"upn": "alice@contoso.com", "wamToken": "super-secret-bearer-token"}
                }
            }
        }"#;
        let redacted = redact_raw_config_json(raw);
        assert!(!redacted.contains("alice@contoso.com"));
        assert!(!redacted.contains("super-secret-bearer-token"));
        assert!(redacted.contains("<redacted>"));
        // Non-secret fields survive untouched.
        assert!(redacted.contains("echo hi"));
        assert!(redacted.contains("isolation_session"));
    }

    #[test]
    fn redact_raw_config_json_hides_bare_token_and_secret_fields() {
        let raw = r#"{"apiKey": "abc123", "clientSecret": "xyz", "commandLine": "run"}"#;
        let redacted = redact_raw_config_json(raw);
        assert!(!redacted.contains("abc123"));
        assert!(!redacted.contains("xyz"));
        assert!(redacted.contains("run"));
    }

    #[test]
    fn redact_raw_config_json_hides_environment_values_and_proxy_userinfo() {
        let raw = r#"{
            "process": {
                "env": ["API_KEY=hunter2", "PATH=C:\\Windows"]
            },
            "network": {
                "proxy": {
                    "url": "http://user:password@proxy.example:8080"
                }
            }
        }"#;
        let redacted = redact_raw_config_json(raw);
        assert!(!redacted.contains("hunter2"));
        assert!(!redacted.contains("C:\\Windows"));
        assert!(redacted.contains("API_KEY=<redacted>"));
        assert!(redacted.contains("http://***@proxy.example:8080"));
        assert!(!redacted.contains("user:password"));
    }

    #[test]
    fn redact_raw_config_json_falls_back_on_malformed_json() {
        let redacted = redact_raw_config_json("{ not valid json");
        assert_eq!(
            redacted,
            "<unparsable JSON config, omitted from diagnostics>"
        );
    }

    #[test]
    fn env_bool_parses_correctly() {
        // env_bool on non-existent var returns None
        assert!(env_bool("MXC_TEST_NONEXISTENT_VAR_12345").is_none());
    }

    #[test]
    fn pipe_tokens_require_length_and_safe_characters() {
        assert!(is_valid_pipe_token("0123456789abcdef0123456789abcdef"));
        assert!(is_valid_pipe_token("0123456789abcdef0123456789ab-cdef"));
        assert!(!is_valid_pipe_token("0123456789abcdef"));
        assert!(!is_valid_pipe_token("0123456789abcdef0123456789abcde!"));
        assert!(!is_valid_pipe_token("--------------------------------"));
    }

    #[test]
    fn pipe_tokens_reject_low_entropy_repeated_patterns() {
        // Exactly 4 distinct bytes (would have passed the old distinct-byte
        // check) but only 2 bits/char of real entropy: a short pattern
        // repeated to reach the length floor, not a genuinely random token.
        assert!(!is_valid_pipe_token("abcdabcdabcdabcdabcdabcdabcdabcd"));
        assert!(!is_valid_pipe_token("00000000000000000000000000000001"));
    }
}