product-os-server 0.0.55

Product OS : Server provides a full functioning advanced server capable of acting as a web server, command and control distributed network, authentication server, crawling server and more. Fully featured with high level of flexibility.
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
//! Module Tests
//!
//! Unit tests for internal server modules including certificates, configuration,
//! and server setup verification.

#![cfg(feature = "executor_tokio")]

use product_os_server::{ProductOSServer, Body};
use product_os_async_executor::TokioExecutor;
use product_os_server::{ServerConfig, Certificate, CertificateFilesKind};
use product_os_security::Security;

// =============================================================================
// Certificate Configuration Tests
// =============================================================================

/// Test server creation with no certificate configuration (self-signed)
#[tokio::test]
async fn test_certificate_none_generates_self_signed() {
    let mut config = ServerConfig::new();
    config.certificate = None;
    
    let _server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
    // Server should initialize with auto-generated self-signed certificate
}

/// Test server creation with explicit self-signed certificate type
#[tokio::test]
async fn test_certificate_self_signed_explicit() {
    let mut config = ServerConfig::new();
    config.certificate = Some(Certificate {
        file_kind: Some(CertificateFilesKind::SelfSigned),
        files: None,
        entries: None,
        names: Some(vec!["localhost".to_string(), "127.0.0.1".to_string()]),
        serial: None,
        valid_for: None,
    });
    
    let _server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
}

/// Test certificate with custom subject entries
#[tokio::test]
async fn test_certificate_with_entries() {
    use serde_json::json;
    
    let mut config = ServerConfig::new();
    
    let entries = vec![
        serde_json::from_value(json!({"CN": "Test Server"})).unwrap(),
        serde_json::from_value(json!({"O": "Test Organization"})).unwrap(),
    ];
    
    config.certificate = Some(Certificate {
        file_kind: Some(CertificateFilesKind::SelfSigned),
        files: None,
        entries: Some(entries),
        names: Some(vec!["test.local".to_string()]),
        serial: Some(12345),
        valid_for: Some(365),
    });
    
    let _server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
}

/// Test certificate configuration can be updated after server creation
#[cfg(feature = "security_certificates")]
#[tokio::test]
async fn test_certificate_update_after_creation() {
    let config = ServerConfig::new();
    let mut server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
    
    // Update to a new certificate configuration
    let new_cert = Certificate {
        file_kind: Some(CertificateFilesKind::SelfSigned),
        files: None,
        entries: None,
        names: Some(vec!["updated.local".to_string()]),
        serial: None,
        valid_for: Some(30),
    };
    
    server.set_certificate(&Some(new_cert));
}

/// Test CA certificate fallback when files not provided
#[tokio::test]
async fn test_certificate_ca_without_files_fallback() {
    let mut config = ServerConfig::new();
    config.certificate = Some(Certificate {
        file_kind: Some(CertificateFilesKind::CA),
        files: None, // No files provided, should fall back to self-signed
        entries: None,
        names: Some(vec!["ca-fallback.local".to_string()]),
        serial: None,
        valid_for: None,
    });
    
    let _server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
    // Should succeed by falling back to self-signed
}

// =============================================================================
// Security Configuration Tests
// =============================================================================

/// Test server with security enabled
#[tokio::test]
async fn test_security_enabled() {
    let mut config = ServerConfig::new();
    config.security = Some(serde_json::to_value(Security {
        enable: true,
        csrf: false,
        csp: None,
    }).unwrap());
    
    let _server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
}

/// Test server with security disabled
#[tokio::test]
async fn test_security_disabled() {
    let mut config = ServerConfig::new();
    config.security = Some(serde_json::to_value(Security {
        enable: false,
        csrf: false,
        csp: None,
    }).unwrap());
    
    let _server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
}

/// Test security can be set after server creation
#[tokio::test]
async fn test_security_set_after_creation() {
    let config = ServerConfig::new();
    let mut server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
    
    server.set_security(Some(Security {
        enable: true,
        csrf: false,
        csp: None,
    }));
    
    server.set_security(None);
}

// =============================================================================
// CSRF Feature Tests
// =============================================================================

#[cfg(feature = "csrf")]
mod csrf_tests {
    use super::*;
    
    /// Test CSRF protection can be enabled
    #[tokio::test]
    async fn test_csrf_enabled() {
        let mut config = ServerConfig::new();
        config.security = Some(serde_json::to_value(Security {
            enable: true,
            csrf: true,
            csp: None,
        }).unwrap());
        
        let _server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
    }
    
    /// Test CSRF can be toggled via set_security
    #[tokio::test]
    async fn test_csrf_toggle() {
        let config = ServerConfig::new();
        let mut server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
        
        // Enable CSRF
        server.set_security(Some(Security {
            enable: true,
            csrf: true,
            csp: None,
        }));
        
        // Disable CSRF but keep security
        server.set_security(Some(Security {
            enable: true,
            csrf: false,
            csp: None,
        }));
    }
}

