1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! Credential loading and management for reverse proxy mode.
//!
//! Loads API credentials from the system keystore or 1Password at proxy startup.
//! Credentials are stored in `Zeroizing<String>` and injected into
//! requests via headers, URL paths, query parameters, or Basic Auth.
//! The sandboxed agent never sees the real credentials.
//!
//! Route-level configuration (upstream URL, L7 endpoint rules, custom TLS CA)
//! is handled by [`crate::route::RouteStore`], which loads independently of
//! credentials. This module handles only credential-specific concerns.
use crate::config::{InjectMode, RouteConfig};
use crate::error::{ProxyError, Result};
use crate::oauth2::{OAuth2ExchangeConfig, TokenCache};
use base64::Engine;
use std::collections::HashMap;
use tokio_rustls::TlsConnector;
use tracing::{debug, warn};
use zeroize::Zeroizing;
/// A loaded credential ready for injection.
///
/// Contains only credential-specific fields (injection mode, header name/value,
/// raw secret). Route-level configuration (upstream URL, L7 endpoint rules,
/// custom TLS CA) is stored in [`crate::route::LoadedRoute`].
pub struct LoadedCredential {
/// Upstream injection mode
pub inject_mode: InjectMode,
/// Proxy-side injection mode used for phantom token parsing.
pub proxy_inject_mode: InjectMode,
/// Raw credential value from keystore (for modes that need it directly)
pub raw_credential: Zeroizing<String>,
// --- Header mode ---
/// Header name to inject (e.g., "Authorization")
pub header_name: String,
/// Header name used for proxy-side phantom token validation.
pub proxy_header_name: String,
/// Formatted header value (e.g., "Bearer sk-...")
pub header_value: Zeroizing<String>,
// --- URL path mode ---
/// Pattern to match in incoming path (with {} placeholder)
pub path_pattern: Option<String>,
/// Pattern to match in incoming proxy path (with {} placeholder)
pub proxy_path_pattern: Option<String>,
/// Pattern for outgoing path (with {} placeholder)
pub path_replacement: Option<String>,
// --- Query param mode ---
/// Query parameter name
pub query_param_name: Option<String>,
/// Proxy-side query parameter name for phantom token validation.
pub proxy_query_param_name: Option<String>,
}
/// Custom Debug impl that redacts secret values to prevent accidental leakage
/// in logs, panic messages, or debug output.
impl std::fmt::Debug for LoadedCredential {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LoadedCredential")
.field("inject_mode", &self.inject_mode)
.field("proxy_inject_mode", &self.proxy_inject_mode)
.field("raw_credential", &"[REDACTED]")
.field("header_name", &self.header_name)
.field("proxy_header_name", &self.proxy_header_name)
.field("header_value", &"[REDACTED]")
.field("path_pattern", &self.path_pattern)
.field("proxy_path_pattern", &self.proxy_path_pattern)
.field("path_replacement", &self.path_replacement)
.field("query_param_name", &self.query_param_name)
.field("proxy_query_param_name", &self.proxy_query_param_name)
.finish()
}
}
/// An OAuth2 route entry: token cache + upstream URL.
#[derive(Debug)]
pub struct OAuth2Route {
/// Token cache for automatic refresh
pub cache: TokenCache,
/// Upstream URL (e.g., "https://api.example.com")
pub upstream: String,
}
/// Credential store for all configured routes.
#[derive(Debug)]
pub struct CredentialStore {
/// Map from route prefix to loaded credential
credentials: HashMap<String, LoadedCredential>,
/// Map from route prefix to OAuth2 route (token cache + upstream)
oauth2_routes: HashMap<String, OAuth2Route>,
}
impl CredentialStore {
/// Load credentials for all configured routes from the system keystore.
///
/// Routes without a `credential_key` or `oauth2` block are skipped (no
/// credential injection). Routes whose credential is not found (e.g.
/// unset env var) are skipped with a warning — this allows profiles to
/// declare optional credentials without failing when they are unavailable.
///
/// OAuth2 routes perform an initial token exchange at startup. If the
/// exchange fails, the route is skipped (graceful degradation).
///
/// The `tls_connector` is required for OAuth2 token exchange HTTPS calls.
///
/// Returns an error only for hard failures (keystore access errors,
/// config parse errors, non-UTF-8 values).
pub fn load(routes: &[RouteConfig], tls_connector: &TlsConnector) -> Result<Self> {
let mut credentials = HashMap::new();
let mut oauth2_routes = HashMap::new();
for route in routes {
// Normalize prefix: strip leading/trailing slashes so it matches
// the bare service name returned by parse_service_prefix() in
// the reverse proxy path (e.g., "/anthropic" -> "anthropic").
let normalized_prefix = route.prefix.trim_matches('/').to_string();
if let Some(ref key) = route.credential_key {
debug!(
"Loading credential for route prefix: {} (mode: {:?})",
normalized_prefix, route.inject_mode
);
let secret = match nono::keystore::load_secret_by_ref(KEYRING_SERVICE, key) {
Ok(s) => s,
Err(nono::NonoError::SecretNotFound(_)) => {
let hint = if !key.contains("://") && cfg!(target_os = "macos") {
format!(
" To add it to the macOS keychain: security add-generic-password -s \"nono\" -a \"{}\" -w",
key
)
} else {
String::new()
};
warn!(
"Credential '{}' not found for route '{}' — requests will proceed without credential injection.{}",
key, normalized_prefix, hint
);
continue;
}
Err(e) => return Err(ProxyError::Credential(e.to_string())),
};
// Format header value based on mode.
// When inject_header is not "Authorization" (e.g., "PRIVATE-TOKEN",
// "X-API-Key"), the credential is injected as-is unless the user
// explicitly set a custom format. The default "Bearer {}" only
// makes sense for the Authorization header.
let effective_format = if route.inject_header != "Authorization"
&& route.credential_format == "Bearer {}"
{
"{}".to_string()
} else {
route.credential_format.clone()
};
let header_value = match route.inject_mode {
InjectMode::Header => Zeroizing::new(effective_format.replace("{}", &secret)),
InjectMode::BasicAuth => {
// Base64 encode the credential for Basic auth
let encoded =
base64::engine::general_purpose::STANDARD.encode(secret.as_bytes());
Zeroizing::new(format!("Basic {}", encoded))
}
// For url_path and query_param, header_value is not used
InjectMode::UrlPath | InjectMode::QueryParam => Zeroizing::new(String::new()),
};
credentials.insert(
normalized_prefix.clone(),
LoadedCredential {
inject_mode: route.inject_mode.clone(),
proxy_inject_mode: route
.proxy
.as_ref()
.and_then(|p| p.inject_mode.clone())
.unwrap_or_else(|| route.inject_mode.clone()),
raw_credential: secret,
header_name: route.inject_header.clone(),
proxy_header_name: route
.proxy
.as_ref()
.and_then(|p| p.inject_header.clone())
.unwrap_or_else(|| route.inject_header.clone()),
header_value,
path_pattern: route.path_pattern.clone(),
proxy_path_pattern: route
.proxy
.as_ref()
.and_then(|p| p.path_pattern.clone())
.or_else(|| route.path_pattern.clone()),
path_replacement: route.path_replacement.clone(),
query_param_name: route.query_param_name.clone(),
proxy_query_param_name: route
.proxy
.as_ref()
.and_then(|p| p.query_param_name.clone())
.or_else(|| route.query_param_name.clone()),
},
);
continue;
}
// OAuth2 client_credentials path
if let Some(ref oauth2) = route.oauth2 {
debug!(
"Loading OAuth2 credential for route prefix: {}",
route.prefix
);
let client_id =
match nono::keystore::load_secret_by_ref(KEYRING_SERVICE, &oauth2.client_id) {
Ok(s) => s,
Err(nono::NonoError::SecretNotFound(msg)) => {
debug!(
"OAuth2 client_id not available for route '{}': {}",
route.prefix, msg
);
continue;
}
Err(e) => return Err(ProxyError::Credential(e.to_string())),
};
let client_secret = match nono::keystore::load_secret_by_ref(
KEYRING_SERVICE,
&oauth2.client_secret,
) {
Ok(s) => s,
Err(nono::NonoError::SecretNotFound(msg)) => {
debug!(
"OAuth2 client_secret not available for route '{}': {}",
route.prefix, msg
);
continue;
}
Err(e) => return Err(ProxyError::Credential(e.to_string())),
};
let config = OAuth2ExchangeConfig {
token_url: oauth2.token_url.clone(),
client_id,
client_secret,
scope: oauth2.scope.clone(),
};
match TokenCache::new(config, tls_connector.clone()) {
Ok(cache) => {
oauth2_routes.insert(
route.prefix.clone(),
OAuth2Route {
cache,
upstream: route.upstream.clone(),
},
);
}
Err(e) => {
debug!(
"OAuth2 token exchange failed for route '{}': {}, skipping",
route.prefix, e
);
continue;
}
}
}
}
Ok(Self {
credentials,
oauth2_routes,
})
}
/// Create an empty credential store (no credential injection).
#[must_use]
pub fn empty() -> Self {
Self {
credentials: HashMap::new(),
oauth2_routes: HashMap::new(),
}
}
/// Get a static credential for a route prefix, if configured.
#[must_use]
pub fn get(&self, prefix: &str) -> Option<&LoadedCredential> {
self.credentials.get(prefix)
}
/// Get an OAuth2 route (token cache + upstream) for a route prefix, if configured.
#[must_use]
pub fn get_oauth2(&self, prefix: &str) -> Option<&OAuth2Route> {
self.oauth2_routes.get(prefix)
}
/// Check if any credentials (static or OAuth2) are loaded.
#[must_use]
pub fn is_empty(&self) -> bool {
self.credentials.is_empty() && self.oauth2_routes.is_empty()
}
/// Number of loaded credentials (static + OAuth2).
#[must_use]
pub fn len(&self) -> usize {
self.credentials.len() + self.oauth2_routes.len()
}
/// Returns the set of route prefixes that have loaded credentials
/// (both static keystore and OAuth2 routes).
#[must_use]
pub fn loaded_prefixes(&self) -> std::collections::HashSet<String> {
self.credentials
.keys()
.chain(self.oauth2_routes.keys())
.cloned()
.collect()
}
}
/// The keyring service name used by nono for all credentials.
/// Uses the same constant as `nono::keystore::DEFAULT_SERVICE` to ensure consistency.
const KEYRING_SERVICE: &str = nono::keystore::DEFAULT_SERVICE;
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
static ENV_LOCK: Mutex<()> = Mutex::new(());
struct EnvVarGuard {
original: Vec<(&'static str, Option<String>)>,
}
#[allow(clippy::disallowed_methods)]
impl EnvVarGuard {
fn set_all(vars: &[(&'static str, &str)]) -> Self {
let original = vars
.iter()
.map(|(key, _)| (*key, std::env::var(key).ok()))
.collect::<Vec<_>>();
for (key, value) in vars {
std::env::set_var(key, value);
}
Self { original }
}
}
#[allow(clippy::disallowed_methods)]
impl Drop for EnvVarGuard {
fn drop(&mut self) {
for (key, value) in self.original.iter().rev() {
match value {
Some(value) => std::env::set_var(key, value),
None => std::env::remove_var(key),
}
}
}
}
/// Build a TLS connector for tests (never used for real connections).
fn test_tls_connector() -> TlsConnector {
let mut root_store = rustls::RootCertStore::empty();
root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
let tls_config = rustls::ClientConfig::builder_with_provider(Arc::new(
rustls::crypto::ring::default_provider(),
))
.with_safe_default_protocol_versions()
.unwrap()
.with_root_certificates(root_store)
.with_no_client_auth();
TlsConnector::from(Arc::new(tls_config))
}
#[test]
fn test_empty_credential_store() {
let store = CredentialStore::empty();
assert!(store.is_empty());
assert_eq!(store.len(), 0);
assert!(store.get("openai").is_none());
assert!(store.get("/openai").is_none());
assert!(store.get_oauth2("/openai").is_none());
}
#[test]
fn test_loaded_credential_debug_redacts_secrets() {
// Security: Debug output must NEVER contain real secret values.
// This prevents accidental leakage in logs, panic messages, or
// tracing output at debug level.
let cred = LoadedCredential {
inject_mode: InjectMode::Header,
proxy_inject_mode: InjectMode::Header,
raw_credential: Zeroizing::new("sk-secret-12345".to_string()),
header_name: "Authorization".to_string(),
proxy_header_name: "Authorization".to_string(),
header_value: Zeroizing::new("Bearer sk-secret-12345".to_string()),
path_pattern: None,
proxy_path_pattern: None,
path_replacement: None,
query_param_name: None,
proxy_query_param_name: None,
};
let debug_output = format!("{:?}", cred);
// Must contain REDACTED markers
assert!(
debug_output.contains("[REDACTED]"),
"Debug output should contain [REDACTED], got: {}",
debug_output
);
// Must NOT contain the actual secret
assert!(
!debug_output.contains("sk-secret-12345"),
"Debug output must not contain the real secret"
);
assert!(
!debug_output.contains("Bearer sk-secret"),
"Debug output must not contain the formatted secret"
);
// Non-secret fields should still be visible
assert!(debug_output.contains("Authorization"));
}
#[test]
fn test_load_no_credential_routes() {
let tls = test_tls_connector();
let routes = vec![RouteConfig {
prefix: "/test".to_string(),
upstream: "https://example.com".to_string(),
credential_key: None,
inject_mode: InjectMode::Header,
inject_header: "Authorization".to_string(),
credential_format: "Bearer {}".to_string(),
path_pattern: None,
path_replacement: None,
query_param_name: None,
proxy: None,
env_var: None,
endpoint_rules: vec![],
tls_ca: None,
tls_client_cert: None,
tls_client_key: None,
oauth2: None,
}];
let store = CredentialStore::load(&routes, &tls);
assert!(store.is_ok());
let store = store.unwrap_or_else(|_| CredentialStore::empty());
assert!(store.is_empty());
}
#[test]
fn test_get_oauth2_returns_none_for_non_oauth2_routes() {
let store = CredentialStore::empty();
assert!(store.get_oauth2("openai").is_none());
assert!(store.get_oauth2("my-api").is_none());
}
#[test]
fn test_is_empty_false_with_only_oauth2_routes() {
// Simulate a store with only OAuth2 routes by constructing directly.
// We can't call load() with a real OAuth2 config (no token server),
// so we build the struct manually to test the is_empty/len logic.
use std::time::Duration;
let cache = make_test_token_cache("test-token", Duration::from_secs(3600));
let mut oauth2_routes = HashMap::new();
oauth2_routes.insert(
"my-api".to_string(),
OAuth2Route {
cache,
upstream: "https://api.example.com".to_string(),
},
);
let store = CredentialStore {
credentials: HashMap::new(),
oauth2_routes,
};
assert!(
!store.is_empty(),
"store with OAuth2 routes should not be empty"
);
assert_eq!(store.len(), 1);
assert!(store.get_oauth2("my-api").is_some());
assert!(store.get("my-api").is_none());
}
#[test]
fn test_loaded_prefixes_includes_oauth2() {
use std::time::Duration;
let cache = make_test_token_cache("test-token", Duration::from_secs(3600));
let mut oauth2_routes = HashMap::new();
oauth2_routes.insert(
"my-api".to_string(),
OAuth2Route {
cache,
upstream: "https://api.example.com".to_string(),
},
);
let store = CredentialStore {
credentials: HashMap::new(),
oauth2_routes,
};
let prefixes = store.loaded_prefixes();
assert!(prefixes.contains("my-api"));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_load_oauth2_unreachable_endpoint_skips_route() {
use crate::config::OAuth2Config;
let _lock = ENV_LOCK.lock().unwrap();
let _env = EnvVarGuard::set_all(&[
("TEST_OAUTH2_CLIENT_ID", "test-client"),
("TEST_OAUTH2_CLIENT_SECRET", "test-secret"),
]);
let tls = test_tls_connector();
let routes = vec![RouteConfig {
prefix: "my-api".to_string(),
upstream: "https://api.example.com".to_string(),
credential_key: None,
inject_mode: InjectMode::Header,
inject_header: "Authorization".to_string(),
credential_format: "Bearer {}".to_string(),
path_pattern: None,
path_replacement: None,
query_param_name: None,
proxy: None,
env_var: Some("MY_API_KEY".to_string()),
endpoint_rules: vec![],
tls_ca: None,
tls_client_cert: None,
tls_client_key: None,
oauth2: Some(OAuth2Config {
// Non-routable address: exchange will fail at TCP connect
token_url: "https://127.0.0.1:1/oauth/token".to_string(),
// Use env:// refs that point at test env vars
client_id: "env://TEST_OAUTH2_CLIENT_ID".to_string(),
client_secret: "env://TEST_OAUTH2_CLIENT_SECRET".to_string(),
scope: String::new(),
}),
}];
let store = CredentialStore::load(&routes, &tls);
// load() should succeed (route skipped, not hard error)
assert!(
store.is_ok(),
"load should not fail on unreachable OAuth2 endpoint"
);
let store = store.unwrap();
// The route should have been skipped (token exchange failed)
assert!(
store.is_empty(),
"unreachable OAuth2 endpoint should result in skipped route"
);
assert!(store.get_oauth2("my-api").is_none());
}
/// Build a test `TokenCache` with a pre-populated token.
fn make_test_token_cache(token: &str, ttl: std::time::Duration) -> TokenCache {
use crate::oauth2::OAuth2ExchangeConfig;
let config = OAuth2ExchangeConfig {
token_url: "https://127.0.0.1:1/oauth/token".to_string(),
client_id: Zeroizing::new("test-client".to_string()),
client_secret: Zeroizing::new("test-secret".to_string()),
scope: String::new(),
};
TokenCache::new_from_parts(config, test_tls_connector(), token, ttl)
}
}