alien-bindings 3.3.73

Alien direct in-process resource bindings
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
use super::*;
use crate::{
    sandbox_egress::tests::Harness,
    traits::{CreateSandboxRequest, Sandbox as SandboxTrait},
};
use alien_azure_clients::azure::sandbox_data_plane::{CreateSandbox, MockSandboxDataPlaneApi};
use alien_client_core::ErrorData as ClientError;
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use std::sync::Mutex;

type Record = Arc<Mutex<Option<Sandbox>>>;
type Request = Arc<Mutex<Option<CreateSandbox>>>;

// Azure returns the enforced HTTP policy both flat and under `http`.
fn readback_policy(policy: &EgressPolicy) -> EgressPolicy {
    let mut value = serde_json::to_value(policy).unwrap();
    value["enforcementMode"] = serde_json::json!("Enforced");
    value["http"] = value.clone();
    serde_json::from_value(value).unwrap()
}

fn provider(manager: SandboxEgressManager, corrupt: bool) -> (AzureSandbox, Record, Request) {
    let record: Record = Arc::new(Mutex::new(None));
    let request: Request = Arc::new(Mutex::new(None));
    let mut client = MockSandboxDataPlaneApi::new();
    let saved = record.clone();
    let submitted = request.clone();
    client
        .expect_create_sandbox()
        .times(1)
        .returning(move |_, req| {
            assert_eq!(
                req.customer_vnet_connection_name.as_deref(),
                Some("default")
            );
            let mut labels = req.labels.clone();
            if corrupt {
                labels.remove(IDENTITY_LABEL);
            }
            let sandbox = Sandbox {
                id: "571fa784-7be7-5d9e-9cff-8e9a11414684".into(),
                labels,
                vnet_connection_name: Some("default".into()),
                egress_policy: req.egress.as_ref().map(readback_policy),
                state: Some("Running".into()),
            };
            *submitted.lock().unwrap() = Some(req);
            *saved.lock().unwrap() = Some(sandbox.clone());
            Ok(sandbox)
        });
    let saved = record.clone();
    client.expect_get_sandbox().returning(move |_, id| {
        assert_eq!(id, "571fa784-7be7-5d9e-9cff-8e9a11414684");
        saved.lock().unwrap().clone().ok_or_else(|| {
            AlienError::new(ClientError::HttpResponseError {
                message: "not found".into(),
                url: "https://example.invalid/sandboxes/vendor-id".into(),
                http_status: 404,
                http_request_text: None,
                http_response_text: None,
            })
        })
    });
    let saved = record.clone();
    client
        .expect_delete_sandbox()
        .times(1)
        .returning(move |_, id| {
            assert_eq!(id, "571fa784-7be7-5d9e-9cff-8e9a11414684");
            saved.lock().unwrap().take();
            Ok(())
        });
    let sandbox = AzureSandbox::new(
        Arc::new(client),
        "group".into(),
        "ubuntu".into(),
        alien_core::SandboxEgress::Internet,
        None,
        "1000m".into(),
        "2048Mi".into(),
        None,
    )
    .with_egress_manager(
        Arc::new(manager),
        Some(RuntimePolicy::Allow {
            allow: vec!["api.example.com".into()],
        }),
    );
    (sandbox, record, request)
}

#[tokio::test]
async fn an_agent_sandbox_boots_behind_a_60s_gateway_startup_gate() {
    let h = Harness::new().await;
    let mut sandbox = AzureSandbox::new(
        Arc::new(MockSandboxDataPlaneApi::new()),
        "group".into(),
        "ubuntu".into(),
        alien_core::SandboxEgress::Internet,
        None,
        "1000m".into(),
        "2048Mi".into(),
        None,
    )
    .with_egress_manager(Arc::new(h.reopen().await), None);
    sandbox.agent = true;
    let mut env = BTreeMap::new();
    let mut labels = BTreeMap::from([(
        SANDBOX_EXPIRY_LABEL.to_string(),
        (chrono::Utc::now().timestamp_millis() + 600_000).to_string(),
    )]);
    sandbox
        .prepare_identity(&mut env, &mut labels)
        .await
        .unwrap();
    assert_eq!(env["ALIEN_SANDBOX_STARTUP_EGRESS_GATE"], "1");
    assert_eq!(env["ALIEN_SANDBOX_STARTUP_GATE_VNET"], "1");
    assert_eq!(env["ALIEN_SANDBOX_STARTUP_GATE_BOUND_SECS"], "60");
    assert!(env["ALIEN_SANDBOX_STARTUP_GATE_CONTROL"].contains(':'));
    // That variable makes the agent install its in-guest transparent redirect, which the Azure
    // kernel cannot run (no nftables, no `ip rule`); the agent would never become ready.
    assert!(!env.contains_key("ALIEN_SANDBOX_EGRESS_GATEWAY"));
    assert_eq!(
        env["ALIEN_SANDBOX_MUST_DROP_PUBLIC"],
        "1.1.1.1:8443,1.1.1.1:8080"
    );
}

