hf_robot_account/store.rs
1//! Where the credential lives, and the care its file needs.
2//!
3//! **Not in a config file.** Every mechanism a robot's configuration has is wrong for a secret:
4//! something prints what a robot has changed, something else shows the whole file in an editor,
5//! and "what was configured on this robot" is a report somebody generates. A bearer token would
6//! be in all three.
7//!
8//! This module is also where the **cross-process file format** is defined, which is the reason
9//! [`read_access_token`] exists next to the writer rather than in whichever daemon reads it. The
10//! process that performs the login is privileged; the process that *uses* the token — a relay, a
11//! media daemon — usually is not, and has no business linking the rest of this crate. One key at
12//! one level, pinned by a test here, is the whole contract between them.
13
14use std::path::{Path, PathBuf};
15
16use serde::{Deserialize, Serialize};
17
18use crate::{Error, Identity, now_secs};
19
20/// What is on disk.
21///
22/// The shape mirrors what the token endpoint returns, plus the two things it does not: an
23/// absolute expiry (the response gives a duration, and a duration is meaningless after a reboot)
24/// and the username, so a status call answers without a network round trip.
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26pub struct Stored {
27 /// The bearer token. **This key at this level is what other processes read.**
28 pub access_token: String,
29 /// Absent when Hugging Face issues none, which makes the token unrenewable rather than broken.
30 #[serde(default, skip_serializing_if = "Option::is_none")]
31 pub refresh_token: Option<String>,
32 /// Unix seconds. Absent means "the server did not say", which is treated as not expiring.
33 #[serde(default, skip_serializing_if = "Option::is_none")]
34 pub expires_at: Option<i64>,
35 /// As `/oauth/userinfo` reported it at login.
36 #[serde(default, skip_serializing_if = "Option::is_none")]
37 pub username: Option<String>,
38}
39
40impl Stored {
41 /// Seconds until the access token expires; negative once it has. [`i64::MAX`] when unknown.
42 pub fn expires_in(&self) -> i64 {
43 match self.expires_at {
44 None => i64::MAX,
45 Some(at) => at.saturating_sub(now_secs()),
46 }
47 }
48
49 /// What a caller is told about this credential.
50 pub fn identity(&self) -> Identity {
51 Identity {
52 username: self
53 .username
54 .clone()
55 .unwrap_or_else(|| "unknown".to_string()),
56 token_expires_in: self.expires_in(),
57 refreshable: self.refresh_token.is_some(),
58 }
59 }
60}
61
62/// The token file, and the three operations anything has on it.
63///
64/// **Configurable rather than abstract.** A path, an optional group and a mode cover the
65/// differences between boards that actually exist: a different filesystem layout, a robot with no
66/// group to share the token with, a stricter mode. What they do not cover is a credential that
67/// does not live in a file at all — a TPM, a keyring — and that is a reason to add a trait when
68/// somebody has one, not before.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct FileStore {
71 path: PathBuf,
72 group: Option<String>,
73 mode: u32,
74}
75
76impl FileStore {
77 /// A credential at `path`, readable only by the user that writes it.
78 pub fn at(path: impl Into<PathBuf>) -> Self {
79 Self {
80 path: path.into(),
81 group: None,
82 mode: 0o600,
83 }
84 }
85
86 /// Let one more group read it, by **name**.
87 ///
88 /// By name because `systemd-sysusers` and its equivalents allocate dynamically: a number
89 /// written down is right on one board and wrong on the next. This also relaxes the mode to
90 /// `0640`, since group ownership without the group-read bit gives nobody anything — call
91 /// [`Self::mode`] afterwards for the unusual case where that is what you meant.
92 ///
93 /// A group that does not exist on this system is a warning and a token that stays private to
94 /// its owner, not an error: a login that failed because a developer's laptop has no such
95 /// group would be a worse outcome than a token the other daemon cannot read yet.
96 pub fn readable_by_group(mut self, group: impl Into<String>) -> Self {
97 self.group = Some(group.into());
98 self.mode = 0o640;
99 self
100 }
101
102 /// Override the mode the file ends up with.
103 pub fn mode(mut self, mode: u32) -> Self {
104 self.mode = mode;
105 self
106 }
107
108 /// Where the credential is.
109 pub fn path(&self) -> &Path {
110 &self.path
111 }
112
113 /// What is stored, or `None` when the robot belongs to nobody.
114 ///
115 /// A file that will not parse is `None` with a warning rather than an error: the recovery for
116 /// a corrupt credential is signing in again, and a daemon that refuses to start — or a status
117 /// call that fails — because of one would make that harder rather than safer.
118 pub fn load(&self) -> Option<Stored> {
119 let bytes = std::fs::read(&self.path).ok()?;
120 match serde_json::from_slice::<Stored>(&bytes) {
121 Ok(stored) => Some(stored),
122 Err(e) => {
123 tracing::warn!(
124 path = %self.path.display(),
125 error = %e,
126 "the stored account credential does not parse; treating this robot as signed out"
127 );
128 None
129 }
130 }
131 }
132
133 /// Replace the credential, atomically, readable only by its owner and the named group.
134 ///
135 /// **The one window this cannot close.** Hugging Face rotates the refresh token on every
136 /// refresh, so between "the server issued a new pair" and "the new pair is on disk" the old
137 /// refresh token is already dead. A power cut in that window leaves a robot holding a
138 /// credential Hugging Face will not renew, and no ordering here fixes it — the rotation
139 /// happened on their side. It surfaces as a refresh failure in [`crate::Status::last_error`]
140 /// and is fixed by signing in again, which is why [`crate::maintain`] starts trying a week
141 /// early rather than on the last day.
142 pub fn save(&self, stored: &Stored) -> Result<(), Error> {
143 let bytes = serde_json::to_vec_pretty(stored).map_err(|e| Error::Io {
144 path: self.path.clone(),
145 source: std::io::Error::other(e),
146 })?;
147
148 // Written 0600 first and relaxed afterwards, so the file is never group- or
149 // world-readable while it is owned by the writing user's default group.
150 write_private(&self.path, &bytes)?;
151 let Some(group) = self.group.as_deref() else {
152 return set_mode(&self.path, self.mode);
153 };
154 // **Neither of the two ways this can fail may fail the save.** By the time a token is
155 // being written somebody has approved a code on their phone, and losing the credential
156 // over a group would make them do the whole flow again. A half-provisioned board has no
157 // such group; an unprivileged writer cannot give a file to a group it is not in. Both
158 // leave the token private to its owner and say so once, which is a robot whose other
159 // daemon cannot read the token yet rather than a robot that is not signed in.
160 //
161 // The mode is only relaxed **after** the group actually changed. Relaxing it first — or
162 // anyway — would hand group-read to the writer's own default group, which is wider than
163 // what was asked for and is the mistake this ordering exists to prevent.
164 let complaint = match ownership::group_id(group) {
165 None => "no such group on this system",
166 Some(gid) => match ownership::set_group(&self.path, gid) {
167 Ok(()) => return set_mode(&self.path, self.mode),
168 Err(_) => "this process may not give a file to that group",
169 },
170 };
171 tracing::warn!(
172 group,
173 path = %self.path.display(),
174 why = complaint,
175 "the token stays private to its owner — a process that reads it through that group \
176 will not be able to"
177 );
178 Ok(())
179 }
180
181 /// Forget the credential. Returns who it belonged to, if anyone.
182 ///
183 /// Clearing nothing is not an error: signing out twice is not a failure.
184 pub fn clear(&self) -> Result<Option<String>, Error> {
185 let was = self.load().and_then(|s| s.username);
186 match std::fs::remove_file(&self.path) {
187 Ok(()) => Ok(was),
188 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
189 Err(e) => Err(Error::Io {
190 path: self.path.clone(),
191 source: e,
192 }),
193 }
194 }
195}
196
197/// The access token out of a credential file, or `None` when the robot belongs to nobody.
198///
199/// **The reading half, for a process that is not the one that writes.** Deliberately the smallest
200/// possible reader: one field, so a record that grows another does not break the parse, and no
201/// dependency on anything else in this crate's behaviour.
202///
203/// Read on every use rather than cached. A login that happens while the reader is running has to
204/// take effect without a restart — it may arrive over Bluetooth, minutes or months after the
205/// process started — and re-reading a small file costs nothing on any path that would care.
206pub fn read_access_token(path: &Path) -> Option<String> {
207 #[derive(Deserialize)]
208 struct Credential {
209 access_token: String,
210 }
211
212 let bytes = std::fs::read(path).ok()?;
213 match serde_json::from_slice::<Credential>(&bytes) {
214 Ok(credential) if !credential.access_token.is_empty() => Some(credential.access_token),
215 Ok(_) => None,
216 Err(e) => {
217 tracing::warn!(
218 path = %path.display(),
219 error = %e,
220 "the account credential does not parse; treating this robot as signed out"
221 );
222 None
223 }
224 }
225}
226
227// ── writing a file that is never briefly readable ────────────────────────────
228
229/// Write via a temp file and rename, with the temp file created `0600` from the start.
230///
231/// The usual write-then-chmod is what this exists to avoid: a token written `0644` and chmodded
232/// afterwards is world-readable for the moment in between, which is exactly the kind of window
233/// that is invisible in testing and permanent in a log.
234fn write_private(path: &Path, bytes: &[u8]) -> Result<(), Error> {
235 use std::io::Write;
236
237 let tmp = path.with_extension("tmp");
238 let io = |source: std::io::Error, path: &Path| Error::Io {
239 path: path.to_path_buf(),
240 source,
241 };
242 {
243 use std::os::unix::fs::OpenOptionsExt as _;
244
245 let mut file = std::fs::OpenOptions::new()
246 .write(true)
247 .create(true)
248 .truncate(true)
249 .mode(0o600)
250 .open(&tmp)
251 .map_err(|e| io(e, &tmp))?;
252 file.write_all(bytes).map_err(|e| io(e, &tmp))?;
253 file.sync_all().map_err(|e| io(e, &tmp))?;
254 }
255 std::fs::rename(&tmp, path).map_err(|e| io(e, path))?;
256 fsync_parent(path)
257}
258
259/// Flush the directory entry, so the rename survives a power cut and not only a crash.
260fn fsync_parent(path: &Path) -> Result<(), Error> {
261 // `parent()` yields `Some("")` for a bare filename, which cannot be opened; the containing
262 // directory in that case is the working directory.
263 let dir = match path.parent() {
264 None => return Ok(()),
265 Some(p) if p.as_os_str().is_empty() => Path::new("."),
266 Some(p) => p,
267 };
268 // Opening a directory read-only and fsyncing it is the portable way to flush its entries on
269 // Linux and macOS.
270 let handle = std::fs::File::open(dir).map_err(|e| Error::Io {
271 path: dir.to_path_buf(),
272 source: e,
273 })?;
274 handle.sync_all().map_err(|e| Error::Io {
275 path: dir.to_path_buf(),
276 source: e,
277 })
278}
279
280fn set_mode(path: &Path, mode: u32) -> Result<(), Error> {
281 use std::os::unix::fs::PermissionsExt as _;
282
283 std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).map_err(|e| Error::Io {
284 path: path.to_path_buf(),
285 source: e,
286 })
287}
288
289/// Group ownership, which is the only part of this crate that needs libc.
290///
291/// Split out so there is one SAFETY argument rather than one per caller. Names rather than
292/// numbers throughout, because `systemd-sysusers` and its equivalents allocate dynamically: a gid
293/// written down is right on one board and wrong on the next.
294mod ownership {
295 use std::path::Path;
296
297 use crate::Error;
298
299 /// The gid of a group by name, or `None` if there is no such group.
300 pub fn group_id(name: &str) -> Option<u32> {
301 let cname = std::ffi::CString::new(name).ok()?;
302 // SAFETY: `getgrnam` takes a NUL-terminated string and returns a pointer into a static
303 // buffer, or null. The one field we need is read immediately and nothing is retained, so
304 // the next caller overwriting that buffer cannot be observed here.
305 let entry = unsafe { libc::getgrnam(cname.as_ptr()) };
306 if entry.is_null() {
307 return None;
308 }
309 // SAFETY: non-null, and `getgrnam` guarantees a fully initialised `group` behind it.
310 // The gid is copied out before anything else can call into the group database.
311 Some(unsafe { (*entry).gr_gid })
312 }
313
314 /// Give the file to a group, leaving its owner alone.
315 pub fn set_group(path: &Path, gid: u32) -> Result<(), Error> {
316 use std::os::unix::ffi::OsStrExt as _;
317
318 let cpath = std::ffi::CString::new(path.as_os_str().as_bytes()).map_err(|_| Error::Io {
319 path: path.to_path_buf(),
320 source: std::io::Error::other("path contains a NUL"),
321 })?;
322 // SAFETY: the pointer is valid for the call; `u32::MAX` is `(uid_t)-1`, which is how
323 // `chown(2)` is told to leave the owner unchanged.
324 let rc = unsafe { libc::chown(cpath.as_ptr(), u32::MAX, gid) };
325 if rc != 0 {
326 return Err(Error::Io {
327 path: path.to_path_buf(),
328 source: std::io::Error::last_os_error(),
329 });
330 }
331 Ok(())
332 }
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338
339 fn store_in(dir: &tempfile::TempDir) -> FileStore {
340 FileStore::at(dir.path().join("hf-token"))
341 }
342
343 fn token(access: &str) -> Stored {
344 Stored {
345 access_token: access.to_string(),
346 refresh_token: Some("refresh-1".into()),
347 expires_at: Some(now_secs() + 30 * 24 * 60 * 60),
348 username: Some("PierreRouanet".into()),
349 }
350 }
351
352 /// The store is a file, and the file survives being replaced.
353 #[test]
354 fn a_credential_round_trips() {
355 let dir = tempfile::tempdir().unwrap();
356 let store = store_in(&dir);
357
358 assert!(store.load().is_none(), "nothing stored yet");
359 store.save(&token("first")).unwrap();
360 assert_eq!(store.load().unwrap().access_token, "first");
361
362 store.save(&token("second")).unwrap();
363 assert_eq!(store.load().unwrap().access_token, "second");
364 assert_eq!(
365 store.clear().unwrap(),
366 Some("PierreRouanet".to_string()),
367 "clear reports who it forgot, so a caller can say so"
368 );
369 assert!(store.load().is_none());
370 assert_eq!(
371 store.clear().unwrap(),
372 None,
373 "clearing nothing is not an error — signing out twice is not a failure"
374 );
375 }
376
377 /// **A token must never be world-readable, at any point.**
378 ///
379 /// The mode is checked on the file that lands, and the temp file it was written through is
380 /// checked by construction: `write_private` opens it `0600` rather than chmodding afterwards,
381 /// which is the window this test cannot see and the reason the helper exists.
382 #[test]
383 fn the_token_file_is_not_world_readable() {
384 use std::os::unix::fs::PermissionsExt as _;
385
386 let dir = tempfile::tempdir().unwrap();
387 for store in [
388 store_in(&dir),
389 store_in(&dir).readable_by_group("no-such-group-exists-here"),
390 ] {
391 store.save(&token("secret")).unwrap();
392
393 let mode = std::fs::metadata(store.path())
394 .unwrap()
395 .permissions()
396 .mode()
397 & 0o777;
398 assert_eq!(
399 mode & 0o007,
400 0,
401 "the token file is readable by other users: {mode:o}"
402 );
403 assert!(
404 !dir.path().join("hf-token.tmp").exists(),
405 "the temp file must not be left behind holding a copy of the token"
406 );
407 }
408 }
409
410 /// The group is a best effort, and a best effort must never cost the token.
411 ///
412 /// Three cases, and only the first one is the happy path. A group that does not exist and a
413 /// group this process may not give a file to are both **warnings**: the credential lands,
414 /// private to its owner, because by the time this runs somebody has approved a code and
415 /// losing it over a permission bit would make them do the whole flow again.
416 #[test]
417 fn the_group_is_a_best_effort_and_never_costs_the_token() {
418 use std::os::unix::fs::PermissionsExt as _;
419
420 let dir = tempfile::tempdir().unwrap();
421 let saved = |store: &FileStore| {
422 store.save(&token("secret")).unwrap();
423 let mode = std::fs::metadata(store.path())
424 .unwrap()
425 .permissions()
426 .mode()
427 & 0o777;
428 (mode, store.load().unwrap().access_token)
429 };
430
431 assert_eq!(
432 saved(&store_in(&dir)),
433 (0o600, "secret".into()),
434 "private by default"
435 );
436
437 assert_eq!(
438 saved(&store_in(&dir).readable_by_group("no-such-group-exists-here")),
439 (0o600, "secret".to_string()),
440 "a group that does not exist leaves the file private, and the token is still stored"
441 );
442
443 // A group this process is definitely not in, unless it is running as root — in which
444 // case `chown` succeeds and the group-read bit is the right answer instead.
445 let (mode, stored) = saved(&store_in(&dir).readable_by_group(OTHER_GROUP));
446 assert_eq!(
447 stored, "secret",
448 "a refused chown must not lose the credential"
449 );
450 assert!(
451 mode == 0o600 || (mode == 0o640 && is_root()),
452 "a chown this process may not do leaves the file private: {mode:o}"
453 );
454
455 // And the group it *can* use gets the bit, which is the whole point of the option.
456 let (mode, _) = saved(&store_in(&dir).readable_by_group(own_group()));
457 assert_eq!(mode, 0o640, "the process's own group can be given read");
458 }
459
460 /// A group no ordinary user is a member of. `wheel` on macOS, `root` on Linux.
461 const OTHER_GROUP: &str = if cfg!(target_os = "macos") {
462 "wheel"
463 } else {
464 "root"
465 };
466
467 fn is_root() -> bool {
468 // SAFETY: `getuid` takes nothing, returns the calling process's real uid, and cannot fail.
469 unsafe { libc::getuid() == 0 }
470 }
471
472 /// The name of this process's own group, which `chown` will always accept.
473 fn own_group() -> String {
474 // SAFETY: `getgid` cannot fail. `getgrgid` returns a pointer into a static buffer or
475 // null; the name is copied out immediately and nothing is retained, so a later caller
476 // overwriting that buffer cannot be observed here.
477 unsafe {
478 let entry = libc::getgrgid(libc::getgid());
479 assert!(
480 !entry.is_null(),
481 "this process's own gid has no group entry"
482 );
483 std::ffi::CStr::from_ptr((*entry).gr_name)
484 .to_string_lossy()
485 .into_owned()
486 }
487 }
488
489 /// **The one key another process reads, at the level it reads it.**
490 ///
491 /// The whole cross-process contract, and this is the writer, so this is where it is pinned.
492 #[test]
493 fn the_stored_shape_is_what_a_reader_reads() {
494 let dir = tempfile::tempdir().unwrap();
495 let store = store_in(&dir);
496 store.save(&token("hf_abc")).unwrap();
497
498 let raw: serde_json::Value =
499 serde_json::from_slice(&std::fs::read(store.path()).unwrap()).unwrap();
500 assert_eq!(
501 raw["access_token"], "hf_abc",
502 "a reader reads exactly this key at exactly this level"
503 );
504 assert!(
505 raw.get("refresh_token").is_some() && raw.get("expires_at").is_some(),
506 "and the rest of the record is the writer's business: {raw}"
507 );
508 assert_eq!(
509 read_access_token(store.path()).as_deref(),
510 Some("hf_abc"),
511 "and the reader in this crate is held to the same contract"
512 );
513 }
514
515 /// The reader takes one field out of whatever the writer wrote, and survives the rest.
516 #[test]
517 fn the_reader_takes_one_field_and_tolerates_the_others() {
518 let dir = tempfile::tempdir().unwrap();
519 let path = dir.path().join("hf-token");
520
521 assert_eq!(read_access_token(&path), None, "no file is no account");
522
523 std::fs::write(
524 &path,
525 r#"{"access_token":"hf_abc","refresh_token":"r","expires_at":1,
526 "username":"x","added_later":true}"#,
527 )
528 .unwrap();
529 assert_eq!(read_access_token(&path).as_deref(), Some("hf_abc"));
530
531 std::fs::write(&path, r#"{"refresh_token":"only"}"#).unwrap();
532 assert_eq!(
533 read_access_token(&path),
534 None,
535 "a record with no token is no use"
536 );
537
538 std::fs::write(&path, "{ not json").unwrap();
539 assert_eq!(read_access_token(&path), None, "corrupt is signed out");
540 }
541
542 /// A file somebody edited by hand reads as "signed out", not as a broken daemon.
543 #[test]
544 fn a_corrupt_credential_is_signed_out_rather_than_an_error() {
545 let dir = tempfile::tempdir().unwrap();
546 let store = store_in(&dir);
547 std::fs::write(store.path(), b"{ this is not json").unwrap();
548 assert!(store.load().is_none());
549 }
550}