graphrt_ffi/
credentials.rs1use std::panic::{AssertUnwindSafe, catch_unwind};
9use std::sync::Arc;
10
11use futures::future::BoxFuture;
12use graphrt_llm::LlmError;
13use graphrt_llm::credentials::{Credential, CredentialSource};
14
15use crate::GraphrtError;
16
17#[derive(Clone, uniffi::Record)]
19pub struct CredentialRecord {
20 pub secret: String,
22 pub expires_at_ms: Option<u64>,
24 pub headers_json: Option<String>,
26 pub base_url: Option<String>,
28}
29
30impl std::fmt::Debug for CredentialRecord {
31 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32 f.debug_struct("CredentialRecord")
33 .field("secret", &"<redacted>")
34 .field("expires_at_ms", &self.expires_at_ms)
35 .field("base_url", &self.base_url)
36 .finish_non_exhaustive()
37 }
38}
39
40#[uniffi::export(with_foreign)]
49pub trait CredentialProvider: Send + Sync {
50 fn get_credential(&self, provider: String) -> Result<CredentialRecord, GraphrtError>;
52 fn invalidate(&self, provider: String);
54}
55
56pub(crate) struct ForeignCredentials {
58 callback: Arc<dyn CredentialProvider>,
59}
60
61impl ForeignCredentials {
62 pub(crate) fn new(callback: Arc<dyn CredentialProvider>) -> Self {
63 Self { callback }
64 }
65}
66
67impl std::fmt::Debug for ForeignCredentials {
68 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69 f.write_str("ForeignCredentials")
70 }
71}
72
73fn call(callback: &Arc<dyn CredentialProvider>, provider: &str) -> Result<Credential, LlmError> {
74 let outcome = catch_unwind(AssertUnwindSafe(|| callback.get_credential(provider.to_owned())));
75 let record = match outcome {
76 Ok(Ok(record)) => record,
77 Ok(Err(e)) => return Err(LlmError::Auth(format!("credential provider failed for `{provider}`: {e}"))),
78 Err(_) => return Err(LlmError::Auth(format!("credential provider panicked for `{provider}`"))),
79 };
80 to_credential(provider, record)
81}
82
83fn to_credential(provider: &str, record: CredentialRecord) -> Result<Credential, LlmError> {
84 if record.secret.is_empty() {
85 return Err(LlmError::Auth(format!("credential provider returned an empty secret for `{provider}`")));
86 }
87 let mut credential = Credential::new(record.secret);
88 if let Some(exp) = record.expires_at_ms {
89 credential = credential.expires_at(exp);
90 }
91 if let Some(raw) = record.headers_json.as_deref().filter(|s| !s.trim().is_empty()) {
92 let headers: indexmap::IndexMap<String, String> = serde_json::from_str(raw).map_err(|e| {
93 LlmError::Config(format!("credential headers for `{provider}` must be a JSON object of strings: {e}"))
94 })?;
95 for (k, v) in headers {
96 credential = credential.header(k, v);
97 }
98 }
99 if let Some(url) = record.base_url.filter(|u| !u.is_empty()) {
100 if !graphrt_llm::credentials::is_secure_endpoint(&url) {
101 return Err(LlmError::Config(format!(
102 "credential base_url for `{provider}` must be https:// (http only for localhost / 10.0.2.2)"
103 )));
104 }
105 credential = credential.base_url(url);
106 }
107 Ok(credential)
108}
109
110impl CredentialSource for ForeignCredentials {
111 fn credential<'a>(&'a self, provider: &'a str) -> BoxFuture<'a, Result<Credential, LlmError>> {
112 let callback = self.callback.clone();
113 let provider = provider.to_owned();
114 Box::pin(async move {
115 match tokio::runtime::Handle::try_current() {
117 Ok(handle) => handle
118 .spawn_blocking(move || call(&callback, &provider))
119 .await
120 .unwrap_or_else(|_| Err(LlmError::Auth("credential provider task failed".into()))),
121 Err(_) => call(&callback, &provider),
122 }
123 })
124 }
125
126 fn invalidate(&self, provider: &str) {
127 let callback = self.callback.clone();
128 let provider = provider.to_owned();
129 let run = move || {
130 let _ = catch_unwind(AssertUnwindSafe(move || callback.invalidate(provider)));
131 };
132 match tokio::runtime::Handle::try_current() {
134 Ok(handle) => drop(handle.spawn_blocking(run)),
135 Err(_) => run(),
136 }
137 }
138}
139
140#[cfg(test)]
141mod tests {
142 use super::*;
143
144 #[test]
145 fn records_are_validated() {
146 let ok = CredentialRecord {
147 secret: "sk-very-secret".into(),
148 expires_at_ms: Some(5),
149 headers_json: Some(r#"{"x-a":"1"}"#.into()),
150 base_url: Some("https://p.example.com/v1".into()),
151 };
152 let c = to_credential("p", ok.clone()).unwrap();
153 assert_eq!(c.headers, vec![("x-a".to_owned(), "1".to_owned())]);
154 assert!(to_credential("p", CredentialRecord { secret: String::new(), ..ok.clone() }).is_err());
155 assert!(to_credential("p", CredentialRecord { headers_json: Some("[1]".into()), ..ok.clone() }).is_err());
156 assert!(to_credential("p", CredentialRecord { base_url: Some("file:///x".into()), ..ok.clone() }).is_err());
157 let plain_http = CredentialRecord { base_url: Some("http://proxy.example.com/v1".into()), ..ok.clone() };
158 assert!(to_credential("p", plain_http).is_err());
159 assert!(!format!("{ok:?}").contains("sk-very-secret"));
160 }
161}