fakecloud-ec2 0.21.0

Amazon EC2 implementation for FakeCloud
Documentation
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
//! Default-VPC bootstrap.
//!
//! Every real AWS account has, per region, a *default VPC* (`172.31.0.0/16`)
//! with an attached internet gateway, a main route table that sends
//! `0.0.0.0/0` at the gateway, one default subnet per Availability Zone, a
//! `default` security group, and a default network ACL. Callers that never
//! touch the VPC APIs (the common case — `RunInstances` with no `SubnetId`)
//! still expect their instances to land in that default VPC and come back from
//! `DescribeInstances` with a real `vpc-…` / `subnet-…`.
//!
//! fakecloud builds the same fixtures the first time an account's EC2 state is
//! constructed ([`Ec2State::new`](crate::state::Ec2State::new)). The resource
//! ids are **deterministic** functions of the account id and a role string
//! (region-independent — see [`deterministic_id`]), so the throwaway empty
//! states that the read paths synthesize as a "not found" fallback report the
//! *same* ids as the persisted account state regardless of the caller's region.
//!
//! Per-VPC packet isolation (issue #1745 phase 2+) keys off this topology: a
//! subnet whose route table has a `0.0.0.0/0 -> igw-…` route is public and gets
//! a routable backing network; a subnet without one is private (`internal`).

use crate::state::{
    Ec2State, InternetGateway, NetworkAcl, NetworkAclAssoc, NetworkAclEntry, Route, RouteTable,
    RouteTableAssociation, SecurityGroup, SecurityGroupRule, Subnet, Vpc,
};

/// CIDR of the default VPC, matching AWS.
const DEFAULT_VPC_CIDR: &str = "172.31.0.0/16";

/// The Availability Zone suffixes that receive a default subnet. AWS creates a
/// default subnet in every AZ; three covers the cardinality every realistic
/// test exercises (and keeps the deterministic CIDR layout simple).
const DEFAULT_AZ_SUFFIXES: [&str; 3] = ["a", "b", "c"];

/// Deterministic EC2 resource id: `<prefix>-<17 hex>` derived from the account
/// and a per-resource `role`. Deliberately **region-independent**: a
/// `MultiAccountState` partitions by account and pins a single region per
/// server, but read handlers build a throwaway `Ec2State::new(account,
/// req.region)` for accounts that don't exist yet — where `req.region` is the
/// caller's SigV4 scope, not the server's region. Seeding the id on the region
/// made those throwaway-derived ids disagree with the persisted account's ids
/// whenever the client region differed from the server's, so a no-subnet launch
/// stamped the instance with a subnet/VPC id that didn't exist in its own
/// account (bug-hunt 2026-06-18 finding 1.1). Dropping region from the seed
/// makes both paths agree; the AZ/CIDR cosmetics below still use the region.
pub(crate) fn deterministic_id(prefix: &str, account: &str, role: &str) -> String {
    let seed = format!("{account}/{role}");
    let h1 = fnv1a64(seed.as_bytes());
    let h2 = fnv1a64(format!("{seed}/salt").as_bytes());
    // 16 hex from the first hash + 1 nibble from the second = the 17 hex chars
    // a modern EC2 long-id carries.
    format!("{prefix}-{:016x}{:01x}", h1, h2 & 0xf)
}

/// FNV-1a 64-bit. A tiny, dependency-free, stable hash — we only need
/// determinism, not cryptographic strength.
fn fnv1a64(bytes: &[u8]) -> u64 {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in bytes {
        h ^= u64::from(*b);
        h = h.wrapping_mul(0x0000_0100_0000_01b3);
    }
    h
}

/// AWS-style AZ-id prefix for a region: `us-east-1 -> use1`. Falls back to the
/// region with dashes stripped for non-`a-b-N` shapes.
fn az_id_prefix(region: &str) -> String {
    let parts: Vec<&str> = region.split('-').collect();
    if parts.len() == 3 && !parts[1].is_empty() {
        format!(
            "{}{}{}",
            parts[0],
            parts[1].chars().next().unwrap_or('x'),
            parts[2]
        )
    } else {
        region.replace('-', "")
    }
}

/// The default VPC id for an account (also exposed so request handlers can
/// resolve the implicit default without re-deriving the seed by hand).
pub(crate) fn default_vpc_id(account: &str) -> String {
    deterministic_id("vpc", account, "default-vpc")
}

