Skip to main content

graphrt_ffi/
credentials.rs

1//! Host-supplied model credentials (Keychain / Keystore, token brokers).
2//!
3//! Apps must not ship provider API keys. Instead a provider is declared in the
4//! runtime config with `"source": "external"` and the app registers a
5//! [`CredentialProvider`] callback that returns the key (bring-your-own-key
6//! from secure storage) or a short-lived token for a proxy.
7
8use 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/// A credential returned by the host.
18#[derive(Clone, uniffi::Record)]
19pub struct CredentialRecord {
20    /// API key or bearer token for the provider (or the app's token for a proxy).
21    pub secret: String,
22    /// Absolute expiry in Unix milliseconds; `None` caches until a 401/403.
23    pub expires_at_ms: Option<u64>,
24    /// Extra request headers as a JSON object (`{"x-tenant": "acme"}`), or `None`.
25    pub headers_json: Option<String>,
26    /// Endpoint override for this credential (e.g. a regional proxy), or `None`.
27    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/// Supplies model credentials. Implemented in the host language.
41///
42/// `get_credential` may block (Keychain, IPC, a network call to your backend);
43/// it is invoked on a background thread. Results are cached until
44/// `expires_at_ms` (minus a refresh margin) or until the provider rejects the
45/// credential, in which case `invalidate` is called and `get_credential` is
46/// asked once more. The provider name `token_broker` is used for the app's own
47/// session token when a token broker entry sets `"app_auth": "external"`.
48#[uniffi::export(with_foreign)]
49pub trait CredentialProvider: Send + Sync {
50    /// Credential for `provider` (the provider name from the runtime config).
51    fn get_credential(&self, provider: String) -> Result<CredentialRecord, GraphrtError>;
52    /// The last credential for `provider` was rejected; drop any cached copy.
53    fn invalidate(&self, provider: String);
54}
55
56/// Adapts a foreign [`CredentialProvider`] to [`CredentialSource`].
57pub(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            // Foreign code may block (Keychain, IPC); keep it off the async workers.
116            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        // A Keychain delete may block: never on an async worker thread.
133        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}