// =============================================================================
// CSP Feature Tests
// =============================================================================

#[cfg(feature = "cspolicy")]
mod csp_tests {
    use super::*;
    use product_os_security::CSPConfig;
    
    /// Test server with CSP configuration
    #[tokio::test]
    async fn test_csp_configuration() {
        let mut config = ServerConfig::new();
        config.security = Some(serde_json::to_value(Security {
            enable: true,
            csrf: false,
            csp: None,
        }).unwrap());
        
        // CSP is automatically applied when security is enabled
        let _server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
    }
    
    /// Test server with custom CSP directives
    #[tokio::test]
    async fn test_csp_with_custom_directives() {
        let mut config = ServerConfig::new();
        
        // Set custom CSP configuration
        let mut csp = CSPConfig::default();
        csp.default_src = Some(vec!["self".to_string()]);
        csp.script_src = Some(vec!["self".to_string(), "https://trusted.com".to_string()]);
        csp.style_src = Some(vec!["self".to_string()]);
        csp.img_src = Some(vec!["self".to_string(), "data:".to_string()]);
        
        config.security = Some(serde_json::to_value(Security {
            enable: true,
            csrf: false,
            csp: Some(csp),
        }).unwrap());
        
        let _server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
    }
}

// =============================================================================
// Compression Feature Tests
// =============================================================================

#[cfg(feature = "compression")]
mod compression_tests {
    use super::*;
    use product_os_server::Compression;
    
    /// Test gzip-only compression
    #[tokio::test]
    async fn test_compression_gzip_only() {
        let config = ServerConfig::new();
        let mut server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
        
        server.set_compression(Some(Compression {
            enable: true,
            gzip: true,
            deflate: false,
            brotli: false,
        }));
    }
    
    /// Test deflate-only compression
    #[tokio::test]
    async fn test_compression_deflate_only() {
        let config = ServerConfig::new();
        let mut server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
        
        server.set_compression(Some(Compression {
            enable: true,
            gzip: false,
            deflate: true,
            brotli: false,
        }));
    }
    
    /// Test brotli-only compression
    #[tokio::test]
    async fn test_compression_brotli_only() {
        let config = ServerConfig::new();
        let mut server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
        
        server.set_compression(Some(Compression {
            enable: true,
            gzip: false,
            deflate: false,
            brotli: true,
        }));
    }
    
    /// Test compression disabled flag
    #[tokio::test]
    async fn test_compression_disabled_with_flag() {
        let config = ServerConfig::new();
        let mut server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
        
        server.set_compression(Some(Compression {
            enable: false,
            gzip: true,
            deflate: true,
            brotli: true,
        }));
        // Even though algorithms are set to true, enable: false should skip compression
    }
}

// =============================================================================
// TLS Feature Tests
// =============================================================================

#[cfg(feature = "tls")]
mod tls_tests {
    use super::*;
    
    /// Test TLS server can be created
    #[tokio::test]
    async fn test_tls_server_creation() {
        let mut config = ServerConfig::new();
        config.network.port = 8443;
        config.network.secure = true;
        
        let _server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
    }
    
    /// Test TLS with custom certificate names
    #[tokio::test]
    async fn test_tls_custom_certificate_names() {
        let mut config = ServerConfig::new();
        config.certificate = Some(Certificate {
            file_kind: Some(CertificateFilesKind::SelfSigned),
            files: None,
            entries: None,
            names: Some(vec![
                "localhost".to_string(),
                "127.0.0.1".to_string(),
                "::1".to_string(),
                "my-app.local".to_string(),
            ]),
            serial: None,
            valid_for: Some(90),
        });
        
        let _server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
    }
}

// =============================================================================
// Dual Server Feature Tests
// =============================================================================

#[cfg(feature = "dual_server")]
mod dual_server_tests {
    use super::*;
    
    /// Test dual server feature compiles correctly
    #[tokio::test]
    async fn test_dual_server_feature_available() {
        let config = ServerConfig::new();
        let _server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
    }
}

// =============================================================================
// Network Configuration Tests
// =============================================================================

/// Test insecure port configuration
#[tokio::test]
async fn test_network_insecure_port_config() {
    let mut config = ServerConfig::new();
    config.network.allow_insecure = true;
    config.network.insecure_port = 8080;
    config.network.insecure_use_different_port = true;
    config.network.insecure_force_secure = false;
    
    let _server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
}

/// Test force secure redirect configuration
#[tokio::test]
async fn test_network_force_secure_config() {
    let mut config = ServerConfig::new();
    config.network.allow_insecure = true;
    config.network.insecure_force_secure = true;
    
    let _server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
}

