Skip to main content

alibi_api/plugins/oauth/providers/
railway.rs

1//! Railway's PKCE grants, ordered scopes and original user-info account identity.
2use super::{
3    OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo,
4    OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use async_trait::async_trait;
7use serde_json::Value;
8
9/// Application-owned Railway configuration. Generic signup and asynchronous
10/// user-info/refresh callbacks remain configurable on the returned provider.
11#[derive(Clone)]
12pub struct RailwayOptions {
13    pub client_id: String,
14    pub client_secret: Option<String>,
15    /// Sent only during authorization-code exchange.
16    pub client_key: Option<String>,
17    pub scope: Vec<String>,
18    pub disable_default_scope: bool,
19    pub authorization_endpoint: Option<String>,
20    pub redirect_uri: Option<String>,
21    /// Trusted transport override retaining Railway's bearer GET and mapping.
22    pub user_info_endpoint: Option<String>,
23    /// Receives the original profile before its raw account identity is resolved.
24    pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
25}
26impl RailwayOptions {
27    #[must_use]
28    pub fn new(client_id: impl Into<String>, client_secret: Option<String>) -> Self {
29        Self {
30            client_id: client_id.into(),
31            client_secret,
32            client_key: None,
33            scope: Vec::new(),
34            disable_default_scope: false,
35            authorization_endpoint: None,
36            redirect_uri: None,
37            user_info_endpoint: None,
38            map_profile_to_user: None,
39        }
40    }
41}
42impl std::fmt::Debug for RailwayOptions {
43    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        formatter
45            .debug_struct("RailwayOptions")
46            .field("client_id", &self.client_id)
47            .field("scope", &self.scope)
48            .field("disable_default_scope", &self.disable_default_scope)
49            .field("authorization_endpoint", &self.authorization_endpoint)
50            .field("redirect_uri", &self.redirect_uri)
51            .finish_non_exhaustive()
52    }
53}
54impl OAuthProvider {
55    #[must_use]
56    pub fn railway(client_id: &str, client_secret: Option<&str>) -> Self {
57        Self::railway_with_options(RailwayOptions::new(
58            client_id,
59            client_secret.map(str::to_owned),
60        ))
61    }
62    #[must_use]
63    pub fn railway_with_options(options: RailwayOptions) -> Self {
64        let secret = options.client_secret.unwrap_or_default();
65        let refresh_authentication = OAuthTokenEndpointAuth::ClientSecretBasic;
66        let endpoint = options
67            .user_info_endpoint
68            .unwrap_or_else(|| "https://backboard.railway.com/oauth/me".into());
69        Self {
70            client_id: options.client_id,
71            client_secret: secret,
72            additional_client_ids: Vec::new(),
73            hosted_domain: None,
74            require_email_verification: false,
75            auth_url: options
76                .authorization_endpoint
77                .filter(|value| !value.is_empty())
78                .unwrap_or_else(|| "https://backboard.railway.com/oauth/auth".into()),
79            token_url: "https://backboard.railway.com/oauth/token".into(),
80            user_info_url: Some(endpoint.clone()),
81            scopes: vec!["openid".into(), "email".into(), "profile".into()],
82            authorization: Some(OAuthAuthorizationPolicy {
83                preserve_raw_profile_scalars: true,
84                source_profile_exceptions: true,
85                allow_missing_access_token: true,
86                preserve_raw_email_errors: true,
87                configured_scopes: options.scope,
88                disable_default_scopes: options.disable_default_scope,
89                require_client_id: true,
90                token_endpoint_auth: Some(refresh_authentication),
91                authorization_code_client_key: options.client_key,
92                redirect_uri: options.redirect_uri,
93                login_hint: false,
94                ..OAuthAuthorizationPolicy::default()
95            }),
96            authorization_params: Vec::new(),
97            account_subject: Some(subject),
98            map_user_info: None,
99            get_user_info: Some(std::sync::Arc::new(RailwayUserInfo {
100                application_mapper: None,
101                endpoint,
102                mapper: options.map_profile_to_user,
103            })),
104            refresh_access_token: None,
105            verify_id_token: None,
106            id_token: None,
107            disable_id_token_sign_in: false,
108            disable_implicit_sign_up: false,
109            disable_sign_up: false,
110            override_user_info_on_sign_in: false,
111        }
112    }
113}
114#[derive(Clone)]
115struct RailwayUserInfo {
116    application_mapper: Option<std::sync::Arc<dyn super::OAuthProfileMapper>>,
117    endpoint: String,
118    mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
119}
120#[async_trait]
121impl OAuthUserInfoHandler for RailwayUserInfo {
122    fn errors_are_exceptions(&self) -> bool {
123        false
124    }
125
126    fn mapped_handler(
127        &self,
128        mapper: std::sync::Arc<dyn super::OAuthProfileMapper>,
129    ) -> Option<std::sync::Arc<dyn OAuthUserInfoHandler>> {
130        let mut handler = self.clone();
131        handler.mapper = None;
132        handler.application_mapper = Some(mapper);
133        Some(std::sync::Arc::new(handler))
134    }
135
136    async fn get_user_info(
137        &self,
138        request: OAuthUserInfoRequest,
139    ) -> Result<OAuthUserInfoResponse, String> {
140        let access_token = super::remaining_profile::bearer_access_token(&request)?;
141        let profile: Value = reqwest::Client::new()
142            .get(&self.endpoint)
143            .bearer_auth(access_token)
144            .send()
145            .await
146            .map_err(|error| error.to_string())?
147            .error_for_status()
148            .map_err(|error| error.to_string())?
149            .json()
150            .await
151            .map_err(|error| error.to_string())?;
152        if profile.is_null()
153            || profile == Value::Bool(false)
154            || profile.as_f64() == Some(0.0)
155            || profile.as_str() == Some("")
156        {
157            return Err("Missing Railway profile".into());
158        }
159        let application_output = if let Some(mapper) = &self.application_mapper {
160            Some(
161                mapper
162                    .map_profile(profile.clone())
163                    .await
164                    .map_err(super::remaining_profile::profile_exception)?,
165            )
166        } else {
167            None
168        };
169        let mapped = self
170            .mapper
171            .map(|mapper| mapper(profile.clone()))
172            .transpose()
173            .map_err(super::remaining_profile::profile_exception)?;
174        // Keep the published raw JSON independently from typed persistence.
175        let mut output = serde_json::Map::new();
176        if let Some(name) = profile.get("name") {
177            drop(output.insert("name".into(), name.clone()));
178        }
179        let email = profile.get("email");
180        if let Some(email) = email {
181            drop(output.insert("email".into(), email.clone()));
182        }
183        if let Some(image) = profile.get("picture") {
184            drop(output.insert("image".into(), image.clone()));
185        }
186        drop(output.insert("emailVerified".into(), Value::Bool(false)));
187        if let Some(user) = &mapped {
188            output.extend(user.public_profile(true));
189        }
190        let user_output = Some(output);
191        let user = match mapped {
192            Some(user) => user,
193            None => OAuthUserInfo {
194                additional_fields: Default::default(),
195                id: profile
196                    .get("sub")
197                    .map(super::remaining_profile::js_string)
198                    .transpose()?
199                    .unwrap_or_default(),
200                // Signup uses Source's `user.name || ""`, while account-info
201                // above retains the original raw field.
202                name: scalar(profile.get("name").filter(|value| {
203                    !matches!(value, Value::Bool(false)) && value.as_f64() != Some(0.0)
204                }))?,
205                email: email.and_then(Value::as_str).unwrap_or_default().into(),
206                image: scalar(profile.get("picture"))?,
207                email_verified: false,
208            },
209        };
210        let mut response = OAuthUserInfoResponse {
211            user_output,
212            user,
213            data: profile,
214        };
215        if let Some(mapped) = application_output {
216            super::apply_application_mapping(&mut response, mapped)?;
217        }
218        Ok(response)
219    }
220}
221fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
222    match value {
223        None | Some(Value::Null) => Ok(None),
224        Some(Value::String(value)) => Ok(Some(value.clone())),
225        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
226            .map(Some)
227            .map_err(|error| error.to_string()),
228        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
229        Some(Value::Array(_) | Value::Object(_)) => Ok(None),
230    }
231}
232fn subject(profile: &Value) -> Result<String, String> {
233    super::remaining_profile::raw_subject(profile.get("sub"))
234}