Skip to main content

alien_core/
gcp_sandbox_gateway.rs

1//! The GCP wiring that sends every Internet sandbox's outbound traffic through the egress gateway.
2//!
3//! Agent Platform connects a sandbox to the deployment's VPC through a Private Service Connect
4//! interface: a network attachment on a dedicated subnet. Traffic from the sandbox enters the VPC
5//! from that subnet, and the firewall lets it reach the gateway's proxy and nothing else.
6//!
7//! Setup creates the wiring twice, as Terraform and as direct API calls. Both render from the
8//! description in this file (names, ranges, ports, role permissions and firewall rules), and a
9//! differential test compares the two, so the two setup surfaces cannot drift apart.
10
11/// The one switch for Google Cloud internet egress through the gateway. While it is `false`,
12/// every plan-time path (build, release, the Terraform and CloudFormation render, deployment
13/// preparation) refuses a Google Cloud sandbox with egress `internet`, so no setup creates the
14/// network attachment, the gateway VMs or Private Service Connect resources, and no template
15/// pins a project to Private Service Connect. Flipping it to `true` is the whole release step,
16/// once the on-demand live test (`alien-test`, `gcp_sandbox_internet_live`) passes.
17pub const INTERNET_EGRESS_AVAILABLE: bool = false;
18
19/// The refusal while [`INTERNET_EGRESS_AVAILABLE`] is off. Build, render and deployment checks
20/// all give this text.
21pub 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
24/// Said at plan time for a Google Cloud sandbox on Google's default network. The first sandbox a
25/// project runs fixes its networking for good, so a project that started on the default network
26/// can never host a gateway-backed `internet` sandbox.
27pub 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
32/// Whether Google Cloud sandboxes may declare egress `internet`: the switch, or a test that
33/// turned it on for its own thread or its whole process.
34pub fn internet_egress_available() -> bool {
35    INTERNET_EGRESS_AVAILABLE || test_switch::forced()
36}
37
38/// Whether this stack's Google Cloud internet sandboxes can be planned: the switch is on and the
39/// gateway image setup will run serves the admin protocol the sandbox binding requires. A gateway
40/// without it would fail every sandbox create after setup built the gateway VMs, so the flip
41/// also bumps the release's gateway pin. Build, render and deployment checks all ask this.
42pub 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
49/// The gateway image a test installs in place of the release pin, if one turned it on.
50pub(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    /// The released public gateway image the flip pins (v3.3.76, by digest). It serves the admin
61    /// protocol the sandbox binding requires and reads sandbox links, and it is what the live
62    /// test runs.
63    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    /// Turns Google Cloud internet egress on for every thread of this process, for good, with
84    /// [`FLIPPED_GATEWAY_IMAGE`] as the gateway: the live test, whose build, manager and
85    /// controllers run on the runtime's worker threads, plans and deploys the stack the flipped
86    /// release would. Never used by unit tests, which share a process and must see the switch off.
87    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    /// Keeps the switch on for the current thread until it is dropped.
93    #[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    /// Turns Google Cloud internet egress on for the current thread, as the flip release would:
104    /// the switch on and [`FLIPPED_GATEWAY_IMAGE`] as the gateway. Tests only; production code
105    /// never reaches this.
106    pub fn enable_internet_egress_for_test() -> InternetEgressForTest {
107        enable_internet_egress_with_gateway_image_for_test(FLIPPED_GATEWAY_IMAGE)
108    }
109
110    /// Turns the switch on for the current thread with `image` as the gateway, for a test of a
111    /// flip that did not bump the gateway pin.
112    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
139/// Range of the attachment's own subnet. Sandbox traffic enters the VPC from addresses in it. A
140/// regular subnet of at least /28 that is not 100.64.0.0/20 or 240.0.0.0/4.
141pub const ATTACHMENT_CIDR: &str = "192.168.250.0/28";
142
143/// Range of the gateway subnet, the only subnet with Cloud NAT.
144pub const GATEWAY_CIDR: &str = "192.168.251.0/27";
145
146/// Host numbers of the two gateway VMs inside the gateway subnet (`.10` and `.11`). GCP reserves
147/// the first two and last two addresses of a subnet.
148pub const GATEWAY_HOSTS: [u8; 2] = [10, 11];
149
150/// The port the gateway container's proxy listens on.
151pub const CONTAINER_PROXY_PORT: u16 = 3128;
152
153/// The port of the gateway's authenticated policy administration. Never reachable from the
154/// attachment range.
155pub const ADMIN_PORT: u16 = 3129;
156
157/// The port the sandboxes connect to on the gateway VMs, the one setting that says which port
158/// crosses from Agent Platform's tenant into the VPC. Only tcp/22 does today (measured, not
159/// documented by Google). Every place that needs the port reads it from the setup-recorded
160/// network data, which setup writes from this default.
161pub const DEFAULT_PROXY_PORT: u16 = 22;
162
163/// The network tag the gateway VMs carry and the firewall rules target.
164pub const GATEWAY_TAG: &str = "alien-sandbox-gateway";
165
166/// Permissions the Agent Platform service agent needs on the attachment. It must hold them, and
167/// they must have propagated, before the first template names the attachment: a template that
168/// fails on them leaves that attachment unusable for good.
169pub const ATTACHMENT_ROLE_PERMISSIONS: [&str; 2] = [
170    "compute.networkAttachments.get",
171    "compute.networkAttachments.update",
172];
173
174/// Seconds setup waits after binding the role, before anything creates a template. Three minutes
175/// worked in a measurement and ninety seconds did not.
176pub const ROLE_PROPAGATION_SECONDS: u64 = 180;
177
178/// A name the wiring gives a resource: `{resource prefix}-{suffix}`, at most 63 characters with no
179/// leading or trailing dash. Terraform computes the same string in HCL.
180pub 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
189/// Custom role ids allow letters, digits, `_` and `.`, at most 64 characters.
190pub 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
204/// The gateway VMs' machine type unless the setup says otherwise: at least 2 vCPUs and 4 GiB.
205pub const DEFAULT_MACHINE_TYPE: &str = "e2-standard-2";
206
207/// The gateway VMs' boot image.
208pub const BOOT_IMAGE: &str = "projects/ubuntu-os-cloud/global/images/family/ubuntu-2404-lts-amd64";
209
210/// The gateway VMs' boot disk size.
211pub const BOOT_DISK_GB: u32 = 20;
212
213/// Account id of the gateways' identity: `sbx-gw-` and the prefix, at most 30 characters and
214/// never ending in a dash. The Terraform emitter renders the same with `trim(substr(..))`.
215pub 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
224/// The condition that limits the gateways' secret access to the given secrets of the deployment
225/// vault. `secrets` are the secret names without the vault prefix.
226pub 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
238/// Name suffixes of every resource of the wiring.
239pub 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    /// Name suffix of gateway VM `index`.
251    pub fn vm(index: usize) -> String {
252        format!("sbx-gateway-{index}")
253    }
254}
255
256/// Where a firewall rule's traffic comes from.
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub enum RuleSource {
259    /// The attachment subnet: sandbox traffic.
260    Attachment,
261    /// The gateway subnet: the peer gateway.
262    Gateway,
263    /// The deployment's workload subnet: the manager's path to the admin port.
264    Workload,
265}
266
267/// One firewall rule of the wiring. Every rule is ingress to the gateway VMs (the tag) except the
268/// catch-all deny, which covers the whole VPC from the attachment range.
269#[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    /// `None` is every protocol and port.
276    pub tcp_ports: Option<Vec<u16>>,
277    /// Targets only the gateway VMs. A rule that does not covers the whole network.
278    pub gateway_only: bool,
279    pub log: bool,
280}
281
282/// The firewall rules, in priority order. `proxy_port` is the port sandboxes connect to.
283///
284/// - the attachment subnet reaches the gateways on `proxy_port` and nothing else;
285/// - the admin port answers only the peer gateway and the deployment's workloads;
286/// - everything else from the attachment subnet is denied and logged, in the whole VPC.
287///
288/// The VPC denies ingress by default. The deny rule exists to log, and to win over any broad allow
289/// a customer's network carries at a lower priority.
290pub 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
322/// The gateway VMs' private addresses, from the gateway range.
323pub 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
335/// Full path of the network attachment a template names.
336pub fn attachment_path(project: &str, region: &str, name: &str) -> String {
337    format!("projects/{project}/regions/{region}/networkAttachments/{name}")
338}
339
340/// Regions where Agent Platform accepts a sandbox template with a network attachment and private
341/// ingress. Measured by creating one in each region: us-central1 accepts it, and us-east1,
342/// us-east4, us-west1, europe-west1, europe-west2, europe-west4 and asia-southeast1 answer "not yet
343/// available in region". Google lists no regions for it, so this is an allowlist: a region joins
344/// it when a template there is accepted. A sandbox that declares `internet` anywhere else is
345/// refused at plan time. It never falls back to open outbound.
346pub const REGIONS_WITH_PRIVATE_SERVICE_CONNECT: &[&str] = &["us-central1"];
347
348/// Why `internet` cannot be hosted in `region`, or `None` when it can.
349pub fn region_refusal(region: &str) -> Option<String> {
350    if REGIONS_WITH_PRIVATE_SERVICE_CONNECT.contains(&region) {
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
360/// The refusal for a project whose sandbox placement is already pinned to the default network.
361pub 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
365/// The gateway VM's boot script with three `%s` values, in order: the project id, the region and
366/// the JSON of the secrets vault binding. Terraform fills them with `format`, direct setup with
367/// [`startup_script`]. It installs Docker, writes the environment file and a unit that redirects
368/// the proxy port from the attachment range to the container's own port (limited to that range,
369/// so no other source reaches the proxy through it) and runs the gateway as one hardened,
370/// unprivileged container. The container is unchanged: it listens on 3128.
371pub 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
422/// [`startup_script_template`] with its values filled for direct setup.
423pub 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    /// The switch ships off; a test can turn it on for its own thread only, and the guard
442    /// turns it off again.
443    #[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    /// The flip needs both the switch and a gateway image that serves the admin protocol: the
458    /// switch alone, with the image this release pins today, still refuses.
459    #[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}