jmespath_extensions 0.9.0

Extended functions for JMESPath queries - 400+ functions for strings, arrays, dates, hashing, encoding, geo, and more
Documentation
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
//! Network and IP address functions.
//!
//! This module provides network functions for JMESPath queries.
//!
//! For complete function reference with signatures and examples, see the
//! [`functions`](crate::functions) module documentation or use `jpx --list-category network`.
//!
//! # Example
//!
//! ```rust
//! use jmespath::{Runtime, Variable};
//! use jmespath_extensions::network;
//!
//! let mut runtime = Runtime::new();
//! runtime.register_builtin_functions();
//! network::register(&mut runtime);
//! ```

use std::collections::HashSet;
use std::net::Ipv4Addr;
use std::rc::Rc;
use std::str::FromStr;

use ipnetwork::{IpNetwork, Ipv4Network};

use crate::common::Function;
use crate::register_if_enabled;
use crate::{ArgumentType, Context, JmespathError, Rcvar, Runtime, Signature, Variable};

/// Register all network functions with the runtime.
pub fn register(runtime: &mut Runtime) {
    runtime.register_function("ip_to_int", Box::new(IpToIntFn::new()));
    runtime.register_function("int_to_ip", Box::new(IntToIpFn::new()));
    runtime.register_function("cidr_contains", Box::new(CidrContainsFn::new()));
    runtime.register_function("cidr_network", Box::new(CidrNetworkFn::new()));
    runtime.register_function("cidr_broadcast", Box::new(CidrBroadcastFn::new()));
    runtime.register_function("cidr_prefix", Box::new(CidrPrefixFn::new()));
    runtime.register_function("is_private_ip", Box::new(IsPrivateIpFn::new()));
}

/// Register only enabled network functions with the runtime.
pub fn register_filtered(runtime: &mut Runtime, enabled: &HashSet<&str>) {
    register_if_enabled!(runtime, enabled, "ip_to_int", Box::new(IpToIntFn::new()));
    register_if_enabled!(runtime, enabled, "int_to_ip", Box::new(IntToIpFn::new()));
    register_if_enabled!(
        runtime,
        enabled,
        "cidr_contains",
        Box::new(CidrContainsFn::new())
    );
    register_if_enabled!(
        runtime,
        enabled,
        "cidr_network",
        Box::new(CidrNetworkFn::new())
    );
    register_if_enabled!(
        runtime,
        enabled,
        "cidr_broadcast",
        Box::new(CidrBroadcastFn::new())
    );
    register_if_enabled!(
        runtime,
        enabled,
        "cidr_prefix",
        Box::new(CidrPrefixFn::new())
    );
    register_if_enabled!(
        runtime,
        enabled,
        "is_private_ip",
        Box::new(IsPrivateIpFn::new())
    );
}

// =============================================================================
// ip_to_int(s) -> number
// =============================================================================

pub struct IpToIntFn {
    signature: Signature,
}

impl Default for IpToIntFn {
    fn default() -> Self {
        Self::new()
    }
}

impl IpToIntFn {
    pub fn new() -> Self {
        Self {
            signature: Signature::new(vec![ArgumentType::String], None),
        }
    }
}

impl Function for IpToIntFn {
    fn evaluate(&self, args: &[Rcvar], ctx: &mut Context<'_>) -> Result<Rcvar, JmespathError> {
        self.signature.validate(args, ctx)?;
        let s = args[0].as_string().unwrap();

        match Ipv4Addr::from_str(s) {
            Ok(ip) => {
                let int_val: u32 = ip.into();
                Ok(Rc::new(Variable::Number(
                    serde_json::Number::from_f64(int_val as f64).unwrap(),
                )))
            }
            Err(_) => Ok(Rc::new(Variable::Null)),
        }
    }
}

// =============================================================================
// int_to_ip(n) -> string
// =============================================================================

pub struct IntToIpFn {
    signature: Signature,
}

impl Default for IntToIpFn {
    fn default() -> Self {
        Self::new()
    }
}

impl IntToIpFn {
    pub fn new() -> Self {
        Self {
            signature: Signature::new(vec![ArgumentType::Number], None),
        }
    }
}

impl Function for IntToIpFn {
    fn evaluate(&self, args: &[Rcvar], ctx: &mut Context<'_>) -> Result<Rcvar, JmespathError> {
        self.signature.validate(args, ctx)?;
        let n = args[0].as_number().unwrap();

        if n < 0.0 || n > u32::MAX as f64 {
            return Ok(Rc::new(Variable::Null));
        }

        let ip = Ipv4Addr::from(n as u32);
        Ok(Rc::new(Variable::String(ip.to_string())))
    }
}

