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
//! Actix Middleware for IP filter. Support glob pattern.
//!
//! ## Documentation
//! * [API Documentation](https://docs.rs/actix-ip-filter/)
//! * Cargo package: [actix-ip-filter](https://crates.io/crates/actix-ip-filter)
//! ## Usage
//! ```rust
//! use actix_web::{App, HttpServer, HttpRequest, web, middleware};
//! use actix_ip_filter::IPFilter;
//!
//! async fn index(req: HttpRequest) -> &'static str {
//!     "Hello world"
//! }
//!
//! #[actix_web::main]
//! async fn main() -> std::io::Result<()> {
//!     HttpServer::new(|| App::new()
//!         // enable logger
//!         .wrap(middleware::Logger::default())
//!         // setup ip filters
//!         .wrap(
//!             IPFilter::new()
//!                 .allow(vec!["172.??.6*.12"])
//!                 .block(vec!["192.168.1.222"])
//!         )
//!         // register simple route, handle all methods
//!         .service(web::resource("/").to(index))
//!     )
//!         .bind("0.0.0.0:8080")?;
//!     Ok(())
//! }
//!
//! ```
//! ## Limiting to certain paths
//! You can limit the allow/block actions to a certain set of patterns representing URL paths.
//! The following code will only allow/block to paths matching the patterns `/my/path*` and
//! `/my/other/*.csv`.
//! ```rust
//! use actix_web::{App, HttpServer, HttpRequest, web, middleware};
//! use actix_ip_filter::IPFilter;
//!
//! async fn i_am_protected() -> &'static str {
//!     "I am a protected resource"
//! }
//!
//! async fn i_am_unprotected() -> &'static str {
//!     "I am NOT a protected resource"
//! }
//!
//! #[actix_web::main]
//! async fn main() -> std::io::Result<()> {
//!
//!
//!     HttpServer::new(|| App::new()
//!         // enable logger
//!         .wrap(middleware::Logger::default())
//!         // setup ip filters
//!         .wrap(
//!             IPFilter::new()
//!                 .allow(vec!["172.??.6*.12"])
//!                 .block(vec!["192.168.1.222"])
//!                 .limit_to(vec!["/my/path/*"])
//!         )
//!         // register simple protected route
//!         .service(web::resource("/my/path/resource").to(i_am_protected))
//!         // register simple unprotected route
//!         .service(web::resource("/other/path/resource").to(i_am_unprotected))
//!     )
//!         .bind("0.0.0.0:8000");
//!     Ok(())
//! }
//! ```
//! ## Allow and block callbacks
//! You can add an allow handler and a block handler. These handlers will be called whenever a
//! request succeeds at passing an ip filter (allow handler) or it is blocked (block handler).
//! This last allows you to customize the error response. The callbacks will not be called on
//! unprotected paths.
//!
//! ### The allow handler.
//! The allow handler must take three positional arguments and no return type:
//! ```rust
//! use actix_ip_filter::IPFilter;
//! use actix_web::dev::ServiceRequest;
//!
//! fn my_allow_handler(flt: &IPFilter, ip: &str, req: &ServiceRequest) {
//!     //Do smth
//! }
//!
//! ```
//! The parameters passed to the functions are borrows of the `IPFilter`, the ip of the request and
//! the request.
//!
//! You can attach the handler to an `IPFilter` like this:
//! ```rust
//! use actix_web::{App, HttpServer, HttpRequest, web, middleware};
//! use actix_ip_filter::IPFilter;
//! use actix_web::dev::ServiceRequest;
//!
//! fn my_allow_handler(flt: &IPFilter, ip: &str, req: &ServiceRequest) {
//!     //Do smth
//! }
//!
//! async fn i_am_protected() -> &'static str {
//!     "I am a protected resource"
//! }
//!
//! async fn i_am_unprotected() -> &'static str {
//!     "I am NOT a protected resource"
//! }
//!
//! #[actix_web::main]
//! async fn main() -> std::io::Result<()> {
//!
//!
//!     HttpServer::new(|| App::new()
//!         // enable logger
//!         .wrap(middleware::Logger::default())
//!         // setup ip filters
//!         .wrap(
//!             IPFilter::new()
//!                 .allow(vec!["172.??.6*.12"])
//!                 .block(vec!["192.168.1.222"])
//!                 .limit_to(vec!["/my/path/*"])
//!                 .on_allow(my_allow_handler)
//!         )
//!         // register simple protected route
//!         .service(web::resource("/my/path/resource").to(i_am_protected))
//!         // register simple unprotected route
//!         .service(web::resource("/other/path/resource").to(i_am_unprotected))
//!     )
//!         .bind("0.0.0.0:8000");
//!     Ok(())
//! }
//! ```
//! ### The block handler
//! The allow handler must take three positional arguments and and optional body response as a
//! response:
//! ```rust
//! use actix_ip_filter::IPFilter;
//! use actix_web::dev::ServiceRequest;
//! use actix_web::HttpResponse;
//!
//! fn my_block_handler(flt: &IPFilter, ip: &str, req: &ServiceRequest) -> Option<HttpResponse> {
//!     Some(HttpResponse::UseProxy().json("{\"result\": \"error\"}"))
//! }
//! ```
//! The parameters passed to the functions are borrows of the `IPFilter`, the ip of the request and
//! the request.
//!
//! If the handler returns None, then the default error response is used.
//! You can attach the handler to an `IPFilter` like this:
//! ```rust
//! use actix_web::{App, HttpServer, HttpRequest, web, middleware};
//! use actix_ip_filter::IPFilter;
//! use actix_web::dev::ServiceRequest;
//! use actix_web::HttpResponse;
//!
//! fn my_block_handler(flt: &IPFilter, ip: &str, req: &ServiceRequest) -> Option<HttpResponse> {
//!     Some(HttpResponse::UseProxy().json("{\"result\": \"error\"}"))
//! }
//!
//! async fn i_am_protected() -> &'static str {
//!     "I am a protected resource"
//! }
//!
//! async fn i_am_unprotected() -> &'static str {
//!     "I am NOT a protected resource"
//! }
//!
//! #[actix_web::main]
//! async fn main() -> std::io::Result<()> {
//!
//!
//!     HttpServer::new(|| App::new()
//!         // enable logger
//!         .wrap(middleware::Logger::default())
//!         // setup ip filters
//!         .wrap(
//!             IPFilter::new()
//!                 .allow(vec!["172.??.6*.12"])
//!                 .block(vec!["192.168.1.222"])
//!                 .limit_to(vec!["/my/path/*"])
//!                 .on_block(my_block_handler)
//!         )
//!         // register simple protected route
//!         .service(web::resource("/my/path/resource").to(i_am_protected))
//!         // register simple unprotected route
//!         .service(web::resource("/other/path/resource").to(i_am_unprotected))
//!     )
//!         .bind("0.0.0.0:8000");
//!     Ok(())
//! }
//! ```