#[tokio::test]
async fn an_agent_sandbox_with_two_gateway_replicas_proxies_through_a_loopback_failover() {
    let h = Harness::new().await;
    let mut sandbox = AzureSandbox::new(
        Arc::new(MockSandboxDataPlaneApi::new()),
        "group".into(),
        "ubuntu".into(),
        alien_core::SandboxEgress::Internet,
        None,
        "1000m".into(),
        "2048Mi".into(),
        None,
    )
    .with_egress_manager(
        Arc::new(h.reopen_with_replicas(&["10.0.6.4", "10.0.6.5"]).await),
        None,
    );
    sandbox.agent = true;
    let mut env = BTreeMap::new();
    let mut labels = BTreeMap::from([(
        SANDBOX_EXPIRY_LABEL.to_string(),
        (chrono::Utc::now().timestamp_millis() + 600_000).to_string(),
    )]);
    sandbox
        .prepare_identity(&mut env, &mut labels)
        .await
        .unwrap();
    // Neither replica's address is in a command's environment: the agent forwards to both.
    for name in ["HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy"] {
        assert!(env[name].starts_with("http://alien:"), "{name}");
        assert!(env[name].ends_with("@127.0.0.1:18128"), "{}", env[name]);
    }
    assert_eq!(
        env["ALIEN_SANDBOX_PROXY_REPLICAS"],
        "10.0.6.4:3128,10.0.6.5:3128"
    );
    assert_eq!(env["ALIEN_SANDBOX_PROXY_LISTEN"], "127.0.0.1:18128");
    // Either replica proves the path at startup.
    assert_eq!(
        env["ALIEN_SANDBOX_STARTUP_GATE_CONTROL"],
        "10.0.6.4:3128,10.0.6.5:3128"
    );
}

#[tokio::test]
async fn an_image_without_the_agent_keeps_the_single_gateway_address() {
    let h = Harness::new().await;
    let sandbox = AzureSandbox::new(
        Arc::new(MockSandboxDataPlaneApi::new()),
        "group".into(),
        "ubuntu".into(),
        alien_core::SandboxEgress::Internet,
        None,
        "1000m".into(),
        "2048Mi".into(),
        None,
    )
    .with_egress_manager(
        Arc::new(h.reopen_with_replicas(&["10.0.6.4", "10.0.6.5"]).await),
        None,
    );
    let mut env = BTreeMap::new();
    let mut labels = BTreeMap::from([(
        SANDBOX_EXPIRY_LABEL.to_string(),
        (chrono::Utc::now().timestamp_millis() + 600_000).to_string(),
    )]);
    sandbox
        .prepare_identity(&mut env, &mut labels)
        .await
        .unwrap();
    assert!(env["HTTPS_PROXY"].ends_with("@10.0.6.4:3128"));
    assert!(!env.contains_key("ALIEN_SANDBOX_PROXY_REPLICAS"));
}

