use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use axum::Router;
use axum::body::{Body, to_bytes};
use axum::extract::connect_info::ConnectInfo;
use axum::http::{Request, StatusCode, header};
use axum::middleware;
use bengali_spell_checker::SpellChecker;
use serde_json::{Value, json};
use tower::ServiceExt;
use super::guard::ServerConfig;
use super::{apply_timeout, router, router_with};
const AFF: &str = "\
SET UTF-8
FLAG UTF-8
SFX \u{0995} Y 1
SFX \u{0995} 0 \u{09AF}\u{09BC} .
REP 1
REP \u{09B8} \u{09B6}
";
const DIC: &str = "\
2
ঢাকা/\u{0995}
বাংলাদেশ
";
const TEXT: &str = "ঢাকা বাংলাদেস।";
const WORD: &str = "বাংলাদেস";
fn app() -> Router {
let checker = SpellChecker::new(AFF, DIC).expect("sample dictionary");
router(Arc::new(checker))
}
fn configured(server: ServerConfig) -> Router {
let checker = SpellChecker::new(AFF, DIC).expect("sample dictionary");
router_with(Arc::new(checker), server)
}
fn strict_app() -> Router {
let checker = SpellChecker::new("SET UTF-8\nFLAG UTF-8\n", "2\nকলকাতা\nক্যালকাটা\n")
.expect("dictionary")
.with_variants("ক্যালকাটা\tকলকাতা\n");
router(Arc::new(checker))
}
fn utf16_span(text: &str, word: &str) -> (usize, usize) {
let byte_start = text.find(word).expect("word");
let start = text[..byte_start].encode_utf16().count();
let end = start + word.encode_utf16().count();
(start, end)
}
async fn call(app: &Router, request: Request<Body>) -> (StatusCode, Value) {
let response = app.clone().oneshot(request).await.expect("response");
let status = response.status();
let bytes = to_bytes(response.into_body(), usize::MAX)
.await
.expect("body");
let json = serde_json::from_slice(&bytes).expect("json");
(status, json)
}
fn check_request(body: &str) -> Request<Body> {
Request::builder()
.method("POST")
.uri("/api/check")
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from(body.to_owned()))
.unwrap()
}
fn suggest_uri(word: &str, limit: Option<&str>) -> String {
let mut uri = format!("/api/suggest?word={}", form_encode(word));
if let Some(limit) = limit {
uri.push_str("&limit=");
uri.push_str(&form_encode(limit));
}
uri
}
fn form_encode(value: &str) -> String {
let mut out = String::new();
for byte in value.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(char::from(byte));
}
_ => out.push_str(&format!("%{byte:02X}")),
}
}
out
}
#[tokio::test]
async fn health_is_ready_when_the_checker_is_already_loaded() {
let app = app();
for path in ["/api/health", "/health"] {
let (status, body) = call(
&app,
Request::builder().uri(path).body(Body::empty()).unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, json!({ "ready": true }));
}
}
#[tokio::test]
async fn check_returns_misspellings_with_original_offsets_and_suggestions() {
let (start, end) = utf16_span(TEXT, WORD);
let byte_start = TEXT.find(WORD).unwrap();
assert_eq!((start, end), (5, 13));
assert_ne!(start, byte_start);
let (status, body) = call(&app(), check_request(&json!({ "text": TEXT }).to_string())).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
body,
json!({
"misspellings": [{ "word": WORD, "start": start, "end": end, "suggestions": ["বাংলাদেশ"] }]
})
);
}
#[tokio::test]
async fn check_omits_suggestions_when_suggestions_is_false() {
let (start, end) = utf16_span(TEXT, WORD);
let (status, body) = call(
&app(),
check_request(&json!({ "text": TEXT, "suggestions": false }).to_string()),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
body,
json!({ "misspellings": [{ "word": WORD, "start": start, "end": end }] })
);
}
#[tokio::test]
async fn suggest_returns_corrections_for_a_misspelled_word() {
let limits = [None, Some("1"), Some("20")];
let app = app();
for limit in limits {
let (status, body) = call(
&app,
Request::builder()
.uri(suggest_uri(WORD, limit))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
body,
json!({ "word": WORD, "correct": false, "suggestions": ["বাংলাদেশ"] })
);
}
}
#[tokio::test]
async fn suggest_returns_no_suggestions_for_a_correct_word() {
let correct = "বাংলাদেশ";
let (status, body) = call(
&app(),
Request::builder()
.uri(suggest_uri(correct, None))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
body,
json!({ "word": correct, "correct": true, "suggestions": [] })
);
}
#[tokio::test]
async fn check_rejects_invalid_json() {
let (status, body) = call(&app(), check_request("{")).await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(body, json!({ "error": "Invalid JSON" }));
}
#[tokio::test]
async fn check_rejects_a_missing_text_field() {
let (status, body) = call(&app(), check_request("{}")).await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(body, json!({ "error": "text must be a string" }));
}
#[tokio::test]
async fn check_rejects_a_non_string_text_field() {
for text in [json!(1), json!(null)] {
let (status, body) =
call(&app(), check_request(&json!({ "text": text }).to_string())).await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(body, json!({ "error": "text must be a string" }));
}
}
#[tokio::test]
async fn check_rejects_a_non_boolean_suggestions_field() {
let (status, body) = call(
&app(),
check_request(&json!({ "text": WORD, "suggestions": "false" }).to_string()),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(body, json!({ "error": "suggestions must be a boolean" }));
}
#[tokio::test]
async fn suggest_rejects_a_missing_word() {
let app = app();
for path in ["/api/suggest", "/api/suggest?word="] {
let (status, body) = call(
&app,
Request::builder().uri(path).body(Body::empty()).unwrap(),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(body, json!({ "error": "word is required" }));
}
}
#[tokio::test]
async fn check_rejects_an_out_of_range_limit() {
for limit in [json!(0), json!(21), json!(1.5), json!("5")] {
let (status, body) = call(
&app(),
check_request(&json!({ "text": WORD, "limit": limit }).to_string()),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(
body,
json!({ "error": "limit must be an integer from 1 to 20" })
);
}
}
#[tokio::test]
async fn suggest_rejects_an_out_of_range_limit() {
let app = app();
for limit in ["0", "21", "1.5"] {
let (status, body) = call(
&app,
Request::builder()
.uri(suggest_uri(WORD, Some(limit)))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(
body,
json!({ "error": "limit must be an integer from 1 to 20" })
);
}
}
#[tokio::test]
async fn check_rejects_text_longer_than_100000_characters() {
let (status, body) = call(
&app(),
check_request(&json!({ "text": "a".repeat(100_001) }).to_string()),
)
.await;
assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(
body,
json!({ "error": "text must be at most 100000 characters" })
);
}
#[tokio::test]
async fn check_accepts_text_of_100000_characters() {
let (status, body) = call(
&app(),
check_request(&json!({ "text": "a".repeat(100_000) }).to_string()),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, json!({ "misspellings": [] }));
}
#[tokio::test]
async fn check_accepts_the_limit_boundaries() {
let end = WORD.encode_utf16().count();
for limit in [1, 20] {
let (status, body) = call(
&app(),
check_request(&json!({ "text": WORD, "limit": limit }).to_string()),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(
body,
json!({
"misspellings": [{
"word": WORD,
"start": 0,
"end": end,
"suggestions": ["বাংলাদেশ"]
}]
})
);
}
}
#[tokio::test]
async fn check_strict_flags_a_variant_and_rejects_a_non_boolean() {
let app = strict_app();
let (status, body) = call(
&app,
check_request(&json!({ "text": "ক্যালকাটা", "strict": true }).to_string()),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body["misspellings"][0]["word"], json!("ক্যালকাটা"));
assert_eq!(body["misspellings"][0]["suggestions"][0], json!("কলকাতা"));
let (status, body) = call(
&app,
check_request(&json!({ "text": "ক্যালকাটা", "strict": false }).to_string()),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body, json!({ "misspellings": [] }));
let (status, body) = call(
&app,
check_request(&json!({ "text": "ক্যালকাটা", "strict": "true" }).to_string()),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(body, json!({ "error": "strict must be a boolean" }));
}
#[tokio::test]
async fn suggest_strict_is_a_boolean_query() {
let app = strict_app();
let (status, body) = call(
&app,
Request::builder()
.uri(format!("{}&strict=true", suggest_uri("ক্যালকাটা", None)))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(body["correct"], json!(false));
assert_eq!(body["suggestions"][0], json!("কলকাতা"));
let (status, body) = call(
&app,
Request::builder()
.uri(format!("{}&strict=yes", suggest_uri("ক্যালকাটা", None)))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(body, json!({ "error": "strict must be a boolean" }));
}
#[tokio::test]
async fn cors_defaults_to_localhost_and_an_allowlist_replaces_it() {
let app = app();
assert_eq!(
allowed_origin(&app, "http://localhost:3000")
.await
.as_deref(),
Some("http://localhost:3000")
);
assert_eq!(
allowed_origin(&app, "http://127.0.0.1:8787")
.await
.as_deref(),
Some("http://127.0.0.1:8787")
);
assert_eq!(allowed_origin(&app, "https://hoppscotch.io").await, None);
let listed = configured(ServerConfig {
cors: super::guard::CorsPolicy::Allowlist(vec![axum::http::HeaderValue::from_static(
"https://app.example.com",
)]),
..ServerConfig::default()
});
assert_eq!(
allowed_origin(&listed, "https://app.example.com")
.await
.as_deref(),
Some("https://app.example.com")
);
assert_eq!(allowed_origin(&listed, "http://localhost:3000").await, None);
}
async fn allowed_origin(app: &Router, origin: &'static str) -> Option<String> {
let response = app
.clone()
.oneshot(
Request::builder()
.uri("/api/health")
.header(header::ORIGIN, origin)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
response
.headers()
.get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
.and_then(|value| value.to_str().ok())
.map(str::to_owned)
}
#[tokio::test]
async fn check_rejects_a_body_larger_than_the_configured_limit() {
let body = r#"{"text":""}"#;
assert_eq!(body.len(), 11);
let (status, json_body) = call(
&configured(ServerConfig {
max_body_bytes: body.len(),
..ServerConfig::default()
}),
check_request(body),
)
.await;
assert_eq!(status, StatusCode::OK);
assert_eq!(json_body, json!({ "misspellings": [] }));
let (status, json_body) = call(
&configured(ServerConfig {
max_body_bytes: body.len() - 1,
..ServerConfig::default()
}),
check_request(body),
)
.await;
assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(
json_body,
json!({ "error": "request body must be at most 10 bytes" })
);
}
#[tokio::test]
async fn suggest_rejects_a_word_longer_than_1000_characters() {
let (status, body) = call(
&app(),
Request::builder()
.uri(suggest_uri(&"a".repeat(1_001), None))
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(
body,
json!({ "error": "word must be at most 1000 characters" })
);
}
#[tokio::test]
async fn rate_limit_ignores_forwarded_for_unless_the_proxy_is_trusted() {
let tight = ServerConfig {
rate_limit_requests: 1,
..ServerConfig::default()
};
let app = configured(tight);
let first = check_request(&json!({ "text": "" }).to_string());
let mut second = check_request(&json!({ "text": "" }).to_string());
second.headers_mut().insert(
"x-forwarded-for",
axum::http::HeaderValue::from_static("203.0.113.9"),
);
let (status, _) = call(&app, first).await;
assert_eq!(status, StatusCode::OK);
let (status, body) = call(&app, second).await;
assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
assert_eq!(body, json!({ "error": "rate limit exceeded" }));
let trusted = configured(ServerConfig {
rate_limit_requests: 1,
trust_proxy: true,
..ServerConfig::default()
});
let mut from_a = check_request(&json!({ "text": "" }).to_string());
from_a.headers_mut().insert(
"x-forwarded-for",
axum::http::HeaderValue::from_static("9.9.9.9, 203.0.113.1"),
);
let mut from_a_again = check_request(&json!({ "text": "" }).to_string());
from_a_again.headers_mut().insert(
"x-forwarded-for",
axum::http::HeaderValue::from_static("203.0.113.1"),
);
let mut from_b = check_request(&json!({ "text": "" }).to_string());
from_b.headers_mut().insert(
"x-forwarded-for",
axum::http::HeaderValue::from_static("203.0.113.2"),
);
assert_eq!(call(&trusted, from_a).await.0, StatusCode::OK);
assert_eq!(
call(&trusted, from_a_again).await.0,
StatusCode::TOO_MANY_REQUESTS
);
assert_eq!(call(&trusted, from_b).await.0, StatusCode::OK);
}
#[tokio::test]
async fn rate_limit_uses_the_socket_peer_and_does_not_meter_health() {
let app = configured(ServerConfig {
rate_limit_requests: 1,
..ServerConfig::default()
});
for _ in 0..3 {
let (status, _) = call(
&app,
Request::builder()
.uri("/health")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(status, StatusCode::OK);
}
let peer_a = with_peer(
check_request(&json!({ "text": "" }).to_string()),
[203, 0, 113, 5],
);
let peer_a_again = with_peer(
check_request(&json!({ "text": "" }).to_string()),
[203, 0, 113, 5],
);
let mut spoofed = with_peer(
check_request(&json!({ "text": "" }).to_string()),
[203, 0, 113, 5],
);
spoofed.headers_mut().insert(
"x-forwarded-for",
axum::http::HeaderValue::from_static("198.51.100.20"),
);
let peer_b = with_peer(
check_request(&json!({ "text": "" }).to_string()),
[203, 0, 113, 6],
);
assert_eq!(call(&app, peer_a).await.0, StatusCode::OK);
let limited = app.clone().oneshot(peer_a_again).await.unwrap();
assert_eq!(limited.status(), StatusCode::TOO_MANY_REQUESTS);
assert_eq!(
limited
.headers()
.get(header::RETRY_AFTER)
.and_then(|value| value.to_str().ok()),
Some("60")
);
assert_eq!(call(&app, spoofed).await.0, StatusCode::TOO_MANY_REQUESTS);
assert_eq!(call(&app, peer_b).await.0, StatusCode::OK);
}
fn with_peer(mut request: Request<Body>, ip: [u8; 4]) -> Request<Body> {
request
.extensions_mut()
.insert(ConnectInfo(SocketAddr::from((ip, 9))));
request
}
#[tokio::test]
async fn a_slow_handler_returns_a_json_timeout() {
let app = Router::new()
.route(
"/slow",
axum::routing::get(|| async {
tokio::time::sleep(Duration::from_secs(2)).await;
}),
)
.layer(middleware::from_fn(|req, next| {
apply_timeout(req, next, Duration::from_millis(30))
}));
let (status, body) = call(
&app,
Request::builder().uri("/slow").body(Body::empty()).unwrap(),
)
.await;
assert_eq!(status, StatusCode::REQUEST_TIMEOUT);
assert_eq!(body, json!({ "error": "request timed out" }));
}