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

use super::{CheckoutMetadata, ProvisionResult};
use crate::mxc_common::models::W365AgentsProvisionConfig;
use crate::mxc_common::mxc_error::MxcError;
use serde_json::{json, Value};
use std::time::Duration;
use ureq::tls::{RootCerts, TlsConfig, TlsProvider};

const CHECKOUT_TIMEOUT: Duration = Duration::from_secs(45);
const RELEASE_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_RESPONSE: u64 = 1024 * 1024;
pub(super) const USER_AGENT: &str = concat!("mxc/", env!("CARGO_PKG_VERSION"), " (w365_agents)");

pub(super) fn transport_budget(default: Duration) -> Result<Duration, MxcError> {
    #[cfg(feature = "test-support")]
    if let Some(value) = std::env::var_os("MXC_W365_TEST_TIMEOUT_MS") {
        return Ok(Duration::from_millis(
            value
                .to_str()
                .and_then(|value| value.parse::<std::num::NonZeroU64>().ok())
                .ok_or_else(|| MxcError::policy_validation("invalid W365 fixture timeout"))?
                .get(),
        ));
    }
    Ok(default)
}

pub(super) fn with_transport_stack<T: Send>(
    operation: impl FnOnce() -> Result<T, MxcError> + Send,
) -> Result<T, MxcError> {
    // TLS must not run on a foreign FFI caller's small stack. Join before returning.
    std::thread::scope(|scope| {
        std::thread::Builder::new()
            .name("mxc-w365-transport".into())
            .stack_size(2 * 1024 * 1024)
            .spawn_scoped(scope, operation)
            .map_err(|error| {
                MxcError::backend_error(format!("could not start W365 transport: {error}"))
            })?
            .join()
            .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
    })
}

fn guid(value: &str) -> bool {
    // UUID parsing also accepts simple, braced and URN forms; the contract does not.
    value.len() == uuid::fmt::Hyphenated::LENGTH && uuid::Uuid::try_parse(value).is_ok()
}

pub(super) struct Identity {
    pub(super) pool_id: String,
    pub(super) session_id: String,
}

impl Identity {
    pub(super) fn parse(value: &str) -> Result<Self, MxcError> {
        let parts: Vec<_> = value.split(':').collect();
        if parts.len() != 3 || parts[0] != "w365" || !guid(parts[1]) || !guid(parts[2]) {
            return Err(MxcError::malformed_id(
                "w365 sandboxId must contain exactly a pool GUID and a session GUID",
            ));
        }
        Ok(Self {
            pool_id: parts[1].to_ascii_lowercase(),
            session_id: parts[2].to_ascii_lowercase(),
        })
    }

    pub(super) fn encode(&self) -> String {
        format!("w365:{}:{}", self.pool_id, self.session_id)
    }
}

pub(super) fn validate_provision(
    config: Option<&W365AgentsProvisionConfig>,
) -> Result<&W365AgentsProvisionConfig, MxcError> {
    let config = config
        .ok_or_else(|| MxcError::policy_validation("w365Agents.provision.poolId is required"))?;
    if !guid(&config.pool_id)
        || config.user_object_id.as_deref().is_some_and(|id| !guid(id))
        || config
            .user_type
            .as_deref()
            .is_some_and(|kind| !matches!(kind, "Local" | "HumanUser" | "Agentic"))
    {
        return Err(MxcError::policy_validation(
            "invalid W365 pool or user identity",
        ));
    }
    Ok(config)
}

// Deliberately no Debug: the client owns the caller's bearer token.
pub(super) struct Client {
    pub(super) host: String,
    pub(super) token: String,
}

impl Client {
    pub(super) fn from_env() -> Result<Self, MxcError> {
        Self::from_env_keys("W365A_CONTROLPLANE_URL", "W365A_CP_TOKEN")
    }

    pub(super) fn from_env_keys(host_key: &str, token_key: &str) -> Result<Self, MxcError> {
        let read = |name: &str| {
            std::env::var(name).map_err(|_| {
                MxcError::policy_validation(format!(
                    "w365_agents requires {name} in the caller environment"
                ))
            })
        };
        let host = read(host_key)?;
        let token = read(token_key)?;
        let valid_host = host.len() <= 253
            && host.split('.').all(|label| {
                !label.is_empty()
                    && label.len() <= 63
                    && !label.starts_with('-')
                    && !label.ends_with('-')
                    && label
                        .bytes()
                        .all(|b| b.is_ascii_alphanumeric() || b == b'-')
            });
        if !valid_host {
            return Err(MxcError::policy_validation(format!(
                "{host_key} must be a bare ASCII DNS hostname (no URL, port or path)"
            )));
        }
        if token.is_empty() || !token.bytes().all(|b| b.is_ascii_graphic()) {
            return Err(MxcError::policy_validation(format!(
                "{token_key} must be nonempty ASCII without whitespace or control characters"
            )));
        }
        Ok(Self { host, token })
    }

