rullst-core 12.1.1

Core runtime, routing engine, and telemetry for the Rullst framework suite.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
use serde::Deserialize;
use std::{fmt, str::FromStr};

/// Validated runtime environment shared by every Rullst subsystem.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Environment {
    /// Local development with developer tooling enabled.
    #[default]
    Development,
    /// Automated test execution.
    Test,
    /// Production-like pre-release deployment.
    Staging,
    /// Public production deployment with all secure defaults enabled.
    Production,
}

impl Environment {
    /// Resolves environment sources using the documented precedence:
    /// `RULLST_ENV`, legacy `APP_ENV`, then `[app].env` from `Rullst.toml`.
    pub fn resolve(
        rullst_env: Option<&str>,
        app_env: Option<&str>,
        configured_env: Option<&str>,
    ) -> Result<Self, ConfigError> {
        rullst_env
            .or(app_env)
            .or(configured_env)
            .map(Self::from_str)
            .transpose()
            .map(|environment| environment.unwrap_or_default())
    }

    /// Resolves the environment from process variables and an optional config value.
    pub fn detect(configured_env: Option<&str>) -> Result<Self, ConfigError> {
        let rullst_env = read_environment_variable("RULLST_ENV")?;
        let app_env = read_environment_variable("APP_ENV")?;
        Self::resolve(rullst_env.as_deref(), app_env.as_deref(), configured_env)
    }

    /// Whether local-only developer tooling may be exposed.
    pub const fn allows_development_tools(self) -> bool {
        matches!(self, Self::Development)
    }

    /// Whether production security layers and secure cookies are mandatory.
    pub const fn requires_secure_defaults(self) -> bool {
        matches!(self, Self::Staging | Self::Production)
    }
}

impl FromStr for Environment {
    type Err = ConfigError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value.trim().to_ascii_lowercase().as_str() {
            "development" | "dev" | "local" => Ok(Self::Development),
            "test" | "testing" => Ok(Self::Test),
            "staging" | "stage" => Ok(Self::Staging),
            "production" | "prod" => Ok(Self::Production),
            _ => Err(ConfigError::InvalidEnvironment(value.to_string())),
        }
    }
}

impl fmt::Display for Environment {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let value = match self {
            Self::Development => "development",
            Self::Test => "test",
            Self::Staging => "staging",
            Self::Production => "production",
        };
        formatter.write_str(value)
    }
}

/// Strongly typed failures while loading Rullst configuration.
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConfigError {
    /// A configured environment name is not recognized.
    #[error("invalid Rullst environment `{0}`")]
    InvalidEnvironment(String),

    /// An environment variable contains non-Unicode data.
    #[error("environment variable `{0}` is not valid Unicode")]
    NonUnicodeEnvironmentVariable(String),

    /// A configuration file could not be read.
    #[error("failed to read Rullst configuration: {0}")]
    Read(String),

    /// TOML configuration is invalid.
    #[error("failed to parse Rullst configuration: {0}")]
    Parse(String),

    /// A security policy is malformed or would create an ambiguous exemption.
    #[error("invalid security configuration: {0}")]
    InvalidSecurityConfiguration(String),
}

fn read_environment_variable(name: &str) -> Result<Option<String>, ConfigError> {
    match std::env::var(name) {
        Ok(value) => Ok(Some(value)),
        Err(std::env::VarError::NotPresent) => Ok(None),
        Err(std::env::VarError::NotUnicode(_)) => {
            Err(ConfigError::NonUnicodeEnvironmentVariable(name.to_string()))
        }
    }
}

#[derive(Debug, Clone, Deserialize, Default)]
#[non_exhaustive]
/// Main configuration container for Rullst applications.
pub struct RullstConfig {
    #[serde(default)]
    /// General application settings.
    pub app: AppConfig,
    #[serde(default)]
    /// Database settings.
    pub database: DatabaseConfig,
    #[serde(default)]
    /// Security policies and configuration parameters.
    pub security: SecurityConfig,
    #[serde(default)]
    /// File storage settings.
    pub storage: StorageConfig,
}

#[derive(Debug, Clone, Deserialize, Default)]
#[non_exhaustive]
/// Configuration settings for storage drivers.
pub struct StorageConfig {
    /// The root directory for filesystem storage.
    pub root: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Default)]
#[non_exhaustive]
/// General configuration options for the application instance.
pub struct AppConfig {
    /// Environment profile of the application (e.g. "development", "production").
    pub env: Option<String>,
    /// The port number that the HTTP server will bind to.
    pub port: Option<u16>,
}

