eggress-config 1.0.6

TOML configuration and validation for eggress proxy
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
448
449
450
451
452
453
454
455
456
//! Routing rule compilation.
//!
//! Converts validated TOML rule/matcher/action shapes into
//! `eggress_routing` matchers without duplicating validation.

use std::sync::Arc;

use eggress_core::{ProtocolId, RejectReason};
use eggress_routing::UpstreamGroupId;

use crate::error::ConfigError;
use crate::model::{ConfigFile, LeafMatcher, MatchExprConfig, RuleConfig};

pub(crate) fn compile_reject_reason(s: &str) -> Result<RejectReason, ConfigError> {
    match s {
        "unsupported-protocol" => Ok(RejectReason::UnsupportedProtocol),
        "auth-required" => Ok(RejectReason::AuthRequired),
        "access-denied" => Ok(RejectReason::AccessDenied),
        "blocked" => Ok(RejectReason::Blocked),
        "internal-error" => Ok(RejectReason::InternalError),
        _ => Err(ConfigError::validation(
            "reject",
            &format!("unknown reject reason: {}", s),
        )),
    }
}

pub(crate) fn compile_protocol(s: &str) -> Result<ProtocolId, ConfigError> {
    match s {
        "http" => Ok(ProtocolId::Http),
        "httponly" => Ok(ProtocolId::Http),
        "socks4" => Ok(ProtocolId::Socks4),
        "socks5" => Ok(ProtocolId::Socks5),
        "shadowsocks" => Ok(ProtocolId::Shadowsocks),
        "ssr" => Ok(ProtocolId::ShadowsocksR),
        "trojan" => Ok(ProtocolId::Trojan),
        "h2" => Ok(ProtocolId::Http2),
        "h3" => {
            #[cfg(feature = "quic")]
            {
                Ok(ProtocolId::Http3)
            }
            #[cfg(not(feature = "quic"))]
            {
                Err(ConfigError::validation(
                    "protocols",
                    "HTTP/3 requires the optional 'quic' feature",
                ))
            }
        }
        "quic" => {
            #[cfg(feature = "quic")]
            {
                Ok(ProtocolId::Quic)
            }
            #[cfg(not(feature = "quic"))]
            {
                Err(ConfigError::validation(
                    "protocols",
                    "QUIC requires the optional 'quic' feature",
                ))
            }
        }
        "websocket" | "ws" | "wss" => Ok(ProtocolId::WebSocket),
        "raw" | "tunnel" => Ok(ProtocolId::Raw),
        "echo" => Ok(ProtocolId::Echo),
        _ => Err(ConfigError::validation(
            "protocols",
            &format!("unknown protocol: {}", s),
        )),
    }
}

pub(crate) fn compile_transport(s: &str) -> Result<eggress_routing::TransportKind, ConfigError> {
    match s {
        "tcp" => Ok(eggress_routing::TransportKind::Tcp),
        "udp" => Ok(eggress_routing::TransportKind::Udp),
        "reverse_tcp" => Ok(eggress_routing::TransportKind::ReverseTcp),
        _ => Err(ConfigError::validation(
            "transport",
            &format!("unknown transport: {}", s),
        )),
    }
}