/// The default security-group id for an account.
pub(crate) fn default_security_group_id(account: &str) -> String {
    deterministic_id("sg", account, "default-sg")
}

/// Populate `state` with the default VPC topology. Called once at state
/// construction; idempotent in practice because the deterministic ids collide
/// on re-entry.
pub(crate) fn bootstrap_default_network(state: &mut Ec2State) {
    let account = state.account_id.clone();
    let region = if state.region.is_empty() {
        "us-east-1".to_string()
    } else {
        state.region.clone()
    };

    let vpc_id = default_vpc_id(&account);
    let igw_id = deterministic_id("igw", &account, "default-igw");
    let rtb_id = deterministic_id("rtb", &account, "default-rtb");
    let acl_id = deterministic_id("acl", &account, "default-acl");
    let sg_id = default_security_group_id(&account);

    // --- default VPC ---
    state.vpcs.insert(
        vpc_id.clone(),
        Vpc {
            vpc_id: vpc_id.clone(),
            cidr_block: DEFAULT_VPC_CIDR.to_string(),
            state: "available".to_string(),
            dhcp_options_id: "default".to_string(),
            instance_tenancy: "default".to_string(),
            is_default: true,
            enable_dns_support: true,
            enable_dns_hostnames: true,
            cidr_associations: Vec::new(),
        },
    );

    // --- internet gateway, attached to the default VPC ---
    state.internet_gateways.insert(
        igw_id.clone(),
        InternetGateway {
            internet_gateway_id: igw_id.clone(),
            attachments: vec![(vpc_id.clone(), "available".to_string())],
        },
    );

    // --- default subnets, one per AZ ---
    let az_prefix = az_id_prefix(&region);
    let mut subnet_ids = Vec::new();
    for (idx, suffix) in DEFAULT_AZ_SUFFIXES.iter().enumerate() {
        let subnet_id = deterministic_id("subnet", &account, &format!("default-subnet-{suffix}"));
        let az = format!("{region}{suffix}");
        state.subnets.insert(
            subnet_id.clone(),
            Subnet {
                subnet_id: subnet_id.clone(),
                vpc_id: vpc_id.clone(),
                // /20 blocks carved from 172.31.0.0/16: .0, .16, .32 …
                cidr_block: format!("172.31.{}.0/20", idx * 16),
                availability_zone: az,
                availability_zone_id: format!("{az_prefix}-az{}", idx + 1),
                state: "available".to_string(),
                available_ip_address_count: 4091,
                default_for_az: true,
                // Default subnets auto-assign public IPs, matching AWS.
                map_public_ip_on_launch: true,
                assign_ipv6_address_on_creation: false,
                map_customer_owned_ip_on_launch: false,
                enable_dns64: false,
                private_dns_hostname_type: "ip-name".to_string(),
            },
        );
        subnet_ids.push(subnet_id);
    }

    // --- main route table: local + default route at the IGW (public) ---
    let mut associations = vec![RouteTableAssociation {
        association_id: deterministic_id("rtbassoc", &account, "default-rtb-main"),
        route_table_id: rtb_id.clone(),
        subnet_id: None,
        gateway_id: None,
        main: true,
    }];
    for sid in &subnet_ids {
        associations.push(RouteTableAssociation {
            association_id: deterministic_id("rtbassoc", &account, &format!("default-rtb-{sid}")),
            route_table_id: rtb_id.clone(),
            subnet_id: Some(sid.clone()),
            gateway_id: None,
            main: false,
        });
    }
    state.route_tables.insert(
        rtb_id.clone(),
        RouteTable {
            route_table_id: rtb_id.clone(),
            vpc_id: vpc_id.clone(),
            routes: vec![
                Route {
                    destination_cidr_block: Some(DEFAULT_VPC_CIDR.to_string()),
                    gateway_id: Some("local".to_string()),
                    ..Default::default()
                },
                Route {
                    destination_cidr_block: Some("0.0.0.0/0".to_string()),
                    gateway_id: Some(igw_id.clone()),
                    ..Default::default()
                },
            ],
            associations,
        },
    );

    // --- default security group: allow all from self, allow all egress ---
    state.security_groups.insert(
        sg_id.clone(),
        SecurityGroup {
            group_id: sg_id.clone(),
            group_name: "default".to_string(),
            description: "default VPC security group".to_string(),
            vpc_id: vpc_id.clone(),
            rules: vec![
                SecurityGroupRule {
                    rule_id: deterministic_id("sgr", &account, "default-sg-ingress"),
                    group_id: sg_id.clone(),
                    is_egress: false,
                    ip_protocol: "-1".to_string(),
                    from_port: -1,
                    to_port: -1,
                    cidr_ipv4: None,
                    cidr_ipv6: None,
                    prefix_list_id: None,
                    referenced_group_id: Some(sg_id.clone()),
                    description: String::new(),
                },
                SecurityGroupRule {
                    rule_id: deterministic_id("sgr", &account, "default-sg-egress"),
                    group_id: sg_id.clone(),
                    is_egress: true,
                    ip_protocol: "-1".to_string(),
                    from_port: -1,
                    to_port: -1,
                    cidr_ipv4: Some("0.0.0.0/0".to_string()),
                    cidr_ipv6: None,
                    prefix_list_id: None,
                    referenced_group_id: None,
                    description: String::new(),
                },
            ],
        },
    );

    // --- default network ACL: allow-all, associated with every default subnet ---
    let nacl_associations = subnet_ids
        .iter()
        .map(|sid| NetworkAclAssoc {
            association_id: deterministic_id("aclassoc", &account, &format!("default-acl-{sid}")),
            subnet_id: sid.clone(),
        })
        .collect();
    state.network_acls.insert(
        acl_id.clone(),
        NetworkAcl {
            network_acl_id: acl_id.clone(),
            vpc_id: vpc_id.clone(),
            is_default: true,
            entries: vec![
                allow_all_entry(false),
                deny_all_entry(false),
                allow_all_entry(true),
                deny_all_entry(true),
            ],
            associations: nacl_associations,
        },
    );
}

