1
//! Configuration logic for onion service reverse proxy.
2

            
3
use derive_builder::Builder;
4
use derive_deftly::Deftly;
5
use serde::{Deserialize, Serialize};
6
use std::{net::SocketAddr, ops::RangeInclusive, str::FromStr};
7
use tracing::warn;
8
//use tor_config::derive_deftly_template_Flattenable;
9
use tor_config::{define_list_builder_accessors, define_list_builder_helper, ConfigBuildError};
10

            
11
/// Configuration for a reverse proxy running for one onion service.
12
64
#[derive(Clone, Debug, Builder, Eq, PartialEq)]
13
#[builder(build_fn(error = "ConfigBuildError", validate = "Self::validate"))]
14
#[builder(derive(Debug, Serialize, Deserialize, Deftly, Eq, PartialEq))]
15
#[builder_struct_attr(derive_deftly(tor_config::Flattenable))]
16
pub struct ProxyConfig {
17
    /// A list of rules to apply to incoming requests.  If no rule
18
    /// matches, we take the DestroyCircuit action.
19
    #[builder(sub_builder, setter(custom))]
20
    pub(crate) proxy_ports: ProxyRuleList,
21
    //
22
    // TODO: Someday we may want to allow udp, resolve, etc.  If we do, it will
23
    // be via another option, rather than adding another subtype to ProxySource.
24
}
25

            
26
impl ProxyConfigBuilder {
27
    /// Run checks on this ProxyConfig to ensure that it's valid.
28
64
    fn validate(&self) -> Result<(), ConfigBuildError> {
29
64
        // Make sure that every proxy pattern is actually reachable.
30
64
        let mut covered = rangemap::RangeInclusiveSet::<u16>::new();
31
136
        for rule in self.proxy_ports.access_opt().iter().flatten() {
32
136
            let range = &rule.source.0;
33
136
            if covered.gaps(range).next().is_none() {
34
2
                return Err(ConfigBuildError::Invalid {
35
2
                    field: "proxy_ports".into(),
36
2
                    problem: format!("Port pattern {} is not reachable", rule.source),
37
2
                });
38
134
            }
39
134
            covered.insert(range.clone());
40
        }
41

            
42
        // Warn about proxy setups that are likely to be surprising.
43
62
        let mut any_forward = false;
44
130
        for rule in self.proxy_ports.access_opt().iter().flatten() {
45
130
            if let ProxyAction::Forward(_, target) = &rule.target {
46
62
                any_forward = true;
47
62
                if !target.is_sufficiently_private() {
48
                    // TODO: here and below, we might want to someday
49
                    // have a mechanism to suppress these warnings,
50
                    // or have them show up only when relevant.
51
                    // For now they are unconditional.
52
                    // See discussion at #1154.
53
                    warn!(
54
                        "Onion service target {} does not look like a private address. \
55
                         Do you really mean to send connections onto the public internet?",
56
                        target
57
                    );
58
62
                }
59
68
            }
60
        }
61

            
62
62
        if !any_forward {
63
            warn!("Onion service is not configured to accept any connections.");
64
62
        }
65

            
66
62
        Ok(())
67
64
    }
68
}
69

            
70
define_list_builder_accessors! {
71
   struct ProxyConfigBuilder {
72
       pub proxy_ports: [ProxyRule],
73
   }
74
}
75

            
76
/// Helper to define builder for ProxyConfig.
77
type ProxyRuleList = Vec<ProxyRule>;
78

            
79
define_list_builder_helper! {
80
   #[derive(Eq, PartialEq)]
81
   pub struct ProxyRuleListBuilder {
82
       pub(crate) values: [ProxyRule],
83
   }
84
   built: ProxyRuleList = values;
85
   default = vec![];
86
130
   item_build: |value| Ok(value.clone());
87
}
88

            
89
impl ProxyConfig {
90
    /// Find the configured action to use when receiving a request for a
91
    /// connection on a given port.
92
    pub(crate) fn resolve_port_for_begin(&self, port: u16) -> Option<&ProxyAction> {
93
        self.proxy_ports
94
            .iter()
95
            .find(|rule| rule.source.matches_port(port))
96
            .map(|rule| &rule.target)
97
    }
98
}
99

            
100
/// A single rule in a `ProxyConfig`.
101
///
102
/// Rules take the form of, "When this pattern matches, take this action."
103
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
104
// TODO: we might someday want to accept structs here as well, so that
105
// we can add per-rule fields if we need to.  We can make that an option if/when
106
// it comes up, however.
107
#[serde(from = "ProxyRuleAsTuple", into = "ProxyRuleAsTuple")]
108
pub struct ProxyRule {
109
    /// Any connections to a port matching this pattern match this rule.
110
    source: ProxyPattern,
111
    /// When this rule matches, we take this action.
112
    target: ProxyAction,
113
}
114

            
115
/// Helper type used to (de)serialize ProxyRule.
116
type ProxyRuleAsTuple = (ProxyPattern, ProxyAction);
117
impl From<ProxyRuleAsTuple> for ProxyRule {
118
101
    fn from(value: ProxyRuleAsTuple) -> Self {
119
101
        Self {
120
101
            source: value.0,
121
101
            target: value.1,
122
101
        }
123
101
    }
124
}
125
impl From<ProxyRule> for ProxyRuleAsTuple {
126
    fn from(value: ProxyRule) -> Self {
127
        (value.source, value.target)
128
    }
129
}
130
impl ProxyRule {
131
    /// Create a new ProxyRule mapping `source` to `target`.
132
41
    pub fn new(source: ProxyPattern, target: ProxyAction) -> Self {
133
41
        Self { source, target }
134
41
    }
135
}
136

            
137
/// A set of ports to use when checking how to handle a port.
138
70
#[derive(Clone, Debug, serde::Deserialize, serde_with::SerializeDisplay, Eq, PartialEq)]
139
#[serde(try_from = "ProxyPatternAsEnum")]
140
pub struct ProxyPattern(RangeInclusive<u16>);
141

            
142
/// Representation for a [`ProxyPattern`]. Used while deserializing.
143
#[derive(serde::Deserialize)]
144
#[serde(untagged)]
145
enum ProxyPatternAsEnum {
146
    /// Representation the [`ProxyPattern`] as an integer.
147
    Number(u16),
148
    /// Representation of the [`ProxyPattern`] as a string.
149
    String(String),
150
}
151

            
152
impl TryFrom<ProxyPatternAsEnum> for ProxyPattern {
153
    type Error = ProxyConfigError;
154

            
155
101
    fn try_from(value: ProxyPatternAsEnum) -> Result<Self, Self::Error> {
156
101
        match value {
157
2
            ProxyPatternAsEnum::Number(port) => Self::one_port(port),
158
99
            ProxyPatternAsEnum::String(s) => Self::from_str(&s),
159
        }
160
101
    }
161
}
162

            
163
impl FromStr for ProxyPattern {
164
    type Err = ProxyConfigError;
165

            
166
113
    fn from_str(s: &str) -> Result<Self, Self::Err> {
167
        use ProxyConfigError as PCE;
168
113
        if s == "*" {
169
11
            Ok(Self::all_ports())
170
102
        } else if let Some((left, right)) = s.split_once('-') {
171
20
            let left: u16 = left
172
20
                .parse()
173
20
                .map_err(|e| PCE::InvalidPort(left.to_string(), e))?;
174
20
            let right: u16 = right
175
20
                .parse()
176
21
                .map_err(|e| PCE::InvalidPort(right.to_string(), e))?;
177
18
            Self::port_range(left, right)
178
        } else {
179
83
            let port = s.parse().map_err(|e| PCE::InvalidPort(s.to_string(), e))?;
180
80
            Self::one_port(port)
181
        }
182
113
    }
183
}
184
impl std::fmt::Display for ProxyPattern {
185
8
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186
8
        match self.0.clone().into_inner() {
187
8
            (start, end) if start == end => write!(f, "{}", start),
188
2
            (1, 65535) => write!(f, "*"),
189
4
            (start, end) => write!(f, "{}-{}", start, end),
190
        }
191
8
    }
