use std::fmt::Write as _;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use axum::Router;
use axum::http::{HeaderMap, StatusCode};
use hafas::{
Client, DepartureBoard, Error, LocationName, Place, REDACTED, RtMode, TripSearch, Url,
};
const KEY: &str = "test key+/=";
const ENCODED_KEY: &str = "test+key%2B%2F%3D";
#[derive(Debug, Clone)]
struct Seen {
path: String,
query: Vec<(String, String)>,
user_agent: Option<String>,
}
#[derive(Clone)]
struct Reply {
status: StatusCode,
headers: Vec<(&'static str, &'static str)>,
body: String,
delay: Duration,
}
impl Reply {
fn ok(body: impl Into<String>) -> Self {
Self::status(StatusCode::OK, body)
}
fn status(status: StatusCode, body: impl Into<String>) -> Self {
Self {
status,
headers: Vec::new(),
body: body.into(),
delay: Duration::ZERO,
}
}
}
type Log = Arc<Mutex<Vec<Seen>>>;
async fn serve(reply: Reply) -> (String, Log) {
let log = Arc::new(Mutex::new(Vec::new()));
let seen = Arc::clone(&log);
let app = Router::new().fallback(move |request: axum::extract::Request| {
let reply = reply.clone();
let uri = request.uri().clone();
let url = Url::parse(&format!("http://loopback{uri}")).unwrap();
seen.lock().unwrap().push(Seen {
path: url.path().to_owned(),
query: url.query_pairs().into_owned().collect(),
user_agent: request
.headers()
.get("user-agent")
.map(|value| value.to_str().unwrap().to_owned()),
});
async move {
tokio::time::sleep(reply.delay).await;
let mut headers = HeaderMap::new();
for (name, value) in reply.headers {
headers.insert(name, value.parse().unwrap());
}
(reply.status, headers, reply.body)
}
});
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
(format!("http://{address}"), log)
}
fn fixture(version: &str, name: &str) -> String {
let path = format!(
"{}/../hafas-sim/fixtures/{version}/{name}",
env!("CARGO_MANIFEST_DIR")
);
std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{path}: {error}"))
}
fn client(base: &str) -> Client {
Client::builder(base).access_id(KEY).build().unwrap()
}
fn pairs(seen: &Seen) -> Vec<(&str, &str)> {
seen.query
.iter()
.map(|(name, value)| (name.as_str(), value.as_str()))
.collect()
}
fn assert_no_key(text: &str) {
assert!(!text.contains(KEY), "the key is in {text:?}");
assert!(!text.contains(ENCODED_KEY), "the key is in {text:?}");
assert!(!text.contains("test+key"), "the key is in {text:?}");
}
#[tokio::test]
async fn sends_the_key_the_format_and_the_language_below_the_base_path() {
let (base, log) = serve(Reply::ok(fixture("2.39", "departureBoard.json"))).await;
let client = Client::builder(format!("{base}/hapi"))
.access_id(KEY)
.lang("en")
.user_agent("test/1.0 (+https://example.org)")
.build()
.unwrap();
let board = client
.send(&DepartureBoard {
max_journeys: Some(3),
rt_mode: Some(RtMode::ServerDefault),
..DepartureBoard::new("3000010")
})
.await
.unwrap();
assert_eq!(board.departures.len(), 3);
let log = log.lock().unwrap();
assert_eq!(log.len(), 1);
let seen = &log[0];
assert_eq!(seen.path, "/hapi/departureBoard");
assert_eq!(
seen.user_agent.as_deref(),
Some("test/1.0 (+https://example.org)")
);
assert_eq!(
pairs(seen),
[
("id", "3000010"),
("maxJourneys", "3"),
("rtMode", "SERVER_DEFAULT"),
("format", "json"),
("lang", "en"),
("accessId", KEY),
]
);
}
#[tokio::test]
async fn sends_trip_searches_between_places() {
let (base, log) = serve(Reply::ok(fixture("2.52", "trip.json"))).await;
let list = client(&format!("{base}/"))
.send(&TripSearch {
passlist: Some(true),
..TripSearch::new(
Place::Coord {
lat: 50.1,
lon: 8.6,
},
Place::Id("3004734".to_owned()),
)
})
.await
.unwrap();
assert_eq!(list.trips.len(), 2);
let log = log.lock().unwrap();
assert_eq!(log[0].path, "/trip");
assert_eq!(
pairs(&log[0]),
[
("originCoordLat", "50.1"),
("originCoordLong", "8.6"),
("destId", "3004734"),
("passlist", "1"),
("format", "json"),
("accessId", KEY),
]
);
}
#[test]
fn shows_the_url_without_the_key() {
let client = Client::builder("https://hafas.example.org/api?x=1#y")
.access_id(KEY)
.build()
.unwrap();
assert_eq!(client.base_url().as_str(), "https://hafas.example.org/api/");
assert!(client.has_access_id());
let url = client.url(&LocationName::new("Hauptwache"));
assert_eq!(
url.as_str(),
"https://hafas.example.org/api/location.name?input=Hauptwache&format=json"
);
assert_no_key(&format!("{client:?}"));
assert!(format!("{client:?}").contains(REDACTED));
let builder = Client::builder("https://hafas.example.org/").access_id(KEY);
assert_no_key(&format!("{builder:?}"));
}
#[test]
fn rejects_base_urls_that_are_not_http() {
for base in ["not a url", "ftp://example.org/", "/hapi/"] {
let error = Client::builder(base).build().unwrap_err();
assert!(matches!(error, Error::BaseUrl(_)), "{base}: {error:?}");
}
}
#[tokio::test]
async fn sends_nothing_without_a_key() {
let (base, log) = serve(Reply::ok("{}")).await;
for builder in [
Client::builder(&base),
Client::builder(&base).access_id(""),
Client::builder(&base).access_id(" "),
] {
let client = builder.build().unwrap();
assert!(!client.has_access_id());
let error = client
.send(&LocationName::new("Hauptwache"))
.await
.unwrap_err();
assert!(matches!(error, Error::AccessIdMissing), "{error:?}");
}
assert!(log.lock().unwrap().is_empty());
}
#[tokio::test]
async fn reads_hafas_errors_of_error_responses() {
for version in hafas::DIALECT_VERSIONS {
for (name, status) in [
("errors/auth.json", StatusCode::UNAUTHORIZED),
("errors/auth.xml", StatusCode::UNAUTHORIZED),
("errors/nokey.xml", StatusCode::BAD_REQUEST),
] {
let (base, log) = serve(Reply::status(status, fixture(version, name))).await;
let error = client(&base)
.send(&LocationName::new("Hauptwache"))
.await
.unwrap_err();
let expected = if name.contains("auth") {
"API_AUTH"
} else {
"API_PARAM"
};
assert_eq!(error.code(), Some(expected), "{version}/{name}");
assert_eq!(error.status(), Some(status.as_u16()));
assert_eq!(error.retry_after(), None);
assert_eq!(log.lock().unwrap().len(), 1);
}
}
}
#[tokio::test]
async fn redacts_the_key_in_texts_of_the_server() {
let echo = format!(
r#"{{"errorCode":"API_AUTH","errorText":"access denied for {KEY} at /hapi/x?accessId={ENCODED_KEY}"}}"#
);
for status in [StatusCode::UNAUTHORIZED, StatusCode::OK] {
let (base, _) = serve(Reply::status(status, echo.clone())).await;
let error = client(&base)
.send(&LocationName::new("Hauptwache"))
.await
.unwrap_err();
let text = error.to_string();
assert_eq!(
text,
format!(
"the API answered API_AUTH: access denied for {REDACTED} at /hapi/x?accessId={REDACTED}"
)
);
assert_no_key(&format!("{error:?}"));
}
let body = format!("<html>no access for {KEY}</html>");
let (base, _) = serve(Reply::status(StatusCode::FORBIDDEN, body)).await;
let error = client(&base)
.send(&LocationName::new("Hauptwache"))
.await
.unwrap_err();
assert!(
matches!(error, Error::Status { status: 403, .. }),
"{error:?}"
);
assert_eq!(
error.to_string(),
format!("the server answered 403: <html>no access for {REDACTED}</html>")
);
let start = "x".repeat(195);
let body = format!("{start}{ENCODED_KEY}{KEY}");
let (base, _) = serve(Reply::status(StatusCode::BAD_GATEWAY, body)).await;
let error = client(&base)
.send(&LocationName::new("Hauptwache"))
.await
.unwrap_err();
let Error::Status { message, .. } = &error else {
panic!("{error:?}");
};
assert_eq!(*message, format!("{start}{}", &REDACTED[..5]));
assert!(!message.contains("test"), "{message}");
}
#[tokio::test]
async fn reads_retry_after_and_never_retries() {
let reply = Reply {
headers: vec![("retry-after", "120")],
..Reply::status(StatusCode::SERVICE_UNAVAILABLE, "")
};
let (base, log) = serve(reply).await;
let error = client(&base)
.send(&LocationName::new("Hauptwache"))
.await
.unwrap_err();
assert!(
matches!(error, Error::Status { status: 503, .. }),
"{error:?}"
);
assert_eq!(
error.to_string(),
"the server answered 503: Service Unavailable"
);
assert_eq!(error.retry_after(), Some(Duration::from_secs(120)));
assert_eq!(error.code(), None);
assert_eq!(log.lock().unwrap().len(), 1);
let reply = Reply {
headers: vec![("retry-after", "30")],
..Reply::status(
StatusCode::TOO_MANY_REQUESTS,
r#"{"errorCode":"API_QUOTA","errorText":"quota exceeded"}"#,
)
};
let (base, _) = serve(reply).await;
let error = client(&base)
.send(&LocationName::new("Hauptwache"))
.await
.unwrap_err();
assert_eq!(error.code(), Some("API_QUOTA"));
assert_eq!(error.retry_after(), Some(Duration::from_secs(30)));
}
#[tokio::test]
async fn times_out() {
let reply = Reply {
delay: Duration::from_secs(5),
..Reply::ok("{}")
};
let (base, _) = serve(reply).await;
let client = Client::builder(&base)
.access_id(KEY)
.timeout(Duration::from_millis(100))
.build()
.unwrap();
let error = client
.send(&LocationName::new("Hauptwache"))
.await
.unwrap_err();
assert!(matches!(error, Error::Timeout(_)), "{error:?}");
assert_no_key(&format!("{error:?}"));
}
#[tokio::test]
async fn keeps_the_key_out_of_connection_errors() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
drop(listener);
let error = client(&format!("http://{address}/"))
.send(&LocationName::new("Hauptwache"))
.await
.unwrap_err();
assert!(matches!(error, Error::Http(_)), "{error:?}");
let mut chain = format!("{error:?} {error}");
let mut source = std::error::Error::source(&error);
while let Some(cause) = source {
write!(chain, " {cause}").unwrap();
source = cause.source();
}
assert_no_key(&chain);
assert!(!chain.contains("accessId"), "{chain}");
}