#[derive(Debug, Clone, Deserialize, Default)]
#[non_exhaustive]
/// Database connection configuration.
pub struct DatabaseConfig {
    /// Database connection URL (e.g., `sqlite://rullst.db`).
    pub url: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
/// Configuration options for application security layers.
pub struct SecurityConfig {
    /// SameSite policy for the CSRF cookie ("Lax", "Strict", or "None").
    #[serde(default = "default_same_site")]
    pub csrf_same_site: String,
    /// List of allowed origins for Cross-Origin Resource Sharing (CORS).
    #[serde(default)]
    pub cors_allow_origins: Vec<String>,
    /// Allow browser credentials only for the exact configured CORS origins.
    #[serde(default = "default_false")]
    pub cors_allow_credentials: bool,
    /// Content-Security-Policy (CSP) header value.
    #[serde(default = "default_csp")]
    pub csp: String,
    /// Cross-Origin-Embedder-Policy value. The strict default is `require-corp`;
    /// applications that deliberately embed reviewed credentialless cross-origin
    /// media can opt into `credentialless`, while `unsafe-none` must be an
    /// explicit application-level decision.
    #[serde(default = "default_coep")]
    pub coep: String,
    /// Case-insensitive User-Agent substrings to block in the WAF middleware.
    /// Defaults cover selected crawlers, not general HTTP clients or health probes.
    /// This forgeable header is a traffic preference, never authentication.
    #[serde(default = "default_user_agent_blocklist")]
    pub user_agent_blocklist: Vec<String>,
    /// Enable global automatic PII masking middleware on all textual responses (heavy performance cost).
    #[serde(default = "default_false")]
    pub enable_pii_masking: bool,
    /// Exact POST paths that are exempt from browser CSRF tokens because a mandatory signed
    /// webhook middleware authenticates them. Wildcards and route parameters are rejected.
    #[serde(default)]
    pub csrf_signed_webhook_paths: Vec<String>,
}

/// Strict default CSP template. `{NONCE}` is replaced by the secure headers middleware for each
/// request before the header is emitted.
pub const DEFAULT_CSP_TEMPLATE: &str = "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; script-src 'self' 'nonce-{NONCE}'; style-src 'self' 'nonce-{NONCE}'; img-src 'self' data:; connect-src 'self'; font-src 'self'; worker-src 'self' blob:";

fn default_csp() -> String {
    DEFAULT_CSP_TEMPLATE.to_string()
}

fn default_coep() -> String {
    "require-corp".to_string()
}

fn default_user_agent_blocklist() -> Vec<String> {
    vec![
        "gptbot".to_string(),
        "chatgpt-user".to_string(),
        "google-extended".to_string(),
        "anthropic-ai".to_string(),
        "claude-web".to_string(),
        "cohere-ai".to_string(),
        "bytespider".to_string(),
        "mj12bot".to_string(),
    ]
}

fn default_same_site() -> String {
    "Lax".to_string()
}

fn default_false() -> bool {
    false
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            csrf_same_site: default_same_site(),
            cors_allow_origins: vec![],
            cors_allow_credentials: false,
            csp: default_csp(),
            coep: default_coep(),
            user_agent_blocklist: default_user_agent_blocklist(),
            enable_pii_masking: false,
            csrf_signed_webhook_paths: Vec::new(),
        }
    }
}

