graphrt_llm/
credentials.rs1#[cfg(feature = "http")]
26mod broker;
27mod cached;
28mod sources;
29
30#[cfg(feature = "http")]
31pub use broker::{BrokerAuth, TokenBroker, TokenBrokerConfig};
32pub use cached::{CachedCredentials, DEFAULT_REFRESH_SKEW_MS};
33pub use sources::{EnvCredentials, FnCredentials};
34
35use std::fmt;
36
37use futures::future::BoxFuture;
38
39use crate::error::LlmError;
40
41#[derive(Clone, PartialEq, Eq)]
43pub struct Credential {
44 pub secret: String,
46 pub expires_at_ms: Option<u64>,
48 pub headers: Vec<(String, String)>,
50 pub base_url: Option<String>,
53}
54
55impl Credential {
56 pub fn new(secret: impl Into<String>) -> Self {
57 Self { secret: secret.into(), expires_at_ms: None, headers: Vec::new(), base_url: None }
58 }
59
60 pub fn expires_at(mut self, unix_ms: u64) -> Self {
61 self.expires_at_ms = Some(unix_ms);
62 self
63 }
64
65 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
66 self.headers.push((name.into(), value.into()));
67 self
68 }
69
70 pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
71 self.base_url = Some(base_url.into());
72 self
73 }
74
75 pub fn is_expired_at(&self, now_ms: u64, skew_ms: u64) -> bool {
77 self.expires_at_ms.is_some_and(|exp| now_ms.saturating_add(skew_ms) >= exp)
78 }
79}
80
81pub fn unix_now_ms() -> u64 {
85 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
86 {
87 0
88 }
89 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
90 {
91 std::time::SystemTime::now()
92 .duration_since(std::time::UNIX_EPOCH)
93 .map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
94 .unwrap_or(0)
95 }
96}
97
98impl fmt::Debug for Credential {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 f.debug_struct("Credential")
101 .field("secret", &"<redacted>")
102 .field("expires_at_ms", &self.expires_at_ms)
103 .field("headers", &self.headers.iter().map(|(k, _)| k).collect::<Vec<_>>())
104 .field("base_url", &self.base_url)
105 .finish()
106 }
107}
108
109pub fn is_secure_endpoint(url: &str) -> bool {
112 if url.starts_with("https://") {
113 return true;
114 }
115 let Some(rest) = url.strip_prefix("http://") else {
116 return false;
117 };
118 let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
119 let authority = authority.rsplit_once('@').map_or(authority, |(_, host)| host);
120 let host = match authority.strip_prefix('[') {
121 Some(v6) => v6.split(']').next().unwrap_or_default(),
122 None => authority.rsplit_once(':').map_or(authority, |(h, _)| h),
123 };
124 matches!(host, "localhost" | "::1" | "10.0.2.2")
125 || host.parse::<std::net::Ipv4Addr>().is_ok_and(|ip| ip.is_loopback())
126}
127
128pub fn require_secure_endpoint(url: &str, what: &str) -> Result<(), LlmError> {
130 if is_secure_endpoint(url) {
131 Ok(())
132 } else {
133 Err(LlmError::Config(format!(
134 "{what} must use https:// (plain http is only allowed for localhost / 127.0.0.1 / 10.0.2.2)"
135 )))
136 }
137}
138
139pub trait CredentialSource: Send + Sync + fmt::Debug {
141 fn credential<'a>(&'a self, provider: &'a str) -> BoxFuture<'a, Result<Credential, LlmError>>;
143
144 fn invalidate(&self, provider: &str) {
147 let _ = provider;
148 }
149
150 fn generation(&self) -> u64 {
155 0
156 }
157}
158
159#[derive(Clone)]
161pub struct StaticCredential(Credential);
162
163impl StaticCredential {
164 pub fn new(secret: impl Into<String>) -> Self {
165 Self(Credential::new(secret))
166 }
167
168 pub fn from_credential(credential: Credential) -> Self {
170 Self(credential)
171 }
172}
173
174impl fmt::Debug for StaticCredential {
175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176 f.write_str("StaticCredential(<redacted>)")
177 }
178}
179
180impl CredentialSource for StaticCredential {
181 fn credential<'a>(&'a self, _provider: &'a str) -> BoxFuture<'a, Result<Credential, LlmError>> {
182 Box::pin(futures::future::ready(Ok(self.0.clone())))
183 }
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189
190 #[test]
191 fn debug_never_shows_secrets() {
192 let c = Credential::new("sk-secret").header("x-tenant", "t-secret");
193 let text = format!("{c:?} {:?}", StaticCredential::new("sk-secret"));
194 assert!(!text.contains("sk-secret"));
195 assert!(!text.contains("t-secret"));
196 }
197}