microvms_domain/region.rs
1// SPDX-License-Identifier: Apache-2.0
2//! The five regions that carry MicroVMs, as a closed enum (TRAP-6).
3//!
4//! The Python client checks a region against a frozenset at construction time
5//! (`sandbox.py:314` `require_supported_region`) — strength S2 on the spec's
6//! ladder: the mistake can be written down, and a runtime guard rejects it. Here it
7//! is S1 for the five names: `Region::UsEast1` and its four siblings are the only
8//! values a caller can *type*, so a typo'd region is a compile error rather than a
9//! test that has to run.
10//!
11//! # Why refusing matters more than it looks
12//!
13//! Measured 2026-08-07: a region that does not carry MicroVMs answers
14//! `AccessDeniedException` with the message field **null**. A denied implied IAM action,
15//! such as tagging an image on creation, can return the same response (measured
16//! 2026-10-17, us-east-1, API 2025-09-09; docs/PLATFORM.md). Nothing between the
17//! caller and that answer objects to an unsupported region —
18//! the service model's `endpointPrefix` is `lambda`, so an endpoint resolves for any
19//! region and a client constructs happily. The first API call is the only reporter
20//! and its missing detail cannot distinguish availability from a policy denial.
21//!
22//! No API answers the question either, and the two that look like they might
23//! disagree with each other: `get_available_endpoints` returns an empty list while
24//! `get_available_regions` returns all 34 Lambda regions. So the list is kept by
25//! hand, and keeping it right is the whole correctness condition — in both
26//! directions. A *missing* region refuses a launch AWS would have accepted, which is
27//! the safer direction and still wrong; that is what [`Region::unlisted`] is for. An
28//! *extra* region is worse, because it re-opens the null-message trap for a name
29//! nothing will reject.
30//!
31//! `eu-central-1` was on this list until 2026-08-07 and does **not** carry MicroVMs:
32//! it was one of three regions measured returning the null-message denial.
33
34use std::fmt;
35use std::str::FromStr;
36
37use crate::error::Error;
38
39/// An AWS region, closed over the five that run MicroVMs plus a named escape hatch.
40///
41/// See the module docs for why the five are an enum. [`Region::Unlisted`] is
42/// deliberately a variant rather than a hidden flag: a reader of a call site can
43/// see that someone opted into the trap, and a `match` over regions cannot forget
44/// the case exists.
45#[derive(Clone, Debug, Eq, Hash, PartialEq)]
46pub enum Region {
47 UsEast1,
48 UsEast2,
49 UsWest2,
50 EuWest1,
51 ApNortheast1,
52 /// A region this client has not seen carry MicroVMs.
53 ///
54 /// **You are opting into the null-message trap.** If this region does not run
55 /// MicroVMs, the first control-plane call can answer `AccessDeniedException` with a
56 /// null message, which an IAM denial can also produce. Constructible through
57 /// [`Region::unlisted`], which makes that uncertainty visible at the call site.
58 ///
59 /// It exists because AWS adds regions faster than this list is re-read, and a
60 /// client that refuses a region AWS has just launched in is its own kind of
61 /// wrong. The override costs exactly the diagnostic above.
62 Unlisted(String),
63}
64
65/// The five regions that answered `ListMicrovms` when this was measured
66/// (2026-08-07), smallest-latency-first order not implied — this is the order
67/// `MICROVM_REGIONS` is documented in.
68///
69/// Not model-backed and it cannot be: see the module docs. `constants::as_json`
70/// publishes this set so `tools/check-model-drift.py` can compare the Rust and
71/// Python clients against each other, which is the only check available for a value
72/// no service model states.
73pub const MICROVM_REGIONS: [Region; 5] = [
74 Region::UsEast1,
75 Region::UsEast2,
76 Region::UsWest2,
77 Region::EuWest1,
78 Region::ApNortheast1,
79];
80
81impl Region {
82 /// The wire spelling, which is also the endpoint's middle segment.
83 pub fn as_str(&self) -> &str {
84 match self {
85 Region::UsEast1 => "us-east-1",
86 Region::UsEast2 => "us-east-2",
87 Region::UsWest2 => "us-west-2",
88 Region::EuWest1 => "eu-west-1",
89 Region::ApNortheast1 => "ap-northeast-1",
90 Region::Unlisted(name) => name,
91 }
92 }
93
94 /// Opts into a region this client has not seen carry MicroVMs.
95 ///
96 /// **This is the escape hatch, and it costs you the diagnostic.** If the region
97 /// does not run MicroVMs, the first control-plane call answers
98 /// `AccessDeniedException` with a null message field, which can also mean an
99 /// IAM denial (`docs/PLATFORM.md`, "A null-message AccessDeniedException can mean
100 /// region availability or IAM"). Use it when AWS has launched
101 /// MicroVMs somewhere new, and add the region to [`MICROVM_REGIONS`] in the same
102 /// change.
103 ///
104 /// A supported name passed here comes back as its proper variant rather than as
105 /// [`Region::Unlisted`], so `unlisted("us-east-1") == Region::UsEast1` and
106 /// nothing downstream has to handle two spellings of one region.
107 pub fn unlisted(name: impl Into<String>) -> Region {
108 let name = name.into();
109 match Self::supported(&name) {
110 Some(known) => known,
111 None => Region::Unlisted(name),
112 }
113 }
114
115 /// The variant for a supported name, or `None` for anything else.
116 ///
117 /// The single reader of the five spellings: [`FromStr`] and [`Region::unlisted`]
118 /// both come through here, so there is no second table to drift from the first.
119 fn supported(name: &str) -> Option<Region> {
120 MICROVM_REGIONS
121 .into_iter()
122 .find(|region| region.as_str() == name)
123 }
124
125 /// Whether this is one of the five, rather than an opted-into unlisted name.
126 pub fn is_supported(&self) -> bool {
127 !matches!(self, Region::Unlisted(_))
128 }
129
130 /// The region the environment names: `$AWS_REGION`, then `$AWS_DEFAULT_REGION`, then
131 /// `us-east-1`.
132 ///
133 /// Parsed rather than accepted: an environment variable is a string, and this is the
134 /// boundary where the enum cannot help. A region the client has not seen carry MicroVMs is
135 /// refused with the null-message finding attached; opting in is explicit at a call site
136 /// (`--unlisted-region` in the CLI, `Region.unlisted` in the bindings). `env` is a lookup
137 /// rather than `std::env::var` so a caller (and a test) decides where the variables come
138 /// from. The CLI's region resolution and `microvms_core::preflight::preflight` both read it here.
139 pub fn from_env(env: &dyn Fn(&str) -> Option<String>) -> Result<Region, Error> {
140 match env("AWS_REGION").or_else(|| env("AWS_DEFAULT_REGION")) {
141 Some(name) => name.parse::<Region>().map_err(|error| {
142 Error::invalid_arg(format!(
143 "{error} It arrived from $AWS_REGION or $AWS_DEFAULT_REGION rather than from \
144 a flag; pass --unlisted-region {name:?} (CLI) or Region.unlisted({name:?}) \
145 (bindings) to opt in explicitly."
146 ))
147 }),
148 None => Ok(Region::UsEast1),
149 }
150 }
151}
152
153impl fmt::Display for Region {
154 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155 f.write_str(self.as_str())
156 }
157}
158
159impl FromStr for Region {
160 type Err = Error;
161
162 /// Parses one of the five, and refuses everything else.
163 ///
164 /// The refusal is the point: this is the boundary a region name arrives at from
165 /// a CLI flag or an environment variable, where it is still a string and the
166 /// enum cannot help. A caller who genuinely wants a sixth region reaches for
167 /// [`Region::unlisted`] and says so.
168 fn from_str(name: &str) -> Result<Region, Error> {
169 if let Some(known) = Region::supported(name) {
170 return Ok(known);
171 }
172 let offered = MICROVM_REGIONS
173 .iter()
174 .map(Region::as_str)
175 .collect::<Vec<_>>()
176 .join(", ");
177 Err(Error::invalid_arg(format!(
178 "region {name:?} is not one this client has seen carry MicroVMs ({offered}). \
179 Refused here because the first API call is where the evidence disappears: an \
180 unsupported region answers AccessDeniedException with a null message, which is \
181 indistinguishable from a real IAM denial (docs/PLATFORM.md, 'A null-message AccessDeniedException can mean region availability or IAM'). If AWS has since \
182 launched MicroVMs here, use Region::unlisted({name:?}) and add the region to \
183 MICROVM_REGIONS."
184 )))
185 }
186}
187
188#[cfg(test)]
189mod tests {
190 use super::*;
191 use crate::error::ErrorKind;
192
193 /// The five spellings, written out. A generated list would agree with a typo,
194 /// and a typo here is the *extra region* direction of the correctness condition
195 /// — the direction that re-opens the null-message trap.
196 #[test]
197 fn the_five_supported_regions_are_the_measured_ones() {
198 let names: Vec<&str> = MICROVM_REGIONS.iter().map(Region::as_str).collect();
199 assert_eq!(
200 names,
201 [
202 "us-east-1",
203 "us-east-2",
204 "us-west-2",
205 "eu-west-1",
206 "ap-northeast-1"
207 ]
208 );
209 }
210
211 /// TRAP-6, the falsification case. `eu-central-1` is the specific region that
212 /// was on this list and does not carry MicroVMs, so it is the one a regression
213 /// would most plausibly re-add. The message must name the trap — both halves,
214 /// because "AccessDeniedException" alone reads as an IAM problem and it is the
215 /// word *null* that says otherwise.
216 #[test]
217 fn eu_central_one_is_refused_naming_the_null_message_trap() {
218 let err = "eu-central-1"
219 .parse::<Region>()
220 .expect_err("eu-central-1 does not carry MicroVMs");
221 assert_eq!(err.kind(), ErrorKind::InvalidArg);
222 let message = err.to_string();
223 assert!(
224 message.contains("AccessDeniedException"),
225 "must name the exception: {message}"
226 );
227 assert!(
228 message.contains("null"),
229 "must say the message field is null: {message}"
230 );
231 assert!(
232 message.contains("eu-central-1"),
233 "must name the rejected region: {message}"
234 );
235 }
236
237 /// Every supported name parses back to its own variant. The round trip is what
238 /// makes `as_str` and the parse table one table rather than two.
239 #[test]
240 fn each_supported_region_round_trips_through_its_wire_name() {
241 for region in MICROVM_REGIONS {
242 let parsed: Region = region.as_str().parse().expect("supported name parses");
243 assert_eq!(parsed, region);
244 assert!(parsed.is_supported());
245 }
246 }
247
248 /// The escape hatch produces a distinguishable value rather than a silent pass:
249 /// `is_supported` is false, so a caller — or a cost table that has no rates for
250 /// the region — can still tell the difference.
251 #[test]
252 fn the_escape_hatch_is_visible_in_the_value_it_produces() {
253 let region = Region::unlisted("eu-central-1");
254 assert_eq!(region, Region::Unlisted("eu-central-1".to_string()));
255 assert_eq!(region.as_str(), "eu-central-1");
256 assert!(!region.is_supported());
257 }
258
259 /// A supported name handed to the escape hatch comes back as its proper variant.
260 /// Otherwise `unlisted("us-east-1")` would be a second, unequal spelling of a
261 /// region the client fully supports, and every `match` downstream would need to
262 /// handle both.
263 #[test]
264 fn the_escape_hatch_normalises_a_supported_name_to_its_variant() {
265 assert_eq!(Region::unlisted("us-east-1"), Region::UsEast1);
266 assert!(Region::unlisted("ap-northeast-1").is_supported());
267 }
268
269 /// Nothing plausible-looking sneaks through. These are the shapes a typo takes:
270 /// a real AWS region that lacks MicroVMs, a near-miss on a supported name, a
271 /// case change, and the empty string.
272 #[test]
273 fn near_misses_and_other_aws_regions_are_all_refused() {
274 for name in [
275 "eu-central-1",
276 "ap-southeast-2",
277 "sa-east-1",
278 "us-east-3",
279 "us-west-1",
280 "US-EAST-1",
281 "us-east-1 ",
282 "",
283 ] {
284 let err = name
285 .parse::<Region>()
286 .expect_err("only the five measured regions parse");
287 assert_eq!(err.kind(), ErrorKind::InvalidArg, "{name}");
288 }
289 }
290}