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
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Misc data format validations, shared by multiple Firecracker components.
const MAX_INSTANCE_ID_LEN: usize = 64;
const MIN_INSTANCE_ID_LEN: usize = 1;
#[derive(Debug, PartialEq, Eq, thiserror::Error, displaydoc::Display)]
pub enum ValidatorError {
/// Invalid char ({0}) at position {1}
InvalidChar(char, usize), // (char, position)
/// Invalid len ({0}); the length must be between {1} and {2}
InvalidLen(usize, usize, usize), // (length, min, max)
}
/// Checks that the instance id only contains alphanumeric chars and hyphens
/// and that the size is between 1 and 64 characters.
pub fn validate_instance_id(input: &str) -> Result<(), ValidatorError> {
if input.len() > MAX_INSTANCE_ID_LEN || input.len() < MIN_INSTANCE_ID_LEN {
return Err(ValidatorError::InvalidLen(
input.len(),
MIN_INSTANCE_ID_LEN,
MAX_INSTANCE_ID_LEN,
));
}
for (i, c) in input.chars().enumerate() {
if !(c == '-' || c.is_alphanumeric()) {
return Err(ValidatorError::InvalidChar(c, i));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_validate_instance_id() {
assert_eq!(
format!("{}", validate_instance_id("").unwrap_err()),
"Invalid len (0); the length must be between 1 and 64"
);
validate_instance_id("12-3aa").unwrap();
assert_eq!(
format!("{}", validate_instance_id("12_3aa").unwrap_err()),
"Invalid char (_) at position 2"
);
assert_eq!(
validate_instance_id("12:3aa").unwrap_err(),
ValidatorError::InvalidChar(':', 2)
);
assert_eq!(
validate_instance_id(str::repeat("a", MAX_INSTANCE_ID_LEN + 1).as_str()).unwrap_err(),
ValidatorError::InvalidLen(
MAX_INSTANCE_ID_LEN + 1,
MIN_INSTANCE_ID_LEN,
MAX_INSTANCE_ID_LEN
)
);
}
}