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
use crate::;
pub use crate;
/// Builtin Shield Middleware
///
/// This middleware provides comprehensive HTTP security header protection for web applications.
/// It automatically sets various security headers that help protect against common web vulnerabilities
/// including XSS attacks, clickjacking, content sniffing, MIME type confusion, and other security threats.
/// The middleware is highly configurable, allowing you to customize each security feature according
/// to your application's specific requirements while maintaining secure defaults.
///
/// ## Features
///
/// * **Content Security Policy (CSP)** - Prevents XSS and data injection attacks
/// * **HTTP Strict Transport Security (HSTS)** - Forces HTTPS connections and prevents downgrade attacks
/// * **X-Frame-Options (Frameguard)** - Prevents clickjacking by controlling frame embedding
/// * **X-Content-Type-Options** - Prevents MIME type sniffing attacks
/// * **X-XSS-Protection** - Enables and configures browser XSS filtering
/// * **Referrer Policy** - Controls referrer information leakage across origins
/// * **DNS Prefetch Control** - Manages DNS prefetching behavior for privacy
/// * **IE No Open** - Prevents Internet Explorer from executing downloaded files
/// * **Hide Powered-By** - Removes X-Powered-By header to hide server technology
/// * **Permissions Policy** - Controls browser feature and API access
/// * **Cross-Origin Opener Policy** - Manages cross-origin window references
/// * **Cross-Origin Resource Policy** - Controls cross-origin resource access
/// * **Cross-Origin Embedder Policy** - Enables process isolation for sensitive resources
/// * **Origin Agent Cluster** - Requests origin-keyed agent clustering
/// * **Cross Domain Policy** - Controls Flash/Silverlight cross-domain access
/// * **Thread-safe operation** - Safe for concurrent use across multiple threads
/// * **Zero-overhead when disabled** - Individual features can be disabled with no performance cost
/// * **Secure defaults** - All features enabled with security-first default configurations
///
/// ## Security Headers Overview
///
/// ### Content Security Policy (CSP)
/// The most powerful security header, CSP prevents XSS attacks by controlling which resources
/// the browser is allowed to load and execute. The default policy is restrictive but functional:
/// * `default-src 'self'` - Only allow resources from the same origin
/// * `script-src 'self'` - Only allow scripts from the same origin
/// * `style-src 'self' 'unsafe-inline'` - Allow same-origin styles plus necessary inline styles
/// * `img-src 'self' data: https:` - Allow images from same origin, data URLs, and HTTPS sources
/// * `object-src 'none'` - Block all plugins and embedded objects
///
/// ### HTTP Strict Transport Security (HSTS)
/// Forces browsers to use HTTPS connections and prevents protocol downgrade attacks:
/// * Default max-age of 1 year (31536000 seconds)
/// * Includes subdomains by default for comprehensive protection
/// * Preload disabled by default (requires manual submission to browser preload lists)
///
/// ### Cross-Origin Policies
/// Modern security headers that provide fine-grained control over cross-origin interactions:
/// * **COOP** - Prevents malicious sites from accessing your window objects
/// * **CORP** - Controls which sites can embed your resources
/// * **COEP** - Enables process isolation by requiring explicit opt-in for cross-origin resources
///
/// ## Configuration
///
/// The middleware accepts an optional `ShieldConfig` struct. If no configuration is provided,
/// secure defaults are used for all features. Each security feature can be individually
/// configured or disabled as needed.
///
/// ## Examples
///
/// Basic usage with secure defaults:
///
/// ```rust
/// use ripress::app::App;
///
/// let mut app = App::new();
/// app.use_shield(None); // Uses ShieldConfig::default() with secure settings
/// ```
///
/// Custom CSP configuration for a web application:
///
/// ```rust
/// use ripress::{app::App, middlewares::shield::*};
/// use std::collections::HashMap;
///
/// let mut app = App::new();
///
/// let mut csp_directives = HashMap::new();
/// csp_directives.insert("default-src".to_string(), "'self'".to_string());
/// csp_directives.insert("script-src".to_string(), "'self' 'unsafe-eval' https://cdn.jsdelivr.net".to_string());
/// csp_directives.insert("style-src".to_string(), "'self' 'unsafe-inline' https://fonts.googleapis.com".to_string());
/// csp_directives.insert("font-src".to_string(), "'self' https://fonts.gstatic.com".to_string());
/// csp_directives.insert("img-src".to_string(), "'self' data: https: blob:".to_string());
/// csp_directives.insert("connect-src".to_string(), "'self' https://api.example.com".to_string());
///
/// let config = ShieldConfig {
/// content_security_policy: ContentSecurityPolicy {
/// enabled: true,
/// directives: csp_directives,
/// report_only: false,
/// },
/// hsts: Hsts {
/// enabled: true,
/// max_age: 63072000, // 2 years
/// include_subdomains: true,
/// preload: true,
/// },
/// ..Default::default()
/// };
///
/// app.use_shield(Some(config));
/// ```
///
/// Development configuration with relaxed CSP:
///
/// ```rust
/// use ripress::{app::App, middlewares::shield::*};
/// use std::collections::HashMap;
///
/// let mut app = App::new();
///
/// let mut csp_directives = HashMap::new();
/// csp_directives.insert("default-src".to_string(), "'self' 'unsafe-eval' 'unsafe-inline'".to_string());
///
/// let config = ShieldConfig {
/// content_security_policy: ContentSecurityPolicy {
/// enabled: true,
/// directives: csp_directives,
/// report_only: true, // Report violations but don't block
/// },
/// hsts: Hsts {
/// enabled: false, // Disable HSTS in development
/// ..Default::default()
/// },
/// ..Default::default()
/// };
///
/// app.use_shield(Some(config));
/// ```
///
/// API-only configuration with minimal headers:
///
/// ```rust
/// use ripress::{app::App, middlewares::shield::*};
///
/// let mut app = App::new();
///
/// let config = ShieldConfig {
/// content_security_policy: ContentSecurityPolicy {
/// enabled: false, // No CSP needed for API-only applications
/// ..Default::default()
/// },
/// frameguard: Frameguard {
/// enabled: false, // No frame protection needed for APIs
/// ..Default::default()
/// },
/// xss_filter: XssFilter {
/// enabled: false, // No XSS protection needed for APIs
/// ..Default::default()
/// },
/// cross_origin_resource_policy: CrossOriginResourcePolicy::CrossOrigin, // Allow cross-origin API access
/// ..Default::default()
/// };
///
/// app.use_shield(Some(config));
/// ```
///
/// ## Performance Considerations
///
/// * **Minimal overhead** - Headers are set once per response with negligible CPU cost
/// * **Memory efficient** - Configuration is shared via cloning, no per-request allocation
/// * **Disabled features** - Features with `enabled: false` are completely skipped
/// * **String operations** - Header values are computed once and cached when possible
/// * **Zero allocation** - No dynamic memory allocation during request processing
///
/// ## Security Best Practices
///
/// * **Test CSP thoroughly** - Content Security Policy can break functionality if misconfigured
/// * **Use report-only mode first** - Test CSP with `report_only: true` before enforcing
/// * **Monitor CSP violations** - Set up violation reporting to catch policy violations
/// * **Keep HSTS max-age reasonable** - Very long HSTS periods can cause accessibility issues
/// * **Review cross-origin policies** - Ensure CORP/COOP settings match your application architecture
/// * **Disable unused features** - Turn off security headers that don't apply to your application type
///
/// ## Compatibility Notes
///
/// * **Modern browsers** - All headers are supported by modern browsers (Chrome 60+, Firefox 55+, Safari 12+)
/// * **Legacy browser graceful degradation** - Older browsers ignore unknown headers without issues
/// * **X-XSS-Protection deprecation** - This header is deprecated in modern browsers but kept for legacy support
/// * **IE-specific headers** - Some headers like X-Download-Options only affect Internet Explorer
///
/// ## Troubleshooting
///
/// Common issues and solutions:
/// * **CSP blocking resources** - Check browser console for violation reports, update directives accordingly
/// * **HSTS not working** - Ensure you're serving over HTTPS, HSTS is ignored on HTTP
/// * **Frame embedding issues** - Adjust frameguard settings if legitimate embedding is blocked
/// * **API CORS issues** - Configure cross-origin policies appropriately for API endpoints
/// * **Development vs production** - Use different configurations for development and production environments
///
/// ## Thread Safety
///
/// The middleware is fully thread-safe:
/// * Configuration structs implement `Clone` for efficient sharing
/// * No mutable state is maintained between requests
/// * Safe for use in multi-threaded web servers
/// * Header setting operations are atomic and isolated per response
/// Creates a shield middleware function
///
/// Returns a middleware function that sets comprehensive security headers on HTTP responses
/// to protect against common web vulnerabilities. The middleware applies all configured
/// security headers efficiently with minimal performance overhead.
///
/// ## Parameters
///
/// * `config` - Optional shield configuration. If `None`, uses `ShieldConfig::default()`
/// which enables all security features with secure default settings.
///
/// ## Returns
///
/// A middleware function compatible with the ripress framework that:
/// * Sets security headers on all HTTP responses
/// * Applies configuration-specific security policies
/// * Operates efficiently with minimal CPU and memory overhead
/// * Handles disabled features by skipping them entirely
/// * Provides thread-safe operation across concurrent requests
///
/// ## Security Headers Applied
///
/// When using default configuration, the following headers are set:
/// * **Content-Security-Policy** - Restrictive policy allowing only same-origin resources
/// * **Strict-Transport-Security** - 1-year HSTS with includeSubDomains
/// * **X-Frame-Options** - DENY to prevent clickjacking
/// * **X-Content-Type-Options** - nosniff to prevent MIME confusion
/// * **X-XSS-Protection** - not sent by default (header deprecated in modern browsers)
/// * **Referrer-Policy** - strict-origin-when-cross-origin for privacy
/// * **X-DNS-Prefetch-Control** - off to improve privacy
/// * **X-Download-Options** - noopen for IE security
/// * **Permissions-Policy** - Restrictive policy disabling camera, microphone, etc.
/// * **Cross-Origin-Opener-Policy** - same-origin for process isolation
/// * **Cross-Origin-Resource-Policy** - same-origin for resource protection
/// * **Cross-Origin-Embedder-Policy** - unsafe-none for compatibility
/// * **Origin-Agent-Cluster** - ?1 for improved isolation
/// * **X-Permitted-Cross-Domain-Policies** - none to disable legacy policies
/// * **X-Powered-By** - Header removed to hide server information
///
/// ## Performance Characteristics
///
/// * **Low CPU overhead** - Headers are set with simple string operations
/// * **Minimal memory usage** - Configuration is shared via cloning
/// * **No I/O operations** - All processing happens in memory
/// * **Disabled feature skip** - Features with `enabled: false` are completely bypassed
/// * **String reuse** - Header values are computed once per configuration
///
/// ## Thread Safety
///
/// The middleware is fully thread-safe:
/// * Configuration is cloned for each request processing
/// * No shared mutable state between requests
/// * Safe for use in multi-threaded web servers
/// * All header operations are isolated per response
///
/// ## Usage Examples
///
/// Basic usage with secure defaults:
/// ```rust
/// use ripress::app::App;
///
/// let mut app = App::new();
/// app.use_shield(None); // Applies all security headers with defaults
/// ```
///
/// Custom configuration:
/// ```rust
/// use ripress::{app::App, middlewares::shield::*};
///
/// let mut app = App::new();
/// let config = ShieldConfig {
/// hsts: Hsts {
/// enabled: true,
/// max_age: 63072000, // 2 years
/// include_subdomains: true,
/// preload: true,
/// },
/// frameguard: Frameguard {
/// enabled: true,
/// action: "sameorigin".to_string(),
/// domain: None,
/// },
/// ..Default::default()
/// };
/// app.use_shield(Some(config));
/// ```
pub + Send + Sync + 'static
/// Sets Content-Security-Policy header based on configuration
///
/// Constructs and sets the CSP header from the provided directives map.
/// Uses Content-Security-Policy-Report-Only header when report_only is true.
pub
/// Sets Strict-Transport-Security header based on HSTS configuration
///
/// Constructs HSTS header with max-age, includeSubDomains, and preload directives
/// as configured. Only sets header when HSTS is enabled.
pub
/// Sets X-Frame-Options header based on frameguard configuration
///
/// Supports DENY, SAMEORIGIN, and ALLOW-FROM actions. Falls back to DENY
/// if an invalid action is specified or if ALLOW-FROM is used without a domain.
pub
/// Sets X-Content-Type-Options header to prevent MIME sniffing
///
/// Always sets the header to "nosniff" when enabled, as this is the only
/// valid value for this security header.
pub
/// Sets X-XSS-Protection header based on XSS filter configuration
///
/// Constructs the header value with mode and optional report URI.
/// This header is deprecated but included for legacy browser support.
pub
/// Sets Referrer-Policy header based on configuration
///
/// Controls how much referrer information is sent when navigating away from the page.
/// Uses the configured policy string directly as the header value.
pub
/// Sets X-DNS-Prefetch-Control header based on configuration
///
/// Controls DNS prefetching behavior. Sets to "on" when allowed,
/// "off" when disabled for privacy protection.
pub
/// Sets X-Download-Options header for Internet Explorer protection
///
/// Always sets the header to "noopen" when enabled, preventing IE from
/// executing downloaded files in the site's context.
pub
/// Removes X-Powered-By header when hide powered-by is enabled
///
/// Removes any existing X-Powered-By header to prevent disclosure of
/// server technology information to potential attackers.
pub
/// Sets Permissions-Policy header based on feature configuration
///
/// Constructs the header from the features HashMap, formatting each feature
/// with its allowlist. Empty allowlists result in () (disabled), while
/// populated allowlists are formatted as space-separated quoted origins.
pub
/// Sets Cross-Origin-Opener-Policy header based on policy configuration
///
/// Maps the enum variant to the appropriate header value string.
/// This header controls cross-origin window references and process isolation.
pub
/// Sets Cross-Origin-Resource-Policy header based on policy configuration
///
/// Maps the enum variant to the appropriate header value string.
/// This header controls cross-origin resource embedding permissions.
pub
/// Sets Cross-Origin-Embedder-Policy header based on policy configuration
///
/// Maps the enum variant to the appropriate header value string.
/// This header controls cross-origin resource requirements for embedder isolation.
pub
/// Sets Origin-Agent-Cluster header when enabled
///
/// Always sets the header to "?1" when enabled, requesting origin-keyed
/// agent clustering for improved process isolation.
pub
/// Sets X-Permitted-Cross-Domain-Policies header based on policy configuration
///
/// Controls Adobe Flash Player and Reader cross-domain policy file permissions.
/// Uses the configured policy string directly as the header value.
pub