zlayer-proxy 0.11.10

High-performance reverse proxy with TLS termination and L4/L7 routing
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
//! Network policy access control for the reverse proxy.
//!
//! This module provides [`NetworkPolicyChecker`], which evaluates incoming
//! requests against [`NetworkPolicySpec`] access rules to determine whether
//! a source IP is allowed to reach a given service/port combination.

use std::net::IpAddr;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, warn};
use zlayer_spec::{AccessAction, AccessRule, NetworkPolicySpec};

/// Checks incoming requests against network access policies.
///
/// When a request arrives, the checker:
/// 1. Finds all networks whose CIDRs contain the source IP.
/// 2. If no networks match, access is allowed (default open).
/// 3. If any matching network has a deny rule for the target, access is denied.
/// 4. If any matching network has an allow rule for the target, access is allowed.
/// 5. If the source belongs to a network but no rules match, access is denied
///    (having a network policy implies explicit access control).
#[derive(Clone)]
pub struct NetworkPolicyChecker {
    policies: Arc<RwLock<Vec<NetworkPolicySpec>>>,
}

impl NetworkPolicyChecker {
    /// Create a new checker backed by the given shared policy list.
    pub fn new(policies: Arc<RwLock<Vec<NetworkPolicySpec>>>) -> Self {
        Self { policies }
    }

    /// Check if `source_ip` is allowed to access a target service on the given port.
    ///
    /// Returns `true` if access is allowed, `false` if denied.
    ///
    /// The `deployment` parameter exists for forward compatibility with
    /// per-deployment rules; pass `"*"` when the deployment is unknown.
    pub async fn check_access(
        &self,
        source_ip: IpAddr,
        service: &str,
        deployment: &str,
        port: u16,
    ) -> bool {
        let policies = self.policies.read().await;

        let matching_networks: Vec<&NetworkPolicySpec> = policies
            .iter()
            .filter(|p| ip_in_cidrs(source_ip, &p.cidrs))
            .collect();

        // No network policy governs this IP — allow by default.
        if matching_networks.is_empty() {
            return true;
        }

        // Phase 1: explicit deny takes priority.
        for network in &matching_networks {
            for rule in &network.access_rules {
                if rule_matches(rule, service, deployment, port)
                    && rule.action == AccessAction::Deny
                {
                    warn!(
                        source = %source_ip,
                        network = %network.name,
                        service = %service,
                        port = %port,
                        "Network policy denied access"
                    );
                    return false;
                }
            }
        }

        // Phase 2: explicit allow.
        for network in &matching_networks {
            for rule in &network.access_rules {
                if rule_matches(rule, service, deployment, port)
                    && rule.action == AccessAction::Allow
                {
                    debug!(
                        source = %source_ip,
                        network = %network.name,
                        service = %service,
                        port = %port,
                        "Network policy allowed access"
                    );
                    return true;
                }
            }
        }

        // Source is governed by a network policy but no rules matched — default deny.
        warn!(
            source = %source_ip,
            service = %service,
            port = %port,
            "Source in network policy but no matching rule; default deny"
        );
        false
    }
}

/// Returns `true` if `ip` falls within any of the given CIDR strings.
fn ip_in_cidrs(ip: IpAddr, cidrs: &[String]) -> bool {
    for cidr_str in cidrs {
        if let Some((net_str, prefix_str)) = cidr_str.split_once('/') {
            let Ok(net_addr) = net_str.parse::<IpAddr>() else {
                continue;
            };
            let Ok(prefix_len) = prefix_str.parse::<u32>() else {
                continue;
            };
            if cidr_contains(net_addr, prefix_len, ip) {
                return true;
            }
        }
    }
    false
}

/// Returns `true` if `addr` is within the CIDR `network/prefix_len`.
fn cidr_contains(network: IpAddr, prefix_len: u32, addr: IpAddr) -> bool {
    match (network, addr) {
        (IpAddr::V4(net), IpAddr::V4(ip)) => {
            let prefix_len = prefix_len.min(32);
            if prefix_len == 0 {
                return true;
            }
            let mask = u32::MAX.checked_shl(32 - prefix_len).unwrap_or(0);
            (u32::from(net) & mask) == (u32::from(ip) & mask)
        }
        (IpAddr::V6(net), IpAddr::V6(ip)) => {
            let prefix_len = prefix_len.min(128);
            if prefix_len == 0 {
                return true;
            }
            let mask = u128::MAX.checked_shl(128 - prefix_len).unwrap_or(0);
            (u128::from(net) & mask) == (u128::from(ip) & mask)
        }
        _ => false, // v4 vs v6 mismatch
    }
}

