viceroy-lib 0.17.0

Viceroy implementation details.
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
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error};
use std::collections::HashMap;
use std::fmt::Display;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::sync::Arc;

/// Acls is a mapping of names to acl.
#[derive(Clone, Debug, Default)]
pub struct Acls {
    acls: HashMap<String, Arc<Acl>>,
}

impl Acls {
    pub fn new() -> Self {
        Self {
            acls: HashMap::new(),
        }
    }

    pub fn get_acl(&self, name: &str) -> Option<&Arc<Acl>> {
        self.acls.get(name)
    }

    pub fn insert(&mut self, name: String, acl: Acl) {
        self.acls.insert(name, Arc::new(acl));
    }
}

/// An acl is a collection of acl entries.
///
/// The JSON representation of this struct intentionally matches the JSON
/// format used to create/update ACLs via api.fastly.com. The goal being
/// to allow users to use the same JSON in Viceroy as in production.
///
/// Example:
///
/// ```json
///    { "entries": [
///        { "op": "create", "prefix": "1.2.3.0/24", "action": "BLOCK" },
///        { "op": "create", "prefix": "23.23.23.23/32", "action": "ALLOW" },
///        { "op": "update", "prefix": "FACE::/32", "action": "ALLOW" }
///    ]}
/// ```
///
/// Note that, in Viceroy, the `op` field is ignored.
#[derive(Debug, Default, Deserialize)]
pub struct Acl {
    pub(crate) entries: Vec<Entry>,
}

impl Acl {
    /// Lookup performs a naive lookup of the given IP address
    /// over the acls entries.
    ///
    /// If the IP matches multiple ACL entries, then:
    /// - The most specific match is returned (longest mask),
    /// - and in case of a tie, the last entry wins.
    pub fn lookup(&self, ip: IpAddr) -> Option<&Entry> {
        self.entries.iter().fold(None, |acc, entry| {
            if let Some(mask) = entry.prefix.is_match(ip)
                && acc.is_none_or(|prev_match: &Entry| mask >= prev_match.prefix.mask)
            {
                return Some(entry);
            }
            acc
        })
    }
}

/// An entry is an IP prefix and its associated action.
#[derive(Debug, Deserialize, Serialize, PartialEq)]
pub struct Entry {
    prefix: Prefix,
    action: Action,
}

/// A prefix is an IP and network mask.
#[derive(Debug, PartialEq)]
pub struct Prefix {
    ip: IpAddr,
    mask: u8,
}

impl Prefix {
    pub(crate) fn new(ip: IpAddr, mask: u8) -> Self {
        // Normalize IP based on mask.
        let (ip, mask) = match ip {
            IpAddr::V4(v4) => {
                let mask = mask.clamp(1, 32);
                let bit_mask = u32::MAX << (32 - mask);
                (
                    IpAddr::V4(Ipv4Addr::from_bits(v4.to_bits() & bit_mask)),
                    mask,
                )
            }
            IpAddr::V6(v6) => {
                let mask = mask.clamp(1, 128);
                let bit_mask = u128::MAX << (128 - mask);
                (
                    IpAddr::V6(Ipv6Addr::from_bits(v6.to_bits() & bit_mask)),
                    mask,
                )
            }
        };

        Self { ip, mask }
    }

    /// If the given IP matches the prefix, then the prefix's
    /// mask is returned.
    pub(crate) fn is_match(&self, ip: IpAddr) -> Option<u8> {
        let masked = Self::new(ip, self.mask);
        if masked.ip == self.ip {
            Some(self.mask)
        } else {
            None
        }
    }
}

impl Display for Prefix {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("{}/{}", self.ip, self.mask))
    }
}

impl<'de> Deserialize<'de> for Prefix {
    fn deserialize<D>(de: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let v = String::deserialize(de)?;
        let (ip, mask) = v.split_once('/').ok_or(D::Error::custom(format!(
            "invalid format '{}': want IP/MASK",
            v
        )))?;

        let mask = mask
            .parse::<u8>()
            .map_err(|err| D::Error::custom(format!("invalid prefix {}: {}", mask, err)))?;

        // Detect whether the IP is v4 or v6.
        let ip = match ip.contains(':') {
            false => {
                if !(1..=32).contains(&mask) {
                    return Err(D::Error::custom(format!(
                        "mask outside allowed range [1, 32]: {}",
                        mask
                    )));
                }
                ip.parse::<Ipv4Addr>().map(IpAddr::V4)
            }
            true => {
                if !(1..=128).contains(&mask) {
                    return Err(D::Error::custom(format!(
                        "mask outside allowed range [1, 128]: {}",
                        mask
                    )));
                }
                ip.parse::<Ipv6Addr>().map(IpAddr::V6)
            }
        }
        .map_err(|err| D::Error::custom(format!("invalid ip address {}: {}", ip, err)))?;

        Ok(Self::new(ip, mask))
    }
}

