Skip to main content

microvms_domain/
hooks.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The two hook-timeout ceilings, as two types that cannot be swapped.
3//!
4//! Two families of lifecycle hook with ceilings 60x apart:
5//!
6//! * `run`, `resume`, `suspend`, `terminate` — max **60 seconds**. These wait on a
7//!   daemon that is already booted, so 60s is generous and a daemon slower than that
8//!   fails the launch with no way to ask for more time.
9//! * `ready`, `validate` — max **3600 seconds**. These are image-*build* hooks; a
10//!   build hook waits on a Dockerfile.
11//!
12//! Both from the pinned service model (`MicrovmHooks*TimeoutInSecondsInteger` and
13//! `MicrovmImageHooks*TimeoutInSecondsInteger`, API version 2025-09-09), checked
14//! against it by the build gate (TRAP-12).
15//!
16//! # Why two types rather than one with a comment
17//!
18//! Because the trap is the confusion, not the number. A caller who picks one value
19//! large enough for a build hook — 300, say — passes image validation and is rejected
20//! on the run family, *after* the artifact upload, reported as a constraint on a
21//! field they did not know had two different ceilings. Runtime validation rejects
22//! an out-of-range value only after it has been assigned to a hook family.
23//!
24//! Here each ceiling is its own type, so a build timeout in a run-hook field is a
25//! compile error. There is deliberately **no conversion between them** — no `From`,
26//! no `as_run()`, no shared trait with a `secs()` method that a generic function
27//! could use to launder one into the other. A conversion is the whole trap with an
28//! extra step: `BuildHookTimeout::try_new(300)?` is valid, and if it could become a
29//! `RunHookTimeout` the 60s ceiling would be enforced nowhere.
30//!
31//! The only thing both types offer is a way *out* to a plain integer, at the wire
32//! boundary where the request body is built and the field name already says which
33//! family it is.
34
35use std::fmt;
36
37use crate::constants::{
38    MAX_IMAGE_HOOK_TIMEOUT_SEC, MAX_MICROVM_HOOK_TIMEOUT_SEC, MODEL_API_VERSION,
39};
40use crate::error::Error;
41
42/// A timeout for the `run`, `resume`, `suspend`, or `terminate` hook: 1..=60 seconds.
43///
44/// See the module docs for why this cannot be built from a [`BuildHookTimeout`].
45#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
46pub struct RunHookTimeout(u32);
47
48/// A timeout for the `ready` or `validate` image-build hook: 1..=3600 seconds.
49///
50/// See the module docs for why this cannot be built from a [`RunHookTimeout`].
51#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
52pub struct BuildHookTimeout(u32);
53
54impl RunHookTimeout {
55    /// The service ceiling for the MicroVM hook family.
56    pub const MAX_SECS: u32 = MAX_MICROVM_HOOK_TIMEOUT_SEC;
57
58    /// A run-family timeout, or a local reject naming both ceilings.
59    ///
60    /// The error names the *other* family's ceiling too, because the caller who hits
61    /// this is nearly always someone who picked a build-hook number: telling them 60
62    /// is the limit answers a question they did not ask, and telling them the two
63    /// families differ by 60x answers the one they did.
64    pub fn try_new(secs: u32) -> Result<Self, Error> {
65        if (1..=Self::MAX_SECS).contains(&secs) {
66            return Ok(Self(secs));
67        }
68        Err(Error::invalid_arg(out_of_range_message(
69            "microvmHooks",
70            secs,
71            Self::MAX_SECS,
72            BuildHookTimeout::MAX_SECS,
73        )))
74    }
75
76    /// The value to put on the wire. The only way out of the newtype.
77    pub fn as_secs(self) -> u32 {
78        self.0
79    }
80}
81
82impl BuildHookTimeout {
83    /// The service ceiling for the image-hook family.
84    pub const MAX_SECS: u32 = MAX_IMAGE_HOOK_TIMEOUT_SEC;
85
86    /// A build-family timeout, or a local reject naming both ceilings.
87    pub fn try_new(secs: u32) -> Result<Self, Error> {
88        if (1..=Self::MAX_SECS).contains(&secs) {
89            return Ok(Self(secs));
90        }
91        Err(Error::invalid_arg(out_of_range_message(
92            "microvmImageHooks",
93            secs,
94            Self::MAX_SECS,
95            RunHookTimeout::MAX_SECS,
96        )))
97    }
98
99    /// The value to put on the wire. The only way out of the newtype.
100    pub fn as_secs(self) -> u32 {
101        self.0
102    }
103}
104
105impl fmt::Display for RunHookTimeout {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        write!(f, "{}s", self.0)
108    }
109}
110
111impl fmt::Display for BuildHookTimeout {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        write!(f, "{}s", self.0)
114    }
115}
116
117/// The refusal both constructors raise, naming the family, the ceiling, and the
118/// other family's ceiling.
119///
120/// Shared so both constructors describe their family and the other ceiling consistently.
121fn out_of_range_message(block: &str, secs: u32, ceiling: u32, other: u32) -> String {
122    format!(
123        "{block} timeout of {secs}s is outside the accepted range 1..{ceiling} (service model \
124         {MODEL_API_VERSION}). The two hook families have ceilings 60x apart — {block} caps at \
125         {ceiling}s while the other family caps at {other}s — because a build hook waits on a \
126         Dockerfile and a run hook waits on a daemon that is already booted \
127         (docs/PLATFORM.md, 'The `runHookPayload` ceiling is 4096 bytes, and the service model \
128         states it')."
129    )
130}
131
132/// A hook port: 1..=65535 (`HooksPortInteger`).
133///
134/// Here rather than in a caller because it is the same shape of constraint from the
135/// same table, and because the daemon's port is a field a caller sets by hand.
136/// Returned as a `u16` since that is what a port is; the guard exists for the two
137/// values a `u16` still gets wrong — 0, and a figure that arrived as a wider integer.
138pub fn require_hook_port(port: u32) -> Result<u16, Error> {
139    if (1..=u32::from(u16::MAX)).contains(&port) {
140        return Ok(port as u16);
141    }
142    Err(Error::invalid_arg(format!(
143        "hooks.port={port} is outside 1..{} (service model {MODEL_API_VERSION}).",
144        u16::MAX
145    )))
146}
147
148#[cfg(test)]
149mod tests {
150    use proptest::prelude::*;
151
152    use super::*;
153    use crate::error::ErrorKind;
154
155    /// The two ceilings, as literals. The 60x gap is the whole reason there are two
156    /// types, so a change to either number is a change to the design.
157    #[test]
158    fn the_two_families_cap_sixty_seconds_apart_by_a_factor_of_sixty() {
159        assert_eq!(RunHookTimeout::MAX_SECS, 60);
160        assert_eq!(BuildHookTimeout::MAX_SECS, 3600);
161        assert_eq!(
162            BuildHookTimeout::MAX_SECS,
163            RunHookTimeout::MAX_SECS * 60,
164            "the 60x gap is the finding"
165        );
166    }
167
168    /// The inclusive boundaries on both sides, for both families. `0` is refused
169    /// because the model's minimum is 1, and a zero timeout is a hook that cannot
170    /// succeed.
171    #[test]
172    fn each_family_accepts_its_ceiling_and_refuses_one_past_it() {
173        assert_eq!(RunHookTimeout::try_new(1).expect("1s fits").as_secs(), 1);
174        assert_eq!(RunHookTimeout::try_new(60).expect("60s fits").as_secs(), 60);
175        assert!(RunHookTimeout::try_new(0).is_err());
176        assert!(RunHookTimeout::try_new(61).is_err());
177
178        assert_eq!(BuildHookTimeout::try_new(1).expect("1s fits").as_secs(), 1);
179        assert_eq!(
180            BuildHookTimeout::try_new(3600)
181                .expect("3600s fits")
182                .as_secs(),
183            3600
184        );
185        assert!(BuildHookTimeout::try_new(0).is_err());
186        assert!(BuildHookTimeout::try_new(3601).is_err());
187    }
188
189    /// The trap, at the value that triggers it. 300 is a plausible build-hook timeout
190    /// and is legal for the image family; the run family refuses it, and the message
191    /// has to explain *why the same number was fine elsewhere* or the caller reads it
192    /// as arbitrary.
193    #[test]
194    fn a_build_sized_timeout_is_refused_by_the_run_family_naming_both_ceilings() {
195        let build = BuildHookTimeout::try_new(300).expect("300s is legal for a build hook");
196        assert_eq!(build.as_secs(), 300);
197
198        let err = RunHookTimeout::try_new(300).expect_err("300s is not legal for a run hook");
199        assert_eq!(err.kind(), ErrorKind::InvalidArg);
200        let message = err.to_string();
201        assert!(message.contains("microvmHooks"), "{message}");
202        assert!(message.contains("1..60"), "{message}");
203        assert!(
204            message.contains("3600s"),
205            "must name the other ceiling: {message}"
206        );
207        assert!(message.contains("60x apart"), "{message}");
208        assert!(
209            message.contains("2025-09-09"),
210            "must name the model: {message}"
211        );
212    }
213
214    /// The image family's refusal names the run family's ceiling, symmetrically. A
215    /// one-directional message would leave the caller who over-shot 3600 without the
216    /// fact that a smaller number is a different family's limit.
217    #[test]
218    fn the_build_family_refusal_names_the_run_ceiling() {
219        let err = BuildHookTimeout::try_new(7200).expect_err("7200s is past the image ceiling");
220        let message = err.to_string();
221        assert!(message.contains("microvmImageHooks"), "{message}");
222        assert!(message.contains("1..3600"), "{message}");
223        assert!(
224            message.contains("60s"),
225            "must name the other ceiling: {message}"
226        );
227    }
228
229    /// A port outside the model's range is refused; the boundaries are inclusive.
230    #[test]
231    fn a_hook_port_outside_the_model_range_is_refused() {
232        assert_eq!(require_hook_port(1).expect("1 fits"), 1);
233        assert_eq!(require_hook_port(9000).expect("9000 fits"), 9000);
234        assert_eq!(require_hook_port(65535).expect("65535 fits"), 65535);
235        for bad in [0, 65536, u32::MAX] {
236            let err = require_hook_port(bad).expect_err("outside 1..65535");
237            assert_eq!(err.kind(), ErrorKind::InvalidArg, "{bad}");
238            assert!(err.to_string().contains("1..65535"), "{bad}");
239        }
240    }
241
242    proptest! {
243        /// The verdict over the whole domain, for both families at once: accepted iff
244        /// in `1..=ceiling`, and a value legal for one family is refused by the other
245        /// for every figure in the 61..=3600 band. That band is the trap's whole
246        /// surface, and a property that only checked each type separately would not
247        /// assert the two disagree.
248        #[test]
249        fn the_two_ceilings_disagree_across_the_whole_sixty_to_thirty_six_hundred_band(secs: u32) {
250            let run = RunHookTimeout::try_new(secs);
251            let build = BuildHookTimeout::try_new(secs);
252
253            prop_assert_eq!(run.is_ok(), (1..=60).contains(&secs));
254            prop_assert_eq!(build.is_ok(), (1..=3600).contains(&secs));
255
256            if (61..=3600).contains(&secs) {
257                prop_assert!(build.is_ok(), "{} is a legal build timeout", secs);
258                let err = run.expect_err("but not a legal run timeout");
259                prop_assert_eq!(err.kind(), ErrorKind::InvalidArg);
260            }
261            if let Ok(run) = RunHookTimeout::try_new(secs) {
262                prop_assert_eq!(run.as_secs(), secs);
263            }
264            if let Ok(build) = BuildHookTimeout::try_new(secs) {
265                prop_assert_eq!(build.as_secs(), secs);
266            }
267        }
268    }
269}