alibi_api/plugins/oauth/providers/
huggingface.rs1use super::{
3 OAuthAuthorizationPolicy, OAuthProvider, OAuthTokenEndpointAuth, OAuthUserInfo,
4 OAuthUserInfoHandler, OAuthUserInfoRequest, OAuthUserInfoResponse,
5};
6use async_trait::async_trait;
7use serde_json::Value;
8
9#[derive(Clone)]
12pub struct HuggingFaceOptions {
13 pub client_id: String,
14 pub client_secret: Option<String>,
15 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 pub user_info_endpoint: Option<String>,
23 pub map_profile_to_user: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
25}
26impl HuggingFaceOptions {
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 HuggingFaceOptions {
43 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 formatter
45 .debug_struct("HuggingFaceOptions")
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 huggingface(client_id: &str, client_secret: Option<&str>) -> Self {
57 Self::huggingface_with_options(HuggingFaceOptions::new(
58 client_id,
59 client_secret.map(str::to_owned),
60 ))
61 }
62 #[must_use]
63 pub fn huggingface_with_options(options: HuggingFaceOptions) -> Self {
64 let secret = options.client_secret.unwrap_or_default();
65 let authentication = if secret.is_empty() {
66 OAuthTokenEndpointAuth::None
67 } else {
68 OAuthTokenEndpointAuth::ClientSecretPost
69 };
70 let endpoint = options
71 .user_info_endpoint
72 .unwrap_or_else(|| "https://huggingface.co/oauth/userinfo".into());
73 Self {
74 client_id: options.client_id,
75 client_secret: secret,
76 additional_client_ids: Vec::new(),
77 hosted_domain: None,
78 require_email_verification: false,
79 auth_url: options
80 .authorization_endpoint
81 .filter(|value| !value.is_empty())
82 .unwrap_or_else(|| "https://huggingface.co/oauth/authorize".into()),
83 token_url: "https://huggingface.co/oauth/token".into(),
84 user_info_url: Some(endpoint.clone()),
85 scopes: vec!["openid".into(), "profile".into(), "email".into()],
86 authorization: Some(OAuthAuthorizationPolicy {
87 configured_scopes: options.scope,
88 disable_default_scopes: options.disable_default_scope,
89 require_client_id: true,
90 token_endpoint_auth: Some(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(HuggingFaceUserInfo {
100 endpoint,
101 mapper: options.map_profile_to_user,
102 })),
103 refresh_access_token: None,
104 verify_id_token: None,
105 id_token: None,
106 disable_id_token_sign_in: false,
107 disable_implicit_sign_up: false,
108 disable_sign_up: false,
109 override_user_info_on_sign_in: false,
110 }
111 }
112}
113struct HuggingFaceUserInfo {
114 endpoint: String,
115 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
116}
117#[async_trait]
118impl OAuthUserInfoHandler for HuggingFaceUserInfo {
119 async fn get_user_info(
120 &self,
121 request: OAuthUserInfoRequest,
122 ) -> Result<OAuthUserInfoResponse, String> {
123 let access_token = request
124 .access_token
125 .ok_or("Missing Hugging Face access token")?;
126 let profile: Value = reqwest::Client::new()
127 .get(&self.endpoint)
128 .bearer_auth(access_token)
129 .send()
130 .await
131 .map_err(|error| error.to_string())?
132 .error_for_status()
133 .map_err(|error| error.to_string())?
134 .json()
135 .await
136 .map_err(|error| error.to_string())?;
137 let mapped = self
138 .mapper
139 .map(|mapper| mapper(profile.clone()))
140 .transpose()?;
141 let user_output = mapped.as_ref().map(|user| user.public_profile(true));
142 let user = match mapped {
143 Some(user) => user,
144 None => OAuthUserInfo {
145 additional_fields: Default::default(),
146 id: scalar(profile.get("sub"))?.unwrap_or_default(),
147 name: Some(
148 scalar(
149 profile
150 .get("name")
151 .filter(|value| truthy(value))
152 .or_else(|| {
153 profile
154 .get("preferred_username")
155 .filter(|value| truthy(value))
156 }),
157 )?
158 .unwrap_or_default(),
159 ),
160 email: profile
161 .get("email")
162 .and_then(Value::as_str)
163 .unwrap_or_default()
164 .into(),
165 image: scalar(profile.get("picture"))?,
166 email_verified: profile
167 .get("email_verified")
168 .and_then(Value::as_bool)
169 .unwrap_or(false),
170 },
171 };
172 Ok(OAuthUserInfoResponse {
173 user_output,
174 user,
175 data: profile,
176 })
177 }
178}
179fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
180 match value {
181 None | Some(Value::Null) => Ok(None),
182 Some(Value::String(value)) => Ok(Some(value.clone())),
183 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
184 .map(Some)
185 .map_err(|error| error.to_string()),
186 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
187 Some(Value::Array(_) | Value::Object(_)) => {
188 Err("Invalid Hugging Face profile field".into())
189 }
190 }
191}
192fn subject(profile: &Value) -> Result<String, String> {
193 let id = scalar(profile.get("sub"))?.ok_or("Missing Hugging Face sub")?;
194 if id
195 .trim_matches(|character: char| {
196 (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
197 })
198 .is_empty()
199 || id == "null"
200 || id == "undefined"
201 {
202 return Err("Invalid Hugging Face sub".into());
203 }
204 Ok(id)
205}
206
207fn truthy(value: &Value) -> bool {
208 match value {
209 Value::Null => false,
210 Value::Bool(value) => *value,
211 Value::Number(value) => value.as_f64().is_some_and(|value| value != 0.0),
212 Value::String(value) => !value.is_empty(),
213 Value::Array(_) | Value::Object(_) => true,
214 }
215}