impl Serialize for Prefix {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(format!("{}", self).as_str())
    }
}

const ACTION_ALLOW: &str = "ALLOW";
const ACTION_BLOCK: &str = "BLOCK";

/// An action for a prefix.
#[derive(Clone, Debug, PartialEq)]
pub enum Action {
    Allow,
    Block,
    Other(String),
}

impl<'de> Deserialize<'de> for Action {
    fn deserialize<D>(de: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let action = String::deserialize(de)?;
        Ok(match action.to_uppercase().as_str() {
            ACTION_ALLOW => Self::Allow,
            ACTION_BLOCK => Self::Block,
            _ => Self::Other(action),
        })
    }
}

impl Serialize for Action {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Allow => serializer.serialize_str(ACTION_ALLOW),
            Self::Block => serializer.serialize_str(ACTION_BLOCK),
            Self::Other(other) => serializer.serialize_str(format!("Other({})", other).as_str()),
        }
    }
}

#[test]
fn prefix_is_match() {
    let prefix = Prefix::new(Ipv4Addr::new(192, 168, 100, 0).into(), 16);

    assert_eq!(
        prefix.is_match(Ipv4Addr::new(192, 168, 100, 0).into()),
        Some(16)
    );
    assert_eq!(
        prefix.is_match(Ipv4Addr::new(192, 168, 200, 200).into()),
        Some(16)
    );

    assert_eq!(prefix.is_match(Ipv4Addr::new(192, 167, 0, 0).into()), None);
    assert_eq!(prefix.is_match(Ipv4Addr::new(192, 169, 0, 0).into()), None);

    let prefix = Prefix::new(Ipv6Addr::new(0xFACE, 0, 0, 0, 0, 0, 0, 0).into(), 16);
    assert_eq!(
        prefix.is_match(Ipv6Addr::new(0xFACE, 1, 2, 3, 4, 5, 6, 7).into()),
        Some(16)
    );

    let v4 = Ipv4Addr::new(192, 168, 200, 200);
    let v4_as_v6 = v4.to_ipv6_mapped();

    assert_eq!(Prefix::new(v4.into(), 8).is_match(v4_as_v6.into()), None);
    assert_eq!(Prefix::new(v4_as_v6.into(), 8).is_match(v4.into()), None);
}

#[test]
fn acl_lookup() {
    let acl = Acl {
        entries: vec![
            Entry {
                prefix: Prefix::new(Ipv4Addr::new(192, 168, 100, 0).into(), 16),
                action: Action::Block,
            },
            Entry {
                prefix: Prefix::new(Ipv4Addr::new(192, 168, 100, 0).into(), 24),
                action: Action::Block,
            },
            Entry {
                prefix: Prefix::new(Ipv4Addr::new(192, 168, 100, 0).into(), 8),
                action: Action::Block,
            },
        ],
    };

    match acl.lookup(Ipv4Addr::new(192, 168, 100, 1).into()) {
        Some(lookup_match) => {
            assert_eq!(acl.entries[1], *lookup_match);
        }
        None => panic!("expected lookup match"),
    };

    match acl.lookup(Ipv4Addr::new(192, 168, 200, 1).into()) {
        Some(lookup_match) => {
            assert_eq!(acl.entries[0], *lookup_match);
        }
        None => panic!("expected lookup match"),
    };

    match acl.lookup(Ipv4Addr::new(192, 1, 1, 1).into()) {
        Some(lookup_match) => {
            assert_eq!(acl.entries[2], *lookup_match);
        }
        None => panic!("expected lookup match"),
    };

    if let Some(lookup_match) = acl.lookup(Ipv4Addr::new(1, 1, 1, 1).into()) {
        panic!("expected no lookup match, got {:?}", lookup_match)
    };
}