use actix_service::{Service, Transform};
use actix_web::{
    body::{AnyBody, MessageBody},
    dev::{ServiceRequest, ServiceResponse},
    error::ErrorForbidden,
    Error, HttpResponse,
};
use futures_util::future::{ok, FutureExt as _, LocalBoxFuture, Ready};
use glob::Pattern;
use std::error::Error as StdError;
use std::rc::Rc;

fn wrap_pattern(list: Vec<&str>) -> Rc<Vec<Pattern>> {
    Rc::new(
        list.iter()
            .map(|rule| Pattern::new(rule).unwrap())
            .collect(),
    )
}

/// Middleware for filter IP of HTTP requests
pub struct IPFilter {
    use_x_real_ip: bool,
    allowlist: Rc<Vec<Pattern>>,
    blocklist: Rc<Vec<Pattern>>,
    limitlist: Rc<Vec<Pattern>>,
    allow_handler: Option<fn(&Self, &str, &ServiceRequest) -> ()>,
    block_handler: Option<fn(&Self, &str, &ServiceRequest) -> Option<HttpResponse>>,
}

impl Default for IPFilter {
    fn default() -> Self {
        Self {
            use_x_real_ip: false,
            allowlist: Rc::new(vec![]),
            blocklist: Rc::new(vec![]),
            limitlist: Rc::new(vec![]),
            allow_handler: None,
            block_handler: None,
        }
    }
}

impl IPFilter {
    /// Construct `IPFilter` middleware with no arguments
    pub fn new() -> Self {
        Default::default()
    }

    /// Construct `IPFilter` middleware with the provided arguments and no limiting pattern.
    pub fn new_with_opts(allowlist: Vec<&str>, blocklist: Vec<&str>, use_x_real_ip: bool) -> Self {
        IPFilter {
            use_x_real_ip,
            allowlist: wrap_pattern(allowlist),
            blocklist: wrap_pattern(blocklist),
            limitlist: wrap_pattern(vec![]),
            allow_handler: None,
            block_handler: None,
        }
    }