/// Check whether a single access rule matches the given target.
fn rule_matches(rule: &AccessRule, service: &str, deployment: &str, port: u16) -> bool {
    let service_match = rule.service == "*" || rule.service == service;
    let deployment_match = rule.deployment == "*" || rule.deployment == deployment;
    let port_match = rule
        .ports
        .as_ref()
        .is_none_or(|ports| ports.contains(&port));
    service_match && deployment_match && port_match
}

#[cfg(test)]
mod tests {
    use super::*;
    use zlayer_spec::{AccessAction, AccessRule, NetworkPolicySpec};

    fn make_policy(name: &str, cidrs: Vec<&str>, rules: Vec<AccessRule>) -> NetworkPolicySpec {
        NetworkPolicySpec {
            name: name.to_string(),
            cidrs: cidrs.into_iter().map(String::from).collect(),
            access_rules: rules,
            ..Default::default()
        }
    }

    fn allow_rule(service: &str, deployment: &str, ports: Option<Vec<u16>>) -> AccessRule {
        AccessRule {
            service: service.to_string(),
            deployment: deployment.to_string(),
            ports,
            action: AccessAction::Allow,
        }
    }

    fn deny_rule(service: &str, deployment: &str, ports: Option<Vec<u16>>) -> AccessRule {
        AccessRule {
            service: service.to_string(),
            deployment: deployment.to_string(),
            ports,
            action: AccessAction::Deny,
        }
    }

    #[tokio::test]
    async fn test_no_matching_network_allows() {
        let policies = Arc::new(RwLock::new(vec![make_policy(
            "corp",
            vec!["10.0.0.0/8"],
            vec![allow_rule("api", "*", None)],
        )]));
        let checker = NetworkPolicyChecker::new(policies);

        // 192.168.1.1 is not in 10.0.0.0/8 — should allow.
        assert!(
            checker
                .check_access("192.168.1.1".parse().unwrap(), "api", "*", 8080)
                .await
        );
    }

    #[tokio::test]
    async fn test_matching_allow_rule() {
        let policies = Arc::new(RwLock::new(vec![make_policy(
            "corp",
            vec!["10.0.0.0/8"],
            vec![allow_rule("api", "*", None)],
        )]));
        let checker = NetworkPolicyChecker::new(policies);

        // 10.1.2.3 is in 10.0.0.0/8 and rule allows "api" — should allow.
        assert!(
            checker
                .check_access("10.1.2.3".parse().unwrap(), "api", "*", 8080)
                .await
        );
    }

    #[tokio::test]
    async fn test_matching_deny_rule() {
        let policies = Arc::new(RwLock::new(vec![make_policy(
            "restricted",
            vec!["10.0.0.0/8"],
            vec![deny_rule("admin", "*", None)],
        )]));
        let checker = NetworkPolicyChecker::new(policies);

        // 10.1.2.3 is in 10.0.0.0/8 and rule denies "admin" — should deny.
        assert!(
            !checker
                .check_access("10.1.2.3".parse().unwrap(), "admin", "*", 443)
                .await
        );
    }

    #[tokio::test]
    async fn test_deny_takes_priority_over_allow() {
        let policies = Arc::new(RwLock::new(vec![make_policy(
            "mixed",
            vec!["10.0.0.0/8"],
            vec![
                allow_rule("api", "*", None),
                deny_rule("api", "*", Some(vec![9090])),
            ],
        )]));
        let checker = NetworkPolicyChecker::new(policies);

        // Port 8080 is allowed (no deny matches port 8080).
        assert!(
            checker
                .check_access("10.1.2.3".parse().unwrap(), "api", "*", 8080)
                .await
        );

        // Port 9090 is denied (deny rule matches).
        assert!(
            !checker
                .check_access("10.1.2.3".parse().unwrap(), "api", "*", 9090)
                .await
        );
    }

