1use crate::config::{InjectMode, RouteConfig};
9use crate::error::{ProxyError, Result};
10use base64::Engine;
11use std::collections::HashMap;
12use tracing::debug;
13use zeroize::Zeroizing;
14
15pub struct LoadedCredential {
17 pub inject_mode: InjectMode,
19 pub upstream: String,
21 pub raw_credential: Zeroizing<String>,
23
24 pub header_name: String,
27 pub header_value: Zeroizing<String>,
29
30 pub path_pattern: Option<String>,
33 pub path_replacement: Option<String>,
35
36 pub query_param_name: Option<String>,
39}
40
41impl 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#[derive(Debug)]
60pub struct CredentialStore {
61 credentials: HashMap<String, LoadedCredential>,
63}
64
65impl CredentialStore {
66 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 let header_value = match route.inject_mode {
85 InjectMode::Header => {
86 Zeroizing::new(route.credential_format.replace("{}", &secret))
87 }
88 InjectMode::BasicAuth => {
89 let encoded =
91 base64::engine::general_purpose::STANDARD.encode(secret.as_bytes());
92 Zeroizing::new(format!("Basic {}", encoded))
93 }
94 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 #[must_use]
119 pub fn empty() -> Self {
120 Self {
121 credentials: HashMap::new(),
122 }
123 }
124
125 #[must_use]
127 pub fn get(&self, prefix: &str) -> Option<&LoadedCredential> {
128 self.credentials.get(prefix)
129 }
130
131 #[must_use]
133 pub fn is_empty(&self) -> bool {
134 self.credentials.is_empty()
135 }
136
137 #[must_use]
139 pub fn len(&self) -> usize {
140 self.credentials.len()
141 }
142}
143
144const 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 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 assert!(
180 debug_output.contains("[REDACTED]"),
181 "Debug output should contain [REDACTED], got: {}",
182 debug_output
183 );
184 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 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}