fn allow_all_entry(egress: bool) -> NetworkAclEntry {
    NetworkAclEntry {
        rule_number: 100,
        protocol: "-1".to_string(),
        rule_action: "allow".to_string(),
        egress,
        cidr_block: Some("0.0.0.0/0".to_string()),
        ipv6_cidr_block: None,
        port_range: None,
        icmp_type_code: None,
    }
}

fn deny_all_entry(egress: bool) -> NetworkAclEntry {
    NetworkAclEntry {
        rule_number: 32767,
        protocol: "-1".to_string(),
        rule_action: "deny".to_string(),
        egress,
        cidr_block: Some("0.0.0.0/0".to_string()),
        ipv6_cidr_block: None,
        port_range: None,
        icmp_type_code: None,
    }
}

/// True when `subnet_id` resolves to a subnet whose route table carries a
/// `0.0.0.0/0` route at an internet gateway — i.e. a *public* subnet. A subnet
/// without such a route is private and (phase 2) backs onto an `internal`
/// network. Subnets default to their VPC's main route table when not
/// explicitly associated.
// Drives per-subnet networking (chooses `internal` vs routable backing
// networks) from `service/mod.rs` and `instance.rs`.
pub(crate) fn subnet_is_public(state: &Ec2State, subnet_id: &str) -> bool {
    let Some(subnet) = state.subnets.get(subnet_id) else {
        return false;
    };
    // An explicit association wins; otherwise fall back to the VPC's main table.
    let explicit = state.route_tables.values().find(|rt| {
        rt.associations
            .iter()
            .any(|a| a.subnet_id.as_deref() == Some(subnet_id))
    });
    let main = state
        .route_tables
        .values()
        .find(|rt| rt.vpc_id == subnet.vpc_id && rt.associations.iter().any(|a| a.main));
    let rt = explicit.or(main);
    rt.map(route_table_has_igw_default).unwrap_or(false)
}

