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