Skip to main content

commonware_deployer/aws/
authorize.rs

1//! `authorize` subcommand for `ec2`
2
3use crate::aws::{
4    deployer_directory,
5    ec2::{self, *},
6    utils::{exact_cidr, get_public_ip, DEPLOYER_MAX_PORT, DEPLOYER_MIN_PORT, DEPLOYER_PROTOCOL},
7    Config, Error, CREATED_FILE_NAME, DESTROYED_FILE_NAME, MONITORING_REGION,
8};
9use std::{collections::HashSet, fs::File, path::PathBuf};
10use tracing::info;
11
12/// Adds the deployer's IP (or the one provided) to all security groups.
13pub async fn authorize(config_path: &PathBuf, ip: Option<String>) -> Result<(), Error> {
14    // Load configuration
15    let config: Config = {
16        let config_file = File::open(config_path)?;
17        serde_yaml::from_reader(config_file)?
18    };
19    let tag = &config.tag;
20    info!(tag = tag.as_str(), "loaded configuration");
21
22    // Check deployment status
23    let tag_directory = deployer_directory(Some(tag));
24    if !tag_directory.exists() {
25        return Err(Error::DeploymentDoesNotExist(tag.clone()));
26    }
27    let created_file = tag_directory.join(CREATED_FILE_NAME);
28    if !created_file.exists() {
29        return Err(Error::DeploymentNotComplete(tag.clone()));
30    }
31    let destroyed_file = tag_directory.join(DESTROYED_FILE_NAME);
32    if destroyed_file.exists() {
33        return Err(Error::DeploymentAlreadyDestroyed(tag.clone()));
34    }
35
36    // Determine new IP
37    let new_ip = if let Some(ip_str) = ip {
38        // Validate provided IP as IPv4
39        let ip_addr: std::net::IpAddr = ip_str.parse()?;
40        let std::net::IpAddr::V4(ipv4) = ip_addr else {
41            return Err(Error::IpAddrNotV4(ip_addr));
42        };
43        ipv4.to_string()
44    } else {
45        // Fetch public IP
46        get_public_ip().await?
47    };
48    info!(
49        ip = new_ip.as_str(),
50        "adding IP to existing security groups"
51    );
52
53    // Determine all regions involved
54    let mut all_regions = HashSet::new();
55    all_regions.insert(MONITORING_REGION.to_string());
56    for instance in &config.instances {
57        all_regions.insert(instance.region.clone());
58    }
59
60    // Update security groups in each region
61    let mut changes = Vec::new();
62    for region in all_regions {
63        let ec2_client = ec2::create_client(Region::new(region.clone())).await;
64        info!(region = region.as_str(), "created EC2 client");
65
66        // Iterate over all security groups
67        let security_groups = find_security_groups_by_tag(&ec2_client, tag).await?;
68        for sg in security_groups {
69            // Check existing permissions
70            let sg_id = sg.group_id().unwrap();
71            let mut already_allowed = false;
72            for perm in sg.ip_permissions() {
73                // We enforce an exact match to avoid accidentally skipping because
74                // of an ingress rule with different ports or protocols.
75                if perm.ip_protocol() == Some(DEPLOYER_PROTOCOL)
76                    && perm.from_port() == Some(DEPLOYER_MIN_PORT)
77                    && perm.to_port() == Some(DEPLOYER_MAX_PORT)
78                {
79                    for ip_range in perm.ip_ranges() {
80                        if ip_range.cidr_ip() == Some(&exact_cidr(&new_ip)) {
81                            already_allowed = true;
82                            break;
83                        }
84                    }
85                    if already_allowed {
86                        break;
87                    }
88                }
89            }
90
91            // Add ingress rule if not already allowed
92            if already_allowed {
93                info!(sg_id, "IP already allowed");
94                continue;
95            }
96            ec2_client
97                .authorize_security_group_ingress()
98                .group_id(sg_id)
99                .ip_permissions(
100                    IpPermission::builder()
101                        .ip_protocol(DEPLOYER_PROTOCOL)
102                        .from_port(DEPLOYER_MIN_PORT)
103                        .to_port(DEPLOYER_MAX_PORT)
104                        .ip_ranges(IpRange::builder().cidr_ip(exact_cidr(&new_ip)).build())
105                        .build(),
106                )
107                .send()
108                .await
109                .map_err(|err| err.into_service_error())?;
110            info!(sg_id, "added ingress rule for IP");
111            changes.push(sg_id.to_string());
112        }
113    }
114    info!(?changes, "IP added to security groups");
115    Ok(())
116}