/// Test listen all interfaces configuration
#[tokio::test]
async fn test_network_listen_all_interfaces() {
    let mut config = ServerConfig::new();
    config.network.listen_all_interfaces = true;
    config.network.host = "0.0.0.0".to_string();
    
    let _server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
}

/// Test custom host and port configuration
#[tokio::test]
async fn test_network_custom_host_port() {
    let mut config = ServerConfig::new();
    config.network.host = "localhost".to_string();
    config.network.port = 9000;
    config.network.protocol = "http".to_string();
    
    let server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config.clone());
    
    // Verify the config was applied
    let retrieved_config = server.get_config();
    assert_eq!(retrieved_config.network.host, "localhost");
    assert_eq!(retrieved_config.network.port, 9000);
}

// =============================================================================
// Router and Handler Tests
// =============================================================================

/// Test adding multiple routes with different paths
#[tokio::test]
async fn test_router_multiple_paths() {
    use product_os_server::{StatusCode, Response};
    
    let config = ServerConfig::new();
    let mut server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
    
    async fn handler() -> Result<Response<Body>, StatusCode> {
        Ok(Response::new(Body::empty()))
    }
    
    server.add_get("/", handler);
    server.add_get("/api", handler);
    server.add_get("/api/v1", handler);
    server.add_get("/api/v1/users", handler);
    server.add_get("/api/v1/users/:id", handler);
}

/// Test adding handlers for all HTTP methods (using different paths to avoid collision)
#[tokio::test]
async fn test_router_all_methods() {
    use product_os_server::{StatusCode, Response, Method};
    
    let config = ServerConfig::new();
    let mut server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
    
    async fn handler() -> Result<Response<Body>, StatusCode> {
        Ok(Response::new(Body::empty()))
    }
    
    // Use different paths for each method to avoid route collision
    server.add_handler("/resource/get", Method::GET, handler);
    server.add_handler("/resource/post", Method::POST, handler);
    server.add_handler("/resource/put", Method::PUT, handler);
    server.add_handler("/resource/patch", Method::PATCH, handler);
    server.add_handler("/resource/delete", Method::DELETE, handler);
    server.add_handler("/resource/head", Method::HEAD, handler);
    server.add_handler("/resource/options", Method::OPTIONS, handler);
    server.add_handler("/resource/trace", Method::TRACE, handler);
}

/// Test router replacement
#[tokio::test]
async fn test_router_replace() {
    use product_os_server::ProductOSRouter;
    
    let config = ServerConfig::new();
    let mut server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
    
    let new_router = ProductOSRouter::new();
    server.set_router(new_router);
}

// =============================================================================
// Stateful Server Tests
// =============================================================================

/// Test server with complex shared state
#[tokio::test]
async fn test_stateful_server_complex_state() {
    use std::sync::Arc;
    use parking_lot::Mutex;
    use std::collections::HashMap;
    
    #[derive(Clone)]
    #[allow(dead_code)]
    struct ComplexState {
        counter: Arc<Mutex<i32>>,
        cache: Arc<Mutex<HashMap<String, String>>>,
        name: String,
    }
    
    let state = ComplexState {
        counter: Arc::new(Mutex::new(0)),
        cache: Arc::new(Mutex::new(HashMap::new())),
        name: "TestServer".to_string(),
    };
    
    let config = ServerConfig::new();
    let _server: ProductOSServer<ComplexState, TokioExecutor, _> = 
        ProductOSServer::new_with_state_with_config(config, state.clone());
    
    // Verify state is still accessible and mutable
    *state.counter.lock() += 10;
    state.cache.lock().insert("key".to_string(), "value".to_string());
    
    assert_eq!(*state.counter.lock(), 10);
    assert_eq!(state.cache.lock().get("key"), Some(&"value".to_string()));
}

/// Test server with state using new_with_state constructor
#[tokio::test]
async fn test_stateful_server_simple_constructor() {
    #[derive(Clone)]
    #[allow(dead_code)]
    struct SimpleState {
        value: i32,
    }
    
    let state = SimpleState { value: 42 };
    let _server: ProductOSServer<SimpleState, TokioExecutor, _> = 
        ProductOSServer::new_with_state(state);
}

// =============================================================================
// Error Type Tests
// =============================================================================