    pub(super) fn agent(&self, timeout: Duration) -> Result<(ureq::Agent, String), MxcError> {
        let timeout = transport_budget(timeout)?;
        let tls = TlsConfig::builder()
            .provider(TlsProvider::NativeTls)
            .root_certs(RootCerts::PlatformVerifier);
        #[cfg(feature = "test-support")]
        let (tls, port) = test_tls(tls)?;
        #[cfg(feature = "test-support")]
        if port != 443 && self.host != "localhost" {
            return Err(MxcError::policy_validation(
                "W365 fixture ports require localhost",
            ));
        }
        #[cfg(not(feature = "test-support"))]
        let port = 443;
        let config = ureq::Agent::config_builder()
            .user_agent(USER_AGENT)
            .tls_config(tls.build())
            .timeout_global(Some(timeout))
            .max_redirects(0)
            .http_status_as_error(false)
            // Never send caller credentials through an ambient HTTP proxy.
            .proxy(None)
            .build();
        Ok((config.into(), format!("https://{}:{port}", self.host)))
    }

    pub(super) fn checkout(
        &self,
        config: &W365AgentsProvisionConfig,
    ) -> Result<ProvisionResult<CheckoutMetadata>, MxcError> {
        with_transport_stack(|| self.checkout_once(config)).map_err(|mut error| {
            if let Some(details) = error.details.as_mut() {
                details["poolId"] = json!(config.pool_id.to_ascii_lowercase());
            }
            error
        })
    }

    fn checkout_once(
        &self,
        config: &W365AgentsProvisionConfig,
    ) -> Result<ProvisionResult<CheckoutMetadata>, MxcError> {
        let pool = config.pool_id.to_ascii_lowercase();
        let request_id = uuid::Uuid::new_v4().to_string();
        let (agent, base) = self.agent(CHECKOUT_TIMEOUT)?;
        let url = format!("{base}/api/pools/{pool}/sessions?api-version=3.0");
        let mut request = agent
            .post(&url)
            .header("Authorization", format!("Bearer {}", self.token))
            .header("x-ms-client-request-id", &request_id);
        if let Some(kind) = &config.user_type {
            request = request.header("user-type", kind);
        }
        if let Some(oid) = &config.user_object_id {
            request = request.header("user-object-id", oid);
        }
        // One allocation attempt. No polling, retry, redirect or compensating release.
        let response = request.send_empty().map_err(|_| {
            failure(
                "checkout_transport",
                "checkout",
                None,
                &request_id,
                None,
                true,
                None,
            )
        })?;
        let status = response.status().as_u16();
        let server_id = safe_request_id(&response);
        let mut response = response;
        let value = response
            .body_mut()
            .with_config()
            .limit(MAX_RESPONSE)
            .read_to_string()
            .map_err(|_| {
                failure(
                    "checkout_response",
                    "checkout",
                    Some(status),
                    &request_id,
                    server_id.as_deref(),
                    true,
                    None,
                )
            })
            .and_then(|body| {
                // Never include response bodies or ticket-bearing metadata in diagnostics.
                serde_json::from_str::<Value>(&body).map_err(|_| {
                    failure(
                        "unparsable_response",
                        "checkout",
                        Some(status),
                        &request_id,
                        server_id.as_deref(),
                        true,
                        None,
                    )
                })
            });
        let session = value
            .as_ref()
            .ok()
            .and_then(|value| value.get("sessionId"))
            .and_then(Value::as_str)
            .filter(|id| guid(id));
        let identity = session.map(|id| Identity {
            pool_id: pool.clone(),
            session_id: id.to_ascii_lowercase(),
        });
        if !(200..300).contains(&status) {
            let code = match status {
                401 | 403 => "auth_denied",
                404 => "pool_not_found",
                429 => "checkout_throttled",
                500 => "provision_timeout",
                _ => "checkout_failed",
            };
            // Body failures must not replace the HTTP error; a valid ID still permits cleanup.
            return Err(failure(
                code,
                "checkout",
                Some(status),
                &request_id,
                server_id.as_deref(),
                status >= 500 || status == 408 || (200..400).contains(&status),
                identity.as_ref(),
            ));
        }
        let value = value?;
        let reject = |code| {
            failure(
                code,
                "checkout",
                Some(status),
                &request_id,
                server_id.as_deref(),
                true,
                identity.as_ref(),
            )
        };
        let identity = identity
            .as_ref()
            .ok_or_else(|| reject("malformed_session_id"))?;
        if status != 200 {
            return Err(reject("checkout_failed"));
        }
        if let Some(computer) = value.get("computerId") {
            if !computer
                .as_str()
                .is_some_and(|id| guid(id) && id.eq_ignore_ascii_case(&identity.session_id))
            {
                return Err(reject("id_mismatch"));
            }
        }
        if value.get("status").and_then(Value::as_str) != Some("Succeeded") {
            return Err(reject("provision_failed"));
        }
        Ok(ProvisionResult {
            sandbox_id: identity.encode(),
            metadata: Some(CheckoutMetadata {
                pool_id: pool,
                session_id: identity.session_id.clone(),
                computer_id: identity.session_id.clone(),
            }),
        })
    }