192
}
193

            
194
impl ProxyPattern {
195
    /// Return a pattern matching all ports.
196
20
    pub fn all_ports() -> Self {
197
20
        Self::check(1, 65535).expect("Somehow, 1-65535 was not a valid pattern")
198
20
    }
199
    /// Return a pattern matching a single port.
200
    ///
201
    /// Gives an error if the port is zero.
202
118
    pub fn one_port(port: u16) -> Result<Self, ProxyConfigError> {
203
118
        Self::check(port, port)
204
118
    }
205
    /// Return a pattern matching all ports between `low` and `high` inclusive.
206
    ///
207
    /// Gives an error unless `0 < low <= high`.
208
20
    pub fn port_range(low: u16, high: u16) -> Result<Self, ProxyConfigError> {
209
20
        Self::check(low, high)
210
20
    }
211

            
212
    /// Return true if this pattern includes `port`.
213
    pub(crate) fn matches_port(&self, port: u16) -> bool {
214
        self.0.contains(&port)
215
    }
216

            
217
    /// If start..=end is a valid pattern, wrap it as a ProxyPattern. Otherwise return
218
    /// an error.
219
158
    fn check(start: u16, end: u16) -> Result<ProxyPattern, ProxyConfigError> {
220
        use ProxyConfigError as PCE;
221
158
        match (start, end) {
222
            (_, 0) => Err(PCE::ZeroPort),
223
2
            (0, n) => Ok(Self(1..=n)),
224
156
            (low, high) if low > high => Err(PCE::EmptyPortRange),
225
154
            (low, high) => Ok(Self(low..=high)),
226
        }
227
158
    }
228
}
229

            
230
/// An action to take upon receiving an incoming request.
231
#[derive(
232
    Clone,