fn route_table_has_igw_default(rt: &RouteTable) -> bool {
    rt.routes.iter().any(|r| {
        r.destination_cidr_block.as_deref() == Some("0.0.0.0/0")
            && r.gateway_id
                .as_deref()
                .map(|g| g.starts_with("igw-"))
                .unwrap_or(false)
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::Ec2State;

    #[test]
    fn deterministic_id_is_stable_and_shaped() {
        let a = deterministic_id("vpc", "123456789012", "default-vpc");
        let b = deterministic_id("vpc", "123456789012", "default-vpc");
        assert_eq!(a, b);
        assert!(a.starts_with("vpc-"));
        // 17 hex chars after the prefix, matching EC2 long-ids.
        let hex = a.strip_prefix("vpc-").unwrap();
        assert_eq!(hex.len(), 17);
        assert!(hex.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn deterministic_id_varies_by_account_and_role() {
        let base = deterministic_id("vpc", "111111111111", "default-vpc");
        assert_ne!(base, deterministic_id("vpc", "222222222222", "default-vpc"));
        assert_ne!(base, deterministic_id("vpc", "111111111111", "default-igw"));
    }

    #[test]
    fn deterministic_id_is_region_independent() {
        // The id seed deliberately excludes region so read-path (req.region)
        // and persisted (server region) states agree (finding 1.1). Region is
        // not a parameter anymore — this documents the contract by asserting
        // default_vpc_id depends only on the account.
        assert_eq!(
            default_vpc_id("111111111111"),
            deterministic_id("vpc", "111111111111", "default-vpc")
        );
    }

    #[test]
    fn az_id_prefix_matches_aws_shape() {
        assert_eq!(az_id_prefix("us-east-1"), "use1");
        assert_eq!(az_id_prefix("eu-west-2"), "euw2");
        assert_eq!(az_id_prefix("ap-southeast-1"), "aps1");
    }

    #[test]
    fn bootstrap_creates_full_default_topology() {
        let state = Ec2State::new("123456789012", "us-east-1");
        // exactly one VPC, marked default
        assert_eq!(state.vpcs.len(), 1);
        let vpc = state.vpcs.values().next().unwrap();
        assert!(vpc.is_default);
        assert_eq!(vpc.cidr_block, "172.31.0.0/16");
        // one subnet per AZ suffix, all default_for_az + public
        assert_eq!(state.subnets.len(), DEFAULT_AZ_SUFFIXES.len());
        assert!(state.subnets.values().all(|s| s.default_for_az));
        assert!(state.subnets.values().all(|s| s.map_public_ip_on_launch));
        // IGW attached to the default VPC
        assert_eq!(state.internet_gateways.len(), 1);
        let igw = state.internet_gateways.values().next().unwrap();
        assert_eq!(igw.attachments[0].0, vpc.vpc_id);
        // default SG + default NACL
        let sg = state.security_groups.values().next().unwrap();
        assert_eq!(sg.group_name, "default");
        assert!(state.network_acls.values().next().unwrap().is_default);
    }

    #[test]
    fn default_subnets_are_public() {
        let state = Ec2State::new("123456789012", "us-east-1");
        for sid in state.subnets.keys() {
            assert!(
                subnet_is_public(&state, sid),
                "subnet {sid} should be public"
            );
        }
    }

    #[test]
    fn ids_match_across_fresh_states() {
        // The throwaway "empty" states read paths build must agree with the
        // persisted account state on the default VPC id.
        let a = Ec2State::new("123456789012", "us-east-1");
        let b = Ec2State::new("123456789012", "us-east-1");
        let a_vpc: Vec<_> = a.vpcs.keys().collect();
        let b_vpc: Vec<_> = b.vpcs.keys().collect();
        assert_eq!(a_vpc, b_vpc);
        assert_eq!(a_vpc[0], &default_vpc_id("123456789012"));
    }

    #[test]
    fn default_vpc_id_agrees_across_regions() {
        // The crux of finding 1.1: a read-path empty built with the caller's
        // region must derive the SAME default VPC id as the persisted account
        // state built with the server's region.
        let read_path = Ec2State::new("123456789012", "eu-west-1");
        let persisted = Ec2State::new("123456789012", "us-east-1");
        let read_vpc = read_path.vpcs.keys().next().unwrap();
        let persisted_vpc = persisted.vpcs.keys().next().unwrap();
        assert_eq!(read_vpc, persisted_vpc);
        // subnets too (so a no-subnet launch resolves a subnet that exists in
        // the persisted account regardless of the caller's region).
        let read_subnets: std::collections::BTreeSet<_> = read_path.subnets.keys().collect();
        let persisted_subnets: std::collections::BTreeSet<_> = persisted.subnets.keys().collect();
        assert_eq!(read_subnets, persisted_subnets);
    }
}