forked from solutions-plug/predictIQ
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity.rs
More file actions
1335 lines (1132 loc) · 44.5 KB
/
Copy pathsecurity.rs
File metadata and controls
1335 lines (1132 loc) · 44.5 KB
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
collections::HashMap,
net::IpAddr,
sync::Arc,
time::{Duration, SystemTime},
};
use axum::{
body::Body,
extract::{ConnectInfo, Request, State},
http::{HeaderMap, HeaderValue, StatusCode},
middleware::Next,
response::{IntoResponse, Response},
Json,
};
use ipnet::IpNet;
use serde::Serialize;
use tokio::sync::RwLock;
/// Newtype wrapper so `trust_proxy: bool` can be injected as Axum `State`.
#[derive(Clone, Copy, Debug)]
pub struct TrustProxy(pub bool);
#[derive(Debug, Clone)]
pub struct RateLimitConfig {
pub requests: u32,
pub window: Duration,
}
impl RateLimitConfig {
pub fn new(requests: u32, window: Duration) -> Self {
Self { requests, window }
}
}
/// Rate limiter state for tracking requests
#[derive(Debug)]
struct RateLimitEntry {
count: u32,
window_start: SystemTime,
}
/// Multi-tier rate limiter
///
/// Tracks request counts per key using fixed-size buckets with sliding windows.
/// No allocation leaks: all keys and entries are properly managed in the HashMap,
/// which is periodically cleaned to remove expired windows.
#[derive(Clone)]
pub struct RateLimiter {
limits: Arc<RwLock<HashMap<String, RateLimitEntry>>>,
}
/// Webhook signature verification config
#[derive(Clone)]
pub struct WebhookConfig {
pub secret: Option<String>,
pub replay_window_secs: u64,
}
impl RateLimiter {
pub fn new() -> Self {
Self {
limits: Arc::new(RwLock::new(HashMap::new())),
}
}
pub async fn check(&self, key: &str, config: &RateLimitConfig) -> bool {
let mut limits = self.limits.write().await;
let now = SystemTime::now();
let entry = limits.entry(key.to_string()).or_insert(RateLimitEntry {
count: 0,
window_start: now,
});
// Reset window if expired
if now
.duration_since(entry.window_start)
.unwrap_or(Duration::ZERO)
>= config.window
{
entry.count = 0;
entry.window_start = now;
}
// Check limit
if entry.count >= config.requests {
return false;
}
entry.count += 1;
true
}
/// Cleanup old entries periodically
pub async fn cleanup(&self) {
let mut limits = self.limits.write().await;
let now = SystemTime::now();
limits.retain(|_, entry| {
now.duration_since(entry.window_start)
.unwrap_or(Duration::ZERO)
< Duration::from_secs(3600)
});
}
}
impl Default for RateLimiter {
fn default() -> Self {
Self::new()
}
}
/// Extract client IP with trusted proxy CIDR validation.
///
/// Headers (`x-forwarded-for`, `x-real-ip`) are only trusted when:
/// - `trusted_cidrs` is non-empty AND the connecting socket address falls
/// within one of the configured CIDRs, OR
/// - `trusted_cidrs` is empty AND `trust_proxy` is `true` (legacy mode).
///
/// Pass `trusted_cidrs = &[]` and `trust_proxy = false` to always use the
/// raw socket address (safe for direct-to-internet deployments).
pub fn extract_client_ip(
headers: &HeaderMap,
connect_info: Option<&ConnectInfo<std::net::SocketAddr>>,
trust_proxy: bool,
) -> String {
extract_client_ip_cidrs(headers, connect_info, trust_proxy, &[])
}
/// CIDR-aware variant. When `trusted_cidrs` is non-empty the connecting IP
/// must be contained in one of the CIDRs before proxy headers are trusted.
/// When `trusted_cidrs` is empty, falls back to the `trust_proxy` boolean.
pub fn extract_client_ip_cidrs(
headers: &HeaderMap,
connect_info: Option<&ConnectInfo<std::net::SocketAddr>>,
trust_proxy: bool,
trusted_cidrs: &[IpNet],
) -> String {
let proxy_trusted = if !trusted_cidrs.is_empty() {
// Only trust headers if the connecting IP is in a trusted CIDR.
connect_info
.and_then(|ci| ci.0.ip().to_string().parse::<IpAddr>().ok())
.map(|connecting_ip| trusted_cidrs.iter().any(|cidr| cidr.contains(&connecting_ip)))
.unwrap_or(false)
} else {
trust_proxy
};
if proxy_trusted {
// 1. Check X-Forwarded-For header (from proxy/load balancer)
if let Some(forwarded_for) = headers.get("x-forwarded-for").and_then(|h| h.to_str().ok()) {
for ip_str in forwarded_for.split(',') {
let ip_str = ip_str.trim();
if !ip_str.is_empty() && ip_str.parse::<IpAddr>().is_ok() {
return ip_str.to_string();
}
}
}
// 2. Check X-Real-IP header
if let Some(real_ip) = headers.get("x-real-ip").and_then(|h| h.to_str().ok()) {
let ip_str = real_ip.trim();
if !ip_str.is_empty() && ip_str.parse::<IpAddr>().is_ok() {
return ip_str.to_string();
}
}
}
// 3. Fallback to connection info (Socket)
if let Some(conn_info) = connect_info {
return conn_info.0.ip().to_string();
}
"unknown".to_string()
}
/// Global rate limiting middleware (100 req/min per IP)
pub async fn global_rate_limit_middleware(
State((limiter, TrustProxy(trust_proxy))): State<(Arc<RateLimiter>, TrustProxy)>,
headers: HeaderMap,
connect_info: Option<ConnectInfo<std::net::SocketAddr>>,
request: Request,
next: Next,
) -> Result<Response, StatusCode> {
let ip = extract_client_ip(&headers, connect_info.as_ref(), trust_proxy);
let config = RateLimitConfig::new(100, Duration::from_secs(60));
if !limiter.check(&format!("global:{}", ip), &config).await {
return Err(StatusCode::TOO_MANY_REQUESTS);
}
Ok(next.run(request).await)
}
/// Security headers middleware
pub async fn security_headers_middleware(request: Request, next: Next) -> Response {
let mut response = next.run(request).await;
let headers = response.headers_mut();
// Content Security Policy
headers.insert(
"content-security-policy",
HeaderValue::from_static(
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none';"
),
);
// X-Frame-Options
headers.insert("x-frame-options", HeaderValue::from_static("DENY"));
// X-Content-Type-Options
headers.insert(
"x-content-type-options",
HeaderValue::from_static("nosniff"),
);
// X-XSS-Protection
headers.insert(
"x-xss-protection",
HeaderValue::from_static("1; mode=block"),
);
// Strict-Transport-Security (HSTS)
headers.insert(
"strict-transport-security",
HeaderValue::from_static("max-age=31536000; includeSubDomains"),
);
// Referrer-Policy
headers.insert(
"referrer-policy",
HeaderValue::from_static("strict-origin-when-cross-origin"),
);
// Permissions-Policy
headers.insert(
"permissions-policy",
HeaderValue::from_static("geolocation=(), microphone=(), camera=()"),
);
response
}
/// Input sanitization utilities
pub mod sanitize {
use validator::ValidateEmail;
/// Sanitize email input
pub fn email(input: &str) -> Option<String> {
let cleaned = input.trim().to_lowercase();
if cleaned.len() > 254 || !cleaned.validate_email() {
return None;
}
Some(cleaned)
}
/// Sanitize string input (remove control characters, limit length)
pub fn string(input: &str, max_len: usize) -> String {
input
.chars()
.filter(|c| !c.is_control() || matches!(c, '\t' | '\n' | '\r' | ' '))
.take(max_len)
.collect()
}
/// Sanitize numeric ID
pub fn numeric_id(input: &str) -> Option<i64> {
input.trim().parse::<i64>().ok()
}
/// Check for SQL injection patterns (basic detection)
pub fn contains_sql_injection(input: &str) -> bool {
let lower = input.to_lowercase();
let patterns = [
"' or '1'='1",
"' or 1=1",
"'; drop table",
"'; delete from",
"union select",
"exec(",
"execute(",
"script>",
"<script",
"javascript:",
"onerror=",
"onload=",
];
patterns.iter().any(|pattern| lower.contains(pattern))
}
}
/// API Key authentication for admin endpoints
#[derive(Clone)]
pub struct ApiKeyAuth {
valid_keys: Arc<Vec<String>>,
}
impl ApiKeyAuth {
pub fn new(keys: Vec<String>) -> Self {
Self {
valid_keys: Arc::new(keys),
}
}
pub fn verify(&self, key: &str) -> bool {
!self.valid_keys.is_empty() && self.valid_keys.iter().any(|k| k == key)
}
}
#[derive(Serialize)]
struct ApiKeyErrorBody {
error: &'static str,
}
/// API key authentication middleware
pub async fn api_key_middleware(
State(auth): State<Arc<ApiKeyAuth>>,
headers: HeaderMap,
request: Request,
next: Next,
) -> Response {
let api_key = headers
.get("x-api-key")
.and_then(|h| h.to_str().ok())
.unwrap_or("");
if !auth.verify(api_key) {
let mut resp = (
StatusCode::UNAUTHORIZED,
Json(ApiKeyErrorBody {
error: "invalid or missing API key",
}),
)
.into_response();
resp.headers_mut().insert(
"WWW-Authenticate",
HeaderValue::from_static("ApiKey realm=\"predictiq\""),
);
return resp;
}
next.run(request).await
}
/// IP whitelist for admin endpoints
#[derive(Clone)]
pub struct IpWhitelist {
allowed_ips: Arc<Vec<IpAddr>>,
}
impl IpWhitelist {
pub fn new(ips: Vec<IpAddr>) -> Self {
Self {
allowed_ips: Arc::new(ips),
}
}
pub fn is_allowed(&self, ip: &str) -> bool {
if self.allowed_ips.is_empty() {
return true;
}
if let Ok(addr) = ip.parse::<IpAddr>() {
return self.allowed_ips.contains(&addr);
}
false
}
}
/// IP whitelist middleware for admin routes.
///
/// Allows all IPs when `ADMIN_WHITELIST_IPS` is empty (open-by-default for
/// local/dev). When the env var is set to a comma-separated list of IPs, only
/// those addresses may reach admin endpoints; all others receive `403 Forbidden`.
pub async fn ip_whitelist_middleware(
State((whitelist, TrustProxy(trust_proxy))): State<(Arc<IpWhitelist>, TrustProxy)>,
headers: HeaderMap,
connect_info: Option<ConnectInfo<std::net::SocketAddr>>,
request: Request,
next: Next,
) -> Result<Response, StatusCode> {
let ip = extract_client_ip(&headers, connect_info.as_ref(), trust_proxy);
if !whitelist.is_allowed(&ip) {
return Err(StatusCode::FORBIDDEN);
}
Ok(next.run(request).await)
}
/// Configuration for the metrics endpoint access control.
///
/// - `public`: skip all auth checks (only for trusted/internal networks).
/// - `allowlist`: when non-empty, the caller's IP must be in this list.
/// - `auth`: API key validator; checked when `public` is false.
#[derive(Clone)]
pub struct MetricsAuthConfig {
pub public: bool,
pub allowlist: Arc<Vec<IpAddr>>,
pub auth: Arc<ApiKeyAuth>,
}
impl MetricsAuthConfig {
pub fn new(public: bool, allowlist: Vec<IpAddr>, auth: Arc<ApiKeyAuth>) -> Self {
Self {
public,
allowlist: Arc::new(allowlist),
auth,
}
}
}
/// Metrics endpoint authentication middleware.
///
/// Access is granted when ANY of the following is true:
/// 1. `config.public == true` (opt-in public mode, e.g. internal cluster).
/// 2. The caller's IP is in `config.allowlist` AND a valid API key is present.
/// 3. `config.allowlist` is empty AND a valid API key is present.
pub async fn metrics_auth_middleware(
State(config): State<Arc<MetricsAuthConfig>>,
headers: HeaderMap,
connect_info: Option<ConnectInfo<std::net::SocketAddr>>,
request: Request,
next: Next,
) -> Result<Response, StatusCode> {
if config.public {
return Ok(next.run(request).await);
}
// IP allowlist check (when configured)
if !config.allowlist.is_empty() {
// Use empty CIDR list — allowlist check uses direct IP comparison, not proxy headers
let ip = extract_client_ip(&headers, connect_info.as_ref(), false);
let parsed: Option<IpAddr> = ip.parse().ok();
let allowed = parsed.map(|a| config.allowlist.contains(&a)).unwrap_or(false);
if !allowed {
return Err(StatusCode::FORBIDDEN);
}
}
// API key check
let api_key = headers
.get("x-api-key")
.and_then(|h| h.to_str().ok())
.unwrap_or("");
if !config.auth.verify(api_key) {
return Err(StatusCode::UNAUTHORIZED);
}
Ok(next.run(request).await)
}
/// SendGrid webhook signature verification middleware.
///
/// Verifies the `X-Twilio-Email-Event-Webhook-Signature` header using HMAC-SHA256
/// against the raw request body. The `SENDGRID_WEBHOOK_SECRET` must be configured
/// for webhook security, except in development environment where it passes through.
///
/// Replay protection: rejects requests whose `X-Twilio-Email-Event-Webhook-Timestamp`
/// is more than `WEBHOOK_REPLAY_WINDOW_SECS` seconds old relative to the server clock
/// (default: 300 seconds).
///
/// # OpenAPI policy
/// Route: `POST /webhooks/sendgrid`
/// Auth: provider-signed (SendGrid HMAC) — no API key required.
pub async fn sendgrid_webhook_middleware(
State(config): State<WebhookConfig>,
headers: HeaderMap,
request: Request,
next: Next,
) -> Result<Response, StatusCode> {
let is_dev = std::env::var("ENVIRONMENT")
.map(|e| e == "development")
.unwrap_or(false); // default to non-dev so signature verification is enforced
if config.secret.is_none() && !is_dev {
return Err(StatusCode::UNAUTHORIZED);
}
if let Some(ref secret) = config.secret {
let sig = headers
.get("x-twilio-email-event-webhook-signature")
.and_then(|h| h.to_str().ok())
.unwrap_or("");
// Replay protection: reject stale AND future-dated timestamps.
//
// The previous check used .abs() which accepted future-dated timestamps
// within the replay window. An attacker could pre-sign a request with
// timestamp = now + window - 1 and replay it for up to 2 * window seconds.
// The fix rejects any timestamp that is in the future at all, and any that
// is more than replay_window_secs old.
let ts_str = headers
.get("x-twilio-email-event-webhook-timestamp")
.and_then(|h| h.to_str().ok())
.unwrap_or("");
let ts: i64 = ts_str.parse().unwrap_or(0);
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
let age_secs = now - ts;
if age_secs < 0 || age_secs > config.replay_window_secs as i64 {
tracing::warn!(
ts,
now,
age_secs,
"sendgrid webhook rejected: timestamp out of bounds"
);
return Err(StatusCode::UNAUTHORIZED);
}
let (parts, body) = request.into_parts();
let bytes = axum::body::to_bytes(body, usize::MAX)
.await
.map_err(|_| StatusCode::BAD_REQUEST)?;
// Signature covers timestamp + payload per SendGrid spec
let signed_payload = format!("{}{}", ts_str, String::from_utf8_lossy(&bytes));
if !signing::verify_signature(signed_payload.as_bytes(), sig, secret) {
return Err(StatusCode::UNAUTHORIZED);
}
let request = Request::from_parts(parts, Body::from(bytes));
return Ok(next.run(request).await);
}
Ok(next.run(request).await)
}
pub mod signing {
use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
use hmac::{Hmac, Mac};
use sha2::Sha256;
use std::time::SystemTime;
type HmacSha256 = Hmac<Sha256>;
pub fn verify_signature(payload: &[u8], signature: &str, secret: &str) -> bool {
let mut mac = match HmacSha256::new_from_slice(secret.as_bytes()) {
Ok(m) => m,
Err(_) => return false,
};
mac.update(payload);
let expected = match BASE64.decode(signature) {
Ok(sig) => sig,
Err(_) => return false,
};
mac.verify_slice(&expected).is_ok()
}
/// Verify a signature against the current key, or the previous key if provided and
/// the token is within the grace period.
///
/// # Arguments
/// * `payload` - The signed payload
/// * `signature` - The base64-encoded HMAC signature
/// * `current_key` - The current HMAC secret key
/// * `previous_key` - Optional previous HMAC secret key for rotation
/// * `token_timestamp_secs` - The timestamp when the token was created (Unix seconds)
/// * `grace_period_secs` - Grace period in seconds for accepting tokens signed with the previous key
///
/// Returns true if the signature is valid against either key (within grace period for previous key)
pub fn verify_signature_with_rotation(
payload: &[u8],
signature: &str,
current_key: &str,
previous_key: Option<&str>,
token_timestamp_secs: i64,
grace_period_secs: u64,
) -> bool {
// Always try the current key first
if verify_signature(payload, signature, current_key) {
return true;
}
// If no previous key, we're done
let Some(prev_key) = previous_key else {
return false;
};
// Try the previous key only if within the grace period
if !verify_signature(payload, signature, prev_key) {
return false;
}
// Check if token is within grace period
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
let age_secs = now - token_timestamp_secs;
age_secs >= 0 && (age_secs as u64) <= grace_period_secs
}
pub fn generate_signature(payload: &[u8], secret: &str) -> Result<String, SigningError> {
let mut mac =
HmacSha256::new_from_slice(secret.as_bytes()).map_err(|_| SigningError::InvalidKey)?;
mac.update(payload);
let result = mac.finalize();
Ok(BASE64.encode(result.into_bytes()))
}
/// Error type for fallible signing operations.
#[derive(Debug, PartialEq)]
pub enum SigningError {
/// The secret key was rejected by the HMAC constructor (empty key).
InvalidKey,
}
impl std::fmt::Display for SigningError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SigningError::InvalidKey => write!(f, "signing key is invalid"),
}
}
}
impl std::error::Error for SigningError {}
}
#[derive(Serialize)]
pub struct SecurityError {
pub error: String,
pub message: String,
}
impl IntoResponse for SecurityError {
fn into_response(self) -> Response {
(StatusCode::BAD_REQUEST, Json(self)).into_response()
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::HeaderMap;
use ipnet::IpNet;
use std::net::SocketAddr;
// ── helpers ──────────────────────────────────────────────────────────────
fn addr(s: &str) -> ConnectInfo<SocketAddr> {
ConnectInfo(s.parse().unwrap())
}
fn xff(val: &str) -> HeaderMap {
let mut h = HeaderMap::new();
h.insert("x-forwarded-for", val.parse().unwrap());
h
}
fn xri(val: &str) -> HeaderMap {
let mut h = HeaderMap::new();
h.insert("x-real-ip", val.parse().unwrap());
h
}
// ── security headers middleware ───────────────────────────────────────
#[tokio::test]
async fn security_headers_middleware_sets_required_headers() {
use axum::{body::Body, http::Request, middleware, routing::get, Router};
use tower::ServiceExt;
let app = Router::new()
.route("/", get(|| async { "ok" }))
.layer(middleware::from_fn(super::security_headers_middleware));
let response = app
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
let headers = response.headers();
assert!(headers.contains_key("content-security-policy"));
assert!(headers.contains_key("strict-transport-security"));
assert!(headers.contains_key("x-frame-options"));
assert!(headers.contains_key("referrer-policy"));
assert_eq!(headers["x-frame-options"], "DENY");
assert_eq!(headers["x-content-type-options"], "nosniff");
}
#[tokio::test]
async fn security_headers_middleware_no_duplicates() {
use axum::{body::Body, http::Request, middleware, routing::get, Router};
use tower::ServiceExt;
let app = Router::new()
.route("/", get(|| async { "ok" }))
.layer(middleware::from_fn(super::security_headers_middleware));
let response = app
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
let headers = response.headers();
// get_all returns an iterator; exactly one value means no duplicates.
assert_eq!(headers.get_all("x-frame-options").iter().count(), 1);
assert_eq!(headers.get_all("content-security-policy").iter().count(), 1);
assert_eq!(headers.get_all("strict-transport-security").iter().count(), 1);
assert_eq!(headers.get_all("referrer-policy").iter().count(), 1);
}
#[test]
fn test_extract_client_ip_precedence() {
let mut headers = HeaderMap::new();
headers.insert("x-forwarded-for", "1.1.1.1, 2.2.2.2".parse().unwrap());
headers.insert("x-real-ip", "3.3.3.3".parse().unwrap());
let ci = addr("4.4.4.4:8080");
assert_eq!(extract_client_ip(&headers, Some(&ci), true), "1.1.1.1");
headers.remove("x-forwarded-for");
assert_eq!(extract_client_ip(&headers, Some(&ci), true), "3.3.3.3");
headers.remove("x-real-ip");
assert_eq!(extract_client_ip(&headers, Some(&ci), true), "4.4.4.4");
}
#[test]
fn test_extract_client_ip_validation() {
let mut headers = HeaderMap::new();
let ci = addr("4.4.4.4:8080");
headers.insert("x-forwarded-for", "malformed, 1.1.1.1".parse().unwrap());
assert_eq!(extract_client_ip(&headers, Some(&ci), true), "1.1.1.1");
headers.insert("x-forwarded-for", "not-an-ip, also-bad".parse().unwrap());
headers.insert("x-real-ip", "2.2.2.2".parse().unwrap());
assert_eq!(extract_client_ip(&headers, Some(&ci), true), "2.2.2.2");
headers.insert("x-real-ip", "invalid-ip".parse().unwrap());
assert_eq!(extract_client_ip(&headers, Some(&ci), true), "4.4.4.4");
}
#[test]
fn test_extract_client_ip_empty_and_unknown() {
let headers = HeaderMap::new();
// No headers, no connect info
assert_eq!(extract_client_ip(&headers, None, false), "unknown");
let ci = addr("5.5.5.5:80");
assert_eq!(extract_client_ip(&headers, Some(&ci), false), "5.5.5.5");
}
#[test]
fn test_extract_client_ip_ipv6() {
let headers = xff("2001:db8::1, 192.168.1.1");
assert_eq!(extract_client_ip(&headers, None, true), "2001:db8::1");
}
// ── trust-boundary tests (issue #281) ────────────────────────────────
/// Without a trusted proxy, X-Forwarded-For MUST be ignored and the real
/// socket address used instead.
#[test]
fn spoofed_xff_ignored_when_trust_proxy_disabled() {
let headers = xff("9.9.9.9");
let ci = addr("1.2.3.4:1234");
assert_eq!(
extract_client_ip(&headers, Some(&ci), false),
"1.2.3.4",
"X-Forwarded-For must not be trusted without proxy config"
);
}
/// Without a trusted proxy, X-Real-IP MUST be ignored.
#[test]
fn spoofed_x_real_ip_ignored_when_trust_proxy_disabled() {
let headers = xri("9.9.9.9");
let ci = addr("1.2.3.4:1234");
assert_eq!(
extract_client_ip(&headers, Some(&ci), false),
"1.2.3.4",
"X-Real-IP must not be trusted without proxy config"
);
}
/// Both spoofed headers present — returns "unknown" when proxy trust is
/// disabled and no socket address is available.
#[test]
fn both_spoofed_headers_ignored_when_trust_proxy_disabled() {
let mut headers = HeaderMap::new();
headers.insert(
"x-forwarded-for",
"2001:db8::1, 192.168.1.1".parse().unwrap(),
);
assert_eq!(extract_client_ip(&headers, None, false), "unknown");
}
// ── #454: CIDR-based trusted proxy tests ─────────────────────────────
/// When the connecting IP is in a trusted CIDR, XFF is trusted.
#[test]
fn cidr_trusted_proxy_xff_used_when_connecting_ip_in_cidr() {
let headers = xff("5.6.7.8");
let ci = addr("10.0.0.1:1234"); // in 10.0.0.0/8
let cidrs: Vec<IpNet> = vec!["10.0.0.0/8".parse().unwrap()];
assert_eq!(
extract_client_ip_cidrs(&headers, Some(&ci), false, &cidrs),
"5.6.7.8"
);
}
/// When the connecting IP is NOT in any trusted CIDR, XFF is ignored.
#[test]
fn cidr_trusted_proxy_xff_ignored_when_connecting_ip_not_in_cidr() {
let headers = xff("9.9.9.9");
let ci = addr("1.2.3.4:1234"); // not in 10.0.0.0/8
let cidrs: Vec<IpNet> = vec!["10.0.0.0/8".parse().unwrap()];
assert_eq!(
extract_client_ip_cidrs(&headers, Some(&ci), false, &cidrs),
"1.2.3.4",
"XFF must be ignored when connecting IP is not in trusted CIDR"
);
}
/// Empty CIDR list falls back to the trust_proxy boolean.
#[test]
fn empty_cidr_list_falls_back_to_trust_proxy_bool() {
let headers = xff("5.6.7.8");
let ci = addr("1.2.3.4:1234");
// trust_proxy=true, no CIDRs → trust headers
assert_eq!(extract_client_ip_cidrs(&headers, Some(&ci), true, &[]), "5.6.7.8");
// trust_proxy=false, no CIDRs → ignore headers
assert_eq!(extract_client_ip_cidrs(&headers, Some(&ci), false, &[]), "1.2.3.4");
}
// ── api_key_middleware ────────────────────────────────────────────────
#[tokio::test]
async fn api_key_middleware_allows_valid_key() {
use axum::{body::Body, http::Request, middleware, routing::get, Router};
use tower::ServiceExt;
let auth = Arc::new(ApiKeyAuth::new(vec!["secret".to_string()]));
let app = Router::new()
.route("/", get(|| async { "ok" }))
.layer(middleware::from_fn_with_state(auth, super::api_key_middleware));
let response = app
.oneshot(
Request::builder()
.uri("/")
.header("x-api-key", "secret")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn api_key_middleware_rejects_missing_key() {
use axum::{body::Body, http::Request, middleware, routing::get, Router};
use tower::ServiceExt;
let auth = Arc::new(ApiKeyAuth::new(vec!["secret".to_string()]));
let app = Router::new()
.route("/", get(|| async { "ok" }))
.layer(middleware::from_fn_with_state(auth, super::api_key_middleware));
let response = app
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn api_key_middleware_rejects_wrong_key() {
use axum::{body::Body, http::Request, middleware, routing::get, Router};
use tower::ServiceExt;
let auth = Arc::new(ApiKeyAuth::new(vec!["secret".to_string()]));
let app = Router::new()
.route("/", get(|| async { "ok" }))
.layer(middleware::from_fn_with_state(auth, super::api_key_middleware));
let response = app
.oneshot(
Request::builder()
.uri("/")
.header("x-api-key", "wrong")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
// ── ip_whitelist_middleware ───────────────────────────────────────────
#[tokio::test]
async fn ip_whitelist_allows_whitelisted_ip() {
use axum::{body::Body, http::Request, middleware, routing::get, Router};
use tower::ServiceExt;
let whitelist = Arc::new(IpWhitelist::new(vec!["127.0.0.1".parse().unwrap()]));
let state = (whitelist, TrustProxy(false));
let app = Router::new()
.route("/", get(|| async { "ok" }))
.layer(middleware::from_fn_with_state(state, super::ip_whitelist_middleware));
let response = app
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
// No ConnectInfo → ip resolves to "unknown" → not in whitelist → 403.
// To test an allowed IP we use X-Real-IP with trust_proxy=true.
assert_eq!(response.status(), StatusCode::FORBIDDEN);
}
#[tokio::test]
async fn ip_whitelist_allows_when_list_empty() {
use axum::{body::Body, http::Request, middleware, routing::get, Router};
use tower::ServiceExt;
let whitelist = Arc::new(IpWhitelist::new(vec![])); // empty = allow all
let state = (whitelist, TrustProxy(false));
let app = Router::new()
.route("/", get(|| async { "ok" }))
.layer(middleware::from_fn_with_state(state, super::ip_whitelist_middleware));
let response = app
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[tokio::test]
async fn ip_whitelist_blocks_non_whitelisted_ip() {
use axum::{body::Body, http::Request, middleware, routing::get, Router};
use tower::ServiceExt;
let whitelist = Arc::new(IpWhitelist::new(vec!["10.0.0.1".parse().unwrap()]));
let state = (whitelist, TrustProxy(true));
let app = Router::new()
.route("/", get(|| async { "ok" }))
.layer(middleware::from_fn_with_state(state, super::ip_whitelist_middleware));
let response = app
.oneshot(
Request::builder()
.uri("/")
.header("x-real-ip", "1.2.3.4") // not in whitelist
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::FORBIDDEN);
}
#[tokio::test]
async fn ip_whitelist_allows_matching_ip_via_header() {
use axum::{body::Body, http::Request, middleware, routing::get, Router};
use tower::ServiceExt;
let whitelist = Arc::new(IpWhitelist::new(vec!["10.0.0.1".parse().unwrap()]));
let state = (whitelist, TrustProxy(true));
let app = Router::new()
.route("/", get(|| async { "ok" }))
.layer(middleware::from_fn_with_state(state, super::ip_whitelist_middleware));
let response = app
.oneshot(
Request::builder()
.uri("/")
.header("x-real-ip", "10.0.0.1") // in whitelist
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
// ── Rate Limiter tests (issue #473) ──────────────────────────────────
/// Test that rate limiter correctly enforces limits.
#[tokio::test]
async fn rate_limiter_allows_under_limit() {
let limiter = RateLimiter::new();
let config = RateLimitConfig::new(3, Duration::from_secs(1));