1use crate::{
12 HOSTNAME_DESCRIPTION, Input, Integer, Number, boolean, float, hostname, port_number, range_description,
13 range_number, text_description, text_length, white_list_description,
14};
15
16pub trait Validator {
34 type Output;
36
37 fn validate(&self, value: Input<'_>) -> Option<Self::Output>;
41
42 fn description(&self) -> String;
46}
47
48fn text(description: Vec<u8>) -> String {
50 String::from_utf8_lossy(&description).into_owned()
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct Boolean;
58
59impl Validator for Boolean {
60 type Output = bool;
61
62 fn validate(&self, value: Input<'_>) -> Option<bool> {
63 if !boolean(true, value) {
64 return None;
65 }
66 Some(match value {
67 Input::Bool(b) => b,
68 Input::Int(i) => i == 1,
69 Input::Str(s) => matches!(s, b"true" | b"1"),
70 _ => false,
71 })
72 }
73
74 fn description(&self) -> String {
75 "Value must be a valid boolean".to_string()
76 }
77}
78
79impl Validator for Integer {
83 type Output = i64;
84
85 fn validate(&self, value: Input<'_>) -> Option<i64> {
86 match value.numeric() {
87 Some(Number::Int(i)) if self.accepts(true, value) => Some(i),
88 _ => None,
89 }
90 }
91
92 fn description(&self) -> String {
93 let mut description = Vec::new();
94 Integer::description(*self, &mut description);
95 text(description)
96 }
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub struct Float;
104
105impl Validator for Float {
106 type Output = f64;
107
108 fn validate(&self, value: Input<'_>) -> Option<f64> {
109 if !float(true, value) {
110 return None;
111 }
112 value.numeric().map(Number::as_f64)
113 }
114
115 fn description(&self) -> String {
116 "Value must be a valid float".to_string()
117 }
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub struct Range {
125 pub min: i64,
127 pub max: i64,
129}
130
131impl Range {
132 pub fn new(min: i64, max: i64) -> Self {
134 Self { min, max }
135 }
136}
137
138impl Validator for Range {
139 type Output = i64;
140
141 fn validate(&self, value: Input<'_>) -> Option<i64> {
142 match range_number(b"integer", value) {
143 Some(Number::Int(i)) if i >= self.min && i <= self.max => Some(i),
144 _ => None,
145 }
146 }
147
148 fn description(&self) -> String {
149 let mut description = Vec::new();
150 range_description(Number::Int(self.min), Number::Int(self.max), &mut description);
151 text(description)
152 }
153}
154
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub struct Port;
161
162impl Validator for Port {
163 type Output = u16;
164
165 fn validate(&self, value: Input<'_>) -> Option<u16> {
166 let digits;
167 let value = match value {
168 Input::Int(i) => {
169 digits = i.to_string();
170 digits.as_bytes()
171 }
172 Input::Str(s) => s,
173 _ => return None,
174 };
175 if !port_number(value) {
176 return None;
177 }
178 std::str::from_utf8(value).ok()?.parse().ok()
179 }
180
181 fn description(&self) -> String {
182 "Value must be a port between 1 and 65535".to_string()
183 }
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190pub struct Text {
191 pub length: i64,
193 pub min: i64,
195}
196
197impl Text {
198 pub fn new(length: i64) -> Self {
200 Self { length, min: 1 }
201 }
202
203 pub fn min(mut self, min: i64) -> Self {
205 self.min = min;
206 self
207 }
208}
209
210impl Validator for Text {
211 type Output = String;
212
213 fn validate(&self, value: Input<'_>) -> Option<String> {
214 let Input::Str(value) = value else {
215 return None;
216 };
217 if !text_length(value, self.min, self.length) {
218 return None;
219 }
220 String::from_utf8(value.to_vec()).ok()
221 }
222
223 fn description(&self) -> String {
224 let mut description = Vec::new();
225 text_description(self.length, self.min, None, false, &mut description);
226 text(description)
227 }
228}
229
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234pub struct Hostname;
235
236impl Validator for Hostname {
237 type Output = String;
238
239 fn validate(&self, value: Input<'_>) -> Option<String> {
240 let Input::Str(value) = value else {
241 return None;
242 };
243 if !hostname(value) {
244 return None;
245 }
246 String::from_utf8(value.to_vec()).ok()
247 }
248
249 fn description(&self) -> String {
250 HOSTNAME_DESCRIPTION.to_string()
251 }
252}
253
254#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258pub struct WhiteList<'a> {
259 pub list: &'a [&'a str],
261}
262
263impl<'a> WhiteList<'a> {
264 pub fn new(list: &'a [&'a str]) -> Self {
266 Self { list }
267 }
268}
269
270impl Validator for WhiteList<'_> {
271 type Output = String;
272
273 fn validate(&self, value: Input<'_>) -> Option<String> {
274 let Input::Str(value) = value else {
275 return None;
276 };
277 self.list.iter().find(|allowed| allowed.as_bytes() == value).map(|allowed| allowed.to_string())
278 }
279
280 fn description(&self) -> String {
281 let mut description = Vec::new();
282 white_list_description(self.list.join(", ").as_bytes(), &mut description);
283 text(description)
284 }
285}
286
287#[cfg(test)]
288mod tests {
289 use super::*;
290
291 #[test]
292 fn booleans() {
293 assert_eq!(Boolean.validate(Input::Bool(true)), Some(true));
294 assert_eq!(Boolean.validate(Input::Str(b"true")), Some(true));
295 assert_eq!(Boolean.validate(Input::Str(b"0")), Some(false));
296 assert_eq!(Boolean.validate(Input::Int(1)), Some(true));
297 assert_eq!(Boolean.validate(Input::Str(b"yes")), None);
298 assert_eq!(Boolean.validate(Input::Int(2)), None);
299 }
300
301 #[test]
302 fn integers() {
303 let byte = Integer::new(8, true).unwrap();
304 assert_eq!(byte.validate(Input::Int(255)), Some(255));
305 assert_eq!(byte.validate(Input::Str(b"255")), Some(255));
306 assert_eq!(byte.validate(Input::Str(b"256")), None);
307 assert_eq!(byte.validate(Input::Float(1.0)), None);
308 assert_eq!(Validator::description(&byte), "Value must be a valid unsigned 8-bit integer between 0 and 255");
309 }
310
311 #[test]
312 fn floats() {
313 assert_eq!(Float.validate(Input::Float(1.5)), Some(1.5));
314 assert_eq!(Float.validate(Input::Int(15)), Some(15.0));
315 assert_eq!(Float.validate(Input::Str(b"1.5")), Some(1.5));
316 assert_eq!(Float.validate(Input::Str(b"fast")), None);
317 assert_eq!(Float.validate(Input::Bool(true)), None);
318 }
319
320 #[test]
321 fn ranges() {
322 let range = Range::new(0, 10);
323 assert_eq!(range.validate(Input::Int(10)), Some(10));
324 assert_eq!(range.validate(Input::Str(b"0")), Some(0));
325 assert_eq!(range.validate(Input::Str(b"11")), None);
326 assert_eq!(range.validate(Input::Int(-1)), None);
327 assert_eq!(range.validate(Input::Float(5.0)), None);
328 assert_eq!(range.validate(Input::Float(f64::INFINITY)), None);
329 assert_eq!(range.description(), "Value must be a valid range between 0 and 10");
330 }
331
332 #[test]
333 fn ports() {
334 assert_eq!(Port.validate(Input::Int(6379)), Some(6379));
335 assert_eq!(Port.validate(Input::Str(b"65535")), Some(65535));
336 assert_eq!(Port.validate(Input::Str(b"65536")), None);
337 assert_eq!(Port.validate(Input::Str(b"080")), None);
338 assert_eq!(Port.validate(Input::Int(0)), None);
339 assert_eq!(Port.validate(Input::Str(b"127.0.0.1:80")), None);
340 }
341
342 #[test]
343 fn texts() {
344 assert_eq!(Text::new(5).validate(Input::Str(b"redis")), Some("redis".to_string()));
345 assert_eq!(Text::new(5).validate(Input::Str(b"redis6")), None);
346 assert_eq!(Text::new(5).validate(Input::Str(b"")), None);
347 assert_eq!(Text::new(5).min(0).validate(Input::Str(b"")), Some(String::new()));
348 assert_eq!(Text::new(0).validate(Input::Str(&[b'a'; 4096])).map(|text| text.len()), Some(4096));
349 assert_eq!(Text::new(5).validate(Input::Int(5)), None);
350 assert_eq!(Text::new(5).validate(Input::Str(b"\xff")), None);
351 assert_eq!(
352 Text::new(5).description(),
353 "Value must be a valid string and at least 1 chars and no longer than 5 chars"
354 );
355 }
356
357 #[test]
358 fn hostnames() {
359 assert_eq!(Hostname.validate(Input::Str(b"redis.internal")), Some("redis.internal".to_string()));
360 assert_eq!(Hostname.validate(Input::Str(b"redis:6379")), None);
361 assert_eq!(Hostname.validate(Input::Str(b"")), None);
362 }
363
364 #[test]
365 fn white_lists() {
366 let level = WhiteList::new(&["high", "low"]);
367 assert_eq!(level.validate(Input::Str(b"low")), Some("low".to_string()));
368 assert_eq!(level.validate(Input::Str(b"LOW")), None);
369 assert_eq!(level.validate(Input::Int(1)), None);
370 assert_eq!(level.description(), "Value must be one of (high, low)");
371 }
372}