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
//! Custom `serde` deserializer for `FilterMatch`

use core::fmt;
use core::str::FromStr;

use ibc::core::ics24_host::identifier::{ChannelId, PortId};
use itertools::Itertools;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};

/// Represents the ways in which packets can be filtered.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(
    rename_all = "lowercase",
    tag = "policy",
    content = "list",
    deny_unknown_fields
)]
pub enum PacketFilter {
    /// Allow packets from the specified channels.
    Allow(ChannelFilters),
    /// Deny packets from the specified channels.
    Deny(ChannelFilters),
    /// Allow any & all packets.
    AllowAll,
}

impl Default for PacketFilter {
    /// By default, allows all channels & ports.
    fn default() -> Self {
        Self::AllowAll
    }
}

impl PacketFilter {
    /// Returns true if the packets can be relayed on the channel with [`PortId`] and [`ChannelId`],
    /// false otherwise.
    pub fn is_allowed(&self, port_id: &PortId, channel_id: &ChannelId) -> bool {
        match self {
            PacketFilter::Allow(filters) => filters.matches((port_id, channel_id)),
            PacketFilter::Deny(filters) => !filters.matches((port_id, channel_id)),
            PacketFilter::AllowAll => true,
        }
    }
}

/// The internal representation of channel filter policies.
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ChannelFilters(Vec<(PortFilterMatch, ChannelFilterMatch)>);

impl ChannelFilters {
    /// Create a new filter from the given list of port/channel filters.
    pub fn new(filters: Vec<(PortFilterMatch, ChannelFilterMatch)>) -> Self {
        Self(filters)
    }

    /// Indicates whether a match for the given [`PortId`]-[`ChannelId`] pair
    /// exists in the filter policy.
    pub fn matches(&self, channel_port: (&PortId, &ChannelId)) -> bool {
        let (port_id, channel_id) = channel_port;
        self.0.iter().any(|(port_filter, chan_filter)| {
            port_filter.matches(port_id) && chan_filter.matches(channel_id)
        })
    }

    /// Indicates whether this filter policy contains only exact patterns.
    #[inline]
    pub fn is_exact(&self) -> bool {
        self.0.iter().all(|(port_filter, channel_filter)| {
            port_filter.is_exact() && channel_filter.is_exact()
        })
    }

    /// An iterator over the [`PortId`]-[`ChannelId`] pairs that don't contain wildcards.
    pub fn iter_exact(&self) -> impl Iterator<Item = (&PortId, &ChannelId)> {
        self.0.iter().filter_map(|port_chan_filter| {
            if let &(FilterPattern::Exact(ref port_id), FilterPattern::Exact(ref chan_id)) =
                port_chan_filter
            {
                Some((port_id, chan_id))
            } else {
                None
            }
        })
    }
}

impl fmt::Display for ChannelFilters {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            self.0
                .iter()
                .map(|(pid, cid)| format!("{}/{}", pid, cid))
                .join(", ")
        )
    }
}

impl Serialize for ChannelFilters {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use serde::ser::SerializeSeq;

        struct Pair<'a> {
            a: &'a FilterPattern<PortId>,
            b: &'a FilterPattern<ChannelId>,
        }

        impl<'a> Serialize for Pair<'a> {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                let mut seq = serializer.serialize_seq(Some(2))?;
                seq.serialize_element(self.a)?;
                seq.serialize_element(self.b)?;
                seq.end()
            }
        }

        let mut outer_seq = serializer.serialize_seq(Some(self.0.len()))?;

        for (port, channel) in &self.0 {
            outer_seq.serialize_element(&Pair {
                a: port,
                b: channel,
            })?;
        }

        outer_seq.end()
    }
}

/// Newtype wrapper for expressing wildcard patterns compiled to a [`regex::Regex`].
#[derive(Clone, Debug)]
pub struct Wildcard {
    pattern: String,
    regex: regex::Regex,
}

impl Wildcard {
    pub fn new(pattern: String) -> Result<Self, regex::Error> {
        let escaped = regex::escape(&pattern).replace("\\*", "(?:.*)");
        let regex = format!("^{escaped}$").parse()?;
        Ok(Self { pattern, regex })
    }

    #[inline]
    pub fn is_match(&self, text: &str) -> bool {
        self.regex.is_match(text)
    }
}

impl FromStr for Wildcard {
    type Err = regex::Error;

    fn from_str(pattern: &str) -> Result<Self, Self::Err> {
        Self::new(pattern.to_string())
    }
}

impl fmt::Display for Wildcard {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.pattern)
    }
}

impl Serialize for Wildcard {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.pattern)
    }
}

impl PartialEq for Wildcard {
    fn eq(&self, other: &Self) -> bool {
        self.pattern == other.pattern
    }
}

