Skip to main content

microvms_core/control/
token.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Idempotency tokens, unique per attempt by construction (TRAP-1).
3//!
4//! # What a `clientToken` actually is
5//!
6//! A **permanent** idempotency key, not a request deduplication window. Measured
7//! 2026-08-02, the expensive way: delete an image, recreate it from the same bytes
8//! under the same name with a token derived from that identity, and the service
9//! replays the original create as a no-op. The image then sits in `CREATING` with its
10//! builds never scheduled, cannot be deleted (`CREATING` forbids it), and its only
11//! version cannot be dropped either (it is the last one). Two images were wedged that
12//! way for roughly fifteen hours.
13//!
14//! # Fresh defaults and explicit launch recovery
15//!
16//! The previous Python shape defaulted correctly and *accepted* `client_token=<content
17//! digest>` — which is precisely the value that wedges an image, offered as the
18//! natural thing to pass. Image creation still forbids caller tokens:
19//! [`create_token`] and [`run_token`] take a **scope label** and mint the token
20//! themselves. A label lands *next to* the nonce and can never replace it.
21//!
22//! Run requests additionally accept a persisted `client_token` for recovery after a lost
23//! launch response. That opt-in must identify exactly one launch with identical inputs.
24//! A new VM needs a new key, even when its image and other parameters are unchanged.
25//!
26//! # The shape, and which end gets truncated
27//!
28//! `<verb>-<label>-<16 hex>`, with `verb` one of `create` or `run` and the nonce eight
29//! bytes of fresh randomness rendered as sixteen hex characters.
30//!
31//! The label is truncated to its **tail**, not its head: `run`'s scope defaults to the
32//! image identifier, which is a full ARN, and an ARN's distinguishing part is the
33//! resource name at the end while every ARN in a region shares its prefix. Truncating
34//! the head would collapse two different images onto one label.
35//!
36//! The nonce is **never** truncated. That ordering is the whole property: a shortened
37//! label cannot make two attempts collide, because collision-freedom lives entirely in
38//! the sixteen hex characters and the truncation happens before them. Found 2026-08-07
39//! by the drift checker's coverage report naming `RunMicrovmRequestClientTokenString`
40//! as unbound — an ap-northeast-1 ARN carrying a legal 64-character image name mints a
41//! 142-character token, over the 128 ceiling, and botocore does not check `max`, so it
42//! would have gone to the wire and failed a launch on a field the caller never set.
43
44use crate::constants::MAX_CLIENT_TOKEN_LEN;
45
46/// Bytes of randomness folded into every token: eight, so two attempts one second
47/// apart do not collide even under a retry storm.
48///
49/// Rendered as [`TOKEN_NONCE_HEX_LEN`] hex characters. Both constants exist because
50/// the *hex* length is what the ceiling arithmetic needs and deriving it in three
51/// places is three places to get the factor of two wrong.
52const TOKEN_NONCE_BYTES: usize = 8;
53
54/// The nonce's rendered width, `TOKEN_NONCE_BYTES * 2`.
55///
56/// Test-only, and deliberately so: production code renders the nonce by iterating the bytes,
57/// so a second constant it *used* would be a second thing to keep in step. The tests below
58/// need it to check the ceiling arithmetic — and they compare it against
59/// `TOKEN_NONCE_BYTES * 2` rather than trusting it, so a change to either is caught.
60#[cfg(test)]
61const TOKEN_NONCE_HEX_LEN: usize = TOKEN_NONCE_BYTES * 2;
62
63/// How much of the scope label survives into a token.
64///
65/// Not a cosmetic cap — see the module docs for the 142-character token that motivated
66/// it. Sized so that the worst legal scope still fits [`MAX_CLIENT_TOKEN_LEN`]: the
67/// test at the bottom of this file asserts the arithmetic rather than trusting it.
68const MAX_TOKEN_SCOPE_LEN: usize = 64;
69
70/// The verb prefix, closed over the two operations that carry an idempotency token on
71/// this client's paths.
72///
73/// An enum rather than a `&str` parameter because a third verb is a new operation and
74/// should be a change to this file, not a string a call site invents. `UpdateMicrovmImage`
75/// is the third `idempotencyToken: true` member in the model and is deliberately absent:
76/// this client never calls it.
77#[derive(Clone, Copy, Debug, Eq, PartialEq)]
78enum Verb {
79    Create,
80    Run,
81}
82
83impl Verb {
84    fn as_str(self) -> &'static str {
85        match self {
86            Verb::Create => "create",
87            Verb::Run => "run",
88        }
89    }
90}
91
92/// An image-create idempotency token, unique per attempt.
93///
94/// `scope` is a **label only** — a readability aid for whoever reads CloudTrail, folded
95/// in beside the nonce. It cannot become the token, and there is no parameter that can:
96/// see the module docs for the fifteen-hour wedge that closure exists to prevent
97/// (`docs/PLATFORM.md`, "`clientToken` is a permanent idempotency key").
98pub fn create_token(scope: &str) -> String {
99    mint(Verb::Create, scope, &nonce_bytes())
100}
101
102/// A run idempotency token, unique per attempt. Same rule as [`create_token`].
103///
104/// Cheaper to get wrong than the image case — a replayed run returns the original
105/// MicroVM rather than wedging anything — but the failure is worse to read: a caller
106/// who asked for a second VM gets the first one's id back, and two callers then drive
107/// the same guest.
108pub fn run_token(scope: &str) -> String {
109    mint(Verb::Run, scope, &nonce_bytes())
110}
111
112/// Refuse malformed explicit launch keys locally, without echoing caller input.
113pub(crate) fn require_run_token(token: &str) -> Result<(), crate::Error> {
114    if token.is_empty()
115        || token.len() > MAX_CLIENT_TOKEN_LEN
116        || !token.bytes().all(|byte| byte.is_ascii_graphic())
117    {
118        return Err(crate::Error::invalid_arg(format!(
119            "client_token must contain 1..={MAX_CLIENT_TOKEN_LEN} printable ASCII characters without whitespace",
120        )));
121    }
122    Ok(())
123}
124
125/// A caller's log-stream prefix with a fresh per-build discriminator: `<prefix>/<16 hex>`.
126///
127/// # The same mechanism as the token nonce, for the same class of reason
128///
129/// `logging.cloudWatch.logStream` is an **exact** stream name on the wire — prefixes are
130/// unsupported (docs/PLATFORM.md, 'An image build is three VMs and three log streams') —
131/// and one image build emits three log streams. A caller's fixed name sent verbatim
132/// collapses all three of every build, concurrent builds of different images included,
133/// into one stream nothing can tell apart. So the caller's value is a prefix by contract
134/// ([`crate::control::CreateImageRequest::log_stream`]), and this appends eight bytes of
135/// fresh CSPRNG rendered as sixteen hex characters per create attempt — the exact nonce
136/// [`create_token`] folds into an idempotency token, reused rather than reinvented.
137///
138/// The arithmetic that keeps the result legal is `MAX_USER_LOG_STREAM_LEN`'s: the caller's
139/// prefix is capped at 495 before this runs, so `495 + 1 + 16` is exactly the shape's 512
140/// ceiling. The debug assertion holds that rather than trusting it.
141pub(crate) fn resolve_log_stream(prefix: &str) -> String {
142    let nonce = nonce_bytes();
143    let mut resolved = String::with_capacity(prefix.len() + 1 + nonce.len() * 2);
144    resolved.push_str(prefix);
145    resolved.push('/');
146    resolved.push_str(&const_hex::encode(nonce));
147    debug_assert!(
148        resolved.len() <= crate::constants::MAX_LOG_STREAM_LEN,
149        "resolved a {}-character stream name, over the {} ceiling: {resolved}",
150        resolved.len(),
151        crate::constants::MAX_LOG_STREAM_LEN,
152    );
153    resolved
154}
155
156/// The one place a token is assembled, with the randomness passed in.
157///
158/// Split from the two public functions so a test can drive the *format* with a fixed
159/// nonce and still exercise the real assembly, rather than reimplementing the format in
160/// the test and asserting a copy of it against itself.
161fn mint(verb: Verb, scope: &str, nonce: &[u8]) -> String {
162    // The tail, and on a character boundary: `scope` is arbitrary caller text, so
163    // slicing by byte index would panic on a multi-byte character straddling the cut.
164    // `char_indices` finds the first boundary at or after the cut point, which keeps at
165    // most MAX_TOKEN_SCOPE_LEN bytes — never more, which is what the ceiling needs.
166    let label = tail(scope, MAX_TOKEN_SCOPE_LEN);
167
168    let mut token = String::with_capacity(verb.as_str().len() + 2 + label.len() + nonce.len() * 2);
169    token.push_str(verb.as_str());
170    token.push('-');
171    token.push_str(label);
172    token.push('-');
173    // Two lowercase hex digits per byte, so the rendered width is exactly
174    // 2 * nonce.len() and the ceiling arithmetic below holds.
175    token.push_str(&const_hex::encode(nonce));
176
177    debug_assert!(
178        token.len() <= MAX_CLIENT_TOKEN_LEN,
179        "minted a {}-character token, over the {MAX_CLIENT_TOKEN_LEN} ceiling: {token}",
180        token.len()
181    );
182    token
183}
184
185/// The last `max_bytes` bytes of `text`, cut at a character boundary.
186///
187/// Returns a possibly-shorter slice when the boundary falls inside a multi-byte
188/// character, which is the safe direction: the ceiling is an upper bound.
189fn tail(text: &str, max_bytes: usize) -> &str {
190    if text.len() <= max_bytes {
191        return text;
192    }
193    let cut = text.len() - max_bytes;
194    match text.char_indices().find(|(index, _)| *index >= cut) {
195        Some((index, _)) => &text[index..],
196        // Unreachable in practice — the loop above finds the final boundary at worst —
197        // but an empty label is a correct token and a panic is not.
198        None => "",
199    }
200}
201
202/// Eight bytes of fresh randomness per call, from the kernel CSPRNG via `getrandom`.
203///
204/// TRAP-1 needs per-attempt distinctness — the token must not repeat across two
205/// attempts; it does not have to be unguessable. `getrandom` gives the stronger
206/// property anyway, and fails only when the OS pool is genuinely unavailable, in
207/// which state a clock-derived nonce (the old fallback here) risks the exact
208/// collision TRAP-1 exists to prevent.
209fn nonce_bytes() -> [u8; TOKEN_NONCE_BYTES] {
210    let mut bytes = [0u8; TOKEN_NONCE_BYTES];
211    getrandom::fill(&mut bytes).expect("the OS random pool is available");
212    bytes
213}
214
215#[cfg(test)]
216mod tests {
217    use std::collections::HashSet;
218
219    use proptest::prelude::*;
220
221    use super::*;
222
223    /// The worst legal scope, from the discovery that motivated the cap: a full
224    /// ap-northeast-1 image ARN carrying a 64-character image name. This is the value
225    /// that minted 142 characters before the label was truncated.
226    fn worst_legal_scope() -> String {
227        format!(
228            "arn:aws:lambda:ap-northeast-1:123456789012:microvm-image:{}",
229            "a".repeat(crate::constants::MAX_IMAGE_NAME_LEN)
230        )
231    }
232
233    /// The shape, against a fixed nonce so the assertion is on the format rather than
234    /// on a copy of the format. `create-`, the label, `-`, sixteen hex characters.
235    #[test]
236    fn a_token_is_the_verb_the_label_and_sixteen_hex_characters() {
237        let token = mint(
238            Verb::Create,
239            "agentd-conformance",
240            &[0xde, 0xad, 0xbe, 0xef, 0, 1, 2, 3],
241        );
242        assert_eq!(token, "create-agentd-conformance-deadbeef00010203");
243
244        let token = mint(Verb::Run, "vm-7", &[0xff; TOKEN_NONCE_BYTES]);
245        assert_eq!(token, "run-vm-7-ffffffffffffffff");
246    }
247
248    /// The two verbs are the two this client uses, and they are distinguishable in the
249    /// minted value — which is the only reason the verb is in there at all: a CloudTrail
250    /// reader seeing `create-…` knows which call it came from.
251    #[test]
252    fn the_verb_prefix_distinguishes_a_create_from_a_run() {
253        assert!(create_token("img").starts_with("create-"));
254        assert!(run_token("img").starts_with("run-"));
255    }
256
257    /// TRAP-1's headline property, at the scale the success criteria name: 200 draws,
258    /// 200 distinct values.
259    ///
260    /// **Falsification** — replace `nonce_bytes()` in `create_token` with a digest of
261    /// the scope (the exact mistake the Python client's `client_token=` parameter
262    /// invited) and this collapses to one distinct value out of 200. Verified by doing
263    /// it; see the packet's guard proofs.
264    #[test]
265    fn two_hundred_create_tokens_for_one_scope_are_two_hundred_distinct_values() {
266        let scope = "agentd-conformance";
267        let minted: HashSet<String> = (0..200).map(|_| create_token(scope)).collect();
268        assert_eq!(minted.len(), 200, "a repeated token is a wedged image");
269    }
270
271    /// The same for the run path, and across the two verbs at once: 200 of each, 400
272    /// distinct, so a create token can never equal a run token either.
273    #[test]
274    fn create_and_run_tokens_never_collide_with_each_other() {
275        let scope = "arn:aws:lambda:us-east-1:123456789012:microvm-image:img";
276        let mut minted = HashSet::new();
277        for _ in 0..200 {
278            minted.insert(create_token(scope));
279            minted.insert(run_token(scope));
280        }
281        assert_eq!(minted.len(), 400);
282    }
283
284    /// The ceiling, at the value that discovered it. 142 characters before truncation,
285    /// and the assertion is on the real minted length rather than on the arithmetic.
286    #[test]
287    fn the_worst_legal_scope_fits_the_hundred_twenty_eight_character_ceiling() {
288        let scope = worst_legal_scope();
289        assert!(
290            scope.len() > MAX_TOKEN_SCOPE_LEN,
291            "the point of this scope is that it is longer than the label cap"
292        );
293
294        for token in [create_token(&scope), run_token(&scope)] {
295            assert!(
296                token.len() <= MAX_CLIENT_TOKEN_LEN,
297                "{} characters, over the {MAX_CLIENT_TOKEN_LEN} ceiling: {token}",
298                token.len()
299            );
300        }
301    }
302
303    /// The arithmetic behind the cap, stated so a change to any of the three numbers
304    /// fails here rather than on a launch. `run-` is the shorter verb, so `create-`
305    /// bounds the total.
306    #[test]
307    fn the_label_cap_leaves_room_for_the_longest_verb_and_the_whole_nonce() {
308        let longest_verb = Verb::Create.as_str().len();
309        let worst = longest_verb + 1 + MAX_TOKEN_SCOPE_LEN + 1 + TOKEN_NONCE_HEX_LEN;
310        assert!(
311            worst <= MAX_CLIENT_TOKEN_LEN,
312            "the worst legal token is {worst} characters against a ceiling of {MAX_CLIENT_TOKEN_LEN}"
313        );
314        assert_eq!(TOKEN_NONCE_HEX_LEN, TOKEN_NONCE_BYTES * 2);
315    }
316
317    /// The truncation keeps the **tail**. Two ARNs differing only in their resource
318    /// name must produce different labels — truncating the head would collapse them,
319    /// because every ARN in a region shares its prefix.
320    ///
321    /// The image names are long enough that the shared prefix really is what gets cut:
322    /// the ARN prefix alone is 57 characters, so a short name leaves the whole scope
323    /// under the 64-byte cap and the test would pass without exercising truncation at
324    /// all. That near-miss is the reason the length is asserted first.
325    #[test]
326    fn truncation_keeps_the_tail_so_two_arns_stay_distinguishable() {
327        let prefix = "arn:aws:lambda:ap-northeast-1:123456789012:microvm-image:";
328        let first_scope = format!("{prefix}alpha-conformance-image-name");
329        let second_scope = format!("{prefix}omega-conformance-image-name");
330        assert!(
331            first_scope.len() > MAX_TOKEN_SCOPE_LEN,
332            "these scopes must actually be truncated or the test proves nothing"
333        );
334
335        let first = mint(Verb::Run, &first_scope, &[0; TOKEN_NONCE_BYTES]);
336        let second = mint(Verb::Run, &second_scope, &[0; TOKEN_NONCE_BYTES]);
337
338        assert_ne!(first, second, "the distinguishing part is at the end");
339        assert!(first.contains("alpha-conformance-image-name"), "{first}");
340        assert!(second.contains("omega-conformance-image-name"), "{second}");
341        assert!(
342            !first.contains("arn:aws"),
343            "the shared prefix is what got cut: {first}"
344        );
345    }
346
347    /// The nonce survives truncation intact, whatever the label does. This is the
348    /// property that makes collision-freedom independent of the scope: the last sixteen
349    /// characters are always the sixteen hex digits.
350    #[test]
351    fn the_nonce_is_never_the_part_that_gets_cut() {
352        let scope = "z".repeat(4096);
353        let token = mint(Verb::Create, &scope, &[0xab; TOKEN_NONCE_BYTES]);
354        assert!(
355            token.ends_with("abababababababab"),
356            "the whole nonce must survive: {token}"
357        );
358        assert_eq!(
359            token.len(),
360            "create".len() + 1 + MAX_TOKEN_SCOPE_LEN + 1 + TOKEN_NONCE_HEX_LEN
361        );
362    }
363
364    /// A multi-byte scope does not panic and does not overshoot the ceiling. The cut
365    /// point can land inside a character, and slicing by byte index there is a panic in
366    /// a code path a caller reaches by naming an image in their own language.
367    #[test]
368    fn a_multibyte_scope_cuts_on_a_character_boundary_rather_than_panicking() {
369        for scope in ["日本語".repeat(64), "é".repeat(200), "🔥".repeat(50)] {
370            let token = create_token(&scope);
371            assert!(token.len() <= MAX_CLIENT_TOKEN_LEN, "{token}");
372            assert!(token.is_char_boundary(token.len()));
373        }
374    }
375
376    /// An empty scope is a legal token rather than a panic or an empty string: the
377    /// model's minimum is 1, and `create--<nonce>` clears it comfortably.
378    #[test]
379    fn an_empty_scope_still_mints_a_usable_token() {
380        let token = create_token("");
381        assert_eq!(token, format!("create--{}", &token[8..]));
382        // The clientToken shapes state `min: 1`, and nothing outside this crate would catch a
383        // violation of it — the note here used to say botocore enforces `min` locally, which is
384        // true of botocore and irrelevant to a client that signs with `aws-sigv4` and sends with
385        // `reqwest` (issue #24). What makes the constraint unreachable is not a guard but the
386        // minter: the verb and the nonce alone are 23 characters, so the empty label cannot
387        // collapse the token, and that is what the assertion below says.
388        assert_eq!(
389            token.len(),
390            "create".len() + 2 + TOKEN_NONCE_HEX_LEN,
391            "the model's clientToken min is 1 and this clears it: {token}"
392        );
393    }
394
395    proptest! {
396        /// The ceiling and the nonce, over arbitrary caller text. A hand-picked scope
397        /// set is exactly where the multi-byte boundary case hides, and the property
398        /// that matters — every minted token fits, and every one ends in its full nonce
399        /// — has to hold for text this test did not choose.
400        #[test]
401        fn every_scope_mints_a_token_that_fits_and_keeps_its_whole_nonce(scope: String) {
402            let token = mint(Verb::Create, &scope, &[0x5a; TOKEN_NONCE_BYTES]);
403            prop_assert!(token.len() <= MAX_CLIENT_TOKEN_LEN, "{}", token);
404            prop_assert!(token.ends_with("5a5a5a5a5a5a5a5a"), "{}", token);
405            prop_assert!(token.starts_with("create-"), "{}", token);
406        }
407
408        /// Two calls with the *same* scope differ, for any scope. The distinctness test
409        /// above uses one fixed scope; this one asserts the scope cannot be the thing
410        /// that makes two attempts agree — which is precisely what a digest-derived
411        /// token would do.
412        #[test]
413        fn no_scope_makes_two_attempts_produce_the_same_token(scope: String) {
414            prop_assert_ne!(create_token(&scope), create_token(&scope));
415            prop_assert_ne!(run_token(&scope), run_token(&scope));
416        }
417    }
418
419    /// A resolved log stream is the caller's prefix, a `/`, and sixteen hex characters —
420    /// never the prefix verbatim — and two resolutions of one prefix differ.
421    ///
422    /// The distinctness is the whole point: one image build is three VMs writing three
423    /// streams under an exact-name member, so a resolution that could repeat would
424    /// collapse two builds' streams the way a verbatim name collapses every build's.
425    ///
426    /// **Falsification** — return `prefix.to_string()` from `resolve_log_stream` and the
427    /// format assertions and the distinctness assertion all go red.
428    #[test]
429    fn a_resolved_log_stream_carries_the_prefix_a_slash_and_sixteen_fresh_hex() {
430        let first = resolve_log_stream("ci-image");
431        let second = resolve_log_stream("ci-image");
432
433        for resolved in [&first, &second] {
434            assert!(resolved.starts_with("ci-image/"), "{resolved}");
435            let suffix = &resolved["ci-image/".len()..];
436            assert_eq!(suffix.len(), TOKEN_NONCE_HEX_LEN, "{resolved}");
437            assert!(
438                suffix.bytes().all(|b| b.is_ascii_hexdigit()),
439                "the discriminator is hex: {resolved}"
440            );
441            assert_ne!(resolved.as_str(), "ci-image", "never the prefix verbatim");
442        }
443        assert_ne!(
444            first, second,
445            "two creates from one request must resolve to two streams, or concurrent \
446             builds collapse into one"
447        );
448    }
449
450    /// The worst legal prefix — `MAX_USER_LOG_STREAM_LEN` characters — resolves to exactly
451    /// the shape's 512 ceiling, which is the arithmetic the 495 cap exists to hold.
452    #[test]
453    fn the_longest_legal_prefix_resolves_to_exactly_the_shapes_ceiling() {
454        let prefix = "s".repeat(crate::constants::MAX_USER_LOG_STREAM_LEN);
455        let resolved = resolve_log_stream(&prefix);
456        assert_eq!(resolved.len(), crate::constants::MAX_LOG_STREAM_LEN);
457    }
458
459    /// The randomness source produces distinct draws. A `nonce_bytes` that returned a
460    /// constant would pass a format test and fail this one, and it is the single point
461    /// every distinctness property above rests on.
462    #[test]
463    fn the_nonce_source_does_not_repeat_itself() {
464        let drawn: HashSet<[u8; TOKEN_NONCE_BYTES]> = (0..200).map(|_| nonce_bytes()).collect();
465        assert_eq!(drawn.len(), 200);
466        assert!(
467            !drawn.contains(&[0u8; TOKEN_NONCE_BYTES]),
468            "an all-zero draw is the signature of a read that silently did nothing"
469        );
470    }
471}