/// Test error type variants are accessible
#[test]
fn test_error_types() {
    use product_os_server::ProductOSServerError;
    
    let generic = ProductOSServerError::GenericError("test".to_string());
    let init = ProductOSServerError::InitializationError { 
        reason: "test reason".to_string() 
    };
    let config = ProductOSServerError::ConfigurationError { 
        component: "network".to_string(), 
        message: "invalid port".to_string() 
    };
    let cert = ProductOSServerError::CertificateError { 
        message: "invalid cert".to_string() 
    };
    let exec = ProductOSServerError::ExecutorError { 
        message: "spawn failed".to_string() 
    };
    let timeout = ProductOSServerError::Timeout { 
        operation: "lock acquisition".to_string() 
    };
    let lock = ProductOSServerError::LockError { 
        resource: "controller".to_string() 
    };
    
    // Verify Display trait works
    assert!(!format!("{}", generic).is_empty());
    assert!(!format!("{}", init).is_empty());
    assert!(!format!("{}", config).is_empty());
    assert!(!format!("{}", cert).is_empty());
    assert!(!format!("{}", exec).is_empty());
    assert!(!format!("{}", timeout).is_empty());
    assert!(!format!("{}", lock).is_empty());
}

// =============================================================================
// Controller Feature Tests
// =============================================================================

#[cfg(feature = "controller")]
mod controller_tests {
    use super::*;
    use product_os_server::ProductOSServerError;
    
    /// Test controller error variant
    #[tokio::test]
    async fn test_controller_error_type() {
        let controller_err = ProductOSServerError::ControllerError {
            operation: "add_feature".to_string(),
            message: "feature not found".to_string(),
        };
        
        assert!(!format!("{}", controller_err).is_empty());
    }
    
    /// Test store error variant
    #[tokio::test]
    async fn test_store_error_type() {
        let store_err = ProductOSServerError::StoreError {
            store_type: "key-value".to_string(),
            message: "connection failed".to_string(),
        };
        
        assert!(!format!("{}", store_err).is_empty());
    }
    
    /// Test controller can be set to None
    #[tokio::test]
    async fn test_controller_set_none() {
        let config = ServerConfig::new();
        let mut server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
        
        server.set_controller(None);
    }
}

// =============================================================================
// Logging Tests
// =============================================================================

/// Test logging level can be changed multiple times
#[tokio::test]
async fn test_logging_level_changes_multiple() {
    let config = ServerConfig::new();
    let mut server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
    
    // Test various log levels
    server.set_logging(tracing::Level::TRACE);
    server.set_logging(tracing::Level::DEBUG);
    server.set_logging(tracing::Level::INFO);
    server.set_logging(tracing::Level::WARN);
    server.set_logging(tracing::Level::ERROR);
}

// =============================================================================
// WebSocket Feature Tests
// =============================================================================

#[cfg(feature = "ws")]
mod websocket_tests {
    use super::*;
    use product_os_server::{StatusCode, Response};
    
    /// Test WebSocket handler can be added at multiple paths
    #[tokio::test]
    async fn test_ws_multiple_endpoints() {
        let config = ServerConfig::new();
        let mut server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
        
        async fn ws_handler() -> Result<Response<Body>, StatusCode> {
            Ok(Response::new(Body::empty()))
        }
        
        server.add_ws_handler("/ws", ws_handler);
        server.add_ws_handler("/ws/chat", ws_handler);
        server.add_ws_handler("/ws/notifications", ws_handler);
    }
}

// =============================================================================
// SSE Feature Tests
// =============================================================================

#[cfg(feature = "sse")]
mod sse_tests {
    use super::*;
    use product_os_server::{StatusCode, Response};
    
    /// Test SSE handler can be added at multiple paths
    #[tokio::test]
    async fn test_sse_multiple_endpoints() {
        let config = ServerConfig::new();
        let mut server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
        
        async fn sse_handler() -> Result<Response<Body>, StatusCode> {
            Ok(Response::new(Body::empty()))
        }
        
        server.add_sse_handler("/events", sse_handler);
        server.add_sse_handler("/events/updates", sse_handler);
        server.add_sse_handler("/events/notifications", sse_handler);
    }
}

// =============================================================================
// CORS Feature Tests
// =============================================================================

#[cfg(feature = "cors")]
mod cors_tests {
    use super::*;
    use product_os_server::{StatusCode, Response, Method};
    
    /// Test CORS handler with multiple methods
    #[tokio::test]
    async fn test_cors_multiple_methods() {
        let config = ServerConfig::new();
        let mut server: ProductOSServer<(), TokioExecutor, _> = ProductOSServer::new_with_config(config);
        
        async fn cors_handler() -> Result<Response<Body>, StatusCode> {
            Ok(Response::new(Body::empty()))
        }
        
        server.add_cors_handler("/api/resource", Method::GET, cors_handler);
        server.add_cors_handler("/api/resource", Method::POST, cors_handler);
        server.add_cors_handler("/api/resource", Method::PUT, cors_handler);
        server.add_cors_handler("/api/resource", Method::DELETE, cors_handler);
    }
}