utils/
validators.rs

1// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4// Misc data format validations, shared by multiple Firecracker components.
5
6const MAX_INSTANCE_ID_LEN: usize = 64;
7const MIN_INSTANCE_ID_LEN: usize = 1;
8
9#[derive(Debug, PartialEq, Eq, thiserror::Error, displaydoc::Display)]
10pub enum ValidatorError {
11    /// Invalid char ({0}) at position {1}
12    InvalidChar(char, usize), // (char, position)
13    /// Invalid len ({0});  the length must be between {1} and {2}
14    InvalidLen(usize, usize, usize), // (length, min, max)
15}
16
17/// Checks that the instance id only contains alphanumeric chars and hyphens
18/// and that the size is between 1 and 64 characters.
19pub fn validate_instance_id(input: &str) -> Result<(), ValidatorError> {
20    if input.len() > MAX_INSTANCE_ID_LEN || input.len() < MIN_INSTANCE_ID_LEN {
21        return Err(ValidatorError::InvalidLen(
22            input.len(),
23            MIN_INSTANCE_ID_LEN,
24            MAX_INSTANCE_ID_LEN,
25        ));
26    }
27    for (i, c) in input.chars().enumerate() {
28        if !(c == '-' || c.is_alphanumeric()) {
29            return Err(ValidatorError::InvalidChar(c, i));
30        }
31    }
32    Ok(())
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn test_validate_instance_id() {
41        assert_eq!(
42            format!("{}", validate_instance_id("").unwrap_err()),
43            "Invalid len (0);  the length must be between 1 and 64"
44        );
45        validate_instance_id("12-3aa").unwrap();
46        assert_eq!(
47            format!("{}", validate_instance_id("12_3aa").unwrap_err()),
48            "Invalid char (_) at position 2"
49        );
50        assert_eq!(
51            validate_instance_id("12:3aa").unwrap_err(),
52            ValidatorError::InvalidChar(':', 2)
53        );
54        assert_eq!(
55            validate_instance_id(str::repeat("a", MAX_INSTANCE_ID_LEN + 1).as_str()).unwrap_err(),
56            ValidatorError::InvalidLen(
57                MAX_INSTANCE_ID_LEN + 1,
58                MIN_INSTANCE_ID_LEN,
59                MAX_INSTANCE_ID_LEN
60            )
61        );
62    }
63}