233
    Debug,
234
    Default,
235
12
    serde_with::DeserializeFromStr,
236
    serde_with::SerializeDisplay,
237
    Eq,
238
    PartialEq,
239
)]
240
#[non_exhaustive]
241
pub enum ProxyAction {
242
    /// Close the circuit immediately with an error.
243
    #[default]
244
    DestroyCircuit,
245
    /// Accept the client's request and forward it, via some encapsulation method,
246
    /// to some target address.
247
    Forward(Encapsulation, TargetAddr),
248
    /// Close the stream immediately with an error.
249
    RejectStream,
250
    /// Ignore the stream request.
251
    IgnoreStream,
252
}
253

            
254
/// The address to which we forward an accepted connection.
255
#[derive(Clone, Debug, Eq, PartialEq)]
256
#[non_exhaustive]
257
pub enum TargetAddr {
258
    /// An address that we can reach over the internet.
259
    Inet(SocketAddr),
260
    /* TODO (#1246): Put this back.
261
    /// An address of a local unix socket.
262
    Unix(PathBuf),
263
    */
264
}
265

            
266
impl TargetAddr {
267
    /// Return true if this target is sufficiently private that we can be
268
    /// reasonably sure that the user has not misconfigured their onion service
269
    /// to relay traffic onto the public network.
270
62
    fn is_sufficiently_private(&self) -> bool {
271
        use std::net::IpAddr;
272
62
        match self {
273
62
            /* TODO(#1246) */
274
62
            // TargetAddr::Unix(_) => true,
275
62

            
276
62
            // NOTE: We may want to relax these rules in the future!
277
62
            // NOTE: Contrast this with is_local in arti_client::address,
278
62
            // which has a different purpose. Also see #1159.
279
62
            // The purpose of _this_ test is to make sure that the address is
280
62
            // one that will _probably_ not go over the public internet.
281
62
            TargetAddr::Inet(sa) => match sa.ip() {
282
62
                IpAddr::V4(ip) => ip.is_loopback() || ip.is_unspecified() || ip.is_private(),
283
                IpAddr::V6(ip) => ip.is_loopback() || ip.is_unspecified(),
284
            },
285
        }
286
62
    }
287
}
288

            
289
impl FromStr for TargetAddr {
290
    type Err = ProxyConfigError;
291

            
292
81
    fn from_str(s: &str) -> Result<Self, Self::Err> {
293
        use ProxyConfigError as PCE;
294

            
295
        /// Return true if 's' looks like an attempted IPv4 or IPv6 socketaddr.
296
69
        fn looks_like_attempted_addr(s: &str) -> bool {
297
86
            s.starts_with(|c: char| c.is_ascii_digit())
298
4
                || s.strip_prefix('[')
299
5
                    .map(|rhs| rhs.starts_with(|c: char| c.is_ascii_hexdigit() || c == ':'))
300
4
                    .unwrap_or(false)
301
69
        }
302
        /* TODO (#1246): Put this back
303
        if let Some(path) = s.strip_prefix("unix:") {
304
            Ok(Self::Unix(PathBuf::from(path)))
305
        } else
306
        */
307
81
        if let Some(addr) = s.strip_prefix("inet:") {
308
16
            Ok(Self::Inet(addr.parse().map_err(|e| {
309
8
                PCE::InvalidTargetAddr(addr.to_string(), e)
310
16
            })?))
311
69
        } else if looks_like_attempted_addr(s) {
312
            // We check 'looks_like_attempted_addr' before parsing this.
313
            Ok(Self::Inet(
314
67
                s.parse()
315
70
                    .map_err(|e| PCE::InvalidTargetAddr(s.to_string(), e))?,
316
            ))
317
        } else {
318
2
            Err(PCE::UnrecognizedTargetType(s.to_string()))
319
        }
320
81
    }
321
}
322

            
323
impl std::fmt::Display for TargetAddr {
324
4
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
325
4
        match self {
326
4
            TargetAddr::Inet(a) => write!(f, "inet:{}", a),
327
4
            // TODO (#1246): Put this back.
328
4
            // TargetAddr::Unix(p) => write!(f, "unix:{}", p.display()),
329
4
        }
330
4
    }
