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 authorization_params: Vec::new(),
98 account_subject: Some(subject),
99 map_user_info: None,
100 get_user_info: Some(std::sync::Arc::new(HuggingFaceUserInfo {
101 endpoint,
102 mapper: options.map_profile_to_user,
103 })),
104 refresh_access_token: None,
105 verify_id_token: None,
106 id_token: None,
107 disable_id_token_sign_in: false,
108 disable_implicit_sign_up: false,
109 disable_sign_up: false,
110 allow_idp_initiated: false,
111 override_user_info_on_sign_in: false,
112 }
113 }
114}
115struct HuggingFaceUserInfo {
116 endpoint: String,
117 mapper: Option<fn(Value) -> Result<OAuthUserInfo, String>>,
118}
119#[async_trait]
120impl OAuthUserInfoHandler for HuggingFaceUserInfo {
121 async fn get_user_info(
122 &self,
123 request: OAuthUserInfoRequest,
124 ) -> Result<OAuthUserInfoResponse, String> {
125 let access_token = request
126 .access_token
127 .ok_or("Missing Hugging Face access token")?;
128 let profile: Value = reqwest::Client::new()
129 .get(&self.endpoint)
130 .bearer_auth(access_token)
131 .send()
132 .await
133 .map_err(|error| error.to_string())?
134 .error_for_status()
135 .map_err(|error| error.to_string())?
136 .json()
137 .await
138 .map_err(|error| error.to_string())?;
139 let mapped = self
140 .mapper
141 .map(|mapper| mapper(profile.clone()))
142 .transpose()?;
143 let user_output = mapped.as_ref().map(|user| user.public_profile(true));
144 let user = match mapped {
145 Some(user) => user,
146 None => OAuthUserInfo {
147 additional_fields: Map::default(),
148 id: scalar(profile.get("sub"))?.unwrap_or_default(),
149 name: Some(
150 scalar(
151 profile
152 .get("name")
153 .filter(|value| truthy(value))
154 .or_else(|| {
155 profile
156 .get("preferred_username")
157 .filter(|value| truthy(value))
158 }),
159 )?
160 .unwrap_or_default(),
161 ),
162 email: profile
163 .get("email")
164 .and_then(Value::as_str)
165 .unwrap_or_default()
166 .into(),
167 image: scalar(profile.get("picture"))?,
168 email_verified: profile
169 .get("email_verified")
170 .and_then(Value::as_bool)
171 .unwrap_or(false),
172 },
173 };
174 Ok(OAuthUserInfoResponse {
175 user_output,
176 user,
177 data: profile,
178 })
179 }
180}
181fn scalar(value: Option<&Value>) -> Result<Option<String>, String> {
182 match value {
183 None | Some(Value::Null) => Ok(None),
184 Some(Value::String(value)) => Ok(Some(value.clone())),
185 Some(Value::Number(value)) => alibi_core::utils::json::number_to_string(value)
186 .map(Some)
187 .map_err(|error| error.to_string()),
188 Some(Value::Bool(value)) => Ok(Some(value.to_string())),
189 Some(Value::Array(_) | Value::Object(_)) => {
190 Err("Invalid Hugging Face profile field".into())
191 }
192 }
193}
194fn subject(profile: &Value) -> Result<String, String> {
195 let id = scalar(profile.get("sub"))?.ok_or("Missing Hugging Face sub")?;
196 if id
197 .trim_matches(|character: char| {
198 (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
199 })
200 .is_empty()
201 || id == "null"
202 || id == "undefined"
203 {
204 return Err("Invalid Hugging Face sub".into());
205 }
206 Ok(id)
207}
208
209fn truthy(value: &Value) -> bool {
210 match value {
211 Value::Null => false,
212 Value::Bool(value) => *value,
213 Value::Number(value) => value.as_f64().is_some_and(|value| value != 0.0),
214 Value::String(value) => !value.is_empty(),
215 Value::Array(_) | Value::Object(_) => true,
216 }
217}