    pub(super) fn release(&self, identity: &Identity) -> Result<(), MxcError> {
        with_transport_stack(|| self.release_once(identity))
    }

    fn release_once(&self, identity: &Identity) -> Result<(), MxcError> {
        let request_id = uuid::Uuid::new_v4().to_string();
        let (agent, base) = self.agent(RELEASE_TIMEOUT)?;
        let url = format!(
            "{base}/api/sessions/{}?api-version=2.0",
            identity.session_id
        );
        let response = agent
            .delete(&url)
            .header("Authorization", format!("Bearer {}", self.token))
            .header("x-ms-client-request-id", &request_id)
            .header("x-ms-sessionId", &identity.session_id)
            .call()
            .map_err(|_| {
                failure(
                    "release_transport",
                    "release",
                    None,
                    &request_id,
                    None,
                    true,
                    Some(identity),
                )
            })?;
        let status = response.status().as_u16();
        if matches!(status, 200 | 202 | 204 | 404) {
            return Ok(());
        }
        Err(failure(
            if matches!(status, 401 | 403) {
                "auth_denied"
            } else {
                "release_failed"
            },
            "release",
            Some(status),
            &request_id,
            safe_request_id(&response).as_deref(),
            status >= 500 || status == 408 || (200..400).contains(&status),
            Some(identity),
        ))
    }
}

pub(super) fn safe_request_id(response: &ureq::http::Response<ureq::Body>) -> Option<String> {
    response
        .headers()
        .get("x-ms-request-id")
        .and_then(|v| v.to_str().ok())
        .filter(|v| {
            v.len() <= 128
                && v.bytes()
                    .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'))
        })
        .map(str::to_owned)
}

pub(super) fn failure(
    code: &str,
    operation: &str,
    status: Option<u16>,
    client_id: &str,
    server_id: Option<&str>,
    uncertain: bool,
    identity: Option<&Identity>,
) -> MxcError {
    let mut details = json!({
        "code": code, "operation": operation, "possiblySucceeded": uncertain,
        "clientRequestId": client_id,
    });
    if let Some(status) = status {
        details["httpStatus"] = json!(status);
    }
    if let Some(id) = server_id {
        details["requestId"] = json!(id);
    }
    if let Some(id) = identity {
        details["poolId"] = json!(id.pool_id);
        details["sessionId"] = json!(id.session_id);
        details["sandboxId"] = json!(id.encode());
    }
    let mut message = format!("w365_agents {operation} failed: {code}");
    if operation == "checkout" {
        message.push_str(&format!(
            "; clientRequestId={client_id}; possiblySucceeded={uncertain}"
        ));
        if let Some(id) = server_id {
            message.push_str(&format!("; requestId={id}"));
        }
        if let Some(id) = identity {
            message.push_str(&format!(
                "; checkout returned sandboxId {}; retain this ID for explicit release",
                id.encode()
            ));
        }
    }
    MxcError::backend_error(message).with_details(details)
}

#[cfg(feature = "test-support")]
fn test_tls(
    builder: ureq::tls::TlsConfigBuilder,
) -> Result<(ureq::tls::TlsConfigBuilder, u16), MxcError> {
    use ureq::tls::Certificate;
    let ca = std::env::var("MXC_W365_TEST_CA").ok();
    let port = std::env::var("MXC_W365_TEST_PORT").ok();
    match (ca, port) {
        (None, None) => Ok((builder, 443)),
        (Some(path), Some(port)) => {
            let bytes = std::fs::read(path)
                .map_err(|_| MxcError::policy_validation("cannot read fixture CA"))?;
            let cert = Certificate::from_pem(&bytes)
                .map_err(|_| MxcError::policy_validation("invalid fixture CA"))?;
            let port = port
                .parse()
                .map_err(|_| MxcError::policy_validation("invalid fixture port"))?;
            Ok((
                builder.root_certs(RootCerts::Specific(vec![cert].into())),
                port,
            ))
        }
        _ => Err(MxcError::policy_validation(
            "fixture CA and port must be supplied together",
        )),
    }
}