use std::convert::Infallible;
use std::net::{IpAddr, SocketAddr};
use axum::body::to_bytes;
use axum::extract::{FromRef, FromRequest, Request};
use axum::handler::Handler;
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::{MethodRouter, get};
use crate::error::Error;
use crate::notify::{NotifyData, NotifyLimits};
use crate::{Client, NOTIFY_FAIL, NOTIFY_SUCCESS, Params, ProtocolContext};
pub fn callback_route<H, T, S>(handler: H) -> MethodRouter<S>
where
H: Handler<T, S> + Clone,
T: 'static,
S: Clone + Send + Sync + 'static,
{
get(handler.clone()).post(handler)
}
pub fn payer_ip(headers: &HeaderMap, peer: SocketAddr, trust_proxy_headers: bool) -> IpAddr {
if trust_proxy_headers {
for name in ["x-forwarded-for", "x-real-ip"] {
let forwarded = headers
.get(name)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.split(',').next())
.map(str::trim)
.and_then(|value| value.parse::<IpAddr>().ok());
if let Some(ip) = forwarded {
return ip;
}
}
}
peer.ip()
}
#[derive(Clone, Debug)]
pub struct VerifiedNotify(pub NotifyData);
#[derive(Debug)]
pub struct NotifyRejection(pub Error);
impl std::fmt::Display for NotifyRejection {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "epay notify rejected: {}", self.0)
}
}
impl std::error::Error for NotifyRejection {}
impl IntoResponse for NotifyRejection {
fn into_response(self) -> Response {
(StatusCode::OK, NOTIFY_FAIL).into_response()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct NotifyAck(&'static str);
impl NotifyAck {
pub fn ok() -> Self {
Self(NOTIFY_SUCCESS)
}
pub fn fail() -> Self {
Self(NOTIFY_FAIL)
}
}
impl From<crate::Result<()>> for NotifyAck {
fn from(result: crate::Result<()>) -> Self {
if result.is_ok() {
Self::ok()
} else {
Self::fail()
}
}
}
impl IntoResponse for NotifyAck {
fn into_response(self) -> Response {
(StatusCode::OK, self.0).into_response()
}
}
impl FromRef<Client> for ProtocolContext {
fn from_ref(client: &Client) -> Self {
client.protocol_context().clone()
}
}
impl<S> FromRequest<S> for VerifiedNotify
where
S: Send + Sync,
ProtocolContext: FromRef<S>,
{
type Rejection = NotifyRejection;
async fn from_request(request: Request, state: &S) -> Result<Self, Self::Rejection> {
let protocol = ProtocolContext::from_ref(state);
let params = read_notify_params(request).await.map_err(|error| {
sdk_debug!("[epay-sdk] notify input rejected: {error}");
NotifyRejection(error)
})?;
protocol
.verify_notify(¶ms)
.map(VerifiedNotify)
.map_err(|error| {
sdk_debug!("[epay-sdk] notify verification rejected: {error}");
NotifyRejection(error)
})
}
}
#[derive(Clone, Debug)]
pub struct ParsedNotify(pub Params);
impl<S> FromRequest<S> for ParsedNotify
where
S: Send + Sync,
{
type Rejection = NotifyRejection;
async fn from_request(request: Request, _state: &S) -> Result<Self, Self::Rejection> {
read_notify_params(request)
.await
.map(ParsedNotify)
.map_err(|error| {
sdk_debug!("[epay-sdk] notify input rejected: {error}");
NotifyRejection(error)
})
}
}
#[derive(Clone, Debug)]
pub struct NotifyParams(pub Params);
#[derive(Debug)]
pub struct NotifyInputRejection(pub Error);
impl IntoResponse for NotifyInputRejection {
fn into_response(self) -> Response {
(StatusCode::BAD_REQUEST, "invalid epay parameters").into_response()
}
}
impl<S> FromRequest<S> for NotifyParams
where
S: Send + Sync,
{
type Rejection = NotifyInputRejection;
async fn from_request(request: Request, _state: &S) -> Result<Self, Self::Rejection> {
read_notify_params(request)
.await
.map(NotifyParams)
.map_err(NotifyInputRejection)
}
}
#[derive(Debug)]
pub struct VerifiedReturn(pub crate::Result<NotifyData>);
impl<S> FromRequest<S> for VerifiedReturn
where
S: Send + Sync,
ProtocolContext: FromRef<S>,
{
type Rejection = Infallible;
async fn from_request(request: Request, state: &S) -> Result<Self, Self::Rejection> {
let protocol = ProtocolContext::from_ref(state);
let result = match read_notify_params(request).await {
Ok(params) => protocol.verify_notify(¶ms),
Err(error) => Err(error),
};
Ok(Self(result))
}
}
async fn read_notify_params(request: Request) -> crate::Result<Params> {
let limits = NotifyLimits::default();
let (parts, body) = request.into_parts();
let query = parts.uri.query().unwrap_or_default();
if query.len() > limits.max_encoded_bytes {
return Err(Error::notify(format!(
"encoded notification exceeds {} bytes",
limits.max_encoded_bytes
)));
}
let remaining = limits.max_encoded_bytes - query.len();
let bytes = to_bytes(body, remaining)
.await
.map_err(|_| Error::notify("notify body unreadable or too large"))?;
if !bytes.is_empty() && !is_form_content_type(parts.headers.get(header::CONTENT_TYPE)) {
return Err(Error::notify(
"non-empty notify body must be application/x-www-form-urlencoded",
));
}
let body = if bytes.is_empty() {
None
} else {
Some(
std::str::from_utf8(&bytes)
.map_err(|_| Error::notify("notify body is not valid UTF-8"))?,
)
};
crate::notify::parse_raw_notify_params_with_limits(
(!query.is_empty()).then_some(query),
body,
limits,
)?
.canonicalize()
}
fn is_form_content_type(value: Option<&axum::http::HeaderValue>) -> bool {
value
.and_then(|value| value.to_str().ok())
.and_then(|value| value.split(';').next())
.is_some_and(|value| {
value
.trim()
.eq_ignore_ascii_case("application/x-www-form-urlencoded")
})
}
#[cfg(test)]
mod tests {
use super::*;
fn peer() -> SocketAddr {
"10.0.0.7:5000".parse().unwrap()
}
#[test]
fn payer_ip_uses_peer_unless_proxy_headers_are_trusted() {
let mut headers = HeaderMap::new();
headers.insert("x-forwarded-for", "203.0.113.9, 10.0.0.1".parse().unwrap());
headers.insert("x-real-ip", "198.51.100.2".parse().unwrap());
assert_eq!(payer_ip(&headers, peer(), false).to_string(), "10.0.0.7");
assert_eq!(payer_ip(&headers, peer(), true).to_string(), "203.0.113.9");
headers.remove("x-forwarded-for");
assert_eq!(payer_ip(&headers, peer(), true).to_string(), "198.51.100.2");
headers.insert("x-real-ip", "not-an-ip".parse().unwrap());
assert_eq!(payer_ip(&headers, peer(), true).to_string(), "10.0.0.7");
headers.insert("x-forwarded-for", " ::1 ".parse().unwrap());
assert_eq!(payer_ip(&headers, peer(), true).to_string(), "::1");
}
}