foxy/security/
mod.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Security subsystem – runs before/after the main filter pipeline.
6//!
7//! Initially ships with *zero* providers; downstream crates add their own by
8//! implementing [`SecurityProvider`] and registering them on [`ProxyCore`].
9
10pub mod oidc;
11pub mod basic;
12
13#[cfg(test)]
14mod tests;
15
16use std::collections::HashMap;
17use std::future::Future;
18use std::pin::Pin;
19use async_trait::async_trait;
20use std::{fmt, sync::Arc};
21use once_cell::sync::Lazy;
22use serde::Deserialize;
23use std::sync::RwLock as StdRwLock;
24use crate::core::{ProxyError, ProxyRequest, ProxyResponse};
25use crate::{debug_fmt, error_fmt, info_fmt, trace_fmt};
26use crate::security::oidc::{OidcConfig, OidcProvider};
27use crate::security::basic::{BasicAuthConfig, BasicAuthProvider};
28
29/// When in the request/response lifecycle should a provider run?
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum SecurityStage {
32    Pre,
33    Post,
34    Both,
35}
36
37impl SecurityStage {
38    pub const fn is_pre(self) -> bool { matches!(self, Self::Pre | Self::Both) }
39    pub const fn is_post(self) -> bool { matches!(self, Self::Post | Self::Both) }
40}
41
42/// A unit of security logic – e.g. BasicAuth, JWT, OIDC, mTLS …
43#[async_trait]
44pub trait SecurityProvider: fmt::Debug + Send + Sync {
45    /// Which phase(s) does this provider participate in?
46    fn stage(&self) -> SecurityStage;
47    /// Name shown in logs / error messages.
48    fn name(&self) -> &str;
49
50    /// Optionally mutate/validate the inbound request *before* routing.
51    async fn pre(
52        &self,
53        request: ProxyRequest,
54    ) -> Result<ProxyRequest, ProxyError> {
55        trace_fmt!("SecurityChain", "Security provider '{}' skipping pre-auth (default implementation)", self.name());
56        Ok(request)
57    }
58
59    /// Optionally inspect/validate the response *after* the upstream call.
60    async fn post(
61        &self,
62        _request: ProxyRequest,
63        response: ProxyResponse,
64    ) -> Result<ProxyResponse, ProxyError> {
65        trace_fmt!("SecurityChain", "Security provider '{}' skipping post-auth (default implementation)", self.name());
66        Ok(response)
67    }
68}
69
70/// Executes all registered providers.
71#[derive(Debug)]
72pub struct SecurityChain {
73    providers: Vec<Arc<dyn SecurityProvider>>,
74}
75
76impl SecurityChain {
77    pub fn new() -> Self {
78        Self { providers: Vec::new() }
79    }
80
81    /// Build from raw config list.
82    pub async fn from_configs(cfgs: Vec<ProviderConfig>) -> Result<Self, ProxyError> {
83        let mut chain = SecurityChain::new();
84
85        debug_fmt!("SecurityChain", "Building security chain from {} provider configs", cfgs.len());
86
87        for c in cfgs {
88            let provider = SecurityProviderFactory::create_provider(&c.type_, c.config).await?;
89            chain.add(provider);
90        }
91
92        Ok(chain)
93    }
94
95    pub fn add(&mut self, p: Arc<dyn SecurityProvider>) { self.providers.push(p); }
96
97    pub async fn apply_pre(
98        &self,
99        mut req: ProxyRequest,
100    ) -> Result<ProxyRequest, ProxyError> {
101        trace_fmt!("SecurityChain", "Applying security pre-auth chain with {} providers", self.providers.len());
102
103        for p in &self.providers {
104            if p.stage().is_pre() {
105                trace_fmt!("SecurityChain", "Running pre-auth provider: {}", p.name());
106                match p.pre(req).await {
107                    Ok(new_req) => {
108                        req = new_req;
109                    },
110                    Err(e) => {
111                        let err = ProxyError::SecurityError(format!("{}: {}", p.name(), e));
112                        error_fmt!("SecurityChain", "Security pre-auth failed: {}", err);
113                        return Err(err);
114                    }
115                }
116            }
117        }
118        Ok(req)
119    }
120
121    pub async fn apply_post(
122        &self,
123        req: ProxyRequest,
124        mut resp: ProxyResponse,
125    ) -> Result<ProxyResponse, ProxyError> {
126        trace_fmt!("SecurityChain", "Applying security post-auth chain with {} providers", self.providers.len());
127
128        for p in &self.providers {
129            if p.stage().is_post() {
130                trace_fmt!("SecurityChain", "Running post-auth provider: {}", p.name());
131                match p.post(req.clone(), resp).await {
132                    Ok(new_resp) => {
133                        resp = new_resp;
134                    },
135                    Err(e) => {
136                        let err = ProxyError::SecurityError(format!("{}: {}", p.name(), e));
137                        error_fmt!("SecurityChain", "Security post-auth failed: {}", err);
138                        return Err(err);
139                    }
140                }
141            }
142        }
143        Ok(resp)
144    }
145}
146
147#[derive(Debug, Deserialize)]
148pub struct ProviderConfig {
149    #[serde(rename = "type")]
150    pub type_: String,
151    pub config: serde_json::Value,
152}
153
154
155/// Constructor signature every dynamic security provider must implement.
156/// Because providers may need to perform async operations (like OIDC discovery),
157/// the constructor returns a pinned, boxed future.
158pub type SecurityProviderConstructor =
159fn(serde_json::Value) -> Pin<Box<dyn Future<Output = Result<Arc<dyn SecurityProvider>, ProxyError>> + Send>>;
160
161
162/// Global registry for security providers.
163static SECURITY_PROVIDER_REGISTRY: Lazy<StdRwLock<HashMap<String, SecurityProviderConstructor>>> =
164    Lazy::new(|| StdRwLock::new(HashMap::new()));
165
166/// Register a security provider under a unique name.
167pub fn register_security_provider(name: &str, ctor: SecurityProviderConstructor) {
168    SECURITY_PROVIDER_REGISTRY
169        .write()
170        .expect("SECURITY_PROVIDER_REGISTRY poisoned")
171        .insert(name.to_string(), ctor);
172}
173
174/// Internal helper to get a registered security provider constructor.
175fn get_registered_security_provider(name: &str) -> Option<SecurityProviderConstructor> {
176    SECURITY_PROVIDER_REGISTRY
177        .read()
178        .expect("SECURITY_PROVIDER_REGISTRY poisoned")
179        .get(name)
180        .copied()
181}
182
183/// Factory for creating security providers based on configuration.
184#[derive(Debug)]
185pub struct SecurityProviderFactory;
186
187impl SecurityProviderFactory {
188    /// Create a security provider based on its type and configuration.
189    pub async fn create_provider(
190        provider_type: &str,
191        config: serde_json::Value,
192    ) -> Result<Arc<dyn SecurityProvider>, ProxyError> {
193        debug_fmt!("SecurityProviderFactory", "Creating security provider of type '{}'", provider_type);
194        if let Some(ctor) = get_registered_security_provider(provider_type) {
195            return ctor(config).await;
196        }
197
198        match provider_type {
199            "oidc" => {
200                let oidc_config: OidcConfig = serde_json::from_value(config)
201                    .map_err(|e| ProxyError::SecurityError(format!("Invalid OIDC provider config: {}", e)))?;
202                let provider = OidcProvider::discover(oidc_config).await?;
203                Ok(Arc::new(provider))
204            },
205            "basic" => {
206                let basic_auth_config: BasicAuthConfig = serde_json::from_value(config)
207                    .map_err(|e| ProxyError::SecurityError(format!("Invalid Basic Auth provider config: {}", e)))?;
208                let provider = BasicAuthProvider::new(basic_auth_config)?;
209                Ok(Arc::new(provider))
210            },
211            _ => Err(ProxyError::SecurityError(format!("Unknown security provider type: {}", provider_type))),
212        }
213    }
214}