    /// Construct `IPFilter` middleware with the provided arguments and limiting patterns.
    pub fn new_with_opts_limited(
        allowlist: Vec<&str>,
        blocklist: Vec<&str>,
        limitlist: Vec<&str>,
        use_x_real_ip: bool,
    ) -> Self {
        IPFilter {
            use_x_real_ip,
            allowlist: wrap_pattern(allowlist),
            blocklist: wrap_pattern(blocklist),
            limitlist: wrap_pattern(limitlist),
            allow_handler: None,
            block_handler: None,
        }
    }

    /// Use `X-REAL-IP` header to check IP if it is found in request.
    pub fn x_real_ip(mut self, enabled: bool) -> Self {
        self.use_x_real_ip = enabled;
        self
    }

    /// Set allow IP list, it supported glob pattern. It will allow all if vec is empty.
    ///
    /// ## Example
    ///
    /// ```
    /// # use actix_ip_filter::IPFilter;
    /// let middleware = IPFilter::new()
    ///     .allow(vec!["127.??.6*.12", "!1.2.*.4'"]);
    /// ```
    pub fn allow(mut self, allowlist: Vec<&str>) -> Self {
        self.allowlist = wrap_pattern(allowlist);
        self
    }

    /// Set block IP list, it supported glob pattern.
    ///
    /// ## Example
    ///
    /// ```
    /// # use actix_ip_filter::IPFilter;
    /// let middleware = IPFilter::new()
    ///     .block(vec!["127.??.6*.12", "!1.2.*.4'"]);
    /// ```
    pub fn block(mut self, blocklist: Vec<&str>) -> Self {
        self.blocklist = wrap_pattern(blocklist);
        self
    }

    /// Set endpoint limit list, supporting glob pattern.
    ///
    /// ## Example
    ///
    /// ```
    /// # use actix_ip_filter::IPFilter;
    /// let middleware = IPFilter::new()
    ///     .limit_to(vec!["/path/to/protected/resource*", "/protected/file/type/*.csv"]);
    /// ```
    pub fn limit_to(mut self, limitlist: Vec<&str>) -> Self {
        self.limitlist = wrap_pattern(limitlist);
        self
    }

    /// Add allow handler.
    /// ## Example
    ///
    /// ```
    /// # use actix_ip_filter::IPFilter;
    /// # use actix_web::dev::{ServiceResponse, ServiceRequest};
    ///
    /// fn my_custom_handler(filter: &IPFilter, ip: &str, req: &ServiceRequest) {
    ///     // Do smth
    /// }
    ///
    /// let middleware = IPFilter::new()
    ///     .on_allow(my_custom_handler);
    /// ```
    pub fn on_allow(mut self, handler: fn(&Self, &str, &ServiceRequest) -> ()) -> Self {
        self.allow_handler = Some(handler);
        self
    }

    /// Add block handler.
    /// ## Example
    ///
    /// ```
    /// # use actix_ip_filter::IPFilter;
    /// # use actix_web::dev::{ServiceResponse, ServiceRequest};
    /// use actix_web::error::ErrorForbidden;
    /// use actix_web::HttpResponse;
    ///
    /// fn my_custom_handler(filter: &IPFilter, ip: &str, req: &ServiceRequest) -> Option<HttpResponse> {
    ///     Some(HttpResponse::Forbidden().body("My custom forbidden message!"))
    /// }
    ///
    /// let middleware = IPFilter::new()
    ///     .on_block(my_custom_handler);
    /// ```
    pub fn on_block(
        mut self,
        handler: fn(&Self, &str, &ServiceRequest) -> Option<HttpResponse>,
    ) -> Self {
        self.block_handler = Some(handler);
        self
    }
}

impl<S, B> Transform<S, ServiceRequest> for IPFilter
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
    S::Future: 'static,
    B: MessageBody + 'static,
    B::Error: StdError,
{
    type Response = ServiceResponse;
    type Error = Error;
    type Transform = IPFilterMiddleware<S>;
    type InitError = ();
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ok(IPFilterMiddleware {
            service: Rc::new(service),
            use_x_real_ip: self.use_x_real_ip,
            allowlist: Rc::clone(&self.allowlist),
            blocklist: Rc::clone(&self.blocklist),
            limitlist: Rc::clone(&self.limitlist),
            allow_handler: self.allow_handler,
            block_handler: self.block_handler,
        })
    }
}

#[derive(Clone)]
pub struct IPFilterMiddleware<S> {
    service: Rc<S>,
    use_x_real_ip: bool,
    allowlist: Rc<Vec<Pattern>>,
    blocklist: Rc<Vec<Pattern>>,
    limitlist: Rc<Vec<Pattern>>,
    allow_handler: Option<fn(&IPFilter, &str, &ServiceRequest) -> ()>,
    block_handler: Option<fn(&IPFilter, &str, &ServiceRequest) -> Option<HttpResponse>>,
}