/// Represents a single channel to be filtered in a [`ChannelFilters`] list.
#[derive(Clone, Debug, PartialEq)]
pub enum FilterPattern<T> {
    /// A channel specified exactly with its [`PortId`] & [`ChannelId`].
    Exact(T),
    /// A glob of channel(s) specified with a wildcard in either or both [`PortId`] & [`ChannelId`].
    Wildcard(Wildcard),
}

impl<T> FilterPattern<T> {
    /// Indicates whether this filter is specified in part with a wildcard.
    pub fn is_wildcard(&self) -> bool {
        matches!(self, Self::Wildcard(_))
    }

    /// Indicates whether this filter is specified as an exact match.
    pub fn is_exact(&self) -> bool {
        matches!(self, Self::Exact(_))
    }

    /// Matches the given value via strict equality if the filter is an `Exact`, or via
    /// wildcard matching if the filter is a `Pattern`.
    pub fn matches(&self, value: &T) -> bool
    where
        T: PartialEq + ToString,
    {
        match self {
            FilterPattern::Exact(v) => value == v,
            FilterPattern::Wildcard(regex) => regex.is_match(&value.to_string()),
        }
    }

    /// Returns the contained value if this filter contains an `Exact` variant, or
    /// `None` if it contains a `Pattern`.
    pub fn exact_value(&self) -> Option<&T> {
        match self {
            FilterPattern::Exact(value) => Some(value),
            FilterPattern::Wildcard(_) => None,
        }
    }
}

impl<T: fmt::Display> fmt::Display for FilterPattern<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FilterPattern::Exact(value) => write!(f, "{}", value),
            FilterPattern::Wildcard(regex) => write!(f, "{}", regex),
        }
    }
}

impl<T> Serialize for FilterPattern<T>
where
    T: ToString,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            FilterPattern::Exact(e) => serializer.serialize_str(&e.to_string()),
            FilterPattern::Wildcard(t) => serializer.serialize_str(&t.to_string()),
        }
    }
}

/// Type alias for a [`FilterPattern`] containing a [`PortId`].
pub type PortFilterMatch = FilterPattern<PortId>;
/// Type alias for a [`FilterPattern`] containing a [`ChannelId`].
pub type ChannelFilterMatch = FilterPattern<ChannelId>;

impl<'de> Deserialize<'de> for PortFilterMatch {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<PortFilterMatch, D::Error> {
        deserializer.deserialize_string(port::PortFilterMatchVisitor)
    }
}

impl<'de> Deserialize<'de> for ChannelFilterMatch {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<ChannelFilterMatch, D::Error> {
        deserializer.deserialize_string(channel::ChannelFilterMatchVisitor)
    }
}

pub(crate) mod port {
    use super::*;
    use ibc::core::ics24_host::identifier::PortId;

    pub struct PortFilterMatchVisitor;

    impl<'de> de::Visitor<'de> for PortFilterMatchVisitor {
        type Value = PortFilterMatch;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("valid PortId or wildcard")
        }

        fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
            if let Ok(port_id) = PortId::from_str(v) {
                Ok(PortFilterMatch::Exact(port_id))
            } else {
                let wildcard = v.parse().map_err(E::custom)?;
                Ok(PortFilterMatch::Wildcard(wildcard))
            }
        }

        fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
            self.visit_str(&v)
        }
    }
}

pub(crate) mod channel {
    use super::*;
    use ibc::core::ics24_host::identifier::ChannelId;

    pub struct ChannelFilterMatchVisitor;

    impl<'de> de::Visitor<'de> for ChannelFilterMatchVisitor {
        type Value = ChannelFilterMatch;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("valid ChannelId or wildcard")
        }

        fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
            if let Ok(channel_id) = ChannelId::from_str(v) {
                Ok(ChannelFilterMatch::Exact(channel_id))
            } else {
                let wildcard = v.parse().map_err(E::custom)?;
                Ok(ChannelFilterMatch::Wildcard(wildcard))
            }
        }

        fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
            self.visit_str(&v)
        }
    }
}

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

    #[test]
    fn deserialize_packet_filter_policy() {
        let toml_content = r#"
            policy = 'allow'
            list = [
              ['ica*', '*'],
              ['transfer', 'channel-0'],
            ]
            "#;

        let filter_policy: PacketFilter =
            toml::from_str(toml_content).expect("could not parse filter policy");

        dbg!(filter_policy);
    }

    #[test]
    fn serialize_packet_filter_policy() {
        use std::str::FromStr;

        use ibc::core::ics24_host::identifier::{ChannelId, PortId};

        let filter_policy = ChannelFilters(vec![
            (
                FilterPattern::Exact(PortId::from_str("transfer").unwrap()),
                FilterPattern::Exact(ChannelId::from_str("channel-0").unwrap()),
            ),
            (
                FilterPattern::Wildcard("ica*".parse().unwrap()),
                FilterPattern::Wildcard("*".parse().unwrap()),
            ),
        ]);

        let fp = PacketFilter::Allow(filter_policy);
        let toml_str = toml::to_string_pretty(&fp).expect("could not serialize packet filter");

        println!("{}", toml_str);
    }

    #[test]
    fn channel_filter_iter_exact() {
        let toml_content = r#"
            policy = 'deny'
            list = [
              ['ica', 'channel-*'],
              ['ica*', '*'],
              ['transfer', 'channel-0'],
              ['transfer*', 'channel-1'],
              ['ft-transfer', 'channel-2'],
            ]
            "#;

        let pf: PacketFilter = toml::from_str(toml_content).expect("could not parse filter policy");

        if let PacketFilter::Deny(channel_filters) = pf {
            let exact_matches = channel_filters.iter_exact().collect::<Vec<_>>();
            assert_eq!(
                exact_matches,
                vec![
                    (
                        &PortId::from_str("transfer").unwrap(),
                        &ChannelId::from_str("channel-0").unwrap()
                    ),
                    (
                        &PortId::from_str("ft-transfer").unwrap(),
                        &ChannelId::from_str("channel-2").unwrap()
                    )
                ]
            );
        } else {
            panic!("expected `PacketFilter::Deny` variant");
        }
    }

    #[test]
    fn packet_filter_deny_policy() {
        let deny_policy = r#"
            policy = 'deny'
            list = [
              ['ica', 'channel-*'],
              ['ica*', '*'],
              ['transfer', 'channel-0'],
              ['transfer*', 'channel-1'],
              ['ft-transfer', 'channel-2'],
            ]
            "#;

        let pf: PacketFilter = toml::from_str(deny_policy).expect("could not parse filter policy");

        assert!(!pf.is_allowed(
            &PortId::from_str("ft-transfer").unwrap(),
            &ChannelId::from_str("channel-2").unwrap()
        ));
        assert!(pf.is_allowed(
            &PortId::from_str("ft-transfer").unwrap(),
            &ChannelId::from_str("channel-1").unwrap()
        ));
        assert!(pf.is_allowed(
            &PortId::from_str("transfer").unwrap(),
            &ChannelId::from_str("channel-2").unwrap()
        ));
        assert!(!pf.is_allowed(
            &PortId::from_str("ica-1").unwrap(),
            &ChannelId::from_str("channel-2").unwrap()
        ));
    }

    #[test]
    fn packet_filter_allow_policy() {
        let allow_policy = r#"
            policy = 'allow'
            list = [
              ['ica', 'channel-*'],
              ['ica*', '*'],
              ['transfer', 'channel-0'],
              ['transfer*', 'channel-1'],
              ['ft-transfer', 'channel-2'],
            ]
            "#;

        let pf: PacketFilter = toml::from_str(allow_policy).expect("could not parse filter policy");

        assert!(pf.is_allowed(
            &PortId::from_str("ft-transfer").unwrap(),
            &ChannelId::from_str("channel-2").unwrap()
        ));
        assert!(!pf.is_allowed(
            &PortId::from_str("ft-transfer").unwrap(),
            &ChannelId::from_str("channel-1").unwrap()
        ));
        assert!(!pf.is_allowed(
            &PortId::from_str("transfer-1").unwrap(),
            &ChannelId::from_str("channel-2").unwrap()
        ));
        assert!(pf.is_allowed(
            &PortId::from_str("ica-1").unwrap(),
            &ChannelId::from_str("channel-2").unwrap()
        ));
        assert!(pf.is_allowed(
            &PortId::from_str("ica").unwrap(),
            &ChannelId::from_str("channel-1").unwrap()
        ));
    }

    #[test]
    fn packet_filter_regex() {
        let allow_policy = r#"
            policy = 'allow'
            list = [
              ['transfer*', 'channel-1'],
            ]
            "#;

        let pf: PacketFilter = toml::from_str(allow_policy).expect("could not parse filter policy");

        assert!(!pf.is_allowed(
            &PortId::from_str("ft-transfer").unwrap(),
            &ChannelId::from_str("channel-1").unwrap()
        ));
        assert!(!pf.is_allowed(
            &PortId::from_str("ft-transfer-port").unwrap(),
            &ChannelId::from_str("channel-1").unwrap()
        ));
    }

    #[test]
    fn to_string_wildcards() {
        let wildcard = "ica*".parse::<Wildcard>().unwrap();
        assert_eq!(wildcard.to_string(), "ica*".to_string());
    }
}