pub(crate) fn compile_matcher(
    rule: &RuleConfig,
) -> Result<eggress_routing::MatchExpr, ConfigError> {
    if let Some(ref match_expr) = rule.match_expr {
        return compile_match_config(match_expr);
    }

    if let Some(ref exact) = rule.host_exact {
        if rule.host_suffix.is_none()
            && rule.host_regex.is_none()
            && rule.destination_port.is_none()
            && rule.destination_port_regex.is_none()
            && !rule.any.unwrap_or(false)
        {
            return Ok(eggress_routing::MatchExpr::HostExact(Arc::from(
                eggress_routing::normalize_host_for_exact(exact),
            )));
        }
    }
    if let Some(ref suffix) = rule.host_suffix {
        if rule.host_exact.is_none()
            && rule.host_regex.is_none()
            && rule.destination_port.is_none()
            && rule.destination_port_regex.is_none()
            && !rule.any.unwrap_or(false)
        {
            // Normalize once at compile so per-request matching does not
            // re-normalize this constant (O-01).
            return Ok(eggress_routing::MatchExpr::HostSuffix(Arc::from(
                eggress_routing::normalize_host_for_exact(suffix).as_str(),
            )));
        }
    }
    if let Some(ref regex_str) = rule.host_regex {
        if rule.host_exact.is_none()
            && rule.host_suffix.is_none()
            && rule.destination_port.is_none()
            && rule.destination_port_regex.is_none()
            && !rule.any.unwrap_or(false)
        {
            let re = regex::Regex::new(regex_str).map_err(|e| {
                ConfigError::validation(
                    "host_regex",
                    &format!("invalid regex '{}': {}", regex_str, e),
                )
            })?;
            return Ok(eggress_routing::MatchExpr::HostRegex(re));
        }
    }
    if let Some(ref regex_str) = rule.destination_port_regex {
        let re = regex::Regex::new(regex_str).map_err(|e| {
            ConfigError::validation(
                "destination_port_regex",
                &format!("invalid regex '{}': {}", regex_str, e),
            )
        })?;
        if rule.host_exact.is_none()
            && rule.host_suffix.is_none()
            && rule.host_regex.is_none()
            && rule.destination_port.is_none()
            && !rule.any.unwrap_or(false)
        {
            return Ok(eggress_routing::MatchExpr::DestinationPortRegex(re));
        }
    }
    if let Some(port) = rule.destination_port {
        if rule.host_exact.is_none()
            && rule.host_suffix.is_none()
            && rule.host_regex.is_none()
            && rule.destination_port_regex.is_none()
            && !rule.any.unwrap_or(false)
        {
            return Ok(eggress_routing::MatchExpr::DestinationPort(
                eggress_routing::PortMatcher::Exact(port),
            ));
        }
    }
    if rule.any.unwrap_or(false)
        || (rule.host_exact.is_none()
            && rule.host_suffix.is_none()
            && rule.host_regex.is_none()
            && rule.destination_port.is_none())
    {
        return Ok(eggress_routing::MatchExpr::Any);
    }
    Err(ConfigError::validation(&rule.id, "ambiguous matcher"))
}

const MAX_EXPRESSION_DEPTH: usize = 10;
const MAX_NODE_COUNT: usize = 100;

pub(crate) fn compile_match_config(
    config: &MatchExprConfig,
) -> Result<eggress_routing::MatchExpr, ConfigError> {
    let mut node_count = 0;
    compile_match_config_limited(config, 0, &mut node_count)
}

pub(crate) fn compile_match_config_limited(
    config: &MatchExprConfig,
    depth: usize,
    node_count: &mut usize,
) -> Result<eggress_routing::MatchExpr, ConfigError> {
    *node_count += 1;
    if *node_count > MAX_NODE_COUNT {
        return Err(ConfigError::validation(
            "match",
            &format!("expression exceeds maximum node count ({})", MAX_NODE_COUNT),
        ));
    }
    if depth >= MAX_EXPRESSION_DEPTH {
        return Err(ConfigError::validation(
            "match",
            &format!(
                "expression exceeds maximum depth ({})",
                MAX_EXPRESSION_DEPTH
            ),
        ));
    }

    match config {
        MatchExprConfig::Composite(composite) => {
            if let Some(ref all) = composite.all {
                if all.is_empty() {
                    return Err(ConfigError::validation("match.all", "must not be empty"));
                }
                let exprs: Vec<eggress_routing::MatchExpr> = all
                    .iter()
                    .map(|c| compile_match_config_limited(c, depth + 1, node_count))
                    .collect::<Result<Vec<_>, _>>()?;
                return Ok(eggress_routing::MatchExpr::All(exprs));
            }
            if let Some(ref any_of) = composite.any_of {
                if any_of.is_empty() {
                    return Err(ConfigError::validation("match.any_of", "must not be empty"));
                }
                let exprs: Vec<eggress_routing::MatchExpr> = any_of
                    .iter()
                    .map(|c| compile_match_config_limited(c, depth + 1, node_count))
                    .collect::<Result<Vec<_>, _>>()?;
                return Ok(eggress_routing::MatchExpr::AnyOf(exprs));
            }
            if let Some(ref not) = composite.not {
                let inner = compile_match_config_limited(not, depth + 1, node_count)?;
                return Ok(eggress_routing::MatchExpr::Not(Box::new(inner)));
            }
            Err(ConfigError::validation(
                "match",
                "composite must have exactly one of: all, any_of, not",
            ))
        }
        MatchExprConfig::Leaf(leaf) => compile_leaf_matcher(leaf),
    }
}