impl<S, B> Service<ServiceRequest> for IPFilterMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
    S::Future: 'static,
    B: MessageBody + 'static,
    B::Error: StdError,
{
    type Response = ServiceResponse;
    type Error = Error;
    type Future = LocalBoxFuture<'static, Result<ServiceResponse, Error>>;

    actix_service::forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let peer_addr_ip = req.peer_addr().unwrap().ip().to_string();
        let ip = if self.use_x_real_ip {
            match req.headers().get("X-REAL-IP") {
                Some(header) => String::from(header.to_str().unwrap()),
                None => peer_addr_ip,
            }
        } else {
            peer_addr_ip
        };

        if (self.limitlist.is_empty() || self.limitlist.iter().any(|re| re.matches(req.path())))
            && ((!self.allowlist.is_empty() && !self.allowlist.iter().any(|re| re.matches(&ip)))
                || self.blocklist.iter().any(|re| re.matches(&ip)))
        {
            let response_opt: Option<HttpResponse> = if let Some(callback) = self.block_handler {
                callback(&middleware_to_filter(self), &ip, &req)
            } else {
                None
            };
            return if let Some(res) = response_opt {
                Box::pin(ok(req.into_response(res)))
            } else {
                Box::pin(ok(req.error_response(ErrorForbidden("Forbidden"))))
            };
        }

        if let Some(callback) = self.allow_handler {
            if self.limitlist.is_empty() || self.limitlist.iter().any(|re| re.matches(req.path())) {
                callback(&middleware_to_filter(self), &ip, &req)
            }
        }
        let service = Rc::clone(&self.service);
        async move {
            service
                .call(req)
                .await
                .map(|res| res.map_body(|_, body| AnyBody::new_boxed(body)))
        }
        .boxed_local()
    }
}

