Skip to main content

briefcase_core/
control.rs

1//! # Control Plane Abstraction
2//!
3//! Defines the `ControlPlane` trait for looking up client authentication and
4//! authorization records.  Implementations include:
5//!
6//! - **`RemoteControlPlane`**  reads client records from a remote control
7//!   repository (the production source of truth).
8//! - **`LocalControlPlane`**  resolves clients from a static in-memory list
9//!   (useful for dev/test or as a fallback).
10//! - **`FallbackControlPlane`**  chains a *primary* and *secondary* control
11//!   plane: the primary is tried first and, on any error, the secondary is
12//!   consulted.  This lets you run the remote backend as the primary with
13//!   local config as the fallback.
14//!
15//! ## Client record schema
16//!
17//! Records live at `clients/by-key/{sha256(api_key)}.json` in the control
18//! repository.  The JSON schema is defined by [`ClientRecord`].
19//!
20//! ## Extending
21//!
22//! To add a new backend (e.g. PostgreSQL, Redis, Vault), implement the
23//! `ControlPlane` trait and wire it into the server's `AppState`.
24
25use 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//  Errors
34
35#[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//  Client record schema
54
55/// Canonical client record stored in the control plane.
56///
57/// In the remote backend this is the JSON payload at
58/// `clients/by-key/{sha256(api_key)}.json`.
59#[derive(Debug, Clone, Serialize, Deserialize)]
60pub struct ClientRecord {
61    /// Unique human-readable identifier (e.g. "acme", "internal-tools").
62    pub client_id: String,
63
64    /// Whether the client is currently active.  Inactive clients fail auth
65    /// even if the key matches.
66    #[serde(default = "default_active")]
67    pub is_active: bool,
68
69    /// Granted permission strings (e.g. `["read", "write", "replay", "delete"]`).
70    #[serde(default = "default_permissions")]
71    pub permissions: Vec<String>,
72
73    /// Optional per-client rate limit (requests per second).
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub rate_limit_rps: Option<u32>,
76
77    /// Arbitrary key-value metadata.
78    #[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//  Trait
96
97/// Abstraction over the source of truth for client authentication and
98/// authorization.
99///
100/// Implementors resolve an API key to a [`ClientRecord`].  The server calls
101/// this on the `POST /api/v1/auth/validate` path and, optionally, in the
102/// per-request middleware.
103#[cfg(feature = "async")]
104#[async_trait]
105pub trait ControlPlane: Send + Sync {
106    /// Look up a client by raw API key.
107    ///
108    /// Implementations MUST:
109    /// 1. Hash the key (SHA-256) before any network/storage lookup.
110    /// 2. Return `Err(NotFound)` when no record matches.
111    /// 3. Return `Err(Inactive)` when the record exists but `is_active` is
112    ///    false.
113    async fn lookup_client(&self, api_key: &str) -> Result<ClientRecord, ControlPlaneError>;
114
115    /// Quick connectivity check.  Returns `true` if the backend is reachable.
116    async fn health_check(&self) -> bool {
117        true
118    }
119
120    /// Human-readable backend name for logging (e.g. "remote", "local").
121    fn backend_name(&self) -> &str;
122}
123
124//  Helpers
125
126/// SHA-256 hash of an API key, returned as a lowercase hex string.
127pub 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
134//  Local (in-memory) implementation
135
136/// Resolves clients from a static list  typically parsed from env vars.
137///
138/// This is the simplest control plane: no network calls, no hashing lookup.
139/// It uses constant-time comparison for security.
140pub struct LocalControlPlane {
141    clients: Vec<LocalClient>,
142}
143
144/// A client entry for local (in-memory) lookup.
145#[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    /// Create from a list of client entries.
155    pub fn new(clients: Vec<LocalClient>) -> Self {
156        Self { clients }
157    }
158
159    /// Constant-time string comparison.
160    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//  Fallback (chained) implementation
196
197/// Chains a primary and secondary control plane.
198///
199/// On `lookup_client`, the primary is tried first.  If it returns `NotFound`
200/// or `Unreachable`, the secondary is consulted.  Errors like `Inactive` or
201/// `MalformedRecord` from the primary are NOT retried  those indicate the
202/// record *was* found but is invalid.
203#[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            // Record found but inactive  don't retry, this is authoritative
223            Err(ControlPlaneError::Inactive) => Err(ControlPlaneError::Inactive),
224            // Record found but malformed  don't retry
225            Err(ControlPlaneError::MalformedRecord(msg)) => {
226                Err(ControlPlaneError::MalformedRecord(msg))
227            }
228            // Not found or unreachable  try secondary
229            Err(_primary_err) => self.secondary.lookup_client(api_key).await,
230        }
231    }
232
233    async fn health_check(&self) -> bool {
234        // Healthy if either backend is reachable
235        self.primary.health_check().await || self.secondary.health_check().await
236    }
237
238    fn backend_name(&self) -> &str {
239        "fallback"
240    }
241}
242
243//  Tests
244
245#[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); // SHA-256 = 32 bytes = 64 hex chars
267        assert!(h.chars().all(|c| c.is_ascii_hexdigit()));
268    }
269
270    #[test]
271    fn test_hash_api_key_known_value() {
272        // SHA-256("hello") = 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
273        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); // default
286        assert_eq!(record.permissions.len(), 4); // defaults
287        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    // --- LocalControlPlane tests ---
345
346    #[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        // Substring should NOT match
412        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    // --- FallbackControlPlane tests ---
430
431    /// A mock control plane that always returns a fixed record.
432    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                // Recreate the error since Error doesn't impl Clone
469                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}