1pub const INTERNET_EGRESS_AVAILABLE: bool = false;
18
19pub const INTERNET_SANDBOX_UNAVAILABLE: &str = "Google Cloud internet egress through the egress \
22 gateway is not available yet. Use egress none, or deploy the sandbox on another cloud.";
23
24pub const DEFAULT_PLACEMENT_IS_PERMANENT: &str = "this sandbox uses Google's default network. \
28 A Google Cloud project whose first sandbox used the default network can never run sandboxes \
29 with egress `internet` through the deployment's egress gateway, even after every sandbox is \
30 deleted. To use egress `internet` later, deploy to a new project.";
31
32pub fn internet_egress_available() -> bool {
35 INTERNET_EGRESS_AVAILABLE || test_switch::forced()
36}
37
38pub fn internet_egress_available_for(stack: &crate::Stack) -> bool {
43 internet_egress_available()
44 && crate::sandbox_egress::gateway_image_serves_admin_protocol(
45 crate::sandbox_egress::planned_gateway_image(stack),
46 )
47}
48
49pub(crate) fn gateway_image_override() -> Option<&'static str> {
51 test_switch::gateway_image()
52}
53
54#[cfg(any(test, feature = "test-gcp-internet-egress"))]
55mod test_switch {
56 use std::cell::Cell;
57 use std::sync::atomic::{AtomicBool, Ordering};
58 use std::sync::OnceLock;
59
60 pub const FLIPPED_GATEWAY_IMAGE: &str = "ghcr.io/alienplatform/alien-egress-gateway@sha256:f99569e520d8aa9fd647c7c228e10e153fe4aefde0af54b2bbabd1298407b043";
64
65 thread_local! {
66 static FORCED: Cell<bool> = const { Cell::new(false) };
67 static IMAGE: Cell<Option<&'static str>> = const { Cell::new(None) };
68 }
69
70 static FORCED_FOR_PROCESS: AtomicBool = AtomicBool::new(false);
71 static IMAGE_FOR_PROCESS: OnceLock<&'static str> = OnceLock::new();
72
73 pub(super) fn forced() -> bool {
74 FORCED.with(Cell::get) || FORCED_FOR_PROCESS.load(Ordering::SeqCst)
75 }
76
77 pub(super) fn gateway_image() -> Option<&'static str> {
78 IMAGE
79 .with(Cell::get)
80 .or_else(|| IMAGE_FOR_PROCESS.get().copied())
81 }
82
83 pub fn enable_internet_egress_for_process() {
88 let _ = IMAGE_FOR_PROCESS.set(FLIPPED_GATEWAY_IMAGE);
89 FORCED_FOR_PROCESS.store(true, Ordering::SeqCst);
90 }
91
92 #[must_use = "the switch turns off again when the guard is dropped"]
94 pub struct InternetEgressForTest(());
95
96 impl Drop for InternetEgressForTest {
97 fn drop(&mut self) {
98 FORCED.with(|forced| forced.set(false));
99 IMAGE.with(|image| image.set(None));
100 }
101 }
102
103 pub fn enable_internet_egress_for_test() -> InternetEgressForTest {
107 enable_internet_egress_with_gateway_image_for_test(FLIPPED_GATEWAY_IMAGE)
108 }
109
110 pub fn enable_internet_egress_with_gateway_image_for_test(
113 image: &'static str,
114 ) -> InternetEgressForTest {
115 FORCED.with(|forced| forced.set(true));
116 IMAGE.with(|slot| slot.set(Some(image)));
117 InternetEgressForTest(())
118 }
119}
120
121#[cfg(not(any(test, feature = "test-gcp-internet-egress")))]
122mod test_switch {
123 pub(super) fn forced() -> bool {
124 false
125 }
126
127 pub(super) fn gateway_image() -> Option<&'static str> {
128 None
129 }
130}
131
132#[cfg(any(test, feature = "test-gcp-internet-egress"))]
133pub use test_switch::{
134 enable_internet_egress_for_process, enable_internet_egress_for_test,
135 enable_internet_egress_with_gateway_image_for_test, InternetEgressForTest,
136 FLIPPED_GATEWAY_IMAGE,
137};
138
139pub const ATTACHMENT_CIDR: &str = "192.168.250.0/28";
142
143pub const GATEWAY_CIDR: &str = "192.168.251.0/27";
145
146pub const GATEWAY_HOSTS: [u8; 2] = [10, 11];
149
150pub const CONTAINER_PROXY_PORT: u16 = 3128;
152
153pub const ADMIN_PORT: u16 = 3129;
156
157pub const DEFAULT_PROXY_PORT: u16 = 22;
162
163pub const GATEWAY_TAG: &str = "alien-sandbox-gateway";
165
166pub const ATTACHMENT_ROLE_PERMISSIONS: [&str; 2] = [
170 "compute.networkAttachments.get",
171 "compute.networkAttachments.update",
172];
173
174pub const ROLE_PROPAGATION_SECONDS: u64 = 180;
177
178pub fn resource_name(resource_prefix: &str, suffix: &str) -> String {
181 let full = format!("{resource_prefix}-{suffix}");
182 full.chars()
183 .take(63)
184 .collect::<String>()
185 .trim_matches('-')
186 .to_string()
187}
188
189pub fn role_id(resource_prefix: &str) -> String {
191 let full = format!("{resource_prefix}_sandbox_attachment");
192 full.chars()
193 .map(|c| {
194 if c.is_ascii_alphanumeric() || c == '.' {
195 c
196 } else {
197 '_'
198 }
199 })
200 .take(64)
201 .collect()
202}
203
204pub const DEFAULT_MACHINE_TYPE: &str = "e2-standard-2";
206
207pub const BOOT_IMAGE: &str = "projects/ubuntu-os-cloud/global/images/family/ubuntu-2404-lts-amd64";
209
210pub const BOOT_DISK_GB: u32 = 20;
212
213pub fn service_account_id(resource_prefix: &str) -> String {
216 format!("sbx-gw-{resource_prefix}")
217 .chars()
218 .take(30)
219 .collect::<String>()
220 .trim_matches('-')
221 .to_string()
222}
223
224pub fn secret_condition(project_number: &str, vault_prefix: &str, secrets: &[&str]) -> String {
227 secrets
228 .iter()
229 .map(|secret| {
230 format!(
231 "resource.name.startsWith(\"projects/{project_number}/secrets/{vault_prefix}-{secret}/\")"
232 )
233 })
234 .collect::<Vec<_>>()
235 .join(" || ")
236}
237
238pub mod suffix {
240 pub const ATTACHMENT_SUBNET: &str = "sbx-attachment";
241 pub const ATTACHMENT: &str = "sbx-attachment";
242 pub const GATEWAY_SUBNET: &str = "sbx-gateway";
243 pub const ROUTER: &str = "sbx-gateway-router";
244 pub const NAT: &str = "sbx-gateway-nat";
245 pub const GATEWAY_SERVICE_ACCOUNT: &str = "sandbox_gateway";
246 pub const FIREWALL_PROXY: &str = "sbx-allow-proxy";
247 pub const FIREWALL_ADMIN: &str = "sbx-allow-admin";
248 pub const FIREWALL_DENY: &str = "sbx-deny-attachment";
249
250 pub fn vm(index: usize) -> String {
252 format!("sbx-gateway-{index}")
253 }
254}
255
256#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub enum RuleSource {
259 Attachment,
261 Gateway,
263 Workload,
265}
266
267#[derive(Debug, Clone, PartialEq, Eq)]
270pub struct FirewallRule {
271 pub suffix: &'static str,
272 pub priority: u32,
273 pub allow: bool,
274 pub sources: Vec<RuleSource>,
275 pub tcp_ports: Option<Vec<u16>>,
277 pub gateway_only: bool,
279 pub log: bool,
280}
281
282pub fn firewall_rules(proxy_port: u16) -> Vec<FirewallRule> {
291 vec![
292 FirewallRule {
293 suffix: suffix::FIREWALL_PROXY,
294 priority: 900,
295 allow: true,
296 sources: vec![RuleSource::Attachment],
297 tcp_ports: Some(vec![proxy_port]),
298 gateway_only: true,
299 log: true,
300 },
301 FirewallRule {
302 suffix: suffix::FIREWALL_ADMIN,
303 priority: 900,
304 allow: true,
305 sources: vec![RuleSource::Gateway, RuleSource::Workload],
306 tcp_ports: Some(vec![ADMIN_PORT]),
307 gateway_only: true,
308 log: false,
309 },
310 FirewallRule {
311 suffix: suffix::FIREWALL_DENY,
312 priority: 1000,
313 allow: false,
314 sources: vec![RuleSource::Attachment],
315 tcp_ports: None,
316 gateway_only: false,
317 log: true,
318 },
319 ]
320}
321
322pub fn gateway_ips() -> Vec<String> {
324 let base = GATEWAY_CIDR
325 .split('/')
326 .next()
327 .expect("a CIDR has an address");
328 let prefix: Vec<&str> = base.split('.').take(3).collect();
329 GATEWAY_HOSTS
330 .iter()
331 .map(|host| format!("{}.{host}", prefix.join(".")))
332 .collect()
333}
334
335pub fn attachment_path(project: &str, region: &str, name: &str) -> String {
337 format!("projects/{project}/regions/{region}/networkAttachments/{name}")
338}
339
340pub const REGIONS_WITH_PRIVATE_SERVICE_CONNECT: &[&str] = &["us-central1"];
347
348pub fn region_refusal(region: &str) -> Option<String> {
350 if REGIONS_WITH_PRIVATE_SERVICE_CONNECT.contains(®ion) {
351 return None;
352 }
353 Some(format!(
354 "egress internet on GCP sends sandbox traffic through a Private Service Connect \
355 interface, which Agent Platform does not offer in {region}; use {}",
356 REGIONS_WITH_PRIVATE_SERVICE_CONNECT.join(" or ")
357 ))
358}
359
360pub const PLACEMENT_PINNED_MESSAGE: &str = "egress internet on GCP needs a project that has \
362never run a sandbox without the deployment network: Google pins a project's sandbox placement \
363with its first sandbox and cannot change it. Deploy to a new project, or use egress none";
364
365pub fn startup_script_template(image: &str) -> String {
372 let redirect = if DEFAULT_PROXY_PORT == CONTAINER_PROXY_PORT {
373 String::new()
374 } else {
375 format!(
376 "ExecStartPre=/bin/sh -c 'iptables -t nat -C PREROUTING -s {cidr} -p tcp --dport {port} -j REDIRECT --to-ports {to} || iptables -t nat -I PREROUTING 1 -s {cidr} -p tcp --dport {port} -j REDIRECT --to-ports {to}'",
377 cidr = ATTACHMENT_CIDR,
378 port = DEFAULT_PROXY_PORT,
379 to = CONTAINER_PROXY_PORT,
380 )
381 };
382 let lines = [
383 "#!/bin/bash".to_string(),
384 "set -u".to_string(),
385 "for i in $(seq 1 30); do apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y docker.io iptables && break; sleep 10; done".to_string(),
386 format!("for i in $(seq 1 30); do docker pull {image} && break; sleep 10; done"),
387 "umask 077".to_string(),
388 "cat > /etc/alien-egress-gateway.env <<'ENV'".to_string(),
389 "ALIEN_DEPLOYMENT_TYPE=gcp".to_string(),
390 "GCP_PROJECT_ID=%s".to_string(),
391 "GCP_REGION=%s".to_string(),
392 "ALIEN_SECRETS_BINDING=%s".to_string(),
393 "RUST_LOG=warn".to_string(),
394 "ENV".to_string(),
395 "cat > /etc/systemd/system/alien-egress-gateway.service <<'UNIT'".to_string(),
396 "[Unit]".to_string(),
397 "Description=Alien egress gateway".to_string(),
398 "After=docker.service network-online.target".to_string(),
399 "Requires=docker.service".to_string(),
400 "[Service]".to_string(),
401 "Restart=always".to_string(),
402 "RestartSec=3".to_string(),
403 "ExecStartPre=-/usr/bin/docker rm -f gateway".to_string(),
404 redirect,
405 format!("ExecStart=/usr/bin/docker run --name gateway --env-file /etc/alien-egress-gateway.env --user 1000:1000 --cap-drop ALL --memory 2g --security-opt no-new-privileges --read-only --tmpfs /tmp -p {CONTAINER_PROXY_PORT}:{CONTAINER_PROXY_PORT} -p {ADMIN_PORT}:{ADMIN_PORT} {image}"),
406 "[Install]".to_string(),
407 "WantedBy=multi-user.target".to_string(),
408 "UNIT".to_string(),
409 "systemctl daemon-reload".to_string(),
410 "systemctl enable alien-egress-gateway.service".to_string(),
411 "systemctl restart alien-egress-gateway.service".to_string(),
412 ];
413 let mut text = lines
414 .into_iter()
415 .filter(|line| !line.is_empty())
416 .collect::<Vec<_>>()
417 .join("\n");
418 text.push('\n');
419 text
420}
421
422pub fn startup_script(image: &str, project: &str, region: &str, vault_prefix: &str) -> String {
424 let binding = serde_json::json!({"service": "secret-manager", "vaultPrefix": vault_prefix});
425 let mut values = [project.to_string(), region.to_string(), binding.to_string()].into_iter();
426 let mut out = String::new();
427 let mut rest = startup_script_template(image);
428 while let Some(index) = rest.find("%s") {
429 out.push_str(&rest[..index]);
430 out.push_str(&values.next().expect("three values"));
431 rest = rest[index + 2..].to_string();
432 }
433 out.push_str(&rest);
434 out
435}
436
437#[cfg(test)]
438mod tests {
439 use super::*;
440
441 #[test]
444 fn internet_egress_is_off_until_the_switch_flips() {
445 assert!(!INTERNET_EGRESS_AVAILABLE);
446 assert!(!internet_egress_available());
447 {
448 let _on = enable_internet_egress_for_test();
449 assert!(internet_egress_available());
450 std::thread::spawn(|| assert!(!internet_egress_available()))
451 .join()
452 .unwrap();
453 }
454 assert!(!internet_egress_available());
455 }
456
457 #[test]
460 fn internet_egress_needs_a_gateway_image_that_serves_the_admin_protocol() {
461 let stack = crate::Stack::new("s".into()).build();
462 assert!(!internet_egress_available_for(&stack));
463 {
464 let _on = enable_internet_egress_with_gateway_image_for_test(
465 crate::sandbox_egress::SANDBOX_EGRESS_GATEWAY_IMAGE,
466 );
467 assert_eq!(
468 internet_egress_available_for(&stack),
469 crate::sandbox_egress::gateway_image_serves_admin_protocol(
470 crate::sandbox_egress::SANDBOX_EGRESS_GATEWAY_IMAGE
471 )
472 );
473 }
474 {
475 let _on = enable_internet_egress_for_test();
476 assert!(crate::sandbox_egress::gateway_image_serves_admin_protocol(
477 FLIPPED_GATEWAY_IMAGE
478 ));
479 assert!(crate::sandbox_egress::gateway_image_serves_links(
480 FLIPPED_GATEWAY_IMAGE
481 ));
482 assert_eq!(
483 crate::sandbox_egress::planned_gateway_image(&stack),
484 FLIPPED_GATEWAY_IMAGE
485 );
486 assert!(internet_egress_available_for(&stack));
487 }
488 assert_eq!(
489 crate::sandbox_egress::installed_gateway_image(),
490 crate::sandbox_egress::SANDBOX_EGRESS_GATEWAY_IMAGE
491 );
492 }
493
494 #[test]
495 fn the_boot_script_fills_its_three_values_and_names_the_port_from_the_constant() {
496 let text = startup_script(
497 "registry.example/gw@sha256:abc",
498 "proj",
499 "us-central1",
500 "p-secrets",
501 );
502 assert!(!text.contains("%s"), "{text}");
503 assert!(text.contains("GCP_PROJECT_ID=proj") && text.contains("GCP_REGION=us-central1"));
504 assert!(
505 text.contains(r#"{"service":"secret-manager","vaultPrefix":"p-secrets"}"#),
506 "{text}"
507 );
508 assert!(text.contains(&format!("--dport {DEFAULT_PROXY_PORT}")));
509 assert_eq!(startup_script_template("i").matches("%s").count(), 3);
510 }
511
512 #[test]
513 fn the_service_account_id_fits_the_limit() {
514 assert_eq!(service_account_id("acme"), "sbx-gw-acme");
515 let long = service_account_id(&format!("{}-", "a".repeat(40)));
516 assert!(long.len() <= 30 && !long.ends_with('-'), "{long}");
517 }
518
519 #[test]
520 fn the_secret_condition_names_each_secret_path() {
521 let text = secret_condition("123", "p-secrets", &["a", "b"]);
522 assert_eq!(
523 text,
524 r#"resource.name.startsWith("projects/123/secrets/p-secrets-a/") || resource.name.startsWith("projects/123/secrets/p-secrets-b/")"#
525 );
526 }
527
528 #[test]
529 fn names_are_clamped_and_never_end_in_a_dash() {
530 let name = resource_name(&"a".repeat(70), "sbx-attachment");
531 assert!(name.len() <= 63);
532 assert!(!name.ends_with('-'));
533 assert_eq!(resource_name("acme", "sbx-gateway-0"), "acme-sbx-gateway-0");
534 }
535
536 #[test]
537 fn the_gateway_addresses_sit_in_the_gateway_range() {
538 assert_eq!(gateway_ips(), vec!["192.168.251.10", "192.168.251.11"]);
539 }
540
541 #[test]
542 fn only_the_proxy_port_is_open_to_the_attachment() {
543 for port in [DEFAULT_PROXY_PORT, 2222] {
544 let rules = firewall_rules(port);
545 for rule in rules.iter().filter(|r| r.allow) {
546 if rule.sources.contains(&RuleSource::Attachment) {
547 assert_eq!(rule.tcp_ports, Some(vec![port]));
548 assert!(rule.gateway_only);
549 }
550 }
551 let deny = rules.iter().find(|r| !r.allow).unwrap();
552 assert!(
553 deny.log
554 && deny.priority
555 > rules
556 .iter()
557 .filter(|r| r.allow)
558 .map(|r| r.priority)
559 .max()
560 .unwrap()
561 );
562 assert!(!rules
563 .iter()
564 .any(|r| r.sources.contains(&RuleSource::Attachment)
565 && r.tcp_ports == Some(vec![ADMIN_PORT])));
566 }
567 }
568
569 #[test]
570 fn a_region_without_private_service_connect_is_refused_by_name() {
571 for region in ["us-east4", "europe-west4", "asia-southeast1"] {
572 let text = region_refusal(region).expect("refused");
573 assert!(text.contains(region) && text.contains("us-central1"));
574 }
575 assert!(region_refusal("us-central1").is_none());
576 }
577}