somnytoo 2.0.0

Binary protocol server for secure communications
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
use dotenv::dotenv;
use serde::{Deserialize, Serialize};
use std::env;
use std::net::IpAddr;
use std::time::Duration;

/// Конфигурация фантомной криптосистемы
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct PhantomConfig {
    pub enabled: bool,
    pub session_timeout_ms: u64,
    pub max_sessions: usize,
    pub enable_hardware_acceleration: bool,
    pub constant_time_enforced: bool,
    pub hardware_auth_enabled: bool,
    pub hardware_secret_key: String,
    pub enable_emulation_detection: bool,
    pub min_session_lifetime_ms: u64,
    pub max_operations_per_session: u64,
    pub assembler_type: String, // "auto", "avx2", "neon", "generic"
}

impl Default for PhantomConfig {
    fn default() -> Self {
        dotenv().ok();

        Self {
            enabled: env::var("PHANTOM_ENABLED")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(true),
            session_timeout_ms: env::var("PHANTOM_SESSION_TIMEOUT_MS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(90_000),
            max_sessions: env::var("PHANTOM_MAX_SESSIONS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(100_000),
            enable_hardware_acceleration: env::var("PHANTOM_HW_ACCELERATION")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(true),
            constant_time_enforced: env::var("PHANTOM_CONSTANT_TIME")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(true),
            hardware_auth_enabled: env::var("HARDWARE_AUTH_ENABLED")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(false),
            hardware_secret_key: env::var("HARDWARE_SECRET_KEY")
                .unwrap_or_else(|_| "".to_string()),
            enable_emulation_detection: env::var("ENABLE_EMULATION_DETECTION")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(true),
            min_session_lifetime_ms: env::var("PHANTOM_MIN_SESSION_LIFETIME_MS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(10_000),
            max_operations_per_session: env::var("PHANTOM_MAX_OPERATIONS_PER_SESSION")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(1_000_000),
            assembler_type: env::var("PHANTOM_ASSEMBLER_TYPE")
                .unwrap_or_else(|_| "auto".to_string()),
        }
    }
}

impl PhantomConfig {
    pub fn from_env() -> Self {
        Self::default()
    }

    pub fn validate(&self) -> Result<(), ConfigError> {
        if self.session_timeout_ms < self.min_session_lifetime_ms {
            return Err(ConfigError::InvalidPhantomConfig(
                format!("session_timeout_ms ({}) must be greater than min_session_lifetime_ms ({})",
                        self.session_timeout_ms, self.min_session_lifetime_ms)
            ));
        }

        if self.max_sessions > 1_000_000 {
            return Err(ConfigError::InvalidPhantomConfig(
                "max_sessions cannot exceed 1,000,000".to_string()
            ));
        }

        if self.session_timeout_ms == 0 {
            return Err(ConfigError::InvalidPhantomConfig(
                "session_timeout_ms cannot be zero".to_string()
            ));
        }

        if self.hardware_auth_enabled && self.hardware_secret_key.is_empty() {
            return Err(ConfigError::MissingSecretKey(
                "HARDWARE_SECRET_KEY must be set when hardware_auth_enabled is true".to_string()
            ));
        }

        let valid_assembler_types = ["auto", "avx2", "neon", "generic"];
        if !valid_assembler_types.contains(&self.assembler_type.as_str()) {
            return Err(ConfigError::InvalidPhantomConfig(
                format!("assembler_type must be one of: {:?}", valid_assembler_types)
            ));
        }

        if self.min_session_lifetime_ms < 1000 {
            return Err(ConfigError::InvalidPhantomConfig(
                "min_session_lifetime_ms must be at least 1000ms".to_string()
            ));
        }

        Ok(())
    }

    pub fn get_session_timeout(&self) -> Duration {
        Duration::from_millis(self.session_timeout_ms)
    }

    pub fn get_min_session_lifetime(&self) -> Duration {
        Duration::from_millis(self.min_session_lifetime_ms)
    }

    pub fn should_use_hardware_auth(&self) -> bool {
        self.enabled && self.hardware_auth_enabled
    }

    pub fn get_assembler_type(&self) -> &str {
        &self.assembler_type
    }

    pub fn test_config() -> Self {
        Self {
            enabled: true,
            session_timeout_ms: 30_000,
            max_sessions: 10_000,
            enable_hardware_acceleration: true,
            constant_time_enforced: true,
            hardware_auth_enabled: false,
            hardware_secret_key: "".to_string(),
            enable_emulation_detection: true,
            min_session_lifetime_ms: 5_000,
            max_operations_per_session: 100_000,
            assembler_type: "auto".to_string(),
        }
    }
}

/// Структура конфигурации сервера
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ServerConfig {
    pub host: String,
    pub port: u16,
}

impl ServerConfig {
    /// Загружает конфигурацию из .env файла или переменных окружения
    pub fn from_env() -> Self {
        // Загружаем .env файл (если он есть)
        dotenv().ok();

        // Получаем переменные окружения
        let host = env::var("SERVER_HOST").unwrap_or_else(|_| "0.0.0.0".to_string());
        let port_str = env::var("SERVER_PORT").unwrap_or_else(|_| "8000".to_string());
        let port = port_str.parse::<u16>().unwrap_or(8000);

        // let hmac_secret_key = env::var("HMAC_SECRET_KEY")
        //     .expect("Переменная HMAC_SECRET_KEY не установлена в .env файле");
        // let aes_secret_key = env::var("AES_SECRET_KEY")
        //     .expect("Переменная AES_SECRET_KEY не установлена в .env файле");
        // let psk_secret = env::var("PSK_SECRET")
        //     .expect("Переменная PSK_SECRET не установлена в .env файле");

        ServerConfig {
            host,
            port,
        }
    }

    /// Возвращает строку адреса в виде "0.0.0.0:8000"
    pub fn get_addr(&self) -> String {
        format!("{}:{}", self.host, self.port)
    }
}

pub fn database_url() -> String {
    dotenv().ok();
    env::var("DATABASE_URL").expect("DATABASE_URL must be set in .env file")
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct DatabaseConfig {
    pub primary_url: String,
    pub replica_urls: Vec<String>,
    pub max_connections: u32,
    pub min_connections: u32,
    pub connection_timeout: u64,
    pub acquire_timeout: u64,
    pub idle_timeout: u64,
    pub max_lifetime: u64,
    pub statement_cache_size: usize,
    pub connect_retries: u32,
}

impl Default for DatabaseConfig {
    fn default() -> Self {
        // Используем DATABASE_URL из .env файла
        let db_url = database_url();

        Self {
            primary_url: db_url,
            replica_urls: Vec::new(),
            max_connections: env::var("DB_MAX_CONNECTIONS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(50),
            min_connections: env::var("DB_MIN_CONNECTIONS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(10),
            connection_timeout: env::var("DB_CONNECTION_TIMEOUT")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(30),
            acquire_timeout: env::var("DB_ACQUIRE_TIMEOUT")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(5),
            idle_timeout: env::var("DB_IDLE_TIMEOUT")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(300),
            max_lifetime: env::var("DB_MAX_LIFETIME")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(1800),
            statement_cache_size: env::var("DB_STATEMENT_CACHE_SIZE")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(1000),
            connect_retries: env::var("DB_CONNECT_RETRIES")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(3),
        }
    }
}

impl DatabaseConfig {
    pub fn from_env() -> Self {
        Self::default()
    }

    pub fn validate(&self) -> Result<(), ConfigError> {
        if self.max_connections < self.min_connections {
            return Err(ConfigError::InvalidConnectionPoolSize);
        }

        if self.primary_url.is_empty() {
            return Err(ConfigError::MissingPrimaryUrl);
        }

        if !self.primary_url.starts_with("postgres://") &&
            !self.primary_url.starts_with("postgresql://") {
            return Err(ConfigError::InvalidUrlFormat);
        }

        if self.connection_timeout == 0 {
            return Err(ConfigError::InvalidTimeout("connection_timeout cannot be zero".to_string()));
        }

        if self.acquire_timeout == 0 {
            return Err(ConfigError::InvalidTimeout("acquire_timeout cannot be zero".to_string()));
        }

        if self.max_connections > 1000 {
            return Err(ConfigError::PoolSizeTooLarge);
        }

        if self.statement_cache_size > 10000 {
            return Err(ConfigError::CacheSizeTooLarge);
        }

        Ok(())
    }

    pub fn get_connection_timeout(&self) -> Duration {
        Duration::from_secs(self.connection_timeout)
    }

    pub fn get_acquire_timeout(&self) -> Duration {
        Duration::from_secs(self.acquire_timeout)
    }

    pub fn get_idle_timeout(&self) -> Duration {
        Duration::from_secs(self.idle_timeout)
    }

    pub fn get_max_lifetime(&self) -> Duration {
        Duration::from_secs(self.max_lifetime)
    }

    pub fn test_config() -> Self {
        Self {
            primary_url: "postgres://test:test@localhost/test".to_string(),
            max_connections: 10,
            min_connections: 2,
            connect_retries: 1,
            ..Default::default()
        }
    }
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct SecurityConfig {
    pub max_requests_per_minute: usize,
    pub query_timeout_ms: u64,
    pub max_query_length: usize,
    pub allowed_tables: Vec<String>,
    pub blocked_ips: Vec<IpAddr>,
    pub enable_sql_injection_protection: bool,
    pub enable_rate_limiting: bool,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        dotenv().ok();

        Self {
            max_requests_per_minute: env::var("MAX_REQUESTS_PER_MINUTE")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(1000),
            query_timeout_ms: env::var("QUERY_TIMEOUT_MS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(5000),
            max_query_length: env::var("MAX_QUERY_LENGTH")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(1024 * 1024),
            allowed_tables: Vec::new(),
            blocked_ips: Vec::new(),
            enable_sql_injection_protection: env::var("ENABLE_SQL_INJECTION_PROTECTION")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(true),
            enable_rate_limiting: env::var("ENABLE_RATE_LIMITING")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(true),
        }
    }
}

impl SecurityConfig {
    pub fn from_env() -> Self {
        Self::default()
    }

    pub fn validate(&self) -> Result<(), ConfigError> {
        if self.max_query_length > 10 * 1024 * 1024 {
            return Err(ConfigError::QueryTooLongLimit);
        }

        if self.query_timeout_ms == 0 {
            return Err(ConfigError::InvalidTimeout("query_timeout_ms cannot be zero".to_string()));
        }

        if self.max_requests_per_minute > 1_000_000 {
            return Err(ConfigError::RateLimitTooHigh);
        }

        Ok(())
    }

    pub fn get_query_timeout(&self) -> Duration {
        Duration::from_millis(self.query_timeout_ms)
    }

    pub fn is_table_allowed(&self, table: &str) -> bool {
        self.allowed_tables.is_empty() || self.allowed_tables.iter().any(|t| t == table)
    }

    pub fn is_ip_blocked(&self, ip: &IpAddr) -> bool {
        self.blocked_ips.contains(ip)
    }
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct ScalingConfig {
    pub enable_auto_scaling: bool,
    pub max_replicas: usize,
    pub scale_up_cpu_threshold: f64,
    pub scale_down_cpu_threshold: f64,
    pub scale_up_connections_threshold: usize,
    pub scale_check_interval_seconds: u64,
    pub min_replicas: usize,
}

impl Default for ScalingConfig {
    fn default() -> Self {
        dotenv().ok();

        Self {
            enable_auto_scaling: env::var("ENABLE_AUTO_SCALING")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(true),
            max_replicas: env::var("MAX_REPLICAS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(10),
            scale_up_cpu_threshold: env::var("SCALE_UP_CPU_THRESHOLD")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(80.0),
            scale_down_cpu_threshold: env::var("SCALE_DOWN_CPU_THRESHOLD")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(30.0),
            scale_up_connections_threshold: env::var("SCALE_UP_CONNECTIONS_THRESHOLD")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(1000),
            scale_check_interval_seconds: env::var("SCALE_CHECK_INTERVAL_SECONDS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(60),
            min_replicas: env::var("MIN_REPLICAS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(1),
        }
    }
}

impl ScalingConfig {
    pub fn from_env() -> Self {
        Self::default()
    }

    pub fn validate(&self) -> Result<(), ConfigError> {
        if self.max_replicas < self.min_replicas {
            return Err(ConfigError::InvalidScalingConfig(
                "max_replicas cannot be less than min_replicas".to_string()
            ));
        }

        if self.scale_up_cpu_threshold <= self.scale_down_cpu_threshold {
            return Err(ConfigError::InvalidScalingConfig(
                "scale_up_cpu_threshold must be greater than scale_down_cpu_threshold".to_string()
            ));
        }

        if self.scale_up_cpu_threshold > 100.0 || self.scale_down_cpu_threshold < 0.0 {
            return Err(ConfigError::InvalidScalingConfig(
                "CPU thresholds must be between 0 and 100".to_string()
            ));
        }

        if self.scale_check_interval_seconds == 0 {
            return Err(ConfigError::InvalidScalingConfig(
                "scale_check_interval_seconds cannot be zero".to_string()
            ));
        }

        Ok(())
    }

    pub fn get_scale_check_interval(&self) -> Duration {
        Duration::from_secs(self.scale_check_interval_seconds)
    }
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct CacheConfig {
    pub enable_query_cache: bool,
    pub query_cache_size: usize,
    pub query_cache_ttl_seconds: u64,
    pub enable_prepared_statements: bool,
    pub prepared_statements_cache_size: usize,
}

impl Default for CacheConfig {
    fn default() -> Self {
        dotenv().ok();

        Self {
            enable_query_cache: env::var("ENABLE_QUERY_CACHE")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(true),
            query_cache_size: env::var("QUERY_CACHE_SIZE")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(10000),
            query_cache_ttl_seconds: env::var("QUERY_CACHE_TTL_SECONDS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(300),
            enable_prepared_statements: env::var("ENABLE_PREPARED_STATEMENTS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(true),
            prepared_statements_cache_size: env::var("PREPARED_STATEMENTS_CACHE_SIZE")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(1000),
        }
    }
}

impl CacheConfig {
    pub fn from_env() -> Self {
        Self::default()
    }

    pub fn validate(&self) -> Result<(), ConfigError> {
        if self.query_cache_size > 100_000 {
            return Err(ConfigError::CacheSizeTooLarge);
        }

        if self.prepared_statements_cache_size > 10_000 {
            return Err(ConfigError::CacheSizeTooLarge);
        }

        Ok(())
    }

    pub fn get_query_cache_ttl(&self) -> Duration {
        Duration::from_secs(self.query_cache_ttl_seconds)
    }
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct AppConfig {
    pub database: DatabaseConfig,
    pub security: SecurityConfig,
    pub scaling: ScalingConfig,
    pub cache: CacheConfig,
    pub phantom: PhantomConfig,
    pub log_level: String,
    pub server: ServerConfig,
}

impl Default for AppConfig {
    fn default() -> Self {
        dotenv().ok();

        Self {
            database: DatabaseConfig::from_env(),
            security: SecurityConfig::from_env(),
            scaling: ScalingConfig::from_env(),
            cache: CacheConfig::from_env(),
            phantom: PhantomConfig::from_env(),
            log_level: env::var("LOG_LEVEL").unwrap_or_else(|_| "info".to_string()),
            server: ServerConfig::from_env(),
        }
    }
}

impl AppConfig {
    pub fn from_env() -> Self {
        Self::default()
    }

    pub fn validate(&self) -> Result<(), ConfigError> {
        self.database.validate()?;
        self.security.validate()?;
        self.scaling.validate()?;
        self.cache.validate()?;
        self.phantom.validate()?;

        let valid_log_levels = ["error", "warn", "info", "debug", "trace"];
        if !valid_log_levels.contains(&self.log_level.as_str()) {
            return Err(ConfigError::InvalidLogLevel(self.log_level.clone()));
        }

        Ok(())
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
    #[error("Invalid connection pool size")]
    InvalidConnectionPoolSize,
    #[error("Missing primary database URL")]
    MissingPrimaryUrl,
    #[error("Invalid database URL format")]
    InvalidUrlFormat,
    #[error("Query length limit too high")]
    QueryTooLongLimit,
    #[error("Invalid timeout: {0}")]
    InvalidTimeout(String),
    #[error("Pool size too large")]
    PoolSizeTooLarge,
    #[error("Cache size too large")]
    CacheSizeTooLarge,
    #[error("Rate limit too high")]
    RateLimitTooHigh,
    #[error("Invalid scaling configuration: {0}")]
    InvalidScalingConfig(String),
    #[error("Invalid log level: {0}")]
    InvalidLogLevel(String),
    #[error("Missing secret key: {0}")]
    MissingSecretKey(String),
    #[error("Invalid phantom configuration: {0}")]
    InvalidPhantomConfig(String),
}