// =============================================================================
// cidr_contains(cidr, ip) -> bool
// =============================================================================

pub struct CidrContainsFn {
    signature: Signature,
}

impl Default for CidrContainsFn {
    fn default() -> Self {
        Self::new()
    }
}

impl CidrContainsFn {
    pub fn new() -> Self {
        Self {
            signature: Signature::new(vec![ArgumentType::String, ArgumentType::String], None),
        }
    }
}

impl Function for CidrContainsFn {
    fn evaluate(&self, args: &[Rcvar], ctx: &mut Context<'_>) -> Result<Rcvar, JmespathError> {
        self.signature.validate(args, ctx)?;
        let cidr_str = args[0].as_string().unwrap();
        let ip_str = args[1].as_string().unwrap();

        let network = match IpNetwork::from_str(cidr_str) {
            Ok(n) => n,
            Err(_) => return Ok(Rc::new(Variable::Null)),
        };

        let ip: std::net::IpAddr = match ip_str.parse() {
            Ok(ip) => ip,
            Err(_) => return Ok(Rc::new(Variable::Null)),
        };

        Ok(Rc::new(Variable::Bool(network.contains(ip))))
    }
}

// =============================================================================
// cidr_network(cidr) -> string
// =============================================================================

pub struct CidrNetworkFn {
    signature: Signature,
}

impl Default for CidrNetworkFn {
    fn default() -> Self {
        Self::new()
    }
}

impl CidrNetworkFn {
    pub fn new() -> Self {
        Self {
            signature: Signature::new(vec![ArgumentType::String], None),
        }
    }
}

impl Function for CidrNetworkFn {
    fn evaluate(&self, args: &[Rcvar], ctx: &mut Context<'_>) -> Result<Rcvar, JmespathError> {
        self.signature.validate(args, ctx)?;
        let cidr_str = args[0].as_string().unwrap();

        match Ipv4Network::from_str(cidr_str) {
            Ok(network) => Ok(Rc::new(Variable::String(network.network().to_string()))),
            Err(_) => Ok(Rc::new(Variable::Null)),
        }
    }
}

// =============================================================================
// cidr_broadcast(cidr) -> string
// =============================================================================

pub struct CidrBroadcastFn {
    signature: Signature,
}

impl Default for CidrBroadcastFn {
    fn default() -> Self {
        Self::new()
    }
}

impl CidrBroadcastFn {
    pub fn new() -> Self {
        Self {
            signature: Signature::new(vec![ArgumentType::String], None),
        }
    }
}

impl Function for CidrBroadcastFn {
    fn evaluate(&self, args: &[Rcvar], ctx: &mut Context<'_>) -> Result<Rcvar, JmespathError> {
        self.signature.validate(args, ctx)?;
        let cidr_str = args[0].as_string().unwrap();

        match Ipv4Network::from_str(cidr_str) {
            Ok(network) => Ok(Rc::new(Variable::String(network.broadcast().to_string()))),
            Err(_) => Ok(Rc::new(Variable::Null)),
        }
    }
}

// =============================================================================
// cidr_prefix(cidr) -> number
// =============================================================================

pub struct CidrPrefixFn {
    signature: Signature,
}

impl Default for CidrPrefixFn {
    fn default() -> Self {
        Self::new()
    }
}

impl CidrPrefixFn {
    pub fn new() -> Self {
        Self {
            signature: Signature::new(vec![ArgumentType::String], None),
        }
    }
}

impl Function for CidrPrefixFn {
    fn evaluate(&self, args: &[Rcvar], ctx: &mut Context<'_>) -> Result<Rcvar, JmespathError> {
        self.signature.validate(args, ctx)?;
        let cidr_str = args[0].as_string().unwrap();

        match IpNetwork::from_str(cidr_str) {
            Ok(network) => Ok(Rc::new(Variable::Number(serde_json::Number::from(
                network.prefix(),
            )))),
            Err(_) => Ok(Rc::new(Variable::Null)),
        }
    }
}

// =============================================================================
// is_private_ip(ip) -> bool
// =============================================================================

pub struct IsPrivateIpFn {
    signature: Signature,
}

impl Default for IsPrivateIpFn {
    fn default() -> Self {
        Self::new()
    }
}

impl IsPrivateIpFn {
    pub fn new() -> Self {
        Self {
            signature: Signature::new(vec![ArgumentType::String], None),
        }
    }
}