fn middleware_to_filter<S, B>(middleware: &IPFilterMiddleware<S>) -> IPFilter
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    B: MessageBody + 'static,
    B::Error: StdError,
{
    IPFilter {
        use_x_real_ip: middleware.use_x_real_ip,
        allowlist: middleware.allowlist.clone(),
        blocklist: middleware.blocklist.clone(),
        limitlist: middleware.limitlist.clone(),
        allow_handler: middleware.allow_handler,
        block_handler: middleware.block_handler,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::http::StatusCode;
    use actix_web::test;

    #[actix_rt::test]
    async fn test_allowlist() {
        let ip_filter = IPFilter::new().allow(vec!["192.168.*.11?", "192.168.*.22?"]);
        let mut fltr = ip_filter.new_transform(test::ok_service()).await.unwrap();

        let req = test::TestRequest::with_uri("test")
            .peer_addr("192.168.0.222:8888".parse().unwrap())
            .to_srv_request();
        let resp = test::call_service(&mut fltr, req).await;
        assert_eq!(resp.status(), StatusCode::OK);

        let req = test::TestRequest::with_uri("test")
            .peer_addr("192.168.0.123:8888".parse().unwrap())
            .to_srv_request();
        let resp = test::call_service(&mut fltr, req).await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }

    #[actix_rt::test]
    async fn test_blocklist() {
        let ip_filter = IPFilter::new().block(vec!["192.168.*.2?3"]);
        let mut fltr = ip_filter.new_transform(test::ok_service()).await.unwrap();

        let req = test::TestRequest::with_uri("test")
            .peer_addr("192.168.0.222:8888".parse().unwrap())
            .to_srv_request();
        let resp = test::call_service(&mut fltr, req).await;
        assert_eq!(resp.status(), StatusCode::OK);

        let req = test::TestRequest::with_uri("test")
            .peer_addr("192.168.0.233:8888".parse().unwrap())
            .to_srv_request();
        let resp = test::call_service(&mut fltr, req).await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }

    #[actix_rt::test]
    async fn test_xrealip() {
        let ip_filter = IPFilter::new().allow(vec!["192.168.*.11?"]).x_real_ip(true);
        let mut fltr = ip_filter.new_transform(test::ok_service()).await.unwrap();
        let req = test::TestRequest::default()
            .insert_header(("X-REAL-IP", "192.168.0.111"))
            .peer_addr("192.168.0.222:8888".parse().unwrap())
            .to_srv_request();
        let resp = test::call_service(&mut fltr, req).await;
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[actix_rt::test]
    async fn test_limitlist() {
        let ip_filter = IPFilter::new()
            .block(vec!["192.168.*.11?"])
            .limit_to(vec!["/protected/path/*"]);
        let mut fltr = ip_filter.new_transform(test::ok_service()).await.unwrap();

        let req = test::TestRequest::with_uri("/protected/path/hello")
            .peer_addr("192.168.0.111:8888".parse().unwrap())
            .to_srv_request();

        let resp = test::call_service(&mut fltr, req).await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);

        let req = test::TestRequest::with_uri("/another/path")
            .peer_addr("192.168.0.111:8888".parse().unwrap())
            .to_srv_request();

        let resp = test::call_service(&mut fltr, req).await;
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[actix_rt::test]
    async fn test_allow_handler() {
        let ip_filter = IPFilter::new()
            .allow(vec!["192.168.*.11?"])
            .limit_to(vec!["/protected/path/*"]);

        //let mut allow_count: u32 = 0;

        // Use closure instead of fn in order to capture ip_filter and allow_count.

        //let my_custom_handler = |filter: &IPFilter, ip: &str, req: &ServiceRequest| {
        //    allow_count += 1;
        //    assert_eq!(ip_filter, filter);
        //    assert_eq!(Pattern::new("192.168.*.11?").unwrap().matches(ip), true);
        //    assert_eq!(Pattern::new("/protected/path/*").unwrap().matches(req.path()), true);
        //};

        fn my_custom_handler(_filter: &IPFilter, ip: &str, req: &ServiceRequest) {
            assert_eq!(Pattern::new("192.168.*.11?").unwrap().matches(ip), true);
            assert_eq!(
                Pattern::new("/protected/path/*")
                    .unwrap()
                    .matches(req.path()),
                true
            );
        }

        // De-mut and attach custom handler to IPFilter.
        let ip_filter = ip_filter.on_allow(my_custom_handler);
        let mut fltr = ip_filter.new_transform(test::ok_service()).await.unwrap();

        // Protected path and allowed ip should call the allow callback.
        let req = test::TestRequest::with_uri("/protected/path/hello")
            .peer_addr("192.168.0.111:8888".parse().unwrap())
            .to_srv_request();
        test::call_service(&mut fltr, req).await;
        //assert_eq!(allow_count, 1);

        // Unprotected path should not call the allow callback.
        let req = test::TestRequest::with_uri("/unprotected/path/hello")
            .peer_addr("192.168.0.111:8888".parse().unwrap())
            .to_srv_request();
        test::call_service(&mut fltr, req).await;
        //assert_eq!(allow_count, 1);

        // Protected path and blocked ip should not call the allow callback.
        let req = test::TestRequest::with_uri("/protected/path/hello")
            .peer_addr("192.168.0.222:8888".parse().unwrap())
            .to_srv_request();
        test::call_service(&mut fltr, req).await;
        //assert_eq!(allow_count, 1);
    }

    #[actix_rt::test]
    async fn test_block_handler() {
        fn my_custom_handler(
            _filter: &IPFilter,
            ip: &str,
            req: &ServiceRequest,
        ) -> Option<HttpResponse> {
            assert_eq!(Pattern::new("192.168.*.11?").unwrap().matches(ip), false);
            assert_eq!(
                Pattern::new("/protected/path/*")
                    .unwrap()
                    .matches(req.path()),
                true
            );
            Some(HttpResponse::UseProxy().json("{\"result\": \"error\"}"))
        }

        let mut ip_filter = IPFilter::new()
            .allow(vec!["192.168.*.11?"])
            .limit_to(vec!["/protected/path/*"])
            .on_block(my_custom_handler);
        let mut fltr = ip_filter.new_transform(test::ok_service()).await.unwrap();

        let req = test::TestRequest::with_uri("/protected/path/hello")
            .peer_addr("192.168.0.222:8888".parse().unwrap())
            .to_srv_request();
        let resp = test::call_service(&mut fltr, req).await;
        assert_eq!(resp.status(), StatusCode::USE_PROXY);

        fn logging_handler(
            _filter: &IPFilter,
            _ip: &str,
            _req: &ServiceRequest,
        ) -> Option<HttpResponse> {
            None
        }

        ip_filter = ip_filter.on_block(logging_handler);
        fltr = ip_filter.new_transform(test::ok_service()).await.unwrap();

        let req = test::TestRequest::with_uri("/protected/path/hello")
            .peer_addr("192.168.0.222:8888".parse().unwrap())
            .to_srv_request();
        let resp = test::call_service(&mut fltr, req).await;
        assert_eq!(resp.status(), StatusCode::FORBIDDEN);
    }
}