#[test]
fn acl_json_parse() {
    // In the following JSON, the `op` field should be ignored. It's included
    // to assert that the JSON format used with api.fastly.com to create/modify
    // ACLs can be used in Viceroy as well.
    let input = r#"
    { "entries": [
        { "op": "create", "prefix": "1.2.3.0/24", "action": "BLOCK" },
        { "op": "update", "prefix": "192.168.0.0/16", "action": "BLOCK" },
        { "op": "create", "prefix": "23.23.23.23/32", "action": "ALLOW" },
        { "op": "update", "prefix": "1.2.3.4/32", "action": "ALLOW" },
        { "op": "update", "prefix": "1.2.3.4/8", "action": "ALLOW" }
    ]}
    "#;
    let acl: Acl = serde_json::from_str(input).expect("can decode");

    let want = vec![
        Entry {
            prefix: Prefix {
                ip: IpAddr::V4(Ipv4Addr::new(1, 2, 3, 0)),
                mask: 24,
            },
            action: Action::Block,
        },
        Entry {
            prefix: Prefix {
                ip: IpAddr::V4(Ipv4Addr::new(192, 168, 0, 0)),
                mask: 16,
            },
            action: Action::Block,
        },
        Entry {
            prefix: Prefix {
                ip: IpAddr::V4(Ipv4Addr::new(23, 23, 23, 23)),
                mask: 32,
            },
            action: Action::Allow,
        },
        Entry {
            prefix: Prefix {
                ip: IpAddr::V4(Ipv4Addr::new(1, 2, 3, 4)),
                mask: 32,
            },
            action: Action::Allow,
        },
        Entry {
            prefix: Prefix {
                ip: IpAddr::V4(Ipv4Addr::new(1, 0, 0, 0)),
                mask: 8,
            },
            action: Action::Allow,
        },
    ];

    assert_eq!(acl.entries, want);
}

#[test]
fn prefix_json_roundtrip() {
    let assert_roundtrips = |input: &str, want: &str| {
        let prefix: Prefix =
            serde_json::from_str(format!("\"{}\"", input).as_str()).expect("can decode");
        let got = serde_json::to_string(&prefix).expect("can encode");
        assert_eq!(
            got,
            format!("\"{}\"", want),
            "'{}' roundtrip: got {}, want {}",
            input,
            got,
            want
        );
    };

    assert_roundtrips("255.255.255.255/32", "255.255.255.255/32");
    assert_roundtrips("255.255.255.255/8", "255.0.0.0/8");

    assert_roundtrips("2002::1234:abcd:ffff:c0a8:101/64", "2002:0:0:1234::/64");
    assert_roundtrips("2000::AB/32", "2000::/32");

    // Invalid prefix.
    assert!(serde_json::from_str::<Prefix>("\"1.2.3.4/33\"").is_err());
    assert!(serde_json::from_str::<Prefix>("\"200::/129\"").is_err());
    assert!(serde_json::from_str::<Prefix>("\"200::/none\"").is_err());

    // Invalid IP.
    assert!(serde_json::from_str::<Prefix>("\"1.2.3.four/16\"").is_err());
    assert!(serde_json::from_str::<Prefix>("\"200::end/32\"").is_err());

    // Invalid format.
    assert!(serde_json::from_str::<Prefix>("\"1.2.3.4\"").is_err());
    assert!(serde_json::from_str::<Prefix>("\"200::\"").is_err());
}

#[test]
fn action_json_roundtrip() {
    let assert_roundtrips = |input: &str, want: &str| {
        let action: Action =
            serde_json::from_str(format!("\"{}\"", input).as_str()).expect("can decode");
        let got = serde_json::to_string(&action).expect("can encode");
        assert_eq!(
            got,
            format!("\"{}\"", want),
            "'{}' roundtrip: got {}, want {}",
            input,
            got,
            want
        );
    };

    assert_roundtrips("ALLOW", "ALLOW");
    assert_roundtrips("allow", "ALLOW");
    assert_roundtrips("BLOCK", "BLOCK");
    assert_roundtrips("block", "BLOCK");
    assert_roundtrips("POTATO", "Other(POTATO)");
    assert_roundtrips("potato", "Other(potato)");
}