331
}
332

            
333
/// The method by which we encapsulate a forwarded request.
334
///
335
/// (Right now, only `Simple` is supported, but we may later support
336
/// "HTTP CONNECT", "HAProxy", or others.)
337
#[derive(Clone, Debug, Default, Eq, PartialEq)]
338
#[non_exhaustive]
339
pub enum Encapsulation {
340
    /// Handle a request by opening a local socket to the target address and
341
    /// forwarding the contents verbatim.
342
    ///
343
    /// This does not transmit any information about the circuit origin of the request;
344
    /// only the local port will distinguish one request from another.
345
    #[default]
346
    Simple,
347
}
348

            
349
impl FromStr for ProxyAction {
350
    type Err = ProxyConfigError;
351

            
352
131
    fn from_str(s: &str) -> Result<Self, Self::Err> {
353
131
        if s == "destroy" {
354
24
            Ok(Self::DestroyCircuit)
355
107
        } else if s == "reject" {
356
9
            Ok(Self::RejectStream)
357
98
        } else if s == "ignore" {
358
17
            Ok(Self::IgnoreStream)
359
81
        } else if let Some(addr) = s.strip_prefix("simple:") {
360
            Ok(Self::Forward(Encapsulation::Simple, addr.parse()?))
361
        } else {
362
81
            Ok(Self::Forward(Encapsulation::Simple, s.parse()?))
363
        }
364
131
    }
365
}
366

            
367
impl std::fmt::Display for ProxyAction {
368
10
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
369
10
        match self {
370
2
            ProxyAction::DestroyCircuit => write!(f, "destroy"),
371
4
            ProxyAction::Forward(Encapsulation::Simple, addr) => write!(f, "simple:{}", addr),
372
2
            ProxyAction::RejectStream => write!(f, "reject"),
373
2
            ProxyAction::IgnoreStream => write!(f, "ignore"),
374
        }
375
10
    }
