Skip to main content

nono_proxy/
credential.rs

1//! Credential loading and management for reverse proxy mode.
2//!
3//! Loads API credentials from the system keystore or 1Password at proxy startup.
4//! Credentials are stored in `Zeroizing<String>` and injected into
5//! requests via headers, URL paths, query parameters, or Basic Auth.
6//! The sandboxed agent never sees the real credentials.
7
8use crate::config::{InjectMode, RouteConfig};
9use crate::error::{ProxyError, Result};
10use base64::Engine;
11use std::collections::HashMap;
12use tracing::debug;
13use zeroize::Zeroizing;
14
15/// A loaded credential ready for injection.
16pub struct LoadedCredential {
17    /// Injection mode
18    pub inject_mode: InjectMode,
19    /// Upstream URL (e.g., "https://api.openai.com")
20    pub upstream: String,
21    /// Raw credential value from keystore (for modes that need it directly)
22    pub raw_credential: Zeroizing<String>,
23
24    // --- Header mode ---
25    /// Header name to inject (e.g., "Authorization")
26    pub header_name: String,
27    /// Formatted header value (e.g., "Bearer sk-...")
28    pub header_value: Zeroizing<String>,
29
30    // --- URL path mode ---
31    /// Pattern to match in incoming path (with {} placeholder)
32    pub path_pattern: Option<String>,
33    /// Pattern for outgoing path (with {} placeholder)
34    pub path_replacement: Option<String>,
35
36    // --- Query param mode ---
37    /// Query parameter name
38    pub query_param_name: Option<String>,
39}
40
41/// Custom Debug impl that redacts secret values to prevent accidental leakage
42/// in logs, panic messages, or debug output.
43impl std::fmt::Debug for LoadedCredential {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        f.debug_struct("LoadedCredential")
46            .field("inject_mode", &self.inject_mode)
47            .field("upstream", &self.upstream)
48            .field("raw_credential", &"[REDACTED]")
49            .field("header_name", &self.header_name)
50            .field("header_value", &"[REDACTED]")
51            .field("path_pattern", &self.path_pattern)
52            .field("path_replacement", &self.path_replacement)
53            .field("query_param_name", &self.query_param_name)
54            .finish()
55    }
56}
57
58/// Credential store for all configured routes.
59#[derive(Debug)]
60pub struct CredentialStore {
61    /// Map from route prefix to loaded credential
62    credentials: HashMap<String, LoadedCredential>,
63}
64
65impl CredentialStore {
66    /// Load credentials for all configured routes from the system keystore.
67    ///
68    /// Routes without a `credential_key` are skipped (no credential injection).
69    /// Returns an error if any configured credential fails to load.
70    pub fn load(routes: &[RouteConfig]) -> Result<Self> {
71        let mut credentials = HashMap::new();
72
73        for route in routes {
74            if let Some(ref key) = route.credential_key {
75                debug!(
76                    "Loading credential for route prefix: {} (mode: {:?})",
77                    route.prefix, route.inject_mode
78                );
79
80                let secret = nono::keystore::load_secret_by_ref(KEYRING_SERVICE, key)
81                    .map_err(|e| ProxyError::Credential(e.to_string()))?;
82
83                // Format header value based on mode
84                let header_value = match route.inject_mode {
85                    InjectMode::Header => {
86                        Zeroizing::new(route.credential_format.replace("{}", &secret))
87                    }
88                    InjectMode::BasicAuth => {
89                        // Base64 encode the credential for Basic auth
90                        let encoded =
91                            base64::engine::general_purpose::STANDARD.encode(secret.as_bytes());
92                        Zeroizing::new(format!("Basic {}", encoded))
93                    }
94                    // For url_path and query_param, header_value is not used
95                    InjectMode::UrlPath | InjectMode::QueryParam => Zeroizing::new(String::new()),
96                };
97
98                credentials.insert(
99                    route.prefix.clone(),
100                    LoadedCredential {
101                        inject_mode: route.inject_mode.clone(),
102                        upstream: route.upstream.clone(),
103                        raw_credential: secret,
104                        header_name: route.inject_header.clone(),
105                        header_value,
106                        path_pattern: route.path_pattern.clone(),
107                        path_replacement: route.path_replacement.clone(),
108                        query_param_name: route.query_param_name.clone(),
109                    },
110                );
111            }
112        }
113
114        Ok(Self { credentials })
115    }
116
117    /// Create an empty credential store (no credential injection).
118    #[must_use]
119    pub fn empty() -> Self {
120        Self {
121            credentials: HashMap::new(),
122        }
123    }
124
125    /// Get a credential for a route prefix, if configured.
126    #[must_use]
127    pub fn get(&self, prefix: &str) -> Option<&LoadedCredential> {
128        self.credentials.get(prefix)
129    }
130
131    /// Check if any credentials are loaded.
132    #[must_use]
133    pub fn is_empty(&self) -> bool {
134        self.credentials.is_empty()
135    }
136
137    /// Number of loaded credentials.
138    #[must_use]
139    pub fn len(&self) -> usize {
140        self.credentials.len()
141    }
142}
143
144/// The keyring service name used by nono for all credentials.
145/// Uses the same constant as `nono::keystore::DEFAULT_SERVICE` to ensure consistency.
146const KEYRING_SERVICE: &str = nono::keystore::DEFAULT_SERVICE;
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    #[test]
153    fn test_empty_credential_store() {
154        let store = CredentialStore::empty();
155        assert!(store.is_empty());
156        assert_eq!(store.len(), 0);
157        assert!(store.get("/openai").is_none());
158    }
159
160    #[test]
161    fn test_loaded_credential_debug_redacts_secrets() {
162        // Security: Debug output must NEVER contain real secret values.
163        // This prevents accidental leakage in logs, panic messages, or
164        // tracing output at debug level.
165        let cred = LoadedCredential {
166            inject_mode: InjectMode::Header,
167            upstream: "https://api.openai.com".to_string(),
168            raw_credential: Zeroizing::new("sk-secret-12345".to_string()),
169            header_name: "Authorization".to_string(),
170            header_value: Zeroizing::new("Bearer sk-secret-12345".to_string()),
171            path_pattern: None,
172            path_replacement: None,
173            query_param_name: None,
174        };
175
176        let debug_output = format!("{:?}", cred);
177
178        // Must contain REDACTED markers
179        assert!(
180            debug_output.contains("[REDACTED]"),
181            "Debug output should contain [REDACTED], got: {}",
182            debug_output
183        );
184        // Must NOT contain the actual secret
185        assert!(
186            !debug_output.contains("sk-secret-12345"),
187            "Debug output must not contain the real secret"
188        );
189        assert!(
190            !debug_output.contains("Bearer sk-secret"),
191            "Debug output must not contain the formatted secret"
192        );
193        // Non-secret fields should still be visible
194        assert!(debug_output.contains("api.openai.com"));
195        assert!(debug_output.contains("Authorization"));
196    }
197
198    #[test]
199    fn test_load_no_credential_routes() {
200        let routes = vec![RouteConfig {
201            prefix: "/test".to_string(),
202            upstream: "https://example.com".to_string(),
203            credential_key: None,
204            inject_mode: InjectMode::Header,
205            inject_header: "Authorization".to_string(),
206            credential_format: "Bearer {}".to_string(),
207            path_pattern: None,
208            path_replacement: None,
209            query_param_name: None,
210            env_var: None,
211        }];
212        let store = CredentialStore::load(&routes);
213        assert!(store.is_ok());
214        let store = store.unwrap_or_else(|_| CredentialStore::empty());
215        assert!(store.is_empty());
216    }
217}