impl SecurityConfig {
    /// Validates browser security policy and exact-path CSRF webhook exemptions.
    pub fn validate(&self) -> Result<(), ConfigError> {
        if !matches!(self.csrf_same_site.as_str(), "Lax" | "Strict" | "None") {
            return Err(ConfigError::InvalidSecurityConfiguration(format!(
                "CSRF SameSite policy `{}` must be Lax, Strict, or None",
                self.csrf_same_site
            )));
        }
        let rendered_csp = self.csp.replace("{NONCE}", "validation-nonce");
        if self.csp.trim().is_empty() || rendered_csp.parse::<http::HeaderValue>().is_err() {
            return Err(ConfigError::InvalidSecurityConfiguration(
                "CSP must be a non-empty valid HTTP header value".to_string(),
            ));
        }
        if !matches!(
            self.coep.as_str(),
            "require-corp" | "credentialless" | "unsafe-none"
        ) {
            return Err(ConfigError::InvalidSecurityConfiguration(format!(
                "COEP policy `{}` must be require-corp, credentialless, or unsafe-none",
                self.coep
            )));
        }
        let mut unique_origins = std::collections::HashSet::new();
        for origin in &self.cors_allow_origins {
            let uri = origin.parse::<http::Uri>().map_err(|_| {
                ConfigError::InvalidSecurityConfiguration(format!(
                    "CORS origin `{origin}` must be an exact HTTP(S) origin"
                ))
            })?;
            let valid_scheme = uri
                .scheme_str()
                .is_some_and(|scheme| matches!(scheme, "http" | "https"));
            let valid_origin = valid_scheme
                && uri.authority().is_some()
                && uri.path() == "/"
                && uri.query().is_none()
                && !origin.ends_with('/')
                && !origin.contains(['@', '#', '*'])
                && origin.parse::<http::HeaderValue>().is_ok();
            if !valid_origin {
                return Err(ConfigError::InvalidSecurityConfiguration(format!(
                    "CORS origin `{origin}` must be an exact HTTP(S) origin without path, query, credentials, wildcard, or trailing slash"
                )));
            }
            if !unique_origins.insert(origin) {
                return Err(ConfigError::InvalidSecurityConfiguration(format!(
                    "duplicate CORS origin `{origin}`"
                )));
            }
        }
        let mut unique_paths = std::collections::HashSet::new();
        for path in &self.csrf_signed_webhook_paths {
            let is_exact_absolute_path = path.starts_with('/')
                && path.len() > 1
                && !path.contains(['?', '#', '*', '{', '}', ':'])
                && !path
                    .split('/')
                    .any(|segment| segment == ".." || segment == ".");
            if !is_exact_absolute_path {
                return Err(ConfigError::InvalidSecurityConfiguration(format!(
                    "CSRF signed-webhook exemption `{path}` must be an exact absolute path"
                )));
            }
            if !unique_paths.insert(path) {
                return Err(ConfigError::InvalidSecurityConfiguration(format!(
                    "duplicate CSRF signed-webhook exemption `{path}`"
                )));
            }
        }
        Ok(())
    }
}

static GLOBAL_CONFIG: std::sync::OnceLock<RullstConfig> = std::sync::OnceLock::new();