376
}
377

            
378
/// An error encountered while parsing or applying a proxy configuration.
379
#[derive(Debug, Clone, thiserror::Error)]
380
#[non_exhaustive]
381
pub enum ProxyConfigError {
382
    /// We encountered a proxy target with an unrecognized type keyword.
383
    #[error("Could not parse onion service target type {0:?}")]
384
    UnrecognizedTargetType(String),
385

            
386
    /// A socket address could not be parsed to be invalid.
387
    #[error("Could not parse onion service target address {0:?}")]
388
    InvalidTargetAddr(String, #[source] std::net::AddrParseError),
389

            
390
    /// A socket rule had an source port that couldn't be parsed as a `u16`.
391
    #[error("Could not parse onion service source port {0:?}")]
392
    InvalidPort(String, #[source] std::num::ParseIntError),
393

            
394
    /// A socket rule had a zero source port.
395
    #[error("Zero is not a valid port.")]
396
    ZeroPort,
397

            
398
    /// A socket rule specified an empty port range.
399
    #[error("Port range is empty.")]
400
    EmptyPortRange,
401
}
402

            
403
#[cfg(test)]
404
mod test {
405
    // @@ begin test lint list maintained by maint/add_warning @@
406
    #![allow(clippy::bool_assert_comparison)]
407
    #![allow(clippy::clone_on_copy)]
408
    #![allow(clippy::dbg_macro)]
409
    #![allow(clippy::mixed_attributes_style)]
410
    #![allow(clippy::print_stderr)]
411
    #![allow(clippy::print_stdout)]
412
    #![allow(clippy::single_char_pattern)]
413
    #![allow(clippy::unwrap_used)]
414
    #![allow(clippy::unchecked_duration_subtraction)]
415
    #![allow(clippy::useless_vec)]
416
    #![allow(clippy::needless_pass_by_value)]
417
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
418
    use super::*;
419

            
420
    #[test]
421
    fn pattern_ok() {
422
        use ProxyPattern as P;
423
        assert_eq!(P::from_str("*").unwrap(), P(1..=65535));
424
        assert_eq!(P::from_str("100").unwrap(), P(100..=100));
425
        assert_eq!(P::from_str("100-200").unwrap(), P(100..=200));
426
        assert_eq!(P::from_str("0-200").unwrap(), P(1..=200));
427
    }
428

            
429
    #[test]
430
    fn pattern_display() {
431
        use ProxyPattern as P;
432
        assert_eq!(P::all_ports().to_string(), "*");
433
        assert_eq!(P::one_port(100).unwrap().to_string(), "100");
434
        assert_eq!(P::port_range(100, 200).unwrap().to_string(), "100-200");
435
    }
436

            
437
    #[test]
438
    fn pattern_err() {
439
        use ProxyConfigError as PCE;
440
        use ProxyPattern as P;
441
        assert!(matches!(P::from_str("fred"), Err(PCE::InvalidPort(_, _))));
442
        assert!(matches!(
443
            P::from_str("100-fred"),
444
            Err(PCE::InvalidPort(_, _))
445
        ));
446
        assert!(matches!(P::from_str("100-42"), Err(PCE::EmptyPortRange)));
447
    }
448

            
449
    #[test]
450
    fn target_ok() {
451
        use Encapsulation::Simple;
452
        use ProxyAction as T;
453
        use TargetAddr as A;
454
        assert!(matches!(T::from_str("reject"), Ok(T::RejectStream)));
455
        assert!(matches!(T::from_str("ignore"), Ok(T::IgnoreStream)));
456
        assert!(matches!(T::from_str("destroy"), Ok(T::DestroyCircuit)));
457
        let sa: SocketAddr = "192.168.1.1:50".parse().unwrap();
458
        assert!(
459
            matches!(T::from_str("192.168.1.1:50"), Ok(T::Forward(Simple, A::Inet(a))) if a == sa)
460
        );
461
        assert!(
462
            matches!(T::from_str("inet:192.168.1.1:50"), Ok(T::Forward(Simple, A::Inet(a))) if a == sa)
463
        );
464
        let sa: SocketAddr = "[::1]:999".parse().unwrap();
465
        assert!(matches!(T::from_str("[::1]:999"), Ok(T::Forward(Simple, A::Inet(a))) if a == sa));
466
        assert!(
467
            matches!(T::from_str("inet:[::1]:999"), Ok(T::Forward(Simple, A::Inet(a))) if a == sa)
468
        );
469
        /* TODO (#1246)
470
        let pb = PathBuf::from("/var/run/hs/socket");
471
        assert!(
472
            matches!(T::from_str("unix:/var/run/hs/socket"), Ok(T::Forward(Simple, A::Unix(p))) if p == pb)
473
        );
474
        */
475
    }
476

            
477
    #[test]
478
    fn target_display() {
479
        use Encapsulation::Simple;
480
        use ProxyAction as T;
481
        use TargetAddr as A;
482

            
483
        assert_eq!(T::RejectStream.to_string(), "reject");
484
        assert_eq!(T::IgnoreStream.to_string(), "ignore");
485
        assert_eq!(T::DestroyCircuit.to_string(), "destroy");
486
        assert_eq!(
487
            T::Forward(Simple, A::Inet("192.168.1.1:50".parse().unwrap())).to_string(),
488
            "simple:inet:192.168.1.1:50"
489
        );
490
        assert_eq!(
491
            T::Forward(Simple, A::Inet("[::1]:999".parse().unwrap())).to_string(),
492
            "simple:inet:[::1]:999"
493
        );
494
        /* TODO (#1246)
495
        assert_eq!(
496
            T::Forward(Simple, A::Unix("/var/run/hs/socket".into())).to_string(),
497
            "simple:unix:/var/run/hs/socket"
498
        );
499
        */
500
    }
501

            
502
    #[test]
503
    fn target_err() {
504
        use ProxyAction as T;
505
        use ProxyConfigError as PCE;
506

            
507
        assert!(matches!(
508
            T::from_str("sdakljf"),
509
            Err(PCE::UnrecognizedTargetType(_))
510
        ));
511

            
512
        assert!(matches!(
513
            T::from_str("inet:hello"),
514
            Err(PCE::InvalidTargetAddr(_, _))
515
        ));
516
        assert!(matches!(
517
            T::from_str("inet:wwww.example.com:80"),
518
            Err(PCE::InvalidTargetAddr(_, _))
519
        ));
520

            
521
        assert!(matches!(
522
            T::from_str("127.1:80"),
523
            Err(PCE::InvalidTargetAddr(_, _))
524
        ));
525
        assert!(matches!(
526
            T::from_str("inet:127.1:80"),
527
            Err(PCE::InvalidTargetAddr(_, _))
528
        ));
529
        assert!(matches!(
530
            T::from_str("127.1:80"),
531
            Err(PCE::InvalidTargetAddr(_, _))
532
        ));
533
        assert!(matches!(
534
            T::from_str("inet:2130706433:80"),
535
            Err(PCE::InvalidTargetAddr(_, _))
536
        ));
537

            
538
        assert!(matches!(
539
            T::from_str("128.256.cats.and.dogs"),
540
            Err(PCE::InvalidTargetAddr(_, _))
541
        ));
542
    }
543

            
544
    #[test]
545
    fn deserialize() {
546
        use Encapsulation::Simple;
547
        use TargetAddr as A;
548
        let ex = r#"{
549
            "proxy_ports": [
550
                [ "443", "127.0.0.1:11443" ],
551
                [ "80", "ignore" ],
552
                [ "*", "destroy" ]
553
            ]
554
        }"#;
555
        let bld: ProxyConfigBuilder = serde_json::from_str(ex).unwrap();
556
        let cfg = bld.build().unwrap();
557
        assert_eq!(cfg.proxy_ports.len(), 3);
558
        assert_eq!(cfg.proxy_ports[0].source.0, 443..=443);
559
        assert_eq!(cfg.proxy_ports[1].source.0, 80..=80);
560
        assert_eq!(cfg.proxy_ports[2].source.0, 1..=65535);
561

            
562
        assert_eq!(
563
            cfg.proxy_ports[0].target,
564
            ProxyAction::Forward(Simple, A::Inet("127.0.0.1:11443".parse().unwrap()))
565
        );
566
        assert_eq!(cfg.proxy_ports[1].target, ProxyAction::IgnoreStream);
567
        assert_eq!(cfg.proxy_ports[2].target, ProxyAction::DestroyCircuit);
568
    }
569

            
570
    #[test]
571
    fn validation_fail() {
572
        // this should fail; the third pattern isn't reachable.
573
        let ex = r#"{
574
            "proxy_ports": [
575
                [ "2-300", "127.0.0.1:11443" ],
576
                [ "301-999", "ignore" ],
577
                [ "30-310", "destroy" ]
578
            ]
579
        }"#;
580
        let bld: ProxyConfigBuilder = serde_json::from_str(ex).unwrap();
581
        match bld.build() {
582
            Err(ConfigBuildError::Invalid { field, problem }) => {
583
                assert_eq!(field, "proxy_ports");
584
                assert_eq!(problem, "Port pattern 30-310 is not reachable");
585
            }
586
            other => panic!("Expected an Invalid error; got {other:?}"),
587
        }
588

            
589
        // This should work; the third pattern is not completely covered.
590
        let ex = r#"{
591
            "proxy_ports": [
592
                [ "2-300", "127.0.0.1:11443" ],
593
                [ "302-999", "ignore" ],
594
                [ "30-310", "destroy" ]
595
            ]
596
        }"#;
597
        let bld: ProxyConfigBuilder = serde_json::from_str(ex).unwrap();
598
        assert!(bld.build().is_ok());
599
    }
