Coverage Report

Created: 2026-12-05 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
super-voice-shared/src/tts/validation/inputs.rs
Line
Count
Source
1
// SPDX-License-Identifier: GPL-3.0-only
2
//! Validators for protocol input fields.
3
4
use super::ValidationError;
5
use super::limits;
6
use serde_json::Value;
7
8
/// Validate string fields with length and character restrictions
9
///
10
/// # Errors
11
/// Returns [`ValidationError::StringTooLong`] when `value` exceeds `max_length`,
12
/// or [`ValidationError::InvalidCharacters`] when control characters are found.
13
278
pub fn validate_string(
14
278
    value: &str,
15
278
    field_name: &str,
16
278
    max_length: usize,
17
278
) -> Result<(), ValidationError> {
18
278
    if value.len() > max_length {
19
1
        return Err(ValidationError::StringTooLong {
20
1
            len: value.len(),
21
1
            max: max_length,
22
1
        });
23
277
    }
24
25
    // Check for control characters that could cause issues
26
277
    if value
27
277
        .chars()
28
6.60k
        .any(|c| c.is_control() && 
c != '\n'3
&&
c != '\r'2
&&
c != '\t'2
)
29
    {
30
1
        return Err(ValidationError::InvalidCharacters {
31
1
            field: field_name.to_string(),
32
1
        });
33
276
    }
34
35
276
    Ok(())
36
278
}
37
38
/// Validate optional string fields
39
///
40
/// # Errors
41
/// Propagates errors from [`validate_string`] when `value` is `Some` and
42
/// validation fails.
43
556
pub fn validate_optional_string(
44
556
    value: &Option<String>,
45
556
    field_name: &str,
46
556
    max_length: usize,
47
556
) -> Result<(), ValidationError> {
48
556
    if let Some(s) = value {
49
102
        validate_string(s, field_name, max_length)
?0
;
50
454
    }
51
556
    Ok(())
52
556
}
53
54
/// Validate required string fields (non-empty)
55
///
56
/// # Errors
57
/// Returns [`ValidationError::EmptyField`] when `value` is `None` or empty,
58
/// or propagates errors from [`validate_string`].
59
0
pub fn validate_required_string(
60
0
    value: &Option<String>,
61
0
    field_name: &str,
62
0
    max_length: usize,
63
0
) -> Result<(), ValidationError> {
64
0
    match value {
65
0
        Some(s) if s.is_empty() => Err(ValidationError::EmptyField {
66
0
            field: field_name.to_string(),
67
0
        }),
68
0
        Some(s) => validate_string(s, field_name, max_length),
69
0
        None => Err(ValidationError::EmptyField {
70
0
            field: field_name.to_string(),
71
0
        }),
72
    }
73
0
}
74
75
/// Validate event types list
76
///
77
/// # Errors
78
/// Returns [`ValidationError::TooManyEventTypes`] if the list exceeds
79
/// [`limits::MAX_EVENT_TYPES`], or any error returned by [`validate_string`]
80
/// for invalid event type strings.
81
0
pub fn validate_event_types(event_types: &[String]) -> Result<(), ValidationError> {
82
0
    if event_types.len() > limits::MAX_EVENT_TYPES {
83
0
        return Err(ValidationError::TooManyEventTypes {
84
0
            count: event_types.len(),
85
0
            max: limits::MAX_EVENT_TYPES,
86
0
        });
87
0
    }
88
89
    // Validate each event type string
90
0
    for event_type in event_types {
91
0
        validate_string(event_type, "event_type", limits::MAX_NAME_LENGTH)?;
92
    }
93
94
0
    Ok(())
95
0
}
96
97
/// Validate pagination limit
98
///
99
/// # Errors
100
/// Returns [`ValidationError::InvalidLimit`] if `limit` is 0 or greater
101
/// than [`limits::MAX_EVENTS_LIMIT`].
102
0
pub fn validate_limit(limit: u32) -> Result<(), ValidationError> {
103
0
    if limit == 0 || limit > limits::MAX_EVENTS_LIMIT {
104
0
        return Err(ValidationError::InvalidLimit {
105
0
            limit,
106
0
            max: limits::MAX_EVENTS_LIMIT,
107
0
        });
108
0
    }
109
0
    Ok(())
110
0
}
111
112
/// Validate JSON data size and complexity
113
///
114
/// # Errors
115
/// Returns:
116
/// - [`ValidationError::JsonTooLarge`] if the serialized size exceeds
117
///   [`limits::MAX_JSON_SIZE`].
118
/// - [`ValidationError::JsonTooDeep`] if the nesting depth exceeds
119
///   [`limits::MAX_JSON_DEPTH`].
120
82
pub fn validate_json_value(value: &Value) -> Result<(), ValidationError> {
121
    // Check serialized size
122
82
    let serialized = serde_json::to_vec(value).map_err(|_| ValidationError::JsonTooLarge {
123
0
        size: 0,
124
0
        max: limits::MAX_JSON_SIZE,
125
0
    })?;
126
127
82
    if serialized.len() > limits::MAX_JSON_SIZE {
128
0
        return Err(ValidationError::JsonTooLarge {
129
0
            size: serialized.len(),
130
0
            max: limits::MAX_JSON_SIZE,
131
0
        });
132
82
    }
133
134
    // Check nesting depth
135
82
    check_depth(value, 0, limits::MAX_JSON_DEPTH)
?1
;
136
137
81
    Ok(())
138
82
}
139
140
/// Validate command strings to prevent injection
141
///
142
/// # Errors
143
/// Returns [`ValidationError::InvalidCharacters`] if the command contains
144
/// disallowed characters, or any error returned by [`validate_string`].
145
145
pub fn validate_command(command: &str) -> Result<(), ValidationError> {
146
145
    validate_string(command, "command", limits::MAX_NAME_LENGTH)
?0
;
147
148
    // Only allow alphanumeric characters, underscores, and hyphens
149
145
    if !command
150
145
        .chars()
151
2.10k
        .all(|c| c.is_alphanumeric() || 
c == '_'218
||
c == '-'4
)
152
    {
153
3
        return Err(ValidationError::InvalidCharacters {
154
3
            field: "command".to_string(),
155
3
        });
156
142
    }
157
158
142
    Ok(())
159
145
}
160
161
// Helper to check JSON nesting depth without defining items after statements
162
209
fn check_depth(
163
209
    value: &Value,
164
209
    current_depth: usize,
165
209
    max_depth: usize,
166
209
) -> Result<(), ValidationError> {
167
209
    if current_depth > max_depth {
168
1
        return Err(ValidationError::JsonTooDeep {
169
1
            depth: current_depth,
170
1
            max: max_depth,
171
1
        });
172
208
    }
173
174
208
    match value {
175
        Value::Object(obj) => {
176
92
            for v in obj.values() {
177
127
                check_depth(v, current_depth + 1, max_depth)
?11
;
178
            }
179
        }
180
        Value::Array(arr) => {
181
0
            for v in arr {
182
0
                check_depth(v, current_depth + 1, max_depth)?;
183
            }
184
        }
185
116
        _ => {}
186
    }
187
188
197
    Ok(())
189
209
}
190
191
#[cfg(test)]
192
mod tests {
193
    use super::*;
194
    use serde_json::json;
195
196
    #[test]
197
1
    fn test_validate_string() {
198
        // Valid string
199
1
        assert!(validate_string("hello", "test", 10).is_ok());
200
201
        // Too long
202
1
        assert!(validate_string("hello world!", "test", 5).is_err());
203
204
        // Control characters
205
1
        assert!(validate_string("hello\x00world", "test", 20).is_err());
206
207
        // Allowed whitespace
208
1
        assert!(validate_string("hello\nworld\ttest", "test", 20).is_ok());
209
1
    }
210
211
    #[test]
212
1
    fn test_validate_json_value() {
213
        // Valid JSON
214
1
        let json = json!({"key": "value", "number": 42});
215
1
        assert!(validate_json_value(&json).is_ok());
216
217
        // Too nested - create a deeply nested JSON structure
218
1
        let mut nested = json!({"level_0": {}});
219
        // Build a nested JSON that exceeds the depth limit
220
1
        for i in 1..15 {
221
14
            nested = json!({format!("level_{}", i): nested});
222
        }
223
1
        assert!(validate_json_value(&nested).is_err());
224
1
    }
225
226
    #[test]
227
1
    fn test_validate_command() {
228
        // Valid commands
229
1
        assert!(validate_command("speak").is_ok());
230
1
        assert!(validate_command("get_events").is_ok());
231
1
        assert!(validate_command("set-model").is_ok());
232
233
        // Invalid commands
234
1
        assert!(validate_command("rm -rf /").is_err());
235
1
        assert!(validate_command("cmd; rm -rf /").is_err());
236
1
        assert!(validate_command("cmd|ls").is_err());
237
1
    }
238
}