Skip to main content

hf_robot_account/
lib.rs

1//! Sign a browserless device in to a Hugging Face account, and keep it signed in.
2//!
3//! A robot that only ever talks to a client on its own LAN needs no account. An account is what
4//! makes one reachable from *outside* the LAN: a rendezvous service resolves a bearer token to an
5//! identity, shows a client only its own robots, and the pair of those is the authorisation a
6//! session arrives with. This crate owns the credential and nothing else — it neither knows nor
7//! cares what the token is later presented to.
8//!
9//! # The flow is RFC 8628, because the device has no browser
10//!
11//! The obvious alternative, authorization code + PKCE, points a redirect URI at an HTTP server on
12//! the robot. That needs a redirect URI registered per hostname, and a browser that can resolve
13//! and reach the robot — so logging in requires being on the robot's network with mDNS working,
14//! and the robot is not even the party that authenticates. It merely hosts the landing pad.
15//!
16//! The device grant inverts it. The robot asks Hugging Face for a code, says *"open
17//! hf.co/oauth/device and type `M8HJ-FMGN`"*, and polls. No redirect URI, no hostname, and no
18//! requirement that the authorising device can reach the robot at all — a phone on cellular is
19//! fine. It is also the only one of the two that yields a **refresh token**, which is what keeps
20//! a robot signed in past its first month.
21//!
22//! The cost, stated plainly: somebody types eight characters.
23//!
24//! # Three consequences shape this API
25//!
26//! - **[`Account::login`] returns a code, not a token.** The waiting happens in a task this crate
27//!   spawns, and the caller comes back to [`Account::status`]. A login that reported success by
28//!   holding a connection open would work from a laptop and fail from the device it is for: a
29//!   phone that opens a browser backgrounds itself, and iOS then tears a GATT link down.
30//! - **The caller displays the code, and the code has to be typed.** Hugging Face sends no
31//!   `verification_uri_complete`, and its device page ignores `?user_code=` — so no URL carries
32//!   the code, which makes showing it the caller's whole job. Whether a caller also *opens* the
33//!   page is a property of the surface, not a rule: a terminal keeps the code in the scrollback
34//!   and can open a browser, a phone app must not, because the browser replaces the only screen
35//!   and the code is gone before it was read.
36//! - **A token expires in 30 days and its refresh token rotates.** So [`maintain`] renews well
37//!   before expiry, and the store is written atomically — see [`FileStore::save`] for the one
38//!   window that cannot be closed.
39//!
40//! # Using it
41//!
42//! ```no_run
43//! use std::sync::Arc;
44//! use hf_robot_account::{Account, Config, FileStore, maintain};
45//!
46//! # async fn example() -> Result<(), hf_robot_account::Error> {
47//! let store = FileStore::at("/etc/robot/hf-token").readable_by_group("robot");
48//! let account = Arc::new(Account::new(store, Config::from_env()));
49//!
50//! // Renew the token for as long as this process runs.
51//! tokio::spawn(maintain(Arc::clone(&account)));
52//!
53//! // A client asks to sign in: answer with the code, and let it come back to `status`.
54//! let code = account.login(false).await?;
55//! println!("Open {} and type {}", code.verification_uri, code.user_code);
56//! # Ok(())
57//! # }
58//! ```
59//!
60//! # What is deliberately not here
61//!
62//! **Any notion of what the token is for.** No relay, no rendezvous, no IPC. A daemon wraps these
63//! four methods in whatever protocol it serves and maps [`Error`] onto whatever error codes it
64//! has; this crate has no opinion about either.
65//!
66//! **Windows.** The credential is a file with an owner, a group and a mode; this is a Unix
67//! crate, and says so rather than carrying `cfg` branches nothing compiles.
68//!
69//! **A `TokenStore` trait.** [`FileStore`] takes a path, an optional group and a mode, which
70//! covers every difference between boards that actually exists. A robot that wants a TPM or a
71//! keyring is a reason to add the trait, and adding it then is a smaller change than carrying the
72//! indirection until somebody does.
73
74mod account;
75mod oauth;
76mod store;
77
78use std::time::Duration;
79
80pub use account::{Account, maintain};
81pub use oauth::{
82    DeviceCode, Poll, TokenResponse, http_client, refresh, request_device_code, userinfo,
83};
84pub use store::{FileStore, Stored, read_access_token};
85
86use serde::{Deserialize, Serialize};
87
88/// Hugging Face's first-party device-code OAuth client.
89///
90/// `huggingface_hub`'s `DEVICE_CODE_OAUTH_CLIENT_ID`, which is what `hf auth login` uses. Public
91/// — no secret, and none can be sent: Hugging Face refuses the device grant for a *confidential*
92/// client unless it is given the secret, so an OAuth app that has one cannot be used here. Its
93/// being first-party is also why this crate needs no app registered anywhere and works on a robot
94/// that has never met its manufacturer.
95///
96/// **What it costs is scopes.** This client takes no `scope` parameter, so the token it issues
97/// carries everything Hugging Face grants — `write-repos`, `manage-repos`, `jobs`, `read-billing`
98/// — for a credential whose whole job is proving an identity. A *public* device-code client
99/// registered to your own org with `openid profile read-repos` is one [`Config::client_id`] and
100/// one click by an org admin, and it is the right thing to do before a robot ships.
101pub const HUGGINGFACE_CLIENT_ID: &str = "26be6b09-91c5-47da-9861-d2d2bb7a7e36";
102
103/// Hugging Face.
104pub const HUGGINGFACE: &str = "https://huggingface.co";
105
106/// The variable `huggingface_hub` itself reads to point at a mirror. [`Config::from_env`].
107pub const ENDPOINT_VAR: &str = "HF_ENDPOINT";
108
109/// RFC 8628's fallback when the server sends no `interval`. Hugging Face sends none.
110pub(crate) const DEFAULT_POLL_INTERVAL: u64 = 5;
111
112/// RFC 8628 requires `expires_in`; defaulted defensively so a poll loop stays bounded.
113pub(crate) const DEFAULT_EXPIRES_IN: u64 = 900;
114
115/// Everything about a login that a different robot might want to change.
116///
117/// Constructed with `..Config::default()` rather than a builder: every field is meaningful on its
118/// own, and a struct literal is the one form that shows which of them a caller actually chose.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct Config {
121    /// Where Hugging Face is. [`HUGGINGFACE`], or a mirror.
122    pub endpoint: String,
123    /// Which OAuth client to authenticate as. [`HUGGINGFACE_CLIENT_ID`], or your org's own.
124    pub client_id: String,
125    /// Sent on every request. Name your robot here — it is what a Hub-side log will show.
126    pub user_agent: String,
127    /// How long one HTTP round trip to Hugging Face gets.
128    pub http_timeout: Duration,
129    /// Renew a token with less than this left.
130    ///
131    /// Hugging Face issues 30 days. The default refreshes three-quarters of the way through the
132    /// token's life and leaves a week of retries, which is what a board with a marginal network
133    /// needs — a robot switched off for longer than the whole 30 days cannot be saved by any
134    /// margin, and comes back needing a login.
135    pub refresh_when_under: Duration,
136    /// How often [`maintain`] wakes to look at the token's remaining life.
137    ///
138    /// Slow on purpose: the thing it guards against is a robot that has been on for a month, and
139    /// the cost of asking too often is a request that answers "not yet".
140    pub maintain_interval: Duration,
141}
142
143impl Default for Config {
144    fn default() -> Self {
145        Self {
146            endpoint: HUGGINGFACE.to_string(),
147            client_id: HUGGINGFACE_CLIENT_ID.to_string(),
148            user_agent: concat!("hf-robot-account/", env!("CARGO_PKG_VERSION")).to_string(),
149            http_timeout: Duration::from_secs(20),
150            refresh_when_under: Duration::from_secs(7 * 24 * 60 * 60),
151            maintain_interval: Duration::from_secs(6 * 60 * 60),
152        }
153    }
154}
155
156impl Config {
157    /// [`Config::default`], with [`ENDPOINT_VAR`] honoured if it is set to something non-empty.
158    ///
159    /// Separate from `default` because a library that reads the environment behind its caller's
160    /// back is a surprise, and because a test wants an endpoint that no other test can change
161    /// under it. Reading `HF_ENDPOINT` specifically means a board pointed at a mirror for one
162    /// reason is pointed at it for all of them.
163    pub fn from_env() -> Self {
164        let endpoint = std::env::var(ENDPOINT_VAR)
165            .ok()
166            .filter(|s| !s.trim().is_empty());
167        Self {
168            endpoint: endpoint.unwrap_or_else(|| HUGGINGFACE.to_string()),
169            ..Self::default()
170        }
171    }
172
173    /// As [`Config::default`], against a named endpoint. For tests, mostly.
174    pub fn at(endpoint: impl Into<String>) -> Self {
175        Self {
176            endpoint: endpoint.into(),
177            ..Self::default()
178        }
179    }
180}
181
182// ── what a caller sees ───────────────────────────────────────────────────────
183
184/// A started login: what to show somebody, and how long they have to act on it.
185///
186/// Everything here is meant for a person's eyes except [`interval`](Self::interval), which is the
187/// server's polling cadence and is reported only so a caller can explain a wait.
188#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
189pub struct LoginCode {
190    /// The eight characters somebody types. **Show this.**
191    pub user_code: String,
192    /// Where they type it.
193    pub verification_uri: String,
194    /// The URI that carries the code, where a server sends one.
195    ///
196    /// Hugging Face does not, so this is [`verification_uri`](Self::verification_uri) unchanged —
197    /// their device page ignores a `?user_code=` query, and a URL carrying a query the other end
198    /// drops reads like a promise the page then breaks. The field stays because it is the
199    /// protocol's, and a server that starts sending a real one is then used without a change.
200    pub verification_uri_complete: String,
201    /// How long the code is good for. In [`Status`] this is what is *left*, so a caller can count
202    /// it down rather than repeat the original number.
203    pub expires_in: u64,
204    /// Seconds between polls, as the server asked for them.
205    pub interval: u64,
206}
207
208/// Who a robot belongs to.
209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
210pub struct Identity {
211    /// The Hugging Face username, as `/oauth/userinfo` reports it. What to show a person.
212    ///
213    /// `"unknown"` when the robot holds a token whose owner could not be read at login — a
214    /// network failure on the last and least important call of the flow. [`maintain`] fills it in.
215    pub username: String,
216    /// Seconds until the access token expires; negative once it has, so a caller can say "this
217    /// robot needs signing in again" rather than "signed in" about a credential that is dead.
218    /// [`i64::MAX`] when the server named no expiry.
219    pub token_expires_in: i64,
220    /// Whether a refresh token was stored. `false` means this credential dies at
221    /// [`token_expires_in`](Self::token_expires_in) and nothing can renew it.
222    pub refreshable: bool,
223}
224
225/// Everything [`Account::status`] knows, which is everything a client needs to render a wizard.
226#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
227pub struct Status {
228    /// Who the robot belongs to, or `None` for a robot out of the box.
229    pub account: Option<Identity>,
230    /// A login waiting for approval, with the time *left* on its code.
231    ///
232    /// Carried here so a client that lost track of a code — a phone that backgrounded itself, a
233    /// terminal somebody closed — rejoins the login in flight rather than starting another.
234    pub login: Option<LoginCode>,
235    /// Why the last thing that failed, failed. `None` once something works.
236    ///
237    /// This is where somebody looks to find out why remote access stopped, so it carries refresh
238    /// failures and abandoned logins — and deliberately not a missing username, which is
239    /// cosmetic and did not stop anything.
240    pub last_error: Option<String>,
241}
242
243// ── errors ───────────────────────────────────────────────────────────────────
244
245/// What can go wrong.
246///
247/// Four variants, and two of them are refusals rather than faults: a caller serving this over a
248/// protocol will want to map [`AlreadySignedIn`](Error::AlreadySignedIn) to something meaning
249/// "your request was wrong and here is the parameter that fixes it", and
250/// [`LoginInFlight`](Error::LoginInFlight) to something meaning "busy, try again".
251#[derive(Debug, thiserror::Error)]
252pub enum Error {
253    /// Hugging Face could not be reached, or did not answer usefully.
254    #[error("{0}")]
255    Network(String),
256
257    /// The credential could not be read or written.
258    #[error("{path}: {source}")]
259    Io {
260        /// The file that could not be read or written.
261        path: std::path::PathBuf,
262        /// What the filesystem said.
263        source: std::io::Error,
264    },
265
266    /// A second login while one is still waiting for approval.
267    ///
268    /// Retryable, and the message says where the code that already exists can be read — two
269    /// logins collide during setup, when a console page and a phone are both pointed at the same
270    /// robot, and what that person needs is that a code is already out.
271    #[error(
272        "a login is already waiting for approval — `account status` has the code, or force to \
273         start a new one"
274    )]
275    LoginInFlight,
276
277    /// A login on a robot that already belongs to somebody, without `force`.
278    ///
279    /// A robot changing hands is common enough that the message names the account and the flag
280    /// rather than leaving somebody to hunt for them.
281    #[error(
282        "this robot already belongs to {0}. Sign that account out first, or force to replace it"
283    )]
284    AlreadySignedIn(String),
285}
286
287// ── small things ─────────────────────────────────────────────────────────────
288
289/// Seconds since the Unix epoch, or `0` on a clock that predates it.
290///
291/// `0` rather than a panic: a board whose RTC has not been set yet reads as "everything expired",
292/// which makes a robot ask for a login it may not need — annoying, and better than a daemon that
293/// will not start because the clock is wrong.
294pub(crate) fn now_secs() -> i64 {
295    std::time::SystemTime::now()
296        .duration_since(std::time::UNIX_EPOCH)
297        .map(|d| d.as_secs() as i64)
298        .unwrap_or(0)
299}