1use serde::Deserialize;
8
9use crate::{Config, DEFAULT_EXPIRES_IN, DEFAULT_POLL_INTERVAL, Error};
10
11pub fn http_client(config: &Config) -> Result<reqwest::Client, Error> {
16 reqwest::Client::builder()
17 .user_agent(config.user_agent.clone())
18 .redirect(reqwest::redirect::Policy::limited(5))
21 .build()
22 .map_err(|e| Error::Network(format!("could not build HTTP client: {e}")))
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct DeviceCode {
28 pub device_code: String,
30 pub user_code: String,
32 pub verification_uri: String,
34 pub verification_uri_complete: String,
36 pub expires_in: u64,
38 pub interval: u64,
40}
41
42#[derive(Debug, Deserialize)]
44struct DeviceCodeResponse {
45 device_code: String,
46 user_code: String,
47 verification_uri: String,
48 verification_uri_complete: Option<String>,
49 expires_in: Option<u64>,
50 interval: Option<u64>,
51}
52
53#[derive(Debug, Clone, Deserialize)]
55pub struct TokenResponse {
56 pub access_token: String,
58 #[serde(default)]
60 pub refresh_token: Option<String>,
61 #[serde(default)]
63 pub expires_in: Option<u64>,
64}
65
66impl PartialEq for TokenResponse {
67 fn eq(&self, other: &Self) -> bool {
68 self.access_token == other.access_token
69 && self.refresh_token == other.refresh_token
70 && self.expires_in == other.expires_in
71 }
72}
73impl Eq for TokenResponse {}
74
75#[derive(Debug, Deserialize)]
77struct OAuthError {
78 error: String,
79 #[serde(default)]
80 error_description: Option<String>,
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
85pub enum Poll {
86 Pending,
88 SlowDown,
90 Token(Box<TokenResponse>),
92 Refused(String),
94 Inconclusive(String),
97}
98
99pub async fn request_device_code(
101 client: &reqwest::Client,
102 config: &Config,
103) -> Result<DeviceCode, Error> {
104 let url = format!("{}/oauth/device", config.endpoint);
105 let response = client
106 .post(&url)
107 .timeout(config.http_timeout)
108 .form(&[("client_id", config.client_id.as_str())])
109 .send()
110 .await
111 .map_err(|e| Error::Network(format!("POST {url}: {e}")))?;
112
113 let status = response.status();
114 let body = response
115 .text()
116 .await
117 .map_err(|e| Error::Network(format!("reading {url}: {e}")))?;
118 if !status.is_success() {
119 return Err(Error::Network(format!(
120 "POST {url}: HTTP {status}: {}",
121 body.chars().take(300).collect::<String>()
122 )));
123 }
124
125 let raw: DeviceCodeResponse = serde_json::from_str(&body).map_err(|e| {
126 Error::Network(format!(
127 "POST {url}: could not parse the device code response: {e}"
128 ))
129 })?;
130
131 let verification_uri_complete = raw
140 .verification_uri_complete
141 .unwrap_or_else(|| raw.verification_uri.clone());
142 Ok(DeviceCode {
143 device_code: raw.device_code,
144 user_code: raw.user_code,
145 verification_uri: raw.verification_uri,
146 verification_uri_complete,
147 expires_in: raw.expires_in.unwrap_or(DEFAULT_EXPIRES_IN),
148 interval: raw.interval.unwrap_or(DEFAULT_POLL_INTERVAL),
149 })
150}
151
152pub async fn poll_token(client: &reqwest::Client, config: &Config, device_code: &str) -> Poll {
158 let url = format!("{}/oauth/token", config.endpoint);
159 let response = client
160 .post(&url)
161 .timeout(config.http_timeout)
162 .form(&[
163 ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
164 ("client_id", config.client_id.as_str()),
165 ("device_code", device_code),
166 ])
167 .send()
168 .await;
169
170 let response = match response {
171 Ok(response) => response,
172 Err(e) => return Poll::Inconclusive(format!("POST {url}: {e}")),
173 };
174 if response.status().is_server_error() {
176 return Poll::Inconclusive(format!("POST {url}: HTTP {}", response.status()));
177 }
178 let body = match response.text().await {
179 Ok(body) => body,
180 Err(e) => return Poll::Inconclusive(format!("reading {url}: {e}")),
181 };
182
183 if let Ok(token) = serde_json::from_str::<TokenResponse>(&body) {
184 return Poll::Token(Box::new(token));
185 }
186 match serde_json::from_str::<OAuthError>(&body) {
187 Ok(err) => classify(&err),
188 Err(_) => Poll::Inconclusive(format!(
190 "POST {url}: unexpected answer: {}",
191 body.chars().take(200).collect::<String>()
192 )),
193 }
194}
195
196fn classify(err: &OAuthError) -> Poll {
198 let detail = err
199 .error_description
200 .clone()
201 .unwrap_or_else(|| err.error.clone());
202 match err.error.as_str() {
203 "authorization_pending" => Poll::Pending,
204 "slow_down" => Poll::SlowDown,
205 "expired_token" => Poll::Refused(
206 "the code expired before it was approved — start the login again".to_string(),
207 ),
208 "access_denied" => Poll::Refused("the login was refused on Hugging Face".to_string()),
209 other => Poll::Refused(format!("Hugging Face said {other}: {detail}")),
212 }
213}
214
215pub async fn refresh(
221 client: &reqwest::Client,
222 config: &Config,
223 refresh_token: &str,
224) -> Result<TokenResponse, Error> {
225 let url = format!("{}/oauth/token", config.endpoint);
226 let response = client
227 .post(&url)
228 .timeout(config.http_timeout)
229 .form(&[
230 ("grant_type", "refresh_token"),
231 ("client_id", config.client_id.as_str()),
232 ("refresh_token", refresh_token),
233 ])
234 .send()
235 .await
236 .map_err(|e| Error::Network(format!("POST {url}: {e}")))?;
237 let body = response
238 .text()
239 .await
240 .map_err(|e| Error::Network(format!("reading {url}: {e}")))?;
241 serde_json::from_str::<TokenResponse>(&body).map_err(|_| {
242 let detail = serde_json::from_str::<OAuthError>(&body)
243 .map(|e| format!("{}: {}", e.error, e.error_description.unwrap_or_default()))
244 .unwrap_or_else(|_| body.chars().take(200).collect());
245 Error::Network(format!("could not refresh the account token: {detail}"))
246 })
247}
248
249pub async fn userinfo(
257 client: &reqwest::Client,
258 config: &Config,
259 access_token: &str,
260) -> Result<String, Error> {
261 #[derive(Deserialize)]
262 struct UserInfo {
263 preferred_username: Option<String>,
264 name: Option<String>,
265 }
266
267 let url = format!("{}/oauth/userinfo", config.endpoint);
268 let response = client
269 .get(&url)
270 .timeout(config.http_timeout)
271 .bearer_auth(access_token)
272 .send()
273 .await
274 .map_err(|e| Error::Network(format!("GET {url}: {e}")))?;
275 let status = response.status();
276 let body = response
277 .text()
278 .await
279 .map_err(|e| Error::Network(format!("reading {url}: {e}")))?;
280 if !status.is_success() {
281 return Err(Error::Network(format!("GET {url}: HTTP {status}")));
282 }
283 let info: UserInfo = serde_json::from_str(&body)
284 .map_err(|e| Error::Network(format!("GET {url}: could not parse the answer: {e}")))?;
285 info.preferred_username
286 .or(info.name)
287 .ok_or_else(|| Error::Network(format!("GET {url}: no username in the answer")))
288}
289
290#[cfg(test)]
291mod tests {
292 use super::*;
293
294 #[test]
300 fn oauth_errors_are_classified() {
301 let of = |error: &str| {
302 classify(&OAuthError {
303 error: error.to_string(),
304 error_description: None,
305 })
306 };
307 assert_eq!(of("authorization_pending"), Poll::Pending);
308 assert_eq!(of("slow_down"), Poll::SlowDown);
309 assert!(matches!(of("expired_token"), Poll::Refused(_)));
310 assert!(matches!(of("access_denied"), Poll::Refused(_)));
311 assert!(matches!(of("invalid_client"), Poll::Refused(_)));
314 }
315}