Skip to main content

docsrs_cli/domain/
search_query.rs

1//! Validated search query string.
2
3use std::fmt;
4
5use crate::config::MAX_QUERY_CHARS;
6use crate::error::{AppError, AppResult, ErrorKind};
7
8use super::regex::is_hostile_text_char;
9
10/// Validated search query string.
11#[repr(transparent)]
12#[derive(Debug, Clone, PartialEq, Eq, Hash)]
13pub struct SearchQuery(String);
14
15impl SearchQuery {
16    /// Parses a search query.
17    ///
18    /// When `allow_empty` is true, whitespace-only becomes an empty query (list-all).
19    ///
20    /// # Errors
21    ///
22    /// Returns [`ErrorKind::InvalidInput`] when the query is empty without
23    /// `allow_empty`, or when it exceeds the maximum length.
24    pub fn parse(query: &str, allow_empty: bool) -> AppResult<Self> {
25        let q = query.trim();
26        if !allow_empty && q.is_empty() {
27            return Err(AppError::new(
28                ErrorKind::InvalidInput,
29                "search query is empty",
30            ));
31        }
32        if q.chars().count() > MAX_QUERY_CHARS {
33            return Err(AppError::new(
34                ErrorKind::InvalidInput,
35                format!("query exceeds {MAX_QUERY_CHARS} characters"),
36            ));
37        }
38        // Hostile argv: reject C0/C1 controls and invisible/bidi format chars.
39        // Crates.io query is free text but never needs ZWSP, BOM, or bidi overrides.
40        // ASCII domain types (crate/item/version) do not need NFC; free-text search
41        // is not an identity key — we fail closed on format chars instead of silent strip.
42        if q.chars().any(is_hostile_text_char) {
43            return Err(AppError::new(
44                ErrorKind::InvalidInput,
45                "search query contains control or invisible characters",
46            ));
47        }
48        Ok(Self(q.to_string()))
49    }
50
51    /// Borrow the validated query.
52    #[must_use]
53    pub fn as_str(&self) -> &str {
54        &self.0
55    }
56}
57
58impl AsRef<str> for SearchQuery {
59    fn as_ref(&self) -> &str {
60        self.as_str()
61    }
62}
63
64impl fmt::Display for SearchQuery {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        f.write_str(self.as_str())
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73    use std::mem::size_of;
74
75    #[test]
76    fn search_query_rules() {
77        assert!(SearchQuery::parse("", false).is_err());
78        assert_eq!(SearchQuery::parse("  ", true).unwrap().as_str(), "");
79        assert_eq!(
80            SearchQuery::parse("serde", false).unwrap().as_str(),
81            "serde"
82        );
83        assert!(SearchQuery::parse(&"q".repeat(MAX_QUERY_CHARS + 1), false).is_err());
84        assert!(SearchQuery::parse("evil\0null", false).is_err());
85        assert!(SearchQuery::parse("bad\nline", false).is_err());
86        // Zero-width / bidi format characters (not `char::is_control`).
87        assert!(SearchQuery::parse("evil\u{200B}zwsp", false).is_err());
88        assert!(SearchQuery::parse("evil\u{202E}bidi", false).is_err());
89        assert!(SearchQuery::parse("evil\u{FEFF}bom", false).is_err());
90    }
91
92    #[test]
93    fn search_query_transparent_layout() {
94        assert_eq!(size_of::<SearchQuery>(), size_of::<String>());
95    }
96}