Skip to main content

cloudiful_server/core/
config.rs

1use http::{HeaderValue, Method};
2use std::path::{Path, PathBuf};
3
4use crate::core::error::ServerConfigError;
5
6pub const DEFAULT_LISTEN_ADDR: &str = "127.0.0.1:3000";
7
8#[derive(Clone, Debug, Eq, PartialEq)]
9enum CorsMode {
10    Permissive,
11    Restricted { allowed_origins: Vec<String> },
12}
13
14#[derive(Clone, Debug, Eq, PartialEq)]
15pub struct CorsConfig {
16    mode: CorsMode,
17    allowed_methods: Vec<String>,
18    max_age: Option<usize>,
19}
20
21impl Default for CorsConfig {
22    fn default() -> Self {
23        Self::permissive()
24    }
25}
26
27impl CorsConfig {
28    pub fn permissive() -> Self {
29        Self {
30            mode: CorsMode::Permissive,
31            allowed_methods: Vec::new(),
32            max_age: None,
33        }
34    }
35
36    pub fn restricted<I, S>(allowed_origins: I) -> Self
37    where
38        I: IntoIterator<Item = S>,
39        S: Into<String>,
40    {
41        Self {
42            mode: CorsMode::Restricted {
43                allowed_origins: allowed_origins.into_iter().map(Into::into).collect(),
44            },
45            allowed_methods: vec!["GET".to_string(), "POST".to_string()],
46            max_age: Some(3600),
47        }
48    }
49
50    pub fn with_allowed_methods<I, S>(mut self, allowed_methods: I) -> Self
51    where
52        I: IntoIterator<Item = S>,
53        S: Into<String>,
54    {
55        self.allowed_methods = allowed_methods.into_iter().map(Into::into).collect();
56        self
57    }
58
59    pub fn with_max_age(mut self, max_age: usize) -> Self {
60        self.max_age = Some(max_age);
61        self
62    }
63
64    pub fn is_permissive(&self) -> bool {
65        matches!(self.mode, CorsMode::Permissive)
66    }
67
68    pub fn allowed_origins(&self) -> &[String] {
69        match &self.mode {
70            CorsMode::Permissive => &[],
71            CorsMode::Restricted { allowed_origins } => allowed_origins.as_slice(),
72        }
73    }
74
75    pub fn allowed_methods(&self) -> &[String] {
76        self.allowed_methods.as_slice()
77    }
78
79    pub fn max_age(&self) -> Option<usize> {
80        self.max_age
81    }
82
83    pub(crate) fn validate(&self) -> Result<(), ServerConfigError> {
84        match &self.mode {
85            CorsMode::Permissive => Ok(()),
86            CorsMode::Restricted { allowed_origins } => {
87                if allowed_origins.is_empty() {
88                    return Err(ServerConfigError::MissingCorsOrigins);
89                }
90
91                for origin in allowed_origins {
92                    HeaderValue::from_str(origin)
93                        .map_err(|_| ServerConfigError::InvalidCorsOrigin(origin.clone()))?;
94                }
95
96                if self.allowed_methods.is_empty() {
97                    return Err(ServerConfigError::MissingCorsMethods);
98                }
99
100                for method in &self.allowed_methods {
101                    Method::from_bytes(method.as_bytes())
102                        .map_err(|_| ServerConfigError::InvalidCorsMethod(method.clone()))?;
103                }
104
105                Ok(())
106            }
107        }
108    }
109}
110
111#[derive(Clone, Debug, Default, Eq, PartialEq)]
112pub struct TlsConfig {
113    cert_path: Option<PathBuf>,
114    cert_key_path: Option<PathBuf>,
115}
116
117impl TlsConfig {
118    pub fn new() -> Self {
119        Self::default()
120    }
121
122    pub fn with_cert_path<P>(mut self, cert_path: P) -> Self
123    where
124        P: Into<PathBuf>,
125    {
126        self.cert_path = Some(cert_path.into());
127        self
128    }
129
130    pub fn with_cert_key_path<P>(mut self, cert_key_path: P) -> Self
131    where
132        P: Into<PathBuf>,
133    {
134        self.cert_key_path = Some(cert_key_path.into());
135        self
136    }
137
138    pub fn cert_path(&self) -> Option<&Path> {
139        self.cert_path.as_deref()
140    }
141
142    pub fn cert_key_path(&self) -> Option<&Path> {
143        self.cert_key_path.as_deref()
144    }
145
146    pub(crate) fn validate(self) -> Result<ValidatedTlsConfig, ServerConfigError> {
147        let cert_path = self
148            .cert_path
149            .ok_or(ServerConfigError::MissingTlsCertPath)?;
150        let cert_key_path = self
151            .cert_key_path
152            .ok_or(ServerConfigError::MissingTlsKeyPath)?;
153
154        Ok(ValidatedTlsConfig {
155            cert_path,
156            cert_key_path,
157        })
158    }
159}
160
161#[derive(Clone, Debug, Eq, PartialEq)]
162pub(crate) struct ValidatedTlsConfig {
163    pub(crate) cert_path: PathBuf,
164    pub(crate) cert_key_path: PathBuf,
165}
166
167#[derive(Clone, Debug)]
168pub struct ServerConfig<U = ()> {
169    listen_addr: String,
170    app_data: Option<U>,
171    cors: CorsConfig,
172    tls: Option<TlsConfig>,
173}
174
175impl Default for ServerConfig<()> {
176    fn default() -> Self {
177        Self {
178            listen_addr: DEFAULT_LISTEN_ADDR.to_string(),
179            app_data: None,
180            cors: CorsConfig::default(),
181            tls: None,
182        }
183    }
184}
185
186impl ServerConfig<()> {
187    pub fn new() -> Self {
188        Self::default()
189    }
190}
191
192impl<U> ServerConfig<U> {
193    pub fn with_listen_addr(mut self, listen_addr: impl Into<String>) -> Self {
194        self.listen_addr = listen_addr.into();
195        self
196    }
197
198    pub fn with_app_data<T>(self, app_data: T) -> ServerConfig<T> {
199        ServerConfig {
200            listen_addr: self.listen_addr,
201            app_data: Some(app_data),
202            cors: self.cors,
203            tls: self.tls,
204        }
205    }
206
207    pub fn with_cors(mut self, cors: CorsConfig) -> Self {
208        self.cors = cors;
209        self
210    }
211
212    pub fn with_tls(mut self, tls: TlsConfig) -> Self {
213        self.tls = Some(tls);
214        self
215    }
216
217    pub fn build(self) -> Result<ValidatedServerConfig<U>, ServerConfigError> {
218        if self.listen_addr.trim().is_empty() {
219            return Err(ServerConfigError::MissingListenAddr);
220        }
221
222        self.cors.validate()?;
223        let tls = self.tls.map(TlsConfig::validate).transpose()?;
224
225        Ok(ValidatedServerConfig {
226            listen_addr: self.listen_addr,
227            app_data: self.app_data,
228            cors: self.cors,
229            tls,
230        })
231    }
232}
233
234#[derive(Clone, Debug)]
235pub struct ValidatedServerConfig<U = ()> {
236    pub(crate) listen_addr: String,
237    pub(crate) app_data: Option<U>,
238    pub(crate) cors: CorsConfig,
239    pub(crate) tls: Option<ValidatedTlsConfig>,
240}
241
242impl<U> ValidatedServerConfig<U> {
243    pub fn listen_addr(&self) -> &str {
244        self.listen_addr.as_str()
245    }
246
247    pub fn app_data(&self) -> Option<&U> {
248        self.app_data.as_ref()
249    }
250
251    pub fn cors(&self) -> &CorsConfig {
252        &self.cors
253    }
254
255    pub fn tls_enabled(&self) -> bool {
256        self.tls.is_some()
257    }
258
259    pub fn tls_paths(&self) -> Option<(&Path, &Path)> {
260        self.tls
261            .as_ref()
262            .map(|tls| (tls.cert_path.as_path(), tls.cert_key_path.as_path()))
263    }
264}