Skip to main content

openauth_core/api/
error.rs

1use http::{header, Response, StatusCode};
2use serde::{Deserialize, Serialize};
3
4use crate::error::OpenAuthError;
5use crate::rate_limit::RateLimitRejection;
6
7use super::endpoint::{ApiResponse, Body};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum ApiErrorCode {
11    NotFound,
12    InvalidOrigin,
13    InvalidCallbackUrl,
14    InvalidRedirectUrl,
15    InvalidErrorCallbackUrl,
16    InvalidNewUserCallbackUrl,
17    MissingOrNullOrigin,
18    CrossSiteNavigationLoginBlocked,
19    TooManyRequests,
20}
21
22impl ApiErrorCode {
23    pub fn as_str(self) -> &'static str {
24        match self {
25            Self::NotFound => "NOT_FOUND",
26            Self::InvalidOrigin => "INVALID_ORIGIN",
27            Self::InvalidCallbackUrl => "INVALID_CALLBACK_URL",
28            Self::InvalidRedirectUrl => "INVALID_REDIRECT_URL",
29            Self::InvalidErrorCallbackUrl => "INVALID_ERROR_CALLBACK_URL",
30            Self::InvalidNewUserCallbackUrl => "INVALID_NEW_USER_CALLBACK_URL",
31            Self::MissingOrNullOrigin => "MISSING_OR_NULL_ORIGIN",
32            Self::CrossSiteNavigationLoginBlocked => "CROSS_SITE_NAVIGATION_LOGIN_BLOCKED",
33            Self::TooManyRequests => "TOO_MANY_REQUESTS",
34        }
35    }
36
37    pub fn message(self) -> &'static str {
38        match self {
39            Self::NotFound => "Not Found",
40            Self::InvalidOrigin => "Invalid origin",
41            Self::InvalidCallbackUrl => "Invalid callbackURL",
42            Self::InvalidRedirectUrl => "Invalid redirectURL",
43            Self::InvalidErrorCallbackUrl => "Invalid errorCallbackURL",
44            Self::InvalidNewUserCallbackUrl => "Invalid newUserCallbackURL",
45            Self::MissingOrNullOrigin => "Missing or null Origin",
46            Self::CrossSiteNavigationLoginBlocked => {
47                "Cross-site navigation login blocked. This request appears to be a CSRF attack."
48            }
49            Self::TooManyRequests => "Too many requests. Please try again later.",
50        }
51    }
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub struct ApiErrorResponse {
56    pub code: String,
57    pub message: String,
58    #[serde(default)]
59    #[serde(skip_serializing_if = "Option::is_none")]
60    #[serde(rename = "originalMessage")]
61    pub original_message: Option<String>,
62}
63
64pub fn response(status: StatusCode, body: Body) -> Result<ApiResponse, OpenAuthError> {
65    Response::builder()
66        .status(status)
67        .body(body)
68        .map_err(|error| OpenAuthError::Serialization {
69            context: "building API response",
70            message: error.to_string(),
71        })
72}
73
74pub fn api_error(status: StatusCode, code: ApiErrorCode) -> Result<ApiResponse, OpenAuthError> {
75    let body = serde_json::to_vec(&ApiErrorResponse {
76        code: code.as_str().to_owned(),
77        message: code.message().to_owned(),
78        original_message: None,
79    })
80    .map_err(|error| OpenAuthError::Serialization {
81        context: "serializing API error response",
82        message: error.to_string(),
83    })?;
84
85    Response::builder()
86        .status(status)
87        .header(header::CONTENT_TYPE, "application/json")
88        .body(body)
89        .map_err(|error| OpenAuthError::Serialization {
90            context: "building API error response",
91            message: error.to_string(),
92        })
93}
94
95pub(super) fn rate_limit_response(
96    rejection: RateLimitRejection,
97) -> Result<ApiResponse, OpenAuthError> {
98    let mut response = api_error(StatusCode::TOO_MANY_REQUESTS, ApiErrorCode::TooManyRequests)?;
99    response.headers_mut().insert(
100        "X-Retry-After",
101        http::HeaderValue::from_str(&rejection.retry_after.to_string()).map_err(|error| {
102            OpenAuthError::Serialization {
103                context: "building rate limit response headers",
104                message: error.to_string(),
105            }
106        })?,
107    );
108    Ok(response)
109}