pub(crate) fn compile_leaf_matcher(
    leaf: &LeafMatcher,
) -> Result<eggress_routing::MatchExpr, ConfigError> {
    let mut matchers = Vec::new();

    if let Some(ref exact) = leaf.host_exact {
        matchers.push(eggress_routing::MatchExpr::HostExact(Arc::from(
            eggress_routing::normalize_host_for_exact(exact),
        )));
    }
    if let Some(ref suffix) = leaf.host_suffix {
        matchers.push(eggress_routing::MatchExpr::HostSuffix(Arc::from(
            eggress_routing::normalize_host_for_exact(suffix).as_str(),
        )));
    }
    if let Some(ref regex_str) = leaf.host_regex {
        let re = regex::Regex::new(regex_str).map_err(|e| {
            ConfigError::validation(
                "host_regex",
                &format!("invalid regex '{}': {}", regex_str, e),
            )
        })?;
        matchers.push(eggress_routing::MatchExpr::HostRegex(re));
    }
    if let Some(ref regex_str) = leaf.destination_port_regex {
        let re = regex::Regex::new(regex_str).map_err(|e| {
            ConfigError::validation(
                "destination_port_regex",
                &format!("invalid regex '{}': {}", regex_str, e),
            )
        })?;
        matchers.push(eggress_routing::MatchExpr::DestinationPortRegex(re));
    }
    if let Some(port) = leaf.destination_port {
        matchers.push(eggress_routing::MatchExpr::DestinationPort(
            eggress_routing::PortMatcher::Exact(port),
        ));
    }
    if let Some(ref range) = leaf.destination_port_range {
        if range.len() != 2 {
            return Err(ConfigError::validation(
                "destination_port_range",
                "must have exactly 2 elements [start, end]",
            ));
        }
        let matcher = eggress_routing::PortMatcher::new_range(range[0], range[1])
            .map_err(|e| ConfigError::validation("destination_port_range", &e))?;
        matchers.push(eggress_routing::MatchExpr::DestinationPort(matcher));
    }
    if let Some(ref ports) = leaf.destination_port_set {
        if ports.is_empty() {
            return Err(ConfigError::validation(
                "destination_port_set",
                "must not be empty",
            ));
        }
        let matcher = eggress_routing::PortMatcher::new_set(ports.clone());
        matchers.push(eggress_routing::MatchExpr::DestinationPort(matcher));
    }
    if let Some(ref cidr) = leaf.destination_cidr {
        let net: ipnet::IpNet = cidr.parse().map_err(|e: ipnet::AddrParseError| {
            ConfigError::validation(
                "destination_cidr",
                &format!("invalid CIDR '{}': {}", cidr, e),
            )
        })?;
        matchers.push(eggress_routing::MatchExpr::DestinationCidr(net));
    }
    if let Some(ref cidr) = leaf.source_cidr {
        let net: ipnet::IpNet = cidr.parse().map_err(|e: ipnet::AddrParseError| {
            ConfigError::validation("source_cidr", &format!("invalid CIDR '{}': {}", cidr, e))
        })?;
        matchers.push(eggress_routing::MatchExpr::SourceCidr(net));
    }
    if let Some(source_port) = leaf.source_port {
        matchers.push(eggress_routing::MatchExpr::SourcePort(
            eggress_routing::PortMatcher::Exact(source_port),
        ));
    }
    if let Some(ref name) = leaf.listener {
        matchers.push(eggress_routing::MatchExpr::Listener(Arc::from(
            name.as_str(),
        )));
    }
    if let Some(ref proto) = leaf.protocol {
        let protocol_id = compile_protocol(proto)?;
        matchers.push(eggress_routing::MatchExpr::Protocol(protocol_id));
    }
    if let Some(ref ident) = leaf.identity {
        matchers.push(eggress_routing::MatchExpr::Identity(Arc::from(
            ident.as_str(),
        )));
    }
    if let Some(ref transport_str) = leaf.transport {
        let transport_kind = compile_transport(transport_str)?;
        matchers.push(eggress_routing::MatchExpr::Transport(transport_kind));
    }
    if let Some(ref name) = leaf.reverse_listener {
        matchers.push(eggress_routing::MatchExpr::ReverseListener(Arc::from(
            name.as_str(),
        )));
    }

    match matchers.len() {
        0 => Ok(eggress_routing::MatchExpr::Any),
        1 => Ok(matchers.into_iter().next().expect("len checked to be 1")),
        _ => Ok(eggress_routing::MatchExpr::All(matchers)),
    }
}

