region-proxy 1.2.5

A CLI tool to create a SOCKS proxy through AWS EC2 in any region
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
use anyhow::{bail, Context, Result};
use aws_sdk_ec2::types::{
    Filter, InstanceStateName, InstanceType, IpPermission, IpRange, ResourceType, Tag,
    TagSpecification,
};
use aws_sdk_ec2::Client;
use std::time::Duration;
use tokio::net::TcpStream;
use tokio::time::{sleep, timeout};
use tracing::{debug, info};

const RESOURCE_PREFIX: &str = "region-proxy";

fn created_by_tag() -> Tag {
    Tag::builder()
        .key("CreatedBy")
        .value(RESOURCE_PREFIX)
        .build()
}

fn created_by_filter() -> Filter {
    Filter::builder()
        .name("tag:CreatedBy")
        .values(RESOURCE_PREFIX)
        .build()
}

pub struct Ec2Manager {
    client: Client,
}

impl Ec2Manager {
    pub async fn new(region: &str) -> Result<Self> {
        let config = aws_config::defaults(aws_config::BehaviorVersion::latest())
            .region(aws_sdk_ec2::config::Region::new(region.to_string()))
            .load()
            .await;

        let client = Client::new(&config);
        Ok(Self { client })
    }

    pub async fn find_latest_ami(&self, arm: bool) -> Result<String> {
        let arch = if arm { "arm64" } else { "x86_64" };
        info!("Finding latest Amazon Linux 2023 AMI for {}", arch);

        let resp = self
            .client
            .describe_images()
            .owners("amazon")
            .filters(
                Filter::builder()
                    .name("name")
                    .values(format!("al2023-ami-2023.*-{}", arch))
                    .build(),
            )
            .filters(Filter::builder().name("state").values("available").build())
            .filters(Filter::builder().name("architecture").values(arch).build())
            .send()
            .await
            .context("Failed to describe images")?;

        let ami_id = resp
            .images()
            .iter()
            .max_by_key(|img| img.creation_date().unwrap_or_default())
            .with_context(|| format!("No Amazon Linux 2023 AMI found for architecture {}", arch))?
            .image_id()
            .context("AMI has no image ID")?
            .to_string();

        info!("Found AMI: {}", ami_id);
        Ok(ami_id)
    }

    pub async fn create_security_group(&self) -> Result<String> {
        let group_name = format!("{}-{}", RESOURCE_PREFIX, uuid::Uuid::new_v4());
        info!("Creating security group: {}", group_name);

        let resp = self
            .client
            .create_security_group()
            .group_name(&group_name)
            .description("Temporary security group for region-proxy SSH access")
            .tag_specifications(
                TagSpecification::builder()
                    .resource_type(ResourceType::SecurityGroup)
                    .tags(Tag::builder().key("Name").value(&group_name).build())
                    .tags(created_by_tag())
                    .build(),
            )
            .send()
            .await
            .context("Failed to create security group")?;

        let group_id = resp
            .group_id()
            .context("Security group has no ID")?
            .to_string();

        self.client
            .authorize_security_group_ingress()
            .group_id(&group_id)
            .ip_permissions(
                IpPermission::builder()
                    .ip_protocol("tcp")
                    .from_port(22)
                    .to_port(22)
                    .ip_ranges(IpRange::builder().cidr_ip("0.0.0.0/0").build())
                    .build(),
            )
            .send()
            .await
            .context("Failed to add SSH ingress rule")?;

        info!("Created security group: {}", group_id);
        Ok(group_id)
    }

    pub async fn create_key_pair(&self) -> Result<(String, String)> {
        let key_name = format!("{}-{}", RESOURCE_PREFIX, uuid::Uuid::new_v4());
        info!("Creating key pair: {}", key_name);

        let resp = self
            .client
            .create_key_pair()
            .key_name(&key_name)
            .tag_specifications(
                TagSpecification::builder()
                    .resource_type(ResourceType::KeyPair)
                    .tags(created_by_tag())
                    .build(),
            )
            .send()
            .await
            .context("Failed to create key pair")?;

        let private_key = resp
            .key_material()
            .context("Key pair has no private key")?
            .to_string();

        info!("Created key pair: {}", key_name);
        Ok((key_name, private_key))
    }

    pub async fn launch_instance(
        &self,
        ami_id: &str,
        instance_type: &str,
        security_group_id: &str,
        key_name: &str,
    ) -> Result<String> {
        info!("Launching instance: type={}, ami={}", instance_type, ami_id);

        let instance_type = InstanceType::from(instance_type);

        let resp = self
            .client
            .run_instances()
            .image_id(ami_id)
            .instance_type(instance_type)
            .min_count(1)
            .max_count(1)
            .security_group_ids(security_group_id)
            .key_name(key_name)
            .tag_specifications(
                TagSpecification::builder()
                    .resource_type(ResourceType::Instance)
                    .tags(
                        Tag::builder()
                            .key("Name")
                            .value(format!("{}-instance", RESOURCE_PREFIX))
                            .build(),
                    )
                    .tags(created_by_tag())
                    .build(),
            )
            .send()
            .await
            .context("Failed to launch instance")?;

        let instance_id = resp
            .instances()
            .first()
            .context("No instance returned")?
            .instance_id()
            .context("Instance has no ID")?
            .to_string();

        info!("Launched instance: {}", instance_id);
        Ok(instance_id)
    }

