1use std::collections::HashMap;
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Clone, Default, Serialize, Deserialize)]
20pub struct ScoutConfig {
21 #[serde(default = "default_driver")]
22 pub driver: String,
23 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
27 pub options: HashMap<String, serde_json::Value>,
28}
29
30fn is_secret_key(key: &str) -> bool {
32 let k = key.to_ascii_lowercase();
33 k.ends_with("api_key")
34 || k.ends_with("apikey")
35 || k.ends_with("token")
36 || k.contains("secret")
37 || k.contains("password")
38}
39
40impl std::fmt::Debug for ScoutConfig {
41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42 let options: HashMap<&str, serde_json::Value> = self
43 .options
44 .iter()
45 .map(|(k, v)| {
46 let v = if is_secret_key(k) {
47 serde_json::Value::String("<redacted>".to_string())
48 } else {
49 v.clone()
50 };
51 (k.as_str(), v)
52 })
53 .collect();
54 f.debug_struct("ScoutConfig")
55 .field("driver", &self.driver)
56 .field("options", &options)
57 .finish()
58 }
59}
60
61impl ScoutConfig {
62 pub fn collection() -> Self {
63 Self {
64 driver: "collection".to_string(),
65 ..Self::default()
66 }
67 }
68
69 pub fn elasticsearch(host: impl Into<String>, api_key: Option<String>) -> Self {
70 let mut config = Self::collection();
71 config.driver = "elasticsearch".to_string();
72 config.insert("elasticsearch.host", host.into());
73 if let Some(api_key) = api_key {
74 config.insert("elasticsearch.api_key", api_key);
75 }
76 config
77 }
78
79 pub fn opensearch(host: impl Into<String>, api_key: Option<String>) -> Self {
80 let mut config = Self::collection();
81 config.driver = "opensearch".to_string();
82 config.insert("opensearch.host", host.into());
83 if let Some(api_key) = api_key {
84 config.insert("opensearch.api_key", api_key);
85 }
86 config
87 }
88
89 pub fn meilisearch(host: impl Into<String>, api_key: impl Into<String>) -> Self {
90 let mut config = Self::collection();
91 config.driver = "meilisearch".to_string();
92 config.insert("meilisearch.host", host.into());
93 config.insert("meilisearch.api_key", api_key.into());
94 config
95 }
96
97 pub fn typesense(host: impl Into<String>, api_key: impl Into<String>) -> Self {
98 let mut config = Self::collection();
99 config.driver = "typesense".to_string();
100 config.insert("typesense.host", host.into());
101 config.insert("typesense.api_key", api_key.into());
102 config
103 }
104
105 pub fn algolia(app_id: impl Into<String>, api_key: impl Into<String>) -> Self {
106 let mut config = Self::collection();
107 config.driver = "algolia".to_string();
108 config.insert("algolia.app_id", app_id.into());
109 config.insert("algolia.api_key", api_key.into());
110 config
111 }
112
113 pub fn database(url: impl Into<String>, fields: Vec<String>) -> Self {
114 let mut config = Self::collection();
115 config.driver = "database".to_string();
116 config.insert("database.url", url.into());
117 config.insert("database.fields", serde_json::json!(fields));
118 config
119 }
120
121 pub fn null() -> Self {
122 Self {
123 driver: "null".to_string(),
124 ..Self::collection()
125 }
126 }
127
128 pub fn xunsearch(host: impl Into<String>, project: impl Into<String>) -> Self {
129 let mut config = Self::collection();
130 config.driver = "xunsearch".to_string();
131 config.insert("xunsearch.host", host.into());
132 config.insert("xunsearch.project", project.into());
133 config
134 }
135
136 pub fn insert(&mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) {
137 self.options.insert(key.into(), value.into());
138 }
139
140 pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
141 self.options.get(key)
142 }
143}
144
145fn default_driver() -> String {
146 "collection".to_string()
147}
148
149pub fn validate_index_name(index: &str) -> crate::Result<()> {
160 let bad = index.is_empty()
161 || index.starts_with('.')
162 || index.starts_with('-')
163 || index.starts_with('_')
164 || index.chars().any(|c| {
165 c.is_whitespace()
166 || matches!(
167 c,
168 '/' | '\\' | '*' | '?' | ',' | '+'
170 | '"' | '\'' | ';' | '`'
174 )
175 });
176 if bad {
177 return Err(crate::ScoutError::InvalidIndexName(index.to_string()));
178 }
179 Ok(())
180}
181
182pub fn validate_host(host: &str) -> crate::Result<()> {
190 let authority = host.split_once("://").map_or(host, |(_, rest)| rest);
191 let authority = authority
192 .split(['/', '?', '#'])
193 .next()
194 .unwrap_or_default();
195 if authority.contains('@') {
196 return Err(crate::ScoutError::InvalidHost(
197 "host 内嵌了 userinfo(`user:pass@`),请求失败时密码会随 URL 进日志 —— \
198 请把凭据从 URL 里拿出来"
199 .to_string(),
200 ));
201 }
202 Ok(())
203}
204
205pub fn validate_field_name(field: &str) -> crate::Result<()> {
215 let ok = !field.is_empty()
216 && field
217 .chars()
218 .all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '.'));
219 if !ok {
220 return Err(crate::ScoutError::InvalidFieldName(field.to_string()));
221 }
222 Ok(())
223}
224
225#[cfg(any(
240 feature = "elasticsearch",
241 feature = "meilisearch",
242 feature = "typesense",
243 feature = "algolia"
244))]
245pub(crate) fn same_origin_redirect_policy() -> reqwest::redirect::Policy {
246 reqwest::redirect::Policy::custom(|attempt| {
247 match attempt.previous().first() {
248 Some(first) if same_origin(first, attempt.url()) => attempt.follow(),
249 _ => attempt.stop(),
250 }
251 })
252}
253
254#[cfg(any(
257 feature = "elasticsearch",
258 feature = "meilisearch",
259 feature = "typesense",
260 feature = "algolia"
261))]
262fn same_origin(a: &reqwest::Url, b: &reqwest::Url) -> bool {
263 fn parts(url: &reqwest::Url) -> (&str, Option<&str>, Option<u16>) {
264 (url.scheme(), url.host_str(), url.port_or_known_default())
265 }
266 parts(a) == parts(b)
267}
268
269#[cfg(any(
273 feature = "elasticsearch",
274 feature = "meilisearch",
275 feature = "typesense",
276 feature = "algolia"
277))]
278pub(crate) fn percent_encode(s: &str) -> String {
279 let mut out = String::with_capacity(s.len());
280 for &b in s.as_bytes() {
281 match b {
282 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
283 out.push(b as char)
284 }
285 _ => out.push_str(&format!("%{:02X}", b)),
286 }
287 }
288 out
289}
290
291#[cfg(test)]
292mod tests {
293 use super::*;
294
295 #[test]
296 fn validate_index_name_accepts_valid() {
297 assert!(validate_index_name("books").is_ok());
298 assert!(validate_index_name("a-b_c.d~中文").is_ok());
299 }
300
301 #[test]
302 fn validate_index_name_rejects_invalid() {
303 for bad in [
304 "", " ", "a b", "a/b", "a\\b", ".hidden", "\t", "\n", "a\"b", "a'b", "a;b", "a`b",
305 ] {
306 assert!(validate_index_name(bad).is_err(), "should reject {:?}", bad);
307 }
308 }
309
310 #[test]
311 fn config_debug_redacts_api_keys() {
312 let cfg = ScoutConfig::meilisearch("http://localhost:7700", "super-secret-key");
313 let rendered = format!("{cfg:?}");
314 assert!(
315 !rendered.contains("super-secret-key"),
316 "api key leaked into Debug: {rendered}"
317 );
318 assert!(rendered.contains("<redacted>"));
319 assert!(rendered.contains("http://localhost:7700"));
321 }
322
323 #[test]
324 fn validate_host_rejects_userinfo_without_echoing_it() {
325 let err = validate_host("http://elastic:hunter2@es:9200").unwrap_err();
326 let text = err.to_string();
327 assert!(
328 !text.contains("hunter2"),
329 "credential echoed back in error: {text}"
330 );
331 for good in [
333 "http://es:9200",
334 "https://es.example.com/prefix",
335 "http://127.0.0.1:9200",
336 "localhost:9200",
337 ] {
338 assert!(validate_host(good).is_ok(), "should accept {good:?}");
339 }
340 }
341
342 #[cfg(any(
343 feature = "elasticsearch",
344 feature = "meilisearch",
345 feature = "typesense",
346 feature = "algolia"
347 ))]
348 #[test]
349 fn same_origin_requires_scheme_host_and_port() {
350 let u = |s: &str| reqwest::Url::parse(s).unwrap();
351 assert!(same_origin(&u("https://a.com/x"), &u("https://a.com/y")));
353 assert!(same_origin(&u("http://a.com:80/x"), &u("http://a.com/y")));
354 assert!(!same_origin(&u("https://a.com/x"), &u("https://b.com/y")));
356 assert!(!same_origin(&u("https://a.com/x"), &u("https://a.com:8443/y")));
358 assert!(!same_origin(
359 &u("http://127.0.0.1:8080/x"),
360 &u("http://127.0.0.1:9090/y")
361 ));
362 assert!(!same_origin(
364 &u("https://a.com:8080/x"),
365 &u("http://a.com:8080/y")
366 ));
367 }
368
369 #[test]
370 fn validate_field_name_rejects_expression_breaks() {
371 for bad in [
372 "",
373 "a b",
374 "x:=1 || y",
375 "a&&b",
376 "a,b",
377 "a(b)",
378 "a:b",
379 "a=b",
380 "field\"",
381 ] {
382 assert!(validate_field_name(bad).is_err(), "should reject {bad:?}");
383 }
384 for good in ["title", "author.name", "my_field", "a-b", "价格", "标题.子"] {
386 assert!(validate_field_name(good).is_ok(), "should accept {good:?}");
387 }
388 }
389
390 #[test]
391 fn validate_index_name_rejects_wildcards_and_reserved_prefixes() {
392 for bad in [
395 "_all", "_cat", "*", "a*", "a,b", "books*", "a?b", "+a", "-a", "_hidden",
396 ] {
397 assert!(validate_index_name(bad).is_err(), "should reject {:?}", bad);
398 }
399 for good in ["my_index", "a-b", "books-2024", "c#1", "a~b", "中文索引"] {
401 assert!(validate_index_name(good).is_ok(), "should accept {:?}", good);
402 }
403 }
404
405 #[test]
406 fn invalid_index_name_message_states_the_actual_rules() {
407 let msg = validate_index_name("_all").unwrap_err().to_string();
410 for needle in ["must not start", "`_`", "`*`", "whitespace"] {
411 assert!(
412 msg.contains(needle),
413 "error message should mention {needle:?}, got: {msg}"
414 );
415 }
416 assert!(msg.contains("_all"), "got: {msg}");
418 }
419}