#[tokio::test]
async fn durable_identity_drives_create_reconnect_update_and_termination() {
    let h = Harness::new().await;
    let (sandbox, record, request) = provider(h.reopen().await, false);
    let created = sandbox
        .create(CreateSandboxRequest {
            env: BTreeMap::from([
                ("HTTPS_PROXY".into(), "http://wrong.invalid".into()),
                ("no_proxy".into(), "*".into()),
            ]),
            ..Default::default()
        })
        .await
        .unwrap();
    assert_eq!(created.sandbox_id, "571fa784-7be7-5d9e-9cff-8e9a11414684");
    let req = request.lock().unwrap().clone().unwrap();
    let id = req.labels[IDENTITY_LABEL].clone();
    assert_ne!(id, "571fa784-7be7-5d9e-9cff-8e9a11414684");
    let proxy = req.environment["HTTPS_PROXY"]
        .strip_prefix("http://alien:")
        .unwrap();
    let token = proxy.split('@').next().unwrap();
    let claims: serde_json::Value = serde_json::from_slice(
        &URL_SAFE_NO_PAD
            .decode(token.split('.').nth(1).unwrap())
            .unwrap(),
    )
    .unwrap();
    assert_eq!(claims["sub"], id);
    assert_eq!(
        claims["exp"].as_i64().unwrap(),
        req.labels[SANDBOX_EXPIRY_LABEL].parse::<i64>().unwrap() / 1000
    );
    assert!(
        claims["exp"].as_i64().unwrap() - claims["iat"].as_i64().unwrap()
            <= i64::from(alien_core::AZURE_GATEWAY_MAX_LIFETIME_SECONDS)
    );
    assert_eq!(req.environment["no_proxy"], "localhost,127.0.0.1");
    assert_eq!(
        req.environment["http_proxy"],
        req.environment["HTTPS_PROXY"]
    );
    assert_eq!(
        h.policy(&id),
        Some(RuntimePolicy::Allow {
            allow: vec!["api.example.com".into()]
        })
    );
    assert_eq!(h.policy("571fa784-7be7-5d9e-9cff-8e9a11414684"), None);
    let floor = req.egress.unwrap();
    assert_eq!(floor.default_action, "Allow");
    assert_eq!(floor.traffic_inspection.as_deref(), Some("Partial"));
    // Azure refuses a host:port pattern, and an IP host rule would not open a TCP port anyway:
    // the single catch-all closes the :80/:443 interposer and the NSG carries the gateway path.
    assert_eq!(floor.host_rules.len(), 1);
    assert_eq!(floor.host_rules[0].action, "Deny");
    assert_eq!(floor.host_rules[0].pattern, "*");

    // Reopening the manager loses all in-process state; the provider label remains authoritative.
    let reopened = AzureSandbox {
        egress_manager: Some(Arc::new(h.reopen().await)),
        ..sandbox
    };
    let empty = RuntimePolicy::Allow { allow: vec![] };
    reopened
        .update_egress("571fa784-7be7-5d9e-9cff-8e9a11414684", empty.clone())
        .await
        .unwrap();
    assert_eq!(h.policy(&id), Some(empty.clone()));
    // An omitted policy on reconnect must preserve narrowing, even with a resource default.
    let preserved = reopened
        .get_or_create(CreateSandboxRequest {
            sandbox_id: Some("571fa784-7be7-5d9e-9cff-8e9a11414684".into()),
            ..Default::default()
        })
        .await
        .unwrap();
    assert_eq!(
        preserved.sandbox.sandbox_id,
        "571fa784-7be7-5d9e-9cff-8e9a11414684"
    );
    assert_eq!(h.policy(&id), Some(empty));
    let resolved = reopened
        .get_or_create(CreateSandboxRequest {
            sandbox_id: Some("571fa784-7be7-5d9e-9cff-8e9a11414684".into()),
            egress: Some(RuntimePolicy::Internet),
            ..Default::default()
        })
        .await
        .unwrap();
    assert_eq!(
        resolved.sandbox.sandbox_id,
        "571fa784-7be7-5d9e-9cff-8e9a11414684"
    );
    assert_eq!(h.policy(&id), Some(RuntimePolicy::Internet));
    record.lock().unwrap().as_mut().unwrap().state = Some("Suspended".into());
    reopened
        .update_egress(
            "571fa784-7be7-5d9e-9cff-8e9a11414684",
            RuntimePolicy::Allow { allow: vec![] },
        )
        .await
        .unwrap();
    assert_eq!(h.policy(&id), Some(RuntimePolicy::Allow { allow: vec![] }));
    reopened
        .terminate("571fa784-7be7-5d9e-9cff-8e9a11414684")
        .await
        .unwrap();
    assert!(record.lock().unwrap().is_none());
    assert_eq!(h.policy(&id), None);
}

