alibi_plugins/oauth/providers/
railway.rs1use 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#[derive(Clone)]
13pub struct RailwayOptions {
14 pub client_id: String,
15 pub client_secret: Option<String>,
16 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 pub user_info_endpoint: Option<String>,
24 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 allowed_request_params: Vec::new(),
98 authorization_params: Vec::new(),
99 account_subject: Some(subject),
100 map_user_info: None,
101 get_user_info: Some(std::sync::Arc::new(RailwayUserInfo {
102 application_mapper: None,
103 endpoint,
104 mapper: options.map_profile_to_user,
105 })),
106 refresh_access_token: None,
107 verify_id_token: None,
108 id_token: None,
109 disable_id_token_sign_in: false,
110 disable_implicit_sign_up: false,
111 disable_sign_up: false,
112 allow_idp_initiated: false,
113 override_user_info_on_sign_in: false,
114 }
115 }
116}
117#[derive(Clone)]
118struct RailwayUserInfo {
119 application_mapper: Option<std::sync::Arc<dyn super::OAuthProfileMapper>>,
120 endpoint: String,
121 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
122}
123#[async_trait]
124impl OAuthUserInfoHandler for RailwayUserInfo {
125 fn errors_are_exceptions(&self) -> bool {
126 false
127 }
128
129 fn mapped_handler(
130 &self,
131 mapper: std::sync::Arc<dyn super::OAuthProfileMapper>,
132 ) -> Option<std::sync::Arc<dyn OAuthUserInfoHandler>> {
133 let mut handler = self.clone();
134 handler.mapper = None;
135 handler.application_mapper = Some(mapper);
136 Some(std::sync::Arc::new(handler))
137 }
138
139 async fn get_user_info(
140 &self,
141 request: OAuthUserInfoRequest,
142 ) -> Result<OAuthUserInfoResponse, String> {
143 let access_token = super::remaining_profile::bearer_access_token(&request)?;
144 let profile: Value = reqwest::Client::new()
145 .get(&self.endpoint)
146 .bearer_auth(access_token)
147 .send()
148 .await
149 .map_err(|error| error.to_string())?
150 .error_for_status()
151 .map_err(|error| error.to_string())?
152 .json()
153 .await
154 .map_err(|error| error.to_string())?;
155 if profile.is_null()
156 || profile == Value::Bool(false)
157 || profile.as_f64() == Some(0.0)
158 || profile.as_str() == Some("")
159 {
160 return Err("Missing Railway profile".into());
161 }
162 let application_output = if let Some(mapper) = &self.application_mapper {
163 Some(
164 mapper
165 .map_profile(profile.clone())
166 .await
167 .map_err(super::remaining_profile::profile_exception)?,
168 )
169 } else {
170 None
171 };
172 let mapped = self
173 .mapper
174 .map(|mapper| mapper(profile.clone()))
175 .transpose()
176 .map_err(super::remaining_profile::profile_exception)?;
177 let mut output = serde_json::Map::new();
179 if let Some(name) = profile.get("name") {
180 _ = output.insert("name".into(), name.clone());
181 }
182 let email = profile.get("email");
183 if let Some(email) = email {
184 _ = output.insert("email".into(), email.clone());
185 }
186 if let Some(image) = profile.get("picture") {
187 _ = output.insert("image".into(), image.clone());
188 }
189 _ = output.insert("emailVerified".into(), Value::Bool(false));
190 if let Some(user) = &mapped {
191 output.extend(user.public_profile(true));
192 }
193 let user_output = Some(output);
194 let user = match mapped {
195 Some(user) => user,
196 None => OAuthUserInfo {
197 additional_fields: Map::default(),
198 id: profile
199 .get("sub")
200 .map(super::remaining_profile::js_string)
201 .transpose()?
202 .unwrap_or_default(),
203 name: scalar(profile.get("name").filter(|value| {
206 !matches!(value, Value::Bool(false)) && value.as_f64() != Some(0.0)
207 }))?,
208 email: email.and_then(Value::as_str).unwrap_or_default().into(),
209 image: scalar(profile.get("picture"))?,
210 email_verified: false,
211 },
212 };
213 let mut response = OAuthUserInfoResponse {
214 user_output,
215 user,
216 data: profile,
217 };
218 if let Some(mapped) = application_output {
219 super::apply_application_mapping(&mut response, mapped)?;
220 }
221 Ok(response)
222 }
223}
224fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
225 match value {
226 Some(Value::String(value)) => Ok(Some(value.clone())),
227 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
228 .map(Some)
229 .map_err(|error| error.to_string()),
230 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
231 None | Some(Value::Null | Value::Array(_) | Value::Object(_)) => Ok(None),
232 }
233}
234fn subject(profile: &Value) -> Result<String, String> {
235 super::remaining_profile::raw_subject(profile.get("sub"))
236}