use std::collections::HashMap;
use serde::{Deserialize, Serialize};
#[derive(Clone, Default, Serialize, Deserialize)]
pub struct ScoutConfig {
#[serde(default = "default_driver")]
pub driver: String,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub options: HashMap<String, serde_json::Value>,
}
fn is_secret_key(key: &str) -> bool {
let k = key.to_ascii_lowercase();
k.ends_with("api_key")
|| k.ends_with("apikey")
|| k.ends_with("token")
|| k.contains("secret")
|| k.contains("password")
}
impl std::fmt::Debug for ScoutConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let options: HashMap<&str, serde_json::Value> = self
.options
.iter()
.map(|(k, v)| {
let v = if is_secret_key(k) {
serde_json::Value::String("<redacted>".to_string())
} else {
v.clone()
};
(k.as_str(), v)
})
.collect();
f.debug_struct("ScoutConfig")
.field("driver", &self.driver)
.field("options", &options)
.finish()
}
}
impl ScoutConfig {
pub fn collection() -> Self {
Self {
driver: "collection".to_string(),
..Self::default()
}
}
pub fn elasticsearch(host: impl Into<String>, api_key: Option<String>) -> Self {
let mut config = Self::collection();
config.driver = "elasticsearch".to_string();
config.insert("elasticsearch.host", host.into());
if let Some(api_key) = api_key {
config.insert("elasticsearch.api_key", api_key);
}
config
}
pub fn opensearch(host: impl Into<String>, api_key: Option<String>) -> Self {
let mut config = Self::collection();
config.driver = "opensearch".to_string();
config.insert("opensearch.host", host.into());
if let Some(api_key) = api_key {
config.insert("opensearch.api_key", api_key);
}
config
}
pub fn meilisearch(host: impl Into<String>, api_key: impl Into<String>) -> Self {
let mut config = Self::collection();
config.driver = "meilisearch".to_string();
config.insert("meilisearch.host", host.into());
config.insert("meilisearch.api_key", api_key.into());
config
}
pub fn typesense(host: impl Into<String>, api_key: impl Into<String>) -> Self {
let mut config = Self::collection();
config.driver = "typesense".to_string();
config.insert("typesense.host", host.into());
config.insert("typesense.api_key", api_key.into());
config
}
pub fn algolia(app_id: impl Into<String>, api_key: impl Into<String>) -> Self {
let mut config = Self::collection();
config.driver = "algolia".to_string();
config.insert("algolia.app_id", app_id.into());
config.insert("algolia.api_key", api_key.into());
config
}
pub fn database(url: impl Into<String>, fields: Vec<String>) -> Self {
let mut config = Self::collection();
config.driver = "database".to_string();
config.insert("database.url", url.into());
config.insert("database.fields", serde_json::json!(fields));
config
}
pub fn null() -> Self {
Self {
driver: "null".to_string(),
..Self::collection()
}
}
pub fn xunsearch(host: impl Into<String>, project: impl Into<String>) -> Self {
let mut config = Self::collection();
config.driver = "xunsearch".to_string();
config.insert("xunsearch.host", host.into());
config.insert("xunsearch.project", project.into());
config
}
pub fn insert(&mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) {
self.options.insert(key.into(), value.into());
}
pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
self.options.get(key)
}
}
fn default_driver() -> String {
"collection".to_string()
}
pub fn validate_index_name(index: &str) -> crate::Result<()> {
let bad = index.is_empty()
|| index.starts_with('.')
|| index.starts_with('-')
|| index.starts_with('_')
|| index.chars().any(|c| {
c.is_whitespace()
|| matches!(
c,
'/' | '\\' | '*' | '?' | ',' | '+'
| '"' | '\'' | ';' | '`'
)
});
if bad {
return Err(crate::ScoutError::InvalidIndexName(index.to_string()));
}
Ok(())
}
pub fn validate_host(host: &str) -> crate::Result<()> {
let authority = host.split_once("://").map_or(host, |(_, rest)| rest);
let authority = authority
.split(['/', '?', '#'])
.next()
.unwrap_or_default();
if authority.contains('@') {
return Err(crate::ScoutError::InvalidHost(
"host 内嵌了 userinfo(`user:pass@`),请求失败时密码会随 URL 进日志 —— \
请把凭据从 URL 里拿出来"
.to_string(),
));
}
Ok(())
}
pub fn validate_field_name(field: &str) -> crate::Result<()> {
let ok = !field.is_empty()
&& field
.chars()
.all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '.'));
if !ok {
return Err(crate::ScoutError::InvalidFieldName(field.to_string()));
}
Ok(())
}
#[cfg(any(
feature = "elasticsearch",
feature = "meilisearch",
feature = "typesense",
feature = "algolia"
))]
pub fn same_origin_redirect_policy() -> reqwest::redirect::Policy {
reqwest::redirect::Policy::custom(|attempt| {
match attempt.previous().first() {
Some(first) if same_origin(first, attempt.url()) => attempt.follow(),
_ => attempt.stop(),
}
})
}
#[cfg(any(
feature = "elasticsearch",
feature = "meilisearch",
feature = "typesense",
feature = "algolia"
))]
fn same_origin(a: &reqwest::Url, b: &reqwest::Url) -> bool {
fn parts(url: &reqwest::Url) -> (&str, Option<&str>, Option<u16>) {
(url.scheme(), url.host_str(), url.port_or_known_default())
}
parts(a) == parts(b)
}
#[cfg(any(
feature = "elasticsearch",
feature = "meilisearch",
feature = "typesense",
feature = "algolia"
))]
pub fn percent_encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for &b in s.as_bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
out.push(b as char)
}
_ => out.push_str(&format!("%{:02X}", b)),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn validate_index_name_accepts_valid() {
assert!(validate_index_name("books").is_ok());
assert!(validate_index_name("a-b_c.d~中文").is_ok());
}
#[test]
fn validate_index_name_rejects_invalid() {
for bad in [
"", " ", "a b", "a/b", "a\\b", ".hidden", "\t", "\n", "a\"b", "a'b", "a;b", "a`b",
] {
assert!(validate_index_name(bad).is_err(), "should reject {:?}", bad);
}
}
#[test]
fn config_debug_redacts_api_keys() {
let cfg = ScoutConfig::meilisearch("http://localhost:7700", "super-secret-key");
let rendered = format!("{cfg:?}");
assert!(
!rendered.contains("super-secret-key"),
"api key leaked into Debug: {rendered}"
);
assert!(rendered.contains("<redacted>"));
assert!(rendered.contains("http://localhost:7700"));
}
#[test]
fn validate_host_rejects_userinfo_without_echoing_it() {
let err = validate_host("http://elastic:hunter2@es:9200").unwrap_err();
let text = err.to_string();
assert!(
!text.contains("hunter2"),
"credential echoed back in error: {text}"
);
for good in [
"http://es:9200",
"https://es.example.com/prefix",
"http://127.0.0.1:9200",
"localhost:9200",
] {
assert!(validate_host(good).is_ok(), "should accept {good:?}");
}
}
#[cfg(any(
feature = "elasticsearch",
feature = "meilisearch",
feature = "typesense",
feature = "algolia"
))]
#[test]
fn same_origin_requires_scheme_host_and_port() {
let u = |s: &str| reqwest::Url::parse(s).unwrap();
assert!(same_origin(&u("https://a.com/x"), &u("https://a.com/y")));
assert!(same_origin(&u("http://a.com:80/x"), &u("http://a.com/y")));
assert!(!same_origin(&u("https://a.com/x"), &u("https://b.com/y")));
assert!(!same_origin(&u("https://a.com/x"), &u("https://a.com:8443/y")));
assert!(!same_origin(
&u("http://127.0.0.1:8080/x"),
&u("http://127.0.0.1:9090/y")
));
assert!(!same_origin(
&u("https://a.com:8080/x"),
&u("http://a.com:8080/y")
));
}
#[test]
fn validate_field_name_rejects_expression_breaks() {
for bad in [
"",
"a b",
"x:=1 || y",
"a&&b",
"a,b",
"a(b)",
"a:b",
"a=b",
"field\"",
] {
assert!(validate_field_name(bad).is_err(), "should reject {bad:?}");
}
for good in ["title", "author.name", "my_field", "a-b", "价格", "标题.子"] {
assert!(validate_field_name(good).is_ok(), "should accept {good:?}");
}
}
#[test]
fn validate_index_name_rejects_wildcards_and_reserved_prefixes() {
for bad in [
"_all", "_cat", "*", "a*", "a,b", "books*", "a?b", "+a", "-a", "_hidden",
] {
assert!(validate_index_name(bad).is_err(), "should reject {:?}", bad);
}
for good in ["my_index", "a-b", "books-2024", "c#1", "a~b", "中文索引"] {
assert!(validate_index_name(good).is_ok(), "should accept {:?}", good);
}
}
#[test]
fn invalid_index_name_message_states_the_actual_rules() {
let msg = validate_index_name("_all").unwrap_err().to_string();
for needle in ["must not start", "`_`", "`*`", "whitespace"] {
assert!(
msg.contains(needle),
"error message should mention {needle:?}, got: {msg}"
);
}
assert!(msg.contains("_all"), "got: {msg}");
}
}