#[tokio::test]
async fn total_gateway_state_loss_requires_an_explicit_policy() {
    let h = Harness::new().await;
    let (sandbox, _, request) = provider(h.reopen().await, false);
    sandbox
        .create(CreateSandboxRequest::default())
        .await
        .unwrap();
    let id = request.lock().unwrap().as_ref().unwrap().labels[IDENTITY_LABEL].clone();
    let empty = RuntimePolicy::Allow { allow: vec![] };
    sandbox
        .update_egress("571fa784-7be7-5d9e-9cff-8e9a11414684", empty.clone())
        .await
        .unwrap();
    h.lose_policy_state();

    // Reconnect must not replay the resource default or the earlier create-time policy.
    h.refuse_writes(true);
    assert!(sandbox
        .get("571fa784-7be7-5d9e-9cff-8e9a11414684")
        .await
        .unwrap()
        .is_some());
    let found = sandbox
        .get_or_create(CreateSandboxRequest {
            sandbox_id: Some("571fa784-7be7-5d9e-9cff-8e9a11414684".into()),
            ..Default::default()
        })
        .await
        .unwrap();
    assert_eq!(
        found.sandbox.sandbox_id,
        "571fa784-7be7-5d9e-9cff-8e9a11414684"
    );
    assert_eq!(h.policy(&id), None);
    h.refuse_writes(false);

    sandbox
        .update_egress("571fa784-7be7-5d9e-9cff-8e9a11414684", empty.clone())
        .await
        .unwrap();
    assert_eq!(h.policy(&id), Some(empty.clone()));
    h.lose_policy_state();
    sandbox
        .get_or_create(CreateSandboxRequest {
            sandbox_id: Some("571fa784-7be7-5d9e-9cff-8e9a11414684".into()),
            egress: Some(empty.clone()),
            ..Default::default()
        })
        .await
        .unwrap();
    assert_eq!(h.policy(&id), Some(empty));
    sandbox
        .terminate("571fa784-7be7-5d9e-9cff-8e9a11414684")
        .await
        .unwrap();
}

#[tokio::test]
async fn missing_identity_on_readback_discards_the_sandbox_without_publishing_policy() {
    let h = Harness::new().await;
    let (sandbox, record, request) = provider(h.reopen().await, true);
    let error = sandbox
        .create(CreateSandboxRequest::default())
        .await
        .unwrap_err();
    assert_eq!(error.code, "SANDBOX_NOT_AS_DECLARED");
    assert!(record.lock().unwrap().is_none());
    let id = request.lock().unwrap().as_ref().unwrap().labels[IDENTITY_LABEL].clone();
    assert_eq!(h.policy(&id), None);
}

#[tokio::test]
async fn a_changed_native_floor_is_refused_before_policy_updates() {
    let h = Harness::new().await;
    let (sandbox, record, request) = provider(h.reopen().await, false);
    sandbox
        .create(CreateSandboxRequest::default())
        .await
        .unwrap();
    let id = request.lock().unwrap().as_ref().unwrap().labels[IDENTITY_LABEL].clone();
    record
        .lock()
        .unwrap()
        .as_mut()
        .unwrap()
        .egress_policy
        .as_mut()
        .unwrap()
        .host_rules[0]
        .pattern = "example.com".into();
    let error = sandbox
        .update_egress(
            "571fa784-7be7-5d9e-9cff-8e9a11414684",
            RuntimePolicy::Internet,
        )
        .await
        .unwrap_err();
    assert_eq!(error.code, "SANDBOX_NOT_AS_DECLARED");
    assert_eq!(
        h.policy(&id),
        Some(RuntimePolicy::Allow {
            allow: vec!["api.example.com".into()]
        })
    );
    // Teardown still revokes and deletes a sandbox whose floor no longer matches.
    sandbox
        .terminate("571fa784-7be7-5d9e-9cff-8e9a11414684")
        .await
        .unwrap();
    assert_eq!(h.policy(&id), None);
}