    pub async fn wait_for_instance(&self, instance_id: &str) -> Result<String> {
        info!("Waiting for instance {} to be running...", instance_id);

        let max_attempts = 60;
        for attempt in 1..=max_attempts {
            let resp = self
                .client
                .describe_instances()
                .instance_ids(instance_id)
                .send()
                .await
                .context("Failed to describe instance")?;

            let instance = resp
                .reservations()
                .first()
                .and_then(|r| r.instances().first())
                .context("Instance not found")?;

            let state = instance
                .state()
                .and_then(|s| s.name())
                .unwrap_or(&InstanceStateName::Pending);

            debug!(
                "Instance state: {:?} (attempt {}/{})",
                state, attempt, max_attempts
            );

            if *state == InstanceStateName::Running {
                if let Some(ip) = instance.public_ip_address() {
                    info!("Instance is running with IP: {}", ip);
                    info!("Waiting for SSH port to open...");
                    wait_for_ssh_port(ip).await?;
                    return Ok(ip.to_string());
                }
            }

            if *state == InstanceStateName::Terminated || *state == InstanceStateName::ShuttingDown
            {
                bail!("Instance terminated unexpectedly");
            }

            sleep(Duration::from_secs(5)).await;
        }

        bail!("Timeout waiting for instance to be running");
    }

    pub async fn terminate_instance(&self, instance_id: &str) -> Result<()> {
        info!("Terminating instance: {}", instance_id);

        self.client
            .terminate_instances()
            .instance_ids(instance_id)
            .send()
            .await
            .context("Failed to terminate instance")?;

        let max_attempts = 30;
        for _ in 1..=max_attempts {
            let resp = self
                .client
                .describe_instances()
                .instance_ids(instance_id)
                .send()
                .await?;

            let state = resp
                .reservations()
                .first()
                .and_then(|r| r.instances().first())
                .and_then(|i| i.state())
                .and_then(|s| s.name());

            if state == Some(&InstanceStateName::Terminated) {
                info!("Instance terminated");
                return Ok(());
            }

            sleep(Duration::from_secs(2)).await;
        }

        Ok(())
    }

    pub async fn delete_security_group(&self, group_id: &str) -> Result<()> {
        info!("Deleting security group: {}", group_id);

        for attempt in 1..=5 {
            match self
                .client
                .delete_security_group()
                .group_id(group_id)
                .send()
                .await
            {
                Ok(_) => {
                    info!("Deleted security group");
                    return Ok(());
                }
                Err(e) => {
                    if attempt < 5 {
                        debug!("Retrying security group deletion: {}", e);
                        sleep(Duration::from_secs(5)).await;
                    } else {
                        return Err(e).context("Failed to delete security group");
                    }
                }
            }
        }

        Ok(())
    }

    pub async fn delete_key_pair(&self, key_name: &str) -> Result<()> {
        info!("Deleting key pair: {}", key_name);

        self.client
            .delete_key_pair()
            .key_name(key_name)
            .send()
            .await
            .context("Failed to delete key pair")?;

        info!("Deleted key pair");
        Ok(())
    }

    pub async fn find_orphaned_resources(&self) -> Result<OrphanedResources> {
        let instances_fut = self
            .client
            .describe_instances()
            .filters(created_by_filter())
            .filters(
                Filter::builder()
                    .name("instance-state-name")
                    .values("running")
                    .values("pending")
                    .values("stopping")
                    .values("stopped")
                    .build(),
            )
            .send();

        let sgs_fut = self
            .client
            .describe_security_groups()
            .filters(created_by_filter())
            .send();

        let kps_fut = self
            .client
            .describe_key_pairs()
            .filters(created_by_filter())
            .send();

        let (instances_resp, sgs_resp, kps_resp) = tokio::try_join!(
            async { instances_fut.await.context("Failed to describe instances") },
            async { sgs_fut.await.context("Failed to describe security groups") },
            async { kps_fut.await.context("Failed to describe key pairs") },
        )?;

        let mut orphaned = OrphanedResources::default();

        for reservation in instances_resp.reservations() {
            for instance in reservation.instances() {
                if let Some(id) = instance.instance_id() {
                    orphaned.instance_ids.push(id.to_string());
                }
            }
        }

        for sg in sgs_resp.security_groups() {
            if let Some(id) = sg.group_id() {
                orphaned.security_group_ids.push(id.to_string());
            }
        }

        for kp in kps_resp.key_pairs() {
            if let Some(name) = kp.key_name() {
                orphaned.key_pair_names.push(name.to_string());
            }
        }

        Ok(orphaned)
    }
}

#[derive(Debug, Default)]
pub struct OrphanedResources {
    pub instance_ids: Vec<String>,
    pub security_group_ids: Vec<String>,
    pub key_pair_names: Vec<String>,
}

impl OrphanedResources {
    pub fn is_empty(&self) -> bool {
        self.instance_ids.is_empty()
            && self.security_group_ids.is_empty()
            && self.key_pair_names.is_empty()
    }
}

async fn wait_for_ssh_port(host: &str) -> Result<()> {
    for attempt in 1..=60 {
        match timeout(Duration::from_secs(2), TcpStream::connect((host, 22))).await {
            Ok(Ok(_)) => {
                debug!("SSH port open on attempt {}", attempt);
                return Ok(());
            }
            _ => sleep(Duration::from_millis(500)).await,
        }
    }
    bail!("Timeout waiting for SSH port on {}", host);
}