Skip to main content

weirdnet_model/
token.rs

1//! A Hugging Face access token, for gated and private repos.
2//!
3//! The token is read on the node that downloads, from its own environment or token file, and
4//! only goes into `Authorization` headers to the Hub. It has no serde support, so it can't end
5//! up in a message to another node, and its `Debug` output is redacted.
6
7use std::path::{Path, PathBuf};
8
9/// A Hugging Face access token. `Debug` prints `HfToken(<redacted>)`.
10#[derive(Clone, PartialEq, Eq)]
11pub struct HfToken(String);
12
13impl std::fmt::Debug for HfToken {
14    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15        f.write_str("HfToken(<redacted>)")
16    }
17}
18
19impl HfToken {
20    /// A token from its text (surrounding whitespace dropped); `None` when empty.
21    pub fn new(token: impl AsRef<str>) -> Option<Self> {
22        let t = token.as_ref().trim();
23        (!t.is_empty()).then(|| Self(t.to_string()))
24    }
25
26    /// The token in a file, such as `huggingface-cli login`'s `token` file. A missing file is
27    /// `Ok(None)`.
28    pub fn from_file(path: &Path) -> std::io::Result<Option<Self>> {
29        match std::fs::read_to_string(path) {
30            Ok(text) => Ok(Self::new(text)),
31            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
32            Err(e) => Err(e),
33        }
34    }
35
36    /// This node's token, the way the Hugging Face tools find it: `$HF_TOKEN`, then
37    /// `$HUGGING_FACE_HUB_TOKEN`, then the file at `$HF_TOKEN_PATH`, `$HF_HOME/token` or
38    /// `~/.cache/huggingface/token`. Unreadable files count as no token.
39    pub fn from_env() -> Option<Self> {
40        Self::from_sources(|k| std::env::var(k).ok(), dirs::home_dir())
41    }
42
43    pub(crate) fn from_sources(env: impl Fn(&str) -> Option<String>, home: Option<PathBuf>) -> Option<Self> {
44        if let Some(t) = ["HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"].iter().find_map(|k| env(k).and_then(Self::new)) {
45            return Some(t);
46        }
47        let set = |k: &str| env(k).filter(|v| !v.trim().is_empty()).map(PathBuf::from);
48        let file = set("HF_TOKEN_PATH")
49            .or_else(|| set("HF_HOME").map(|h| h.join("token")))
50            .or_else(|| home.map(|h| h.join(".cache").join("huggingface").join("token")))?;
51        Self::from_file(&file).ok().flatten()
52    }
53
54    /// The `Authorization` header value.
55    pub(crate) fn bearer(&self) -> String {
56        format!("Bearer {}", self.0)
57    }
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[test]
65    fn debug_is_redacted_and_empty_is_none() {
66        let t = HfToken::new(" hf_secret \n").unwrap();
67        assert_eq!(format!("{t:?}"), "HfToken(<redacted>)");
68        assert_eq!(t.bearer(), "Bearer hf_secret");
69        assert!(HfToken::new("  ").is_none());
70    }
71
72    #[test]
73    fn found_like_the_hugging_face_tools() {
74        let tmp = tempfile::tempdir().unwrap();
75        let none = |_: &str| None::<String>;
76        assert_eq!(HfToken::from_sources(none, Some(tmp.path().into())), None);
77        let cache = tmp.path().join(".cache/huggingface");
78        std::fs::create_dir_all(&cache).unwrap();
79        std::fs::write(cache.join("token"), "hf_file\n").unwrap();
80        assert_eq!(HfToken::from_sources(none, Some(tmp.path().into())), HfToken::new("hf_file"));
81        let hf_home = tmp.path().join("hfhome");
82        std::fs::create_dir_all(&hf_home).unwrap();
83        std::fs::write(hf_home.join("token"), "hf_home").unwrap();
84        let home_env = hf_home.display().to_string();
85        let env = move |k: &str| (k == "HF_HOME").then(|| home_env.clone());
86        assert_eq!(HfToken::from_sources(&env, Some(tmp.path().into())), HfToken::new("hf_home"));
87        let env = |k: &str| match k {
88            "HF_TOKEN" => Some("".to_string()),
89            "HUGGING_FACE_HUB_TOKEN" => Some("hf_env".to_string()),
90            _ => None,
91        };
92        assert_eq!(HfToken::from_sources(env, None), HfToken::new("hf_env"));
93    }
94}