Skip to main content

rocketmq_admin_cli/
validators.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use rocketmq_admin_core::core::RocketMQError;
16use rocketmq_admin_core::core::RocketMQResult;
17use rocketmq_admin_core::core::ToolsError;
18
19pub fn validate_namesrv_addr(addr: &str) -> RocketMQResult<()> {
20    if addr.is_empty() {
21        return Err(RocketMQError::Tools(ToolsError::ValidationError {
22            field: "namesrv_addr".to_string(),
23            reason: "NameServer address cannot be empty".to_string(),
24        }));
25    }
26
27    for single_addr in addr.split(';').map(str::trim).filter(|s| !s.is_empty()) {
28        let parts: Vec<&str> = single_addr.split(':').collect();
29
30        if parts.len() != 2 {
31            return Err(RocketMQError::Tools(ToolsError::ValidationError {
32                field: "namesrv_addr".to_string(),
33                reason: format!("Invalid format '{single_addr}', expected 'host:port'"),
34            }));
35        }
36
37        parts[1].parse::<u16>().map_err(|_| {
38            RocketMQError::Tools(ToolsError::ValidationError {
39                field: "namesrv_addr".to_string(),
40                reason: format!("Invalid port '{}' in address '{single_addr}'", parts[1]),
41            })
42        })?;
43    }
44
45    Ok(())
46}
47
48pub fn validate_topic_name(topic: &str) -> RocketMQResult<()> {
49    if topic.is_empty() {
50        return Err(RocketMQError::Tools(ToolsError::ValidationError {
51            field: "topic".to_string(),
52            reason: "Topic name cannot be empty".to_string(),
53        }));
54    }
55
56    if topic.len() > 127 {
57        return Err(RocketMQError::Tools(ToolsError::ValidationError {
58            field: "topic".to_string(),
59            reason: format!("Name '{topic}' exceeds maximum length of 127 characters"),
60        }));
61    }
62
63    const INVALID_CHARS: &[char] = &['/', '\\', '|', '<', '>', '?', '*', '"', ':'];
64
65    if let Some(ch) = topic.chars().find(|c| INVALID_CHARS.contains(c)) {
66        return Err(RocketMQError::Tools(ToolsError::ValidationError {
67            field: "topic".to_string(),
68            reason: format!("Name '{topic}' contains invalid character '{ch}'"),
69        }));
70    }
71
72    Ok(())
73}
74
75pub fn validate_queue_nums(nums: i32, name: &str) -> RocketMQResult<()> {
76    match nums {
77        n if n <= 0 => Err(RocketMQError::Tools(ToolsError::ValidationError {
78            field: name.to_string(),
79            reason: format!("must be positive, got {nums}"),
80        })),
81        n if n > 1024 => Err(RocketMQError::Tools(ToolsError::ValidationError {
82            field: name.to_string(),
83            reason: format!("exceeds maximum value of 1024, got {nums}"),
84        })),
85        _ => Ok(()),
86    }
87}
88
89pub fn validate_perm(perm: i32) -> RocketMQResult<()> {
90    match perm {
91        2 | 4 | 6 => Ok(()),
92        _ => Err(RocketMQError::Tools(ToolsError::ValidationError {
93            field: "perm".to_string(),
94            reason: format!("Invalid value {perm}, valid values are: 2 (read), 4 (write), 6 (read+write)"),
95        })),
96    }
97}
98
99pub fn validate_broker_name(name: &str) -> RocketMQResult<()> {
100    match name {
101        "" => Err(RocketMQError::Tools(ToolsError::ValidationError {
102            field: "broker_name".to_string(),
103            reason: "Broker name cannot be empty".to_string(),
104        })),
105        n if n.len() > 127 => Err(RocketMQError::Tools(ToolsError::ValidationError {
106            field: "broker_name".to_string(),
107            reason: format!("Name '{name}' exceeds maximum length of 127 characters"),
108        })),
109        _ => Ok(()),
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116
117    #[test]
118    fn validates_namesrv_addresses() {
119        assert!(validate_namesrv_addr("192.168.0.1:9876").is_ok());
120        assert!(validate_namesrv_addr("192.168.0.1:9876;192.168.0.2:9876").is_ok());
121        assert!(validate_namesrv_addr("").is_err());
122        assert!(validate_namesrv_addr("192.168.0.1").is_err());
123        assert!(validate_namesrv_addr("192.168.0.1:abc").is_err());
124    }
125
126    #[test]
127    fn validates_topic_names() {
128        assert!(validate_topic_name("test_topic").is_ok());
129        assert!(validate_topic_name("").is_err());
130        assert!(validate_topic_name(&"a".repeat(128)).is_err());
131        assert!(validate_topic_name("topic/name").is_err());
132    }
133
134    #[test]
135    fn validates_queue_nums() {
136        assert!(validate_queue_nums(8, "read_queue_nums").is_ok());
137        assert!(validate_queue_nums(-1, "read_queue_nums").is_err());
138        assert!(validate_queue_nums(0, "read_queue_nums").is_err());
139        assert!(validate_queue_nums(2000, "read_queue_nums").is_err());
140    }
141
142    #[test]
143    fn validates_permissions() {
144        assert!(validate_perm(2).is_ok());
145        assert!(validate_perm(4).is_ok());
146        assert!(validate_perm(6).is_ok());
147        assert!(validate_perm(0).is_err());
148        assert!(validate_perm(8).is_err());
149    }
150
151    #[test]
152    fn validates_broker_names() {
153        assert!(validate_broker_name("broker-a").is_ok());
154        assert!(validate_broker_name("").is_err());
155        assert!(validate_broker_name(&"a".repeat(128)).is_err());
156    }
157}