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
use crate::;
/// Builtin CORS (Cross-Origin Resource Sharing) Middleware
///
/// This middleware handles Cross-Origin Resource Sharing (CORS) by adding appropriate
/// headers to HTTP responses and handling preflight OPTIONS requests. CORS is essential
/// for web applications that need to make cross-origin requests from browsers, such as
/// when a frontend served from one domain needs to access an API on another domain.
///
/// ## Features
///
/// * **Preflight request handling** - Automatically responds to OPTIONS requests
/// * **Dynamic origin reflection** - Can reflect requesting origin for flexible CORS
/// * **Static configuration** - Set fixed allowed origins, methods, and headers
/// * **Credential support** - Optional credential allowing with security considerations
/// * **Header optimization** - Minimal headers when not reflecting requests
/// * **Vary header management** - Proper cache control for dynamic responses
/// * **Security-first defaults** - Conservative defaults that can be relaxed as needed
/// * **Standards compliant** - Follows W3C CORS specification
///
/// ## CORS Behavior Modes
///
/// The middleware operates in two modes based on the presence of CORS request headers:
///
/// ### 1. Reflective Mode (Dynamic)
/// When the request includes both `Origin` and `Access-Control-Request-Method` headers:
/// - **Origin**: Reflects the requesting origin back in `Access-Control-Allow-Origin`
/// - **Methods**: Reflects the requested method back in `Access-Control-Allow-Methods`
/// - **Headers**: Uses requested headers or falls back to configured `allowed_headers`
/// - **Vary**: Adds `Vary` header for proper caching behavior
///
/// ### 2. Static Mode (Default)
/// For regular requests or when CORS headers are missing:
/// - Uses configured static values for all CORS headers
/// - More predictable and cacheable responses
/// - No `Vary` header needed
///
/// ## Configuration Options
///
/// * `allowed_origin` - Origin(s) allowed to access the resource (default: "*")
/// * `allowed_methods` - HTTP methods allowed for cross-origin requests (default: "GET, POST, PUT, DELETE, OPTIONS, HEAD")
/// * `allowed_headers` - Headers allowed in cross-origin requests (default: "Content-Type, Authorization")
/// * `allow_credentials` - Whether to allow credentials (cookies, auth headers) in CORS requests (default: false)
///
/// ## Security Considerations
///
/// ### Origin Validation
/// - **Wildcard (`*`) origins** cannot be used with credentials for security
/// - **Dynamic reflection** should be used carefully - validate origins in production
/// - **Subdomain policies** may require specific origin patterns
///
/// ### Credential Handling
/// - Setting `allow_credentials: true` has security implications
/// - Cannot use wildcard origin with credentials
/// - Consider implementing proper origin validation when using credentials
///
/// ### Header Exposure
/// - Be conservative with `allowed_headers` - only allow what's needed
/// - Some headers (like `Authorization`) may expose sensitive information
/// - Consider the principle of least privilege
///
/// ## Preflight Request Handling
///
/// The middleware automatically handles CORS preflight requests:
/// 1. **Detection**: Identifies OPTIONS requests as potential preflights
/// 2. **Header Addition**: Adds appropriate CORS headers to the response
/// 3. **Early Return**: Returns 200 OK immediately without calling subsequent handlers
/// 4. **Cache Control**: Includes proper `Vary` headers when reflecting requests
///
/// ## Examples
///
/// Basic CORS with default settings (allows all origins):
///
/// ```rust
/// use ripress::{app::App, middlewares::cors::CorsConfig};
///
/// let mut app = App::new();
/// app.use_cors(Some(CorsConfig::default()));
/// ```
///
/// Restrictive CORS for production API:
///
/// ```rust
/// use ripress::{app::App, middlewares::cors::CorsConfig};
///
/// let mut app = App::new();
/// let config = CorsConfig {
/// allowed_origin: "https://myapp.com",
/// allowed_methods: "GET, POST, PUT, DELETE",
/// allowed_headers: "Content-Type, Authorization, X-API-Key",
/// allow_credentials: true,
/// };
/// app.use_cors(Some(config));
/// ```
///
/// Development-friendly CORS (allows localhost variations):
///
/// ```rust
/// use ripress::{app::App, middlewares::cors::CorsConfig};
///
/// let mut app = App::new();
/// let config = CorsConfig {
/// allowed_origin: "*", // Note: Cannot use with credentials
/// allowed_methods: "GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH",
/// allowed_headers: "Content-Type, Authorization, X-Requested-With, Accept, Origin",
/// allow_credentials: false, // Must be false when origin is "*"
/// };
/// app.use_cors(Some(config));
/// ```
///
/// Multiple origin support pattern (requires custom logic):
///
/// ```rust
/// use ripress::{app::App, middlewares::cors::CorsConfig};
///
/// // Note: For true multiple origin support, you may need custom middleware
/// // This example shows single origin configuration
/// let mut app = App::new();
/// let config = CorsConfig {
/// allowed_origin: "https://app.example.com",
/// allowed_methods: "GET, POST, PUT, DELETE, OPTIONS",
/// allowed_headers: "Content-Type, Authorization",
/// allow_credentials: true,
/// };
/// app.use_cors(Some(config));
/// ```
///
/// Using default configuration:
///
/// ```rust
/// use ripress::app::App;
///
/// let mut app = App::new();
/// app.use_cors(None); // Uses CorsConfig::default()
/// ```
///
/// ## Common Use Cases
///
/// ### Single Page Applications (SPAs)
/// ```rust
/// use ripress::middlewares::cors::CorsConfig;
///
/// let config = CorsConfig {
/// allowed_origin: "https://myapp.com",
/// allowed_methods: "GET, POST, PUT, DELETE, PATCH",
/// allowed_headers: "Content-Type, Authorization",
/// allow_credentials: true,
/// };
/// ```
///
/// ### Public APIs
/// ```rust
/// use ripress::middlewares::cors::CorsConfig;
///
/// let config = CorsConfig {
/// allowed_origin: "*",
/// allowed_methods: "GET, POST",
/// allowed_headers: "Content-Type, X-API-Key",
/// allow_credentials: false, // Must be false with "*"
/// };
/// ```
///
/// ### Development/Testing
/// ```rust
/// use ripress::middlewares::cors::CorsConfig;
///
/// let config = CorsConfig {
/// allowed_origin: "*",
/// allowed_methods: "GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH",
/// allowed_headers: "Content-Type, Authorization, X-Requested-With, Accept, Origin, X-Custom-Header",
/// allow_credentials: false,
/// };
/// ```
///
/// ## Response Headers Added
///
/// The middleware adds the following headers based on configuration:
///
/// ### Always Added
/// - `Access-Control-Allow-Origin`: Configured origin or reflected origin
/// - `Access-Control-Allow-Methods`: Configured methods or reflected method
/// - `Access-Control-Allow-Headers`: Configured headers or requested headers
///
/// ### Conditionally Added
/// - `Access-Control-Allow-Credentials`: "true" (only when `allow_credentials: true`)
/// - `Vary`: "Origin, Access-Control-Request-Method, Access-Control-Request-Headers" (only in reflective mode)
///
/// ## Browser Compatibility
///
/// This middleware is compatible with all modern browsers that support CORS:
/// - Chrome 4+
/// - Firefox 3.5+
/// - Safari 4+
/// - Internet Explorer 8+ (with limitations)
/// - Edge (all versions)
///
/// ## Debugging CORS Issues
///
/// Common issues and solutions:
/// - **"CORS policy" errors**: Check that `allowed_origin` matches the requesting domain exactly
/// - **Credential issues**: Ensure `allowed_origin` is not "*" when `allow_credentials` is true
/// - **Method not allowed**: Verify the HTTP method is in `allowed_methods`
/// - **Header not allowed**: Check that custom headers are included in `allowed_headers`
/// - **Preflight failures**: Ensure OPTIONS requests reach the middleware
///
/// ## Performance Notes
///
/// - **Static mode**: More efficient and cacheable
/// - **Reflective mode**: Adds slight overhead for header processing
/// - **Preflight handling**: Early return prevents unnecessary processing
/// - **Header cloning**: Minimal string operations for header management
///
/// ## Standards Compliance
///
/// This middleware implements the CORS specification as defined by:
/// - W3C Cross-Origin Resource Sharing specification
/// - RFC 6454 (The Web Origin Concept)
/// - Follows browser security model requirements
/// Configuration struct for the CORS Middleware
///
/// This struct defines the Cross-Origin Resource Sharing policy for your application.
/// CORS policies determine which origins, methods, and headers are allowed when
/// making cross-origin requests to your server from web browsers.
///
/// ## Field Details
///
/// All string fields use `&'static str` for efficiency, meaning they should be
/// string literals or static strings. This avoids unnecessary memory allocations
/// during request processing.
///
/// ## Security Implications
///
/// CORS configuration directly impacts your application's security posture:
/// - Overly permissive settings can expose your API to unauthorized access
/// - Restrictive settings may break legitimate client applications
/// - Credential handling requires careful origin validation
///
/// ## Default Values
///
/// The default configuration is permissive and suitable for development:
/// - Allows all origins (`*`)
/// - Allows common HTTP methods
/// - Allows basic headers
/// - Disallows credentials (required when using `*` origin)
/// Creates a CORS middleware function
///
/// Returns a middleware function that handles Cross-Origin Resource Sharing (CORS)
/// by adding appropriate headers to responses and handling preflight OPTIONS requests.
/// The middleware supports both static configuration and dynamic origin reflection
/// based on incoming request headers.
///
/// ## Parameters
///
/// * `config` - Optional CORS configuration. If `None`, uses `CorsConfig::default()`
/// which allows all origins with common methods and headers.
///
/// ## Returns
///
/// A middleware function compatible with the ripress framework that:
/// * Adds CORS headers to all responses based on configuration
/// * Automatically handles preflight OPTIONS requests with early termination
/// * Supports both static and reflective CORS modes
/// * Manages proper cache headers for dynamic responses
/// * Handles credential policies securely
///
/// ## Middleware Behavior
///
/// ### For OPTIONS Requests (Preflight)
/// 1. Adds appropriate CORS headers based on request and configuration
/// 2. Returns 200 OK status immediately
/// 3. Does not call subsequent middleware or handlers
/// 4. Includes `Vary` header when reflecting request headers
///
/// ### For Other Requests
/// 1. Adds CORS headers to the response
/// 2. Continues to next middleware/handler
/// 3. Uses static or reflective mode based on request headers
/// 4. Preserves response status and body from downstream handlers
///
/// ## Thread Safety
///
/// The returned middleware is `Send + Sync + Clone` and safe for concurrent use.
/// Configuration is cloned per request to avoid shared mutable state.
///
/// ## Error Handling
///
/// The middleware is designed to be permissive and never fails requests:
/// * Missing headers are handled gracefully
/// * Invalid configurations log warnings but don't block requests
/// * Always allows requests to proceed (except OPTIONS preflights)
///
/// ## Performance Characteristics
///
/// * **Static mode**: Minimal overhead, highly cacheable responses
/// * **Reflective mode**: Slight overhead for header inspection and reflection
/// * **OPTIONS handling**: Early return prevents unnecessary processing
/// * **Header operations**: Efficient string operations with minimal allocation
/// * **Configuration cloning**: Lightweight operation due to `&'static str` usage
pub + Send + Sync + Clone + 'static