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
// Copyright 2024-2025 Tree xie.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use super::{
Error, get_hash_key, get_plugin_factory, get_str_conf, get_str_slice_conf,
};
use async_trait::async_trait;
use bytes::Bytes;
use ctor::ctor;
use http::StatusCode;
use pingap_config::PluginConf;
use pingap_core::{
Ctx, HttpResponse, Plugin, PluginStep, RequestPluginResult, get_client_ip,
};
use pingap_util::IpRules;
use pingora::proxy::Session;
use std::borrow::Cow;
use std::sync::Arc;
use tracing::debug;
type Result<T, E = Error> = std::result::Result<T, E>;
/// IpRestriction plugin provides IP-based access control for HTTP requests.
/// It can be configured to either allow or deny requests based on client IP addresses.
pub struct IpRestriction {
plugin_step: PluginStep, // Defines when plugin runs in request lifecycle (must be Request)
ip_rules: pingap_util::IpRules, // Contains parsed IP addresses and CIDR ranges for matching
restriction_category: String, // "allow": whitelist mode, "deny": blacklist mode
forbidden_resp: HttpResponse, // Customizable 403 response returned when access is denied
hash_value: String, // Unique identifier used for plugin caching/tracking
}
impl TryFrom<&PluginConf> for IpRestriction {
type Error = Error;
/// Attempts to create a new IpRestriction instance from a plugin configuration.
///
/// # Arguments
/// * `value` - Plugin configuration containing IP rules, restriction type, and optional message
///
/// # Returns
/// * `Ok(IpRestriction)` - Successfully created instance
/// * `Err(Error)` - If configuration is invalid (e.g., wrong plugin step)
///
/// # Configuration Example
/// ```toml
/// type = "deny"
/// ip_list = ["192.168.1.1", "10.0.0.0/24"]
/// message = "Access denied"
/// ```
fn try_from(value: &PluginConf) -> Result<Self> {
// Generate unique hash for this plugin instance
let hash_value = get_hash_key(value);
// Parse IP rules from configuration
// Supports both individual IPs ("192.168.1.1") and CIDR ranges ("10.0.0.0/24")
let ip_rules = IpRules::new(&get_str_slice_conf(value, "ip_list"));
// Get custom error message or use default
let mut message = get_str_conf(value, "message");
if message.is_empty() {
message = "Request is forbidden".to_string();
}
let params = Self {
hash_value,
plugin_step: PluginStep::Request,
ip_rules,
restriction_category: get_str_conf(value, "type"),
forbidden_resp: HttpResponse {
status: StatusCode::FORBIDDEN,
body: Bytes::from(message),
..Default::default()
},
};
Ok(params)
}
}
impl IpRestriction {
/// Creates a new IpRestriction plugin instance from the provided configuration.
///
/// # Arguments
/// * `params` - Plugin configuration parameters
///
/// # Returns
/// * `Result<Self>` - New plugin instance or error if configuration is invalid
pub fn new(params: &PluginConf) -> Result<Self> {
debug!(params = params.to_string(), "new ip restriction plugin");
Self::try_from(params)
}
}
#[async_trait]
impl Plugin for IpRestriction {
/// Returns the unique hash key for this plugin instance.
/// Used for caching and identifying plugin instances.
#[inline]
fn config_key(&self) -> Cow<'_, str> {
Cow::Borrowed(&self.hash_value)
}
/// Handles incoming HTTP requests by checking client IP against configured rules.
///
/// # Arguments
/// * `step` - Current plugin execution step
/// * `session` - HTTP session containing request details
/// * `ctx` - Request context for storing/retrieving state
///
/// # Returns
/// * `Ok(None)` - Request is allowed to proceed
/// * `Ok(Some(HttpResponse))` - Request is denied (403) or invalid (400)
/// * `Err(_)` - Internal error occurred during processing
///
/// # Processing Flow
/// 1. Verifies correct plugin step
/// 2. Extracts and caches client IP
/// 3. Checks IP against configured rules
/// 4. Allows or denies request based on restriction type
#[inline]
async fn handle_request(
&self,
step: PluginStep,
session: &mut Session,
ctx: &mut Ctx,
) -> pingora::Result<RequestPluginResult> {
// Skip processing if not in correct plugin step
if step != self.plugin_step {
return Ok(RequestPluginResult::Skipped);
}
// Get client IP address, using cached value if available
// Otherwise extract from X-Forwarded-For or remote address
let ip = ctx
.conn
.client_ip
.get_or_insert_with(|| get_client_ip(session));
// Check if IP matches any configured rules
// Returns error if IP is malformed
let found = match self.ip_rules.is_match(ip) {
Ok(matched) => matched,
Err(e) => {
return Ok(RequestPluginResult::Respond(
HttpResponse::bad_request(e.to_string()),
));
},
};
// Determine if request should be allowed based on:
// - deny mode: block if IP is found in rules (!found)
// - allow mode: block if IP is NOT found in rules (found)
let allow = if self.restriction_category == "deny" {
!found
} else {
found
};
if !allow {
// Return forbidden response with custom message if configured
return Ok(RequestPluginResult::Respond(
self.forbidden_resp.clone(),
));
}
// Allow request to proceed
Ok(RequestPluginResult::Continue)
}
}
#[ctor]
fn init() {
get_plugin_factory().register("ip_restriction", |params| {
Ok(Arc::new(IpRestriction::new(params)?))
});
}
#[cfg(test)]
mod tests {
use super::*;
use http::StatusCode;
use pingap_config::PluginConf;
use pingap_core::{ConnectionInfo, Ctx, PluginStep};
use pingora::proxy::Session;
use pretty_assertions::assert_eq;
use tokio_test::io::Builder;
/// Tests IP restriction parameter parsing and validation.
/// Verifies that:
/// - Plugin step must be "request"
/// - IP rules are correctly parsed
/// - Both individual IPs and CIDR ranges are supported
#[test]
fn test_ip_limit_params() {
let params = IpRestriction::try_from(
&toml::from_str::<PluginConf>(
r###"
ip_list = [
"192.168.1.1",
"10.1.1.1",
"1.1.1.0/24",
"2.1.1.0/24",
]
type = "deny"
"###,
)
.unwrap(),
)
.unwrap();
assert_eq!("request", params.plugin_step.to_string());
let description = format!("{:?}", params.ip_rules);
assert_eq!(true, description.contains("ip_net_list"));
assert_eq!(true, description.contains("[1.1.1.0/24, 2.1.1.0/24]"));
assert_eq!(true, description.contains("ip_set"));
assert_eq!(true, description.contains("10.1.1.1"));
assert_eq!(true, description.contains("192.168.1.1"));
}
/// Tests IP restriction functionality.
/// Verifies:
/// - Deny list blocks matching IPs
/// - Allow list permits matching IPs
/// - CIDR range matching works correctly
/// - IP caching in context functions properly
/// - Correct response codes are returned
#[tokio::test]
async fn test_ip_limit() {
let deny = IpRestriction::new(
&toml::from_str::<PluginConf>(
r###"
type = "deny"
ip_list = [
"192.168.1.1",
"1.1.1.0/24",
]
"###,
)
.unwrap(),
)
.unwrap();
let headers = ["X-Forwarded-For: 2.1.1.2"].join("\r\n");
let input_header =
format!("GET /vicanso/pingap?size=1 HTTP/1.1\r\n{headers}\r\n\r\n");
let mock_io = Builder::new().read(input_header.as_bytes()).build();
let mut session = Session::new_h1(Box::new(mock_io));
session.read_request().await.unwrap();
let result = deny
.handle_request(
PluginStep::Request,
&mut session,
&mut Ctx::default(),
)
.await
.unwrap();
assert_eq!(true, result == RequestPluginResult::Continue);
let headers = ["X-Forwarded-For: 192.168.1.1"].join("\r\n");
let input_header =
format!("GET /vicanso/pingap?size=1 HTTP/1.1\r\n{headers}\r\n\r\n");
let mock_io = Builder::new().read(input_header.as_bytes()).build();
let mut session = Session::new_h1(Box::new(mock_io));
session.read_request().await.unwrap();
let result = deny
.handle_request(
PluginStep::Request,
&mut session,
&mut Ctx::default(),
)
.await
.unwrap();
let RequestPluginResult::Respond(resp) = result else {
panic!("result is not Respond");
};
assert_eq!(403, resp.status.as_u16());
let headers = ["Accept-Encoding: gzip"].join("\r\n");
let input_header =
format!("GET /vicanso/pingap?size=1 HTTP/1.1\r\n{headers}\r\n\r\n");
let mock_io = Builder::new().read(input_header.as_bytes()).build();
let mut session = Session::new_h1(Box::new(mock_io));
session.read_request().await.unwrap();
let result = deny
.handle_request(
PluginStep::Request,
&mut session,
&mut Ctx {
conn: ConnectionInfo {
client_ip: Some("2.1.1.2".to_string()),
..Default::default()
},
..Default::default()
},
)
.await
.unwrap();
assert_eq!(true, result == RequestPluginResult::Continue);
let result = deny
.handle_request(
PluginStep::Request,
&mut session,
&mut Ctx {
conn: ConnectionInfo {
client_ip: Some("1.1.1.2".to_string()),
..Default::default()
},
..Default::default()
},
)
.await
.unwrap();
let RequestPluginResult::Respond(resp) = result else {
panic!("result is not Respond");
};
assert_eq!(StatusCode::FORBIDDEN, resp.status);
let allow = IpRestriction::new(
&toml::from_str::<PluginConf>(
r###"
type = "allow"
ip_list = [
"192.168.1.1",
"1.1.1.0/24",
]
"###,
)
.unwrap(),
)
.unwrap();
let headers = ["X-Forwarded-For: 192.168.1.1"].join("\r\n");
let input_header =
format!("GET /vicanso/pingap?size=1 HTTP/1.1\r\n{headers}\r\n\r\n");
let mock_io = Builder::new().read(input_header.as_bytes()).build();
let mut session = Session::new_h1(Box::new(mock_io));
session.read_request().await.unwrap();
let result = allow
.handle_request(
PluginStep::Request,
&mut session,
&mut Ctx::default(),
)
.await
.unwrap();
assert_eq!(true, result == RequestPluginResult::Continue);
}
}