    #[tokio::test]
    async fn test_network_but_no_matching_rule_denies() {
        let policies = Arc::new(RwLock::new(vec![make_policy(
            "corp",
            vec!["10.0.0.0/8"],
            vec![allow_rule("api", "*", None)],
        )]));
        let checker = NetworkPolicyChecker::new(policies);

        // 10.1.2.3 is in the network, but "frontend" has no matching rule — default deny.
        assert!(
            !checker
                .check_access("10.1.2.3".parse().unwrap(), "frontend", "*", 80)
                .await
        );
    }

    #[tokio::test]
    async fn test_wildcard_service_rule() {
        let policies = Arc::new(RwLock::new(vec![make_policy(
            "admin-net",
            vec!["172.16.0.0/12"],
            vec![allow_rule("*", "*", None)],
        )]));
        let checker = NetworkPolicyChecker::new(policies);

        // Wildcard service rule should match any service.
        assert!(
            checker
                .check_access("172.16.5.10".parse().unwrap(), "anything", "*", 443)
                .await
        );
    }

    #[tokio::test]
    async fn test_port_restriction() {
        let policies = Arc::new(RwLock::new(vec![make_policy(
            "web",
            vec!["10.200.0.0/16"],
            vec![allow_rule("api", "*", Some(vec![80, 443]))],
        )]));
        let checker = NetworkPolicyChecker::new(policies);

        // Port 443 — allowed.
        assert!(
            checker
                .check_access("10.200.1.1".parse().unwrap(), "api", "*", 443)
                .await
        );

        // Port 8080 — not in ports list, no matching rule — default deny.
        assert!(
            !checker
                .check_access("10.200.1.1".parse().unwrap(), "api", "*", 8080)
                .await
        );
    }

    #[tokio::test]
    async fn test_multiple_networks() {
        let policies = Arc::new(RwLock::new(vec![
            make_policy(
                "office",
                vec!["192.168.1.0/24"],
                vec![allow_rule("api", "*", None)],
            ),
            make_policy(
                "vpn",
                vec!["10.200.0.0/16"],
                vec![allow_rule("*", "*", None)],
            ),
        ]));
        let checker = NetworkPolicyChecker::new(policies);

        // Office user can reach "api" but not "admin".
        assert!(
            checker
                .check_access("192.168.1.50".parse().unwrap(), "api", "*", 80)
                .await
        );
        assert!(
            !checker
                .check_access("192.168.1.50".parse().unwrap(), "admin", "*", 80)
                .await
        );

        // VPN user can reach anything.
        assert!(
            checker
                .check_access("10.200.5.5".parse().unwrap(), "admin", "*", 80)
                .await
        );
    }

    #[tokio::test]
    async fn test_empty_policies_allows_all() {
        let policies = Arc::new(RwLock::new(Vec::new()));
        let checker = NetworkPolicyChecker::new(policies);

        assert!(
            checker
                .check_access("1.2.3.4".parse().unwrap(), "anything", "*", 80)
                .await
        );
    }

    #[test]
    fn test_ip_in_cidrs_v4() {
        let cidrs = vec!["10.0.0.0/8".to_string(), "192.168.1.0/24".to_string()];

        assert!(ip_in_cidrs("10.1.2.3".parse().unwrap(), &cidrs));
        assert!(ip_in_cidrs("192.168.1.100".parse().unwrap(), &cidrs));
        assert!(!ip_in_cidrs("172.16.0.1".parse().unwrap(), &cidrs));
    }

    #[test]
    fn test_ip_in_cidrs_v6() {
        let cidrs = vec!["fd00::/64".to_string()];

        assert!(ip_in_cidrs("fd00::1".parse().unwrap(), &cidrs));
        assert!(!ip_in_cidrs("fd01::1".parse().unwrap(), &cidrs));
    }

    #[test]
    fn test_ip_in_cidrs_empty() {
        assert!(!ip_in_cidrs("10.0.0.1".parse().unwrap(), &[]));
    }

    #[test]
    fn test_rule_matches_wildcards() {
        let rule = allow_rule("*", "*", None);
        assert!(rule_matches(&rule, "any-service", "any-deployment", 12345));
    }

    #[test]
    fn test_rule_matches_specific() {
        let rule = allow_rule("api", "prod", Some(vec![443]));

        assert!(rule_matches(&rule, "api", "prod", 443));
        assert!(!rule_matches(&rule, "api", "staging", 443));
        assert!(!rule_matches(&rule, "web", "prod", 443));
        assert!(!rule_matches(&rule, "api", "prod", 80));
    }
}