Skip to main content

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