#[tokio::test]
async fn admin_failure_discards_create_and_does_not_prevent_termination() {
    let h = Harness::new().await;
    let (sandbox, record, request) = provider(h.reopen().await, false);
    h.refuse_writes(true);
    sandbox
        .create(CreateSandboxRequest::default())
        .await
        .expect_err("policy registration refused");
    assert!(record.lock().unwrap().is_none());
    let id = request.lock().unwrap().as_ref().unwrap().labels[IDENTITY_LABEL].clone();
    assert_eq!(h.policy(&id), None);

    h.refuse_writes(false);
    let (sandbox, record, request) = provider(h.reopen().await, false);
    sandbox
        .create(CreateSandboxRequest::default())
        .await
        .unwrap();
    let id = request.lock().unwrap().as_ref().unwrap().labels[IDENTITY_LABEL].clone();
    h.refuse_writes(true);
    sandbox
        .terminate("571fa784-7be7-5d9e-9cff-8e9a11414684")
        .await
        .expect_err("revocation failure reported");
    assert!(
        record.lock().unwrap().is_none(),
        "vendor deletion still completes"
    );
    assert!(
        h.policy(&id).is_some(),
        "failed revocation is not claimed as success"
    );
}

#[tokio::test(start_paused = true)]
async fn a_failed_publish_keeps_its_cause_and_retryability_when_the_revocation_also_fails() {
    let h = Harness::new().await;
    // Both replicas are away (nothing listens there), so no replica acknowledges the new grant and
    // the cleanup revocation cannot reach any either.
    let (sandbox, record, _) = provider(
        h.reopen_with_replicas(&["127.0.0.1", "127.0.0.2"]).await,
        false,
    );
    let error = sandbox
        .create(CreateSandboxRequest::default())
        .await
        .expect_err("publish refused");
    assert!(record.lock().unwrap().is_none(), "the sandbox is discarded");
    assert_eq!(
        error.code, "SANDBOX_EGRESS_GATEWAY_UNAVAILABLE",
        "{error:?}"
    );
    assert!(error.source.is_none(), "no revocation wrapper: {error:?}");
    assert!(
        error.retryable,
        "the publish failure is retryable and the revocation failure must not override it: {error:?}"
    );
}

#[tokio::test]
async fn gateway_readback_refuses_changed_or_unknown_enforcement() {
    let h = Harness::new().await;
    let (sandbox, record, _) = provider(h.reopen().await, false);
    sandbox
        .create(CreateSandboxRequest::default())
        .await
        .unwrap();
    let expected = record
        .lock()
        .unwrap()
        .as_ref()
        .unwrap()
        .egress_policy
        .clone()
        .unwrap();
    let changes = [
        ("/enforcementMode", serde_json::json!("Audit")),
        ("/http/enforcementMode", serde_json::json!("Audit")),
        ("/http/defaultAction", serde_json::json!("Deny")),
        ("/http/hostRules/0/action", serde_json::json!("Allow")),
        ("/hostRules/0/pattern", serde_json::json!("example.com")),
        ("/http", serde_json::json!(null)),
    ];
    for (path, value) in changes {
        let mut altered = serde_json::to_value(&expected).unwrap();
        *altered.pointer_mut(path).unwrap() = value;
        record.lock().unwrap().as_mut().unwrap().egress_policy =
            Some(serde_json::from_value(altered).unwrap());
        let error = sandbox
            .get("571fa784-7be7-5d9e-9cff-8e9a11414684")
            .await
            .unwrap_err();
        assert_eq!(error.code, "SANDBOX_NOT_AS_DECLARED", "{path}");
    }
    for path in ["", "/http"] {
        let mut altered = serde_json::to_value(&expected).unwrap();
        altered.pointer_mut(path).unwrap()["bypass"] = serde_json::json!(true);
        record.lock().unwrap().as_mut().unwrap().egress_policy =
            Some(serde_json::from_value(altered).unwrap());
        let error = sandbox
            .get("571fa784-7be7-5d9e-9cff-8e9a11414684")
            .await
            .unwrap_err();
        assert_eq!(error.code, "SANDBOX_NOT_AS_DECLARED", "{path}/bypass");
    }
    record.lock().unwrap().as_mut().unwrap().egress_policy = Some(expected);
    assert!(sandbox
        .get("571fa784-7be7-5d9e-9cff-8e9a11414684")
        .await
        .unwrap()
        .is_some());
    sandbox
        .terminate("571fa784-7be7-5d9e-9cff-8e9a11414684")
        .await
        .unwrap();
}