impl RullstConfig {
    /// Gets the global configuration reference, initializing it with default values if not set.
    pub fn global() -> &'static RullstConfig {
        GLOBAL_CONFIG.get_or_init(Self::default)
    }

    /// Sets the global configuration instance.
    #[allow(clippy::result_large_err)]
    pub fn set_global(config: Self) -> Result<(), Self> {
        GLOBAL_CONFIG.set(config)
    }

    /// Creates a new `RullstConfig` with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Validates cross-field configuration invariants before any global state is published.
    pub fn validate(&self) -> Result<(), ConfigError> {
        self.security.validate()
    }

    /// Parses a complete `Rullst.toml` document.
    pub fn from_toml(content: &str) -> Result<Self, ConfigError> {
        toml::from_str(content).map_err(|error| ConfigError::Parse(error.to_string()))
    }

    /// Resolves the validated runtime environment for this configuration.
    pub fn environment(&self) -> Result<Environment, ConfigError> {
        Environment::detect(self.app.env.as_deref())
    }

    /// Loads and parses the configuration from a TOML file.
    #[cfg(not(target_arch = "wasm32"))]
    pub async fn load_from_file(path: &str) -> Result<Self, ConfigError> {
        let content = tokio::fs::read_to_string(path)
            .await
            .map_err(|error| ConfigError::Read(error.to_string()))?;
        Self::from_toml(&content)
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::field_reassign_with_default
)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_global_config_access() {
        let config1 = RullstConfig::global();
        let config2 = RullstConfig::global();
        assert!(
            std::ptr::eq(config1, config2),
            "global() should return the same instance"
        );
        assert_eq!(config1.security.csrf_same_site, "Lax");
    }

    #[tokio::test]
    async fn test_load_config_from_file() {
        let temp_dir = "test_config_dir";
        let _ = std::fs::create_dir_all(temp_dir);
        let path = format!("{}/Rullst.toml", temp_dir);

        let toml_content = r#"
[app]
env = "production"
port = 8080

[database]
url = "sqlite::memory:"

[security]
csrf_same_site = "Strict"
cors_allow_origins = ["https://example.com"]
"#;
        tokio::fs::write(&path, toml_content).await.unwrap();

        let config = RullstConfig::load_from_file(&path).await.unwrap();

        assert_eq!(config.app.env.unwrap(), "production");
        assert_eq!(config.app.port.unwrap(), 8080);
        assert_eq!(config.database.url.unwrap(), "sqlite::memory:");
        assert_eq!(config.security.csrf_same_site, "Strict");
        assert_eq!(config.security.cors_allow_origins.len(), 1);
        assert_eq!(config.security.cors_allow_origins[0], "https://example.com");
        assert!(!config.security.cors_allow_credentials);

        let _ = std::fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_default_security_config() {
        let config = SecurityConfig::default();
        assert_eq!(config.csrf_same_site, "Lax");
        assert_eq!(config.coep, "require-corp");
        assert!(config.csp.contains("default-src"));
        assert!(!config.csp.contains("unsafe-inline"));
        assert!(!config.csp.contains("unsafe-eval"));
        assert!(config.user_agent_blocklist.contains(&"gptbot".to_string()));
        assert!(config.csrf_signed_webhook_paths.is_empty());
    }

    #[test]
    fn test_set_global_config() {
        let mut config = RullstConfig::new();
        config.app.env = Some("test_env".to_string());
        let result = RullstConfig::set_global(config);
        match result {
            Ok(_) => assert_eq!(RullstConfig::global().app.env.as_deref(), Some("test_env")),
            Err(c) => assert_eq!(c.app.env.as_deref(), Some("test_env")),
        }
    }

    #[test]
    fn test_deserialize_security_config_defaults() {
        let config: SecurityConfig = toml::from_str("").unwrap();
        assert!(!config.enable_pii_masking);
        assert_eq!(config.coep, "require-corp");
    }

    #[test]
    fn environment_resolution_has_one_precedence_and_validated_aliases() {
        assert_eq!(
            Environment::resolve(Some("prod"), Some("test"), Some("development")).unwrap(),
            Environment::Production
        );
        assert_eq!(
            Environment::resolve(None, Some("STAGE"), Some("development")).unwrap(),
            Environment::Staging
        );
        assert_eq!(
            Environment::resolve(None, None, Some("testing")).unwrap(),
            Environment::Test
        );
        assert_eq!(
            Environment::resolve(None, None, None).unwrap(),
            Environment::Development
        );
        assert!(Environment::resolve(Some("unknown"), None, None).is_err());
    }

    #[test]
    fn only_development_exposes_developer_tools() {
        assert!(Environment::Development.allows_development_tools());
        assert!(!Environment::Test.allows_development_tools());
        assert!(Environment::Staging.requires_secure_defaults());
        assert!(Environment::Production.requires_secure_defaults());
    }

    #[test]
    fn signed_webhook_csrf_exemptions_must_be_exact_paths() {
        let mut config = SecurityConfig::default();
        config.csrf_signed_webhook_paths = vec!["/billing/webhook".to_owned()];
        assert!(config.validate().is_ok());

        for invalid in [
            "billing/webhook",
            "/billing/:provider",
            "/billing/{provider}",
            "/billing/*path",
            "/billing/../admin",
            "/billing/webhook?provider=x",
        ] {
            config.csrf_signed_webhook_paths = vec![invalid.to_owned()];
            assert!(config.validate().is_err(), "{invalid} must be rejected");
        }

        config.csrf_signed_webhook_paths =
            vec!["/billing/webhook".to_owned(), "/billing/webhook".to_owned()];
        assert!(config.validate().is_err());
    }

    #[test]
    fn browser_security_configuration_is_strict_and_exact() {
        let mut config = SecurityConfig::default();
        config.cors_allow_origins = vec![
            "https://academy.example".to_string(),
            "http://localhost:3000".to_string(),
        ];
        assert!(config.validate().is_ok());

        for invalid in [
            "*",
            "academy.example",
            "ftp://academy.example",
            "https://academy.example/",
            "https://academy.example/path",
            "https://user@academy.example",
            "https://academy.example?x=1",
        ] {
            config.cors_allow_origins = vec![invalid.to_string()];
            assert!(config.validate().is_err(), "{invalid} must be rejected");
        }
        config.cors_allow_origins = vec![
            "https://academy.example".to_string(),
            "https://academy.example".to_string(),
        ];
        assert!(config.validate().is_err());
        config.cors_allow_origins.clear();
        config.csrf_same_site = "relaxed".to_string();
        assert!(config.validate().is_err());
        config.csrf_same_site = "Lax".to_string();
        config.csp = "default-src 'self'\r\nx-injected: yes".to_string();
        assert!(config.validate().is_err());
    }

    #[test]
    fn coep_policy_is_explicit_and_closed() {
        let mut config = SecurityConfig::default();
        for policy in ["require-corp", "credentialless", "unsafe-none"] {
            config.coep = policy.to_string();
            assert!(config.validate().is_ok(), "{policy} must be accepted");
        }
        for invalid in ["", "off", "cross-origin", "require-corp\nunsafe-none"] {
            config.coep = invalid.to_string();
            assert!(config.validate().is_err(), "{invalid:?} must be rejected");
        }
    }
}