600

            
601
    #[test]
602
    fn demo() {
603
        let b: ProxyConfigBuilder = toml::de::from_str(
604
            r#"
605
proxy_ports = [
606
    [ 80, "127.0.0.1:10080"],
607
    ["22", "destroy"],
608
    ["265", "ignore"],
609
    # ["1-1024", "unix:/var/run/allium-cepa/socket"], # TODO (#1246))
610
]
611
"#,
612
        )
613
        .unwrap();
614
        let c = b.build().unwrap();
615
        assert_eq!(c.proxy_ports.len(), 3);
616
        assert_eq!(
617
            c.proxy_ports[0],
618
            ProxyRule::new(
619
                ProxyPattern::one_port(80).unwrap(),
620
                ProxyAction::Forward(
621
                    Encapsulation::Simple,
622
                    TargetAddr::Inet("127.0.0.1:10080".parse().unwrap())
623
                )
624
            )
625
        );
626
        assert_eq!(
627
            c.proxy_ports[1],
628
            ProxyRule::new(
629
                ProxyPattern::one_port(22).unwrap(),
630
                ProxyAction::DestroyCircuit
631
            )
632
        );
633
        assert_eq!(
634
            c.proxy_ports[2],
635
            ProxyRule::new(
636
                ProxyPattern::one_port(265).unwrap(),
637
                ProxyAction::IgnoreStream
638
            )
639
        );
640
        /* TODO (#1246)
641
        assert_eq!(
642
            c.proxy_ports[3],
643
            ProxyRule::new(
644
                ProxyPattern::port_range(1, 1024).unwrap(),
645
                ProxyAction::Forward(
646
                    Encapsulation::Simple,
647
                    TargetAddr::Unix("/var/run/allium-cepa/socket".into())
648
                )
649
            )
650
        );
651
        */
652
    }
653
}