Skip to main content

hf_robot_account/
oauth.rs

1//! The Hugging Face half: four requests, and the normalisation their answers need.
2//!
3//! These are public because they are useful on their own — a tool that wants one login and no
4//! daemon can drive them directly — but [`crate::Account`] is what most callers want, because
5//! the interesting part of a device flow is not the requests. It is what owns the waiting.
6
7use serde::Deserialize;
8
9use crate::{Config, DEFAULT_EXPIRES_IN, DEFAULT_POLL_INTERVAL, Error};
10
11/// An HTTP client configured the way every call below expects.
12///
13/// Built per operation rather than held: `status` and `logout` need none at all, and the one
14/// operation that polls in a loop wants a client that lives exactly as long as the loop.
15pub fn http_client(config: &Config) -> Result<reqwest::Client, Error> {
16    reqwest::Client::builder()
17        .user_agent(config.user_agent.clone())
18        // Redirects are followed, but not indefinitely: a redirect loop is a misconfigured
19        // mirror, not something to chase.
20        .redirect(reqwest::redirect::Policy::limited(5))
21        .build()
22        .map_err(|e| Error::Network(format!("could not build HTTP client: {e}")))
23}
24
25/// A started device authorization, with the fields Hugging Face omits filled in.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct DeviceCode {
28    /// The robot's half of the pair. Never shown to anybody; this is what is polled with.
29    pub device_code: String,
30    /// The person's half. Eight characters, typed into a browser somewhere else.
31    pub user_code: String,
32    /// Where to type it.
33    pub verification_uri: String,
34    /// See [`crate::LoginCode::verification_uri_complete`].
35    pub verification_uri_complete: String,
36    /// Seconds the code is good for.
37    pub expires_in: u64,
38    /// Seconds between polls.
39    pub interval: u64,
40}
41
42/// What `POST /oauth/device` answers, before normalisation.
43#[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/// What `POST /oauth/token` answers on success.
54#[derive(Debug, Clone, Deserialize)]
55pub struct TokenResponse {
56    /// The bearer token.
57    pub access_token: String,
58    /// Absent when Hugging Face issues none, which makes the token unrenewable rather than broken.
59    #[serde(default)]
60    pub refresh_token: Option<String>,
61    /// Seconds from now. Absent means the server did not say.
62    #[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/// What `POST /oauth/token` answers while nobody has approved yet.
76#[derive(Debug, Deserialize)]
77struct OAuthError {
78    error: String,
79    #[serde(default)]
80    error_description: Option<String>,
81}
82
83/// One poll of the token endpoint.
84#[derive(Debug, Clone, PartialEq, Eq)]
85pub enum Poll {
86    /// Nobody has approved it yet.
87    Pending,
88    /// The server wants a longer interval. RFC 8628 §3.5: add five seconds.
89    SlowDown,
90    /// Approved.
91    Token(Box<TokenResponse>),
92    /// The user said no, or the code ran out. Either way, start again.
93    Refused(String),
94    /// Anything inconclusive — a 5xx, a proxy's error page, a network blip. **Not** a failure:
95    /// RFC 8628 §3.5 says keep polling until the code expires, and the deadline bounds the wait.
96    Inconclusive(String),
97}
98
99/// Ask Hugging Face to start a device authorization.
100pub 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    // Hugging Face sends neither `interval` nor `verification_uri_complete`, so both are
132    // defaulted here — the same normalisation `huggingface_hub` does, in the same place, so
133    // nothing downstream has to know which fields a server bothered with.
134    //
135    // **The fallback is the plain URI, and the code still has to be typed.** Appending
136    // `?user_code=` looks obvious and is wrong: Hugging Face's device page ignores the parameter,
137    // it survives the login redirect and prefills nothing, and a URL carrying a query the other
138    // end drops is worse than no query because it reads like a promise the page then breaks.
139    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
152/// Poll the token endpoint once.
153///
154/// Infallible by design: every way this can go wrong is one of the [`Poll`] variants, because a
155/// caller polling in a loop has to decide "keep going" or "stop" and a `Result` does not carry
156/// that distinction. A 5xx is not an answer about this login; `access_denied` is.
157pub 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    // A 5xx is a Hugging Face problem, not an answer about this login.
175    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        // JSON without an `error` member, or not JSON at all: a gateway's error page. Transient.
189        Err(_) => Poll::Inconclusive(format!(
190            "POST {url}: unexpected answer: {}",
191            body.chars().take(200).collect::<String>()
192        )),
193    }
194}
195
196/// Which OAuth errors end a login and which are the login working normally.
197fn 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        // An OAuth error we do not know is still an answer about this login rather than a blip:
210        // `invalid_client` and `invalid_grant` will not fix themselves by being asked again.
211        other => Poll::Refused(format!("Hugging Face said {other}: {detail}")),
212    }
213}
214
215/// Exchange a refresh token for a new pair.
216///
217/// **Hugging Face rotates the refresh token**, so the answer's is the one to keep. Storing the one
218/// already on disk is the obvious mistake — the rest of the record is carried over — and it
219/// leaves a robot that renews exactly once and then quietly stops being reachable.
220pub 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
249/// Who a token belongs to.
250///
251/// `/oauth/userinfo` rather than decoding the `id_token`: one round trip against an endpoint that
252/// is part of the flow already, versus a JWT parser and a JWKS fetch for the same string.
253///
254/// `preferred_username` is the handle — `PierreRouanet` — and `name` is a display name that can be
255/// anything, so the handle is preferred and `name` is the fallback.
256pub 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    /// Which OAuth errors end a login, and which are it working normally.
295    ///
296    /// The two in the middle are the ones worth pinning: treating `slow_down` as a failure would
297    /// abandon a login that was about to succeed, and treating `expired_token` as transient would
298    /// poll a dead code until the deadline.
299    #[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        // An error we have never seen is still an answer about this login: `invalid_client` will
312        // not fix itself by being asked again, and polling it for five minutes hides the cause.
313        assert!(matches!(of("invalid_client"), Poll::Refused(_)));
314    }
315}