pub(crate) fn compile_action(
    rule: &RuleConfig,
    group_ids: &std::collections::HashSet<&str>,
) -> Result<eggress_routing::RouteActionSpec, ConfigError> {
    if let Some(direct) = rule.direct {
        if direct {
            return Ok(eggress_routing::RouteActionSpec::Direct);
        }
        return Err(ConfigError::validation(
            &rule.id,
            "direct action must be true",
        ));
    }
    if let Some(ref group) = rule.upstream_group {
        if !group_ids.contains(group.as_str()) {
            return Err(ConfigError::validation(
                &rule.id,
                &format!("unknown upstream group: {}", group),
            ));
        }
        return Ok(eggress_routing::RouteActionSpec::UpstreamGroup(
            UpstreamGroupId(Arc::from(group.as_str())),
        ));
    }
    if let Some(ref reject) = rule.reject {
        let reason = compile_reject_reason(reject)?;
        return Ok(eggress_routing::RouteActionSpec::Reject(reason));
    }
    Err(ConfigError::validation(&rule.id, "missing action"))
}

pub(crate) fn compile_rules(
    config: &ConfigFile,
) -> Result<Vec<eggress_routing::CompiledRule>, ConfigError> {
    let mut compiled_rules = Vec::new();

    let group_ids: std::collections::HashSet<&str> = config
        .upstream_groups
        .as_ref()
        .map(|gs| gs.iter().map(|g| g.id.as_str()).collect())
        .unwrap_or_default();

    if let Some(ref rules) = config.rules {
        for r in rules {
            let matcher = compile_matcher(r)?;
            let action = compile_action(r, &group_ids)?;

            compiled_rules.push(eggress_routing::CompiledRule {
                id: eggress_routing::RuleId(Arc::from(r.id.as_str())),
                matcher,
                action,
            });
        }
    }

    if let Some(ref rules_file_path) = config.rules_file {
        if group_ids.len() > 1 {
            return Err(ConfigError::validation(
                "rules_file",
                "rules_file routes all rules to a single group; multiple groups are not supported with rules_file — use explicit [[rules]] instead",
            ));
        }
        let content = crate::file::load_rules_file(rules_file_path).map_err(|e| {
            ConfigError::validation(
                "rules_file",
                &format!("failed to read '{}': {}", rules_file_path, e),
            )
        })?;
        let compat_rules = eggress_routing::CompatRegexRule::parse_file(&content).map_err(|e| {
            ConfigError::validation(
                "rules_file",
                &format!("failed to parse '{}': {}", rules_file_path, e),
            )
        })?;
        for (idx, compat) in compat_rules.into_iter().enumerate() {
            compiled_rules.push(eggress_routing::CompiledRule {
                id: eggress_routing::RuleId(Arc::from(format!("rules-file-{}", idx + 1).as_str())),
                matcher: eggress_routing::MatchExpr::HostRegex(compat.pattern),
                action: group_ids
                    .iter()
                    .next()
                    .map(|g| {
                        eggress_routing::RouteActionSpec::UpstreamGroup(
                            eggress_routing::UpstreamGroupId(Arc::from(*g)),
                        )
                    })
                    .unwrap_or(eggress_routing::RouteActionSpec::Direct),
            });
        }
    }

    Ok(compiled_rules)
}

pub(crate) fn compile_default_action(config: &ConfigFile) -> eggress_routing::RouteActionSpec {
    let default_str = config.routing.as_ref().and_then(|r| r.default.as_deref());

    match default_str {
        Some("direct") => eggress_routing::RouteActionSpec::Direct,
        Some("reject") => eggress_routing::RouteActionSpec::Reject(RejectReason::Blocked),
        Some(group_id) => {
            eggress_routing::RouteActionSpec::UpstreamGroup(UpstreamGroupId(Arc::from(group_id)))
        }
        None => eggress_routing::RouteActionSpec::Direct,
    }
}