Skip to main content

alibi_plugins/oauth/providers/
atlassian.rs

1//! Atlassian's published scope, PKCE, fixed audience and stable account subject.
2use super::{OAuthAuthorizationPolicy, OAuthProvider, OAuthUserInfo};
3use serde_json::Map;
4use serde_json::Value;
5
6/// Atlassian-specific configuration; callback and persistence policies remain
7/// configurable on the returned OAuth provider.
8#[derive(Clone)]
9pub struct AtlassianOptions {
10    pub client_id: String,
11    pub client_secret: String,
12    pub scope: Vec<String>,
13    pub disable_default_scope: bool,
14    pub prompt: Option<String>,
15    pub authorization_endpoint: Option<String>,
16    pub redirect_uri: Option<String>,
17    /// Trusted user-info transport endpoint, retaining the Atlassian mapping.
18    pub user_info_endpoint: Option<String>,
19    /// Receives the original profile. Its ID cannot replace `account_id`.
20    pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
21}
22impl AtlassianOptions {
23    #[must_use]
24    pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
25        Self {
26            client_id: client_id.into(),
27            client_secret: client_secret.into(),
28            scope: Vec::new(),
29            disable_default_scope: false,
30            prompt: None,
31            authorization_endpoint: None,
32            redirect_uri: None,
33            user_info_endpoint: None,
34            map_profile_to_user: None,
35        }
36    }
37}
38impl std::fmt::Debug for AtlassianOptions {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.debug_struct("AtlassianOptions")
41            .field("client_id", &self.client_id)
42            .field("scope", &self.scope)
43            .field("disable_default_scope", &self.disable_default_scope)
44            .field("prompt", &self.prompt)
45            .field("authorization_endpoint", &self.authorization_endpoint)
46            .field("redirect_uri", &self.redirect_uri)
47            .finish_non_exhaustive()
48    }
49}
50impl OAuthProvider {
51    #[must_use]
52    pub fn atlassian(client_id: &str, client_secret: &str) -> Self {
53        Self::atlassian_with_options(AtlassianOptions::new(client_id, client_secret))
54    }
55    #[must_use]
56    pub fn atlassian_with_options(options: AtlassianOptions) -> Self {
57        let mut provider = Self {
58            client_id: options.client_id,
59            client_secret: options.client_secret,
60            additional_client_ids: Vec::new(),
61            hosted_domain: None,
62            require_email_verification: false,
63            auth_url: String::new(),
64            token_url: String::new(),
65            user_info_url: None,
66            scopes: Vec::new(),
67            authorization: None,
68            allowed_request_params: Vec::new(),
69            authorization_params: Vec::new(),
70            account_subject: None,
71            map_user_info: None,
72            get_user_info: None,
73            refresh_access_token: None,
74            verify_id_token: None,
75            id_token: None,
76            disable_id_token_sign_in: false,
77            disable_implicit_sign_up: false,
78            disable_sign_up: false,
79            allow_idp_initiated: false,
80            override_user_info_on_sign_in: false,
81        };
82        provider.auth_url = options
83            .authorization_endpoint
84            .filter(|value| !value.is_empty())
85            .unwrap_or_else(|| "https://auth.atlassian.com/authorize".into());
86        provider.token_url = "https://auth.atlassian.com/oauth/token".into();
87        provider.user_info_url = Some(
88            options
89                .user_info_endpoint
90                .unwrap_or_else(|| "https://api.atlassian.com/me".into()),
91        );
92        provider.scopes = vec!["read:jira-user".into(), "offline_access".into()];
93        provider.authorization = Some(OAuthAuthorizationPolicy {
94            configured_scopes: options.scope,
95            disable_default_scopes: options.disable_default_scope,
96            prompt: options.prompt,
97            redirect_uri: options.redirect_uri,
98            require_client_secret: true,
99            login_hint: false,
100            ..OAuthAuthorizationPolicy::default()
101        });
102        provider.authorization_params = vec![("audience".into(), "api.atlassian.com".into())];
103        provider.map_user_info = Some(atlassian_user_info);
104        if let Some(mapper) = options.map_profile_to_user {
105            provider.get_user_info = Some(std::sync::Arc::new(AtlassianMappedUserInfo {
106                url: provider.user_info_url.clone().unwrap_or_default(),
107                mapper,
108            }));
109        }
110        provider
111    }
112}
113fn string(value: Option<&Value>) -> Result<Option<String>, String> {
114    match value {
115        Some(Value::String(value)) => Ok(Some(value.clone())),
116        Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
117            .map(Some)
118            .map_err(|error| error.to_string()),
119        Some(Value::Bool(value)) => Ok(Some(value.to_string())),
120        None | Some(Value::Null) => Ok(None),
121        _ => Err("Invalid Atlassian profile field".into()),
122    }
123}
124fn subject(profile: &Value) -> Result<String, String> {
125    let value = string(profile.get("account_id"))?.ok_or("Missing Atlassian account_id")?;
126    if value
127        .trim_matches(|character: char| {
128            (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
129        })
130        .is_empty()
131        || value == "null"
132        || value == "undefined"
133    {
134        return Err("Invalid Atlassian account_id".into());
135    }
136    Ok(value)
137}
138#[expect(
139    clippy::needless_pass_by_value,
140    reason = "signature fixed by the map_user_info callback type"
141)]
142fn atlassian_user_info(profile: Value) -> Result<OAuthUserInfo, String> {
143    let name = match profile.get("name") {
144        Some(Value::Bool(false)) => String::new(),
145        Some(Value::Number(value)) if value.as_f64() == Some(0.0) => String::new(),
146        value => string(value)?.unwrap_or_default(),
147    };
148    Ok(OAuthUserInfo {
149        additional_fields: Map::default(),
150        id: subject(&profile)?,
151        name: Some(name),
152        email: profile
153            .get("email")
154            .and_then(Value::as_str)
155            .unwrap_or_default()
156            .into(),
157        image: string(profile.get("picture"))?,
158        email_verified: false,
159    })
160}
161struct AtlassianMappedUserInfo {
162    url: String,
163    mapper: fn(Value) -> Result<OAuthUserInfo, String>,
164}
165#[async_trait::async_trait]
166impl super::OAuthUserInfoHandler for AtlassianMappedUserInfo {
167    async fn get_user_info(
168        &self,
169        request: super::OAuthUserInfoRequest,
170    ) -> Result<super::OAuthUserInfoResponse, String> {
171        let access_token = request
172            .access_token
173            .ok_or("Missing Atlassian access token")?;
174        let response = reqwest::Client::new()
175            .get(&self.url)
176            .bearer_auth(access_token)
177            .send()
178            .await
179            .map_err(|error| error.to_string())?
180            .error_for_status()
181            .map_err(|error| error.to_string())?;
182        let profile: Value = response.json().await.map_err(|error| error.to_string())?;
183        let mut user = (self.mapper)(profile.clone())?;
184        let user_output = Some(user.public_profile(true));
185        user.id = subject(&profile)?;
186        Ok(super::OAuthUserInfoResponse {
187            user_output,
188            user,
189            data: profile,
190        })
191    }
192}