1use serde::{Deserialize, Serialize};
26use sha2::{Digest, Sha256};
27use std::collections::HashMap;
28use thiserror::Error;
29
30#[cfg(feature = "async")]
31use async_trait::async_trait;
32
33#[derive(Error, Debug)]
36pub enum ControlPlaneError {
37 #[error("Client not found for the provided API key")]
38 NotFound,
39
40 #[error("Client record is inactive (disabled)")]
41 Inactive,
42
43 #[error("Backend unreachable: {0}")]
44 Unreachable(String),
45
46 #[error("Malformed client record: {0}")]
47 MalformedRecord(String),
48
49 #[error("Internal error: {0}")]
50 Internal(String),
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize)]
60pub struct ClientRecord {
61 pub client_id: String,
63
64 #[serde(default = "default_active")]
67 pub is_active: bool,
68
69 #[serde(default = "default_permissions")]
71 pub permissions: Vec<String>,
72
73 #[serde(skip_serializing_if = "Option::is_none")]
75 pub rate_limit_rps: Option<u32>,
76
77 #[serde(default)]
79 pub metadata: HashMap<String, String>,
80}
81
82fn default_active() -> bool {
83 true
84}
85
86fn default_permissions() -> Vec<String> {
87 vec![
88 "read".into(),
89 "write".into(),
90 "replay".into(),
91 "delete".into(),
92 ]
93}
94
95#[cfg(feature = "async")]
104#[async_trait]
105pub trait ControlPlane: Send + Sync {
106 async fn lookup_client(&self, api_key: &str) -> Result<ClientRecord, ControlPlaneError>;
114
115 async fn health_check(&self) -> bool {
117 true
118 }
119
120 fn backend_name(&self) -> &str;
122}
123
124pub fn hash_api_key(api_key: &str) -> String {
128 let mut hasher = Sha256::new();
129 hasher.update(api_key.as_bytes());
130 let result = hasher.finalize();
131 result.iter().map(|b| format!("{:02x}", b)).collect()
132}
133
134pub struct LocalControlPlane {
141 clients: Vec<LocalClient>,
142}
143
144#[derive(Clone, Debug)]
146pub struct LocalClient {
147 pub client_id: String,
148 pub api_key: String,
149 pub permissions: Vec<String>,
150 pub rate_limit_rps: Option<u32>,
151}
152
153impl LocalControlPlane {
154 pub fn new(clients: Vec<LocalClient>) -> Self {
156 Self { clients }
157 }
158
159 fn constant_time_eq(a: &str, b: &str) -> bool {
161 if a.len() != b.len() {
162 return false;
163 }
164 a.as_bytes()
165 .iter()
166 .zip(b.as_bytes().iter())
167 .fold(0u8, |acc, (x, y)| acc | (x ^ y))
168 == 0
169 }
170}
171
172#[cfg(feature = "async")]
173#[async_trait]
174impl ControlPlane for LocalControlPlane {
175 async fn lookup_client(&self, api_key: &str) -> Result<ClientRecord, ControlPlaneError> {
176 for client in &self.clients {
177 if Self::constant_time_eq(&client.api_key, api_key) {
178 return Ok(ClientRecord {
179 client_id: client.client_id.clone(),
180 is_active: true,
181 permissions: client.permissions.clone(),
182 rate_limit_rps: client.rate_limit_rps,
183 metadata: HashMap::new(),
184 });
185 }
186 }
187 Err(ControlPlaneError::NotFound)
188 }
189
190 fn backend_name(&self) -> &str {
191 "local"
192 }
193}
194
195#[cfg(feature = "async")]
204pub struct FallbackControlPlane {
205 primary: Box<dyn ControlPlane>,
206 secondary: Box<dyn ControlPlane>,
207}
208
209#[cfg(feature = "async")]
210impl FallbackControlPlane {
211 pub fn new(primary: Box<dyn ControlPlane>, secondary: Box<dyn ControlPlane>) -> Self {
212 Self { primary, secondary }
213 }
214}
215
216#[cfg(feature = "async")]
217#[async_trait]
218impl ControlPlane for FallbackControlPlane {
219 async fn lookup_client(&self, api_key: &str) -> Result<ClientRecord, ControlPlaneError> {
220 match self.primary.lookup_client(api_key).await {
221 Ok(record) => Ok(record),
222 Err(ControlPlaneError::Inactive) => Err(ControlPlaneError::Inactive),
224 Err(ControlPlaneError::MalformedRecord(msg)) => {
226 Err(ControlPlaneError::MalformedRecord(msg))
227 }
228 Err(_primary_err) => self.secondary.lookup_client(api_key).await,
230 }
231 }
232
233 async fn health_check(&self) -> bool {
234 self.primary.health_check().await || self.secondary.health_check().await
236 }
237
238 fn backend_name(&self) -> &str {
239 "fallback"
240 }
241}
242
243#[cfg(test)]
246mod tests {
247 use super::*;
248
249 #[test]
250 fn test_hash_api_key_deterministic() {
251 let h1 = hash_api_key("sk-test-key-123");
252 let h2 = hash_api_key("sk-test-key-123");
253 assert_eq!(h1, h2);
254 }
255
256 #[test]
257 fn test_hash_api_key_different_keys_different_hashes() {
258 let h1 = hash_api_key("sk-key-a");
259 let h2 = hash_api_key("sk-key-b");
260 assert_ne!(h1, h2);
261 }
262
263 #[test]
264 fn test_hash_api_key_is_hex() {
265 let h = hash_api_key("sk-test");
266 assert_eq!(h.len(), 64); assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
268 }
269
270 #[test]
271 fn test_hash_api_key_known_value() {
272 let h = hash_api_key("hello");
274 assert_eq!(
275 h,
276 "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
277 );
278 }
279
280 #[test]
281 fn test_client_record_deserialize_minimal() {
282 let json = r#"{"client_id": "acme"}"#;
283 let record: ClientRecord = serde_json::from_str(json).unwrap();
284 assert_eq!(record.client_id, "acme");
285 assert!(record.is_active); assert_eq!(record.permissions.len(), 4); assert!(record.rate_limit_rps.is_none());
288 assert!(record.metadata.is_empty());
289 }
290
291 #[test]
292 fn test_client_record_deserialize_full() {
293 let json = r#"{
294 "client_id": "acme",
295 "is_active": false,
296 "permissions": ["read"],
297 "rate_limit_rps": 50,
298 "metadata": {"tier": "enterprise"}
299 }"#;
300 let record: ClientRecord = serde_json::from_str(json).unwrap();
301 assert_eq!(record.client_id, "acme");
302 assert!(!record.is_active);
303 assert_eq!(record.permissions, vec!["read"]);
304 assert_eq!(record.rate_limit_rps, Some(50));
305 assert_eq!(record.metadata.get("tier"), Some(&"enterprise".to_string()));
306 }
307
308 #[test]
309 fn test_client_record_serialize_roundtrip() {
310 let record = ClientRecord {
311 client_id: "test".into(),
312 is_active: true,
313 permissions: vec!["read".into(), "write".into()],
314 rate_limit_rps: Some(100),
315 metadata: HashMap::new(),
316 };
317 let json = serde_json::to_string(&record).unwrap();
318 let back: ClientRecord = serde_json::from_str(&json).unwrap();
319 assert_eq!(back.client_id, "test");
320 assert_eq!(back.permissions, vec!["read", "write"]);
321 assert_eq!(back.rate_limit_rps, Some(100));
322 }
323
324 #[test]
325 fn test_client_record_rate_limit_omitted_in_json() {
326 let record = ClientRecord {
327 client_id: "test".into(),
328 is_active: true,
329 permissions: vec![],
330 rate_limit_rps: None,
331 metadata: HashMap::new(),
332 };
333 let json = serde_json::to_string(&record).unwrap();
334 assert!(!json.contains("rate_limit_rps"));
335 }
336
337 #[test]
338 fn test_client_record_missing_client_id_fails() {
339 let json = r#"{"permissions": ["read"]}"#;
340 let result: Result<ClientRecord, _> = serde_json::from_str(json);
341 assert!(result.is_err());
342 }
343
344 #[tokio::test]
347 async fn test_local_lookup_found() {
348 let cp = LocalControlPlane::new(vec![LocalClient {
349 client_id: "acme".into(),
350 api_key: "sk-acme-123".into(),
351 permissions: vec!["read".into(), "write".into()],
352 rate_limit_rps: Some(100),
353 }]);
354 let record = cp.lookup_client("sk-acme-123").await.unwrap();
355 assert_eq!(record.client_id, "acme");
356 assert!(record.is_active);
357 assert_eq!(record.permissions, vec!["read", "write"]);
358 assert_eq!(record.rate_limit_rps, Some(100));
359 }
360
361 #[tokio::test]
362 async fn test_local_lookup_not_found() {
363 let cp = LocalControlPlane::new(vec![LocalClient {
364 client_id: "acme".into(),
365 api_key: "sk-acme-123".into(),
366 permissions: vec![],
367 rate_limit_rps: None,
368 }]);
369 let result = cp.lookup_client("sk-wrong").await;
370 assert!(matches!(result, Err(ControlPlaneError::NotFound)));
371 }
372
373 #[tokio::test]
374 async fn test_local_lookup_empty_list() {
375 let cp = LocalControlPlane::new(vec![]);
376 let result = cp.lookup_client("sk-anything").await;
377 assert!(matches!(result, Err(ControlPlaneError::NotFound)));
378 }
379
380 #[tokio::test]
381 async fn test_local_lookup_multiple_clients() {
382 let cp = LocalControlPlane::new(vec![
383 LocalClient {
384 client_id: "acme".into(),
385 api_key: "sk-acme".into(),
386 permissions: vec!["read".into()],
387 rate_limit_rps: None,
388 },
389 LocalClient {
390 client_id: "beta".into(),
391 api_key: "sk-beta".into(),
392 permissions: vec!["write".into()],
393 rate_limit_rps: None,
394 },
395 ]);
396 let r1 = cp.lookup_client("sk-acme").await.unwrap();
397 assert_eq!(r1.client_id, "acme");
398
399 let r2 = cp.lookup_client("sk-beta").await.unwrap();
400 assert_eq!(r2.client_id, "beta");
401 }
402
403 #[tokio::test]
404 async fn test_local_constant_time_prevents_substring_match() {
405 let cp = LocalControlPlane::new(vec![LocalClient {
406 client_id: "acme".into(),
407 api_key: "sk-acme-123".into(),
408 permissions: vec![],
409 rate_limit_rps: None,
410 }]);
411 assert!(cp.lookup_client("sk-acme").await.is_err());
413 assert!(cp.lookup_client("sk-acme-1234").await.is_err());
414 assert!(cp.lookup_client("sk-acme-12").await.is_err());
415 }
416
417 #[tokio::test]
418 async fn test_local_backend_name() {
419 let cp = LocalControlPlane::new(vec![]);
420 assert_eq!(cp.backend_name(), "local");
421 }
422
423 #[tokio::test]
424 async fn test_local_health_check() {
425 let cp = LocalControlPlane::new(vec![]);
426 assert!(cp.health_check().await);
427 }
428
429 struct MockControlPlane {
433 name: &'static str,
434 record: Option<ClientRecord>,
435 error: Option<ControlPlaneError>,
436 }
437
438 impl MockControlPlane {
439 fn succeeding(name: &'static str, client_id: &str) -> Self {
440 Self {
441 name,
442 record: Some(ClientRecord {
443 client_id: client_id.into(),
444 is_active: true,
445 permissions: vec!["read".into()],
446 rate_limit_rps: None,
447 metadata: HashMap::new(),
448 }),
449 error: None,
450 }
451 }
452
453 fn failing(name: &'static str, error: ControlPlaneError) -> Self {
454 Self {
455 name,
456 record: None,
457 error: Some(error),
458 }
459 }
460 }
461
462 #[async_trait]
463 impl ControlPlane for MockControlPlane {
464 async fn lookup_client(&self, _api_key: &str) -> Result<ClientRecord, ControlPlaneError> {
465 if let Some(ref record) = self.record {
466 Ok(record.clone())
467 } else if let Some(ref err) = self.error {
468 match err {
470 ControlPlaneError::NotFound => Err(ControlPlaneError::NotFound),
471 ControlPlaneError::Inactive => Err(ControlPlaneError::Inactive),
472 ControlPlaneError::Unreachable(m) => {
473 Err(ControlPlaneError::Unreachable(m.clone()))
474 }
475 ControlPlaneError::MalformedRecord(m) => {
476 Err(ControlPlaneError::MalformedRecord(m.clone()))
477 }
478 ControlPlaneError::Internal(m) => Err(ControlPlaneError::Internal(m.clone())),
479 }
480 } else {
481 Err(ControlPlaneError::NotFound)
482 }
483 }
484
485 fn backend_name(&self) -> &str {
486 self.name
487 }
488 }
489
490 #[tokio::test]
491 async fn test_fallback_primary_succeeds() {
492 let primary = MockControlPlane::succeeding("primary", "from-primary");
493 let secondary = MockControlPlane::succeeding("secondary", "from-secondary");
494 let cp = FallbackControlPlane::new(Box::new(primary), Box::new(secondary));
495
496 let record = cp.lookup_client("any-key").await.unwrap();
497 assert_eq!(record.client_id, "from-primary");
498 }
499
500 #[tokio::test]
501 async fn test_fallback_primary_not_found_falls_through() {
502 let primary = MockControlPlane::failing("primary", ControlPlaneError::NotFound);
503 let secondary = MockControlPlane::succeeding("secondary", "from-secondary");
504 let cp = FallbackControlPlane::new(Box::new(primary), Box::new(secondary));
505
506 let record = cp.lookup_client("any-key").await.unwrap();
507 assert_eq!(record.client_id, "from-secondary");
508 }
509
510 #[tokio::test]
511 async fn test_fallback_primary_unreachable_falls_through() {
512 let primary =
513 MockControlPlane::failing("primary", ControlPlaneError::Unreachable("timeout".into()));
514 let secondary = MockControlPlane::succeeding("secondary", "from-secondary");
515 let cp = FallbackControlPlane::new(Box::new(primary), Box::new(secondary));
516
517 let record = cp.lookup_client("any-key").await.unwrap();
518 assert_eq!(record.client_id, "from-secondary");
519 }
520
521 #[tokio::test]
522 async fn test_fallback_primary_inactive_does_not_fall_through() {
523 let primary = MockControlPlane::failing("primary", ControlPlaneError::Inactive);
524 let secondary = MockControlPlane::succeeding("secondary", "from-secondary");
525 let cp = FallbackControlPlane::new(Box::new(primary), Box::new(secondary));
526
527 let result = cp.lookup_client("any-key").await;
528 assert!(matches!(result, Err(ControlPlaneError::Inactive)));
529 }
530
531 #[tokio::test]
532 async fn test_fallback_primary_malformed_does_not_fall_through() {
533 let primary = MockControlPlane::failing(
534 "primary",
535 ControlPlaneError::MalformedRecord("bad json".into()),
536 );
537 let secondary = MockControlPlane::succeeding("secondary", "from-secondary");
538 let cp = FallbackControlPlane::new(Box::new(primary), Box::new(secondary));
539
540 let result = cp.lookup_client("any-key").await;
541 assert!(matches!(result, Err(ControlPlaneError::MalformedRecord(_))));
542 }
543
544 #[tokio::test]
545 async fn test_fallback_both_not_found() {
546 let primary = MockControlPlane::failing("primary", ControlPlaneError::NotFound);
547 let secondary = MockControlPlane::failing("secondary", ControlPlaneError::NotFound);
548 let cp = FallbackControlPlane::new(Box::new(primary), Box::new(secondary));
549
550 let result = cp.lookup_client("any-key").await;
551 assert!(matches!(result, Err(ControlPlaneError::NotFound)));
552 }
553
554 #[tokio::test]
555 async fn test_fallback_backend_name() {
556 let primary = MockControlPlane::succeeding("primary", "x");
557 let secondary = MockControlPlane::succeeding("secondary", "y");
558 let cp = FallbackControlPlane::new(Box::new(primary), Box::new(secondary));
559 assert_eq!(cp.backend_name(), "fallback");
560 }
561}