Skip to main content

che_rest/
config.rs

1use std::path::Path;
2
3use crate::error::AppResult;
4
5#[derive(Debug, Clone, Default, serde::Deserialize)]
6pub struct AppConfig {
7    #[serde(default)]
8    pub database: DatabaseConfig,
9    #[serde(default)]
10    pub server: ServerConfig,
11    #[serde(default)]
12    pub auth: AuthConfig,
13    #[serde(default)]
14    pub media: MediaConfig,
15}
16
17#[derive(Debug, Clone, serde::Deserialize)]
18#[serde(default)]
19pub struct MediaConfig {
20    pub root: String,
21}
22
23impl Default for MediaConfig {
24    fn default() -> Self {
25        Self {
26            root: "uploads".into(),
27        }
28    }
29}
30
31#[derive(Debug, Clone, serde::Deserialize)]
32#[serde(default)]
33pub struct ServerConfig {
34    pub host: String,
35    pub port: u16,
36    pub api_prefix: String,
37}
38
39impl Default for ServerConfig {
40    fn default() -> Self {
41        Self {
42            host: "127.0.0.1".to_string(),
43            port: 3000,
44            api_prefix: "/api".to_string(),
45        }
46    }
47}
48
49#[derive(Debug, Clone, Default, serde::Deserialize)]
50#[serde(default)]
51pub struct AuthConfig {
52    pub session: SessionConfig,
53}
54
55#[derive(Debug, Clone, serde::Deserialize)]
56#[serde(default)]
57pub struct SessionConfig {
58    pub cookie_name: String,
59    pub csrf_cookie_name: String,
60    pub ttl_seconds: i64,
61    pub renewal_window_seconds: i64,
62    pub absolute_ttl_seconds: i64,
63    pub secure: bool,
64    pub same_site: String,
65}
66
67impl Default for SessionConfig {
68    fn default() -> Self {
69        Self {
70            cookie_name: "che_rest_session".to_string(),
71            csrf_cookie_name: "csrf_token".to_string(),
72            ttl_seconds: 604_800,
73            renewal_window_seconds: 86_400,
74            absolute_ttl_seconds: 2_592_000,
75            secure: false,
76            same_site: "Lax".to_string(),
77        }
78    }
79}
80
81#[derive(Debug, Clone, serde::Deserialize)]
82#[serde(default)]
83pub struct DatabaseConfig {
84    pub url: String,
85    pub max_connections: u32,
86}
87
88impl Default for DatabaseConfig {
89    fn default() -> Self {
90        Self {
91            url: default_database_url().to_string(),
92            max_connections: 10,
93        }
94    }
95}
96
97impl DatabaseConfig {
98    pub(crate) async fn connect(&self) -> Result<che_orm::Database, che_orm::OrmError> {
99        let url = self.connection_url()?;
100        let pool_size = if cfg!(feature = "sqlite") && url == ":memory:" {
101            1
102        } else {
103            self.max_connections as usize
104        };
105        che_orm::Database::connect_with_pool_size(url, pool_size).await
106    }
107
108    fn connection_url(&self) -> Result<String, che_orm::OrmError> {
109        #[cfg(feature = "sqlite")]
110        {
111            if self.url.contains("://") && !self.url.starts_with("sqlite://") {
112                return Err(che_orm::OrmError::Configuration(
113                    "this build requires a SQLite URL or file path".into(),
114                ));
115            }
116            Ok(sqlite_path(&self.url))
117        }
118        #[cfg(all(feature = "postgres", not(feature = "sqlite")))]
119        {
120            if !(self.url.starts_with("postgres://") || self.url.starts_with("postgresql://")) {
121                return Err(che_orm::OrmError::Configuration(
122                    "this build requires a postgres:// or postgresql:// URL".into(),
123                ));
124            }
125            // Preserve credentials, TLS, options/search_path and all query parameters.
126            Ok(self.url.clone())
127        }
128    }
129}
130
131fn default_database_url() -> &'static str {
132    if cfg!(feature = "postgres") {
133        "postgresql://localhost/che_rest"
134    } else {
135        "sqlite://db.sqlite?mode=rwc"
136    }
137}
138
139pub(crate) fn backend_name() -> &'static str {
140    if cfg!(feature = "postgres") {
141        "PostgreSQL"
142    } else {
143        "SQLite"
144    }
145}
146
147pub(crate) fn sqlite_path(url: &str) -> String {
148    url.strip_prefix("sqlite://")
149        .and_then(|value| value.split('?').next())
150        .filter(|value| !value.is_empty())
151        .unwrap_or(url)
152        .to_string()
153}
154
155impl AppConfig {
156    pub fn from_file(path: impl AsRef<Path>) -> AppResult<Self> {
157        let content = std::fs::read_to_string(path)?;
158        Ok(toml::from_str(&content)?)
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::AppConfig;
165
166    #[test]
167    fn backend_urls_are_validated_without_disclosing_credentials() {
168        let mut config = super::DatabaseConfig::default();
169        #[cfg(feature = "postgres")]
170        {
171            config.url = "postgresql://user:secret@localhost/app?sslmode=require&options=-csearch_path%3Dtenant".into();
172            assert_eq!(config.connection_url().unwrap(), config.url);
173            config.url = "sqlite://wrong.sqlite".into();
174        }
175        #[cfg(feature = "sqlite")]
176        {
177            config.url = "postgresql://user:secret@localhost/app".into();
178        }
179        let error = config.connection_url().unwrap_err().to_string();
180        assert!(!error.contains("secret"));
181        assert!(!error.contains(&config.url));
182    }
183
184    #[test]
185    fn session_config_is_optional() {
186        let config: AppConfig = toml::from_str("[database]\nurl = 'sqlite://db.sqlite'").unwrap();
187        assert_eq!(config.auth.session.cookie_name, "che_rest_session");
188        assert_eq!(config.auth.session.ttl_seconds, 604_800);
189        assert_eq!(config.server.host, "127.0.0.1");
190        assert_eq!(config.server.port, 3000);
191        assert_eq!(config.server.api_prefix, "/api");
192        assert_eq!(config.media.root, "uploads");
193    }
194}