impl Function for IsPrivateIpFn {
    fn evaluate(&self, args: &[Rcvar], ctx: &mut Context<'_>) -> Result<Rcvar, JmespathError> {
        self.signature.validate(args, ctx)?;
        let ip_str = args[0].as_string().unwrap();

        match Ipv4Addr::from_str(ip_str) {
            Ok(ip) => Ok(Rc::new(Variable::Bool(ip.is_private()))),
            Err(_) => Ok(Rc::new(Variable::Null)),
        }
    }
}

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

    fn setup() -> Runtime {
        let mut runtime = Runtime::new();
        runtime.register_builtin_functions();
        register(&mut runtime);
        runtime
    }

    #[test]
    fn test_ip_to_int() {
        let runtime = setup();
        let data = Variable::from_json(r#""192.168.1.1""#).unwrap();
        let expr = runtime.compile("ip_to_int(@)").unwrap();
        let result = expr.search(&data).unwrap();
        // 192.168.1.1 = 192*256^3 + 168*256^2 + 1*256 + 1 = 3232235777
        assert_eq!(result.as_number().unwrap(), 3232235777.0);
    }

    #[test]
    fn test_int_to_ip() {
        let runtime = setup();
        let data = Variable::from_json(r#"3232235777"#).unwrap();
        let expr = runtime.compile("int_to_ip(@)").unwrap();
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_string().unwrap(), "192.168.1.1");
    }

    #[test]
    fn test_ip_roundtrip() {
        let runtime = setup();
        let data = Variable::from_json(r#""10.0.0.1""#).unwrap();
        let expr = runtime.compile("int_to_ip(ip_to_int(@))").unwrap();
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_string().unwrap(), "10.0.0.1");
    }

    #[test]
    fn test_cidr_contains_true() {
        let runtime = setup();
        let data =
            Variable::from_json(r#"{"cidr": "192.168.1.0/24", "ip": "192.168.1.100"}"#).unwrap();
        let expr = runtime.compile("cidr_contains(cidr, ip)").unwrap();
        let result = expr.search(&data).unwrap();
        assert!(result.as_boolean().unwrap());
    }

    #[test]
    fn test_cidr_contains_false() {
        let runtime = setup();
        let data =
            Variable::from_json(r#"{"cidr": "192.168.1.0/24", "ip": "192.168.2.1"}"#).unwrap();
        let expr = runtime.compile("cidr_contains(cidr, ip)").unwrap();
        let result = expr.search(&data).unwrap();
        assert!(!result.as_boolean().unwrap());
    }

    #[test]
    fn test_cidr_network() {
        let runtime = setup();
        let data = Variable::from_json(r#""192.168.1.100/24""#).unwrap();
        let expr = runtime.compile("cidr_network(@)").unwrap();
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_string().unwrap(), "192.168.1.0");
    }

    #[test]
    fn test_cidr_broadcast() {
        let runtime = setup();
        let data = Variable::from_json(r#""192.168.1.0/24""#).unwrap();
        let expr = runtime.compile("cidr_broadcast(@)").unwrap();
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_string().unwrap(), "192.168.1.255");
    }

    #[test]
    fn test_cidr_prefix() {
        let runtime = setup();
        let data = Variable::from_json(r#""10.0.0.0/8""#).unwrap();
        let expr = runtime.compile("cidr_prefix(@)").unwrap();
        let result = expr.search(&data).unwrap();
        assert_eq!(result.as_number().unwrap(), 8.0);
    }

    #[test]
    fn test_is_private_ip_true() {
        let runtime = setup();
        // 192.168.x.x is private
        let data = Variable::from_json(r#""192.168.1.1""#).unwrap();
        let expr = runtime.compile("is_private_ip(@)").unwrap();
        let result = expr.search(&data).unwrap();
        assert!(result.as_boolean().unwrap());
    }

    #[test]
    fn test_is_private_ip_10() {
        let runtime = setup();
        // 10.x.x.x is private
        let data = Variable::from_json(r#""10.0.0.1""#).unwrap();
        let expr = runtime.compile("is_private_ip(@)").unwrap();
        let result = expr.search(&data).unwrap();
        assert!(result.as_boolean().unwrap());
    }

    #[test]
    fn test_is_private_ip_false() {
        let runtime = setup();
        // 8.8.8.8 is public (Google DNS)
        let data = Variable::from_json(r#""8.8.8.8""#).unwrap();
        let expr = runtime.compile("is_private_ip(@)").unwrap();
        let result = expr.search(&data).unwrap();
        assert!(!result.as_boolean().unwrap());
    }
}