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, ErrorDetail, Subject};
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 [`crate::error::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::of(ErrorDetail::Empty {
28                subject: Subject::SearchQuery,
29            }));
30        }
31        if q.chars().count() > MAX_QUERY_CHARS {
32            return Err(AppError::of(ErrorDetail::TooLong {
33                subject: Subject::SearchQuery,
34                limit: MAX_QUERY_CHARS,
35            }));
36        }
37        // Hostile argv: reject C0/C1 controls and invisible/bidi format chars.
38        // Crates.io query is free text but never needs ZWSP, BOM, or bidi overrides.
39        // ASCII domain types (crate/item/version) do not need NFC; free-text search
40        // is not an identity key — we fail closed on format chars instead of silent strip.
41        if q.chars().any(is_hostile_text_char) {
42            return Err(AppError::of(ErrorDetail::ControlCharacters {
43                subject: Subject::SearchQuery,
44            }));
45        }
46        Ok(Self(q.to_string()))
47    }
48
49    /// Borrow the validated query.
50    #[must_use]
51    pub fn as_str(&self) -> &str {
52        &self.0
53    }
54}
55
56impl AsRef<str> for SearchQuery {
57    fn as_ref(&self) -> &str {
58        self.as_str()
59    }
60}
61
62impl fmt::Display for SearchQuery {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        f.write_str(self.as_str())
65    }
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71    use std::mem::size_of;
72
73    #[test]
74    fn search_query_rules() {
75        assert!(SearchQuery::parse("", false).is_err());
76        assert_eq!(SearchQuery::parse("  ", true).unwrap().as_str(), "");
77        assert_eq!(
78            SearchQuery::parse("serde", false).unwrap().as_str(),
79            "serde"
80        );
81        assert!(SearchQuery::parse(&"q".repeat(MAX_QUERY_CHARS + 1), false).is_err());
82        assert!(SearchQuery::parse("evil\0null", false).is_err());
83        assert!(SearchQuery::parse("bad\nline", false).is_err());
84        // Zero-width / bidi format characters (not `char::is_control`).
85        assert!(SearchQuery::parse("evil\u{200B}zwsp", false).is_err());
86        assert!(SearchQuery::parse("evil\u{202E}bidi", false).is_err());
87        assert!(SearchQuery::parse("evil\u{FEFF}bom", false).is_err());
88    }
89
90    #[test]
91    fn search_query_transparent_layout() {
92        assert_eq!(size_of::<SearchQuery>(), size_of::<String>());
93    }
94}