asterust-junos 0.2.0

Typed Juniper JunOS config views (interfaces, OSPF, BGP, IS-IS, routing instances, policy options, firewall filters, system) extracted from an asterust config tree.
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
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! `policy-options { ... }`: policy statements, communities, prefix lists and AS paths.

use crate::{active_children, list_values, named_children, split_keyword, split_name, statements, top_level, unquote};
use asterust::config::{Config, ConfigLine};

/// A `route-filter <prefix> <match-type>` condition.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct RouteFilter {
    pub prefix: String,
    /// Everything after the prefix, e.g. `"exact"`, `"orlonger"`, `"upto /24"`.
    pub match_type: Option<String>,
}

/// The match conditions of a term's `from` or `to` statement. Conditions not listed here are ignored.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicyConditions {
    pub protocols: Vec<String>,
    pub families: Vec<String>,
    pub communities: Vec<String>,
    pub as_paths: Vec<String>,
    pub prefix_lists: Vec<String>,
    /// The raw `prefix-list-filter` argument, e.g. `"CUSTOMERS orlonger"`.
    pub prefix_list_filters: Vec<String>,
    pub route_filters: Vec<RouteFilter>,
    pub neighbors: Vec<String>,
    /// Subroutine policies from `policy`.
    pub policies: Vec<String>,
}

/// The flow-control action ending a term.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum PolicyAction {
    Accept,
    Reject,
    NextTerm,
    NextPolicy,
}

/// How a `then community` action changes the route's communities.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CommunityOperation {
    Add,
    Set,
    Delete,
}

/// A `then community (add | set | delete) <name>` action.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct CommunityAction {
    pub operation: CommunityOperation,
    pub community: String,
}

/// The actions of a term's `then` statement. Actions not listed here are ignored.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicyActions {
    pub action: Option<PolicyAction>,
    /// Everything after `metric`, e.g. `"63"` or `"add 10"`.
    pub metric: Option<String>,
    pub local_preference: Option<String>,
    pub next_hop: Option<String>,
    pub as_path_prepend: Option<String>,
    pub communities: Vec<CommunityAction>,
}

/// One term of a policy statement.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicyTerm {
    /// `None` for the unnamed term, which is the only one in a policy written without `term` statements.
    pub name: Option<String>,
    pub from: PolicyConditions,
    pub to: PolicyConditions,
    pub then: PolicyActions,
}

/// A `policy-statement <name>`. An unnamed term is placed last.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicyStatement {
    pub name: String,
    pub terms: Vec<PolicyTerm>,
}

/// A `community <name> members ...`, which may be a standard, extended or large community.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Community {
    pub name: String,
    pub members: Vec<String>,
    pub invert_match: bool,
}

/// A `prefix-list <name>`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PrefixList {
    pub name: String,
    pub prefixes: Vec<String>,
    pub apply_path: Option<String>,
}

/// An `as-path <name> <regular-expression>`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AsPath {
    pub name: String,
    pub regex: String,
}

/// An `as-path-group <name>` of AS path expressions.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct AsPathGroup {
    pub name: String,
    pub as_paths: Vec<AsPath>,
}

/// The top-level `policy-options` configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicyOptions {
    pub policy_statements: Vec<PolicyStatement>,
    pub communities: Vec<Community>,
    pub prefix_lists: Vec<PrefixList>,
    pub as_paths: Vec<AsPath>,
    pub as_path_groups: Vec<AsPathGroup>,
}

/// The top-level `policy-options` block, or `None` if there is none.
pub fn policy_options(config: &Config) -> Option<PolicyOptions> {
    let root = top_level(config, "policy-options")?;
    Some(PolicyOptions {
        policy_statements: named_children(root, "policy-statement")
            .map(|(name, line)| parse_policy(name, line))
            .collect(),
        communities: active_children(root).filter_map(parse_community).collect(),
        prefix_lists: named_children(root, "prefix-list")
            .map(|(name, line)| parse_prefix_list(name, line))
            .collect(),
        as_paths: active_children(root).filter_map(parse_as_path).collect(),
        as_path_groups: named_children(root, "as-path-group")
            .map(|(name, line)| AsPathGroup {
                name: name.to_string(),
                as_paths: active_children(line).filter_map(parse_as_path).collect(),
            })
            .collect(),
    })
}

fn parse_policy(name: &str, line: &ConfigLine) -> PolicyStatement {
    let mut terms: Vec<PolicyTerm> = named_children(line, "term")
        .map(|(term_name, term)| parse_term(Some(term_name), term))
        .collect();
    let has_unnamed_term = active_children(line).any(|c| {
        ["from", "to", "then"]
            .iter()
            .any(|k| c.text == *k || c.arg(k).is_some())
    });
    if has_unnamed_term {
        terms.push(parse_term(None, line));
    }
    PolicyStatement {
        name: name.to_string(),
        terms,
    }
}

fn parse_term(name: Option<&str>, line: &ConfigLine) -> PolicyTerm {
    PolicyTerm {
        name: name.map(str::to_string),
        from: parse_conditions(line, "from"),
        to: parse_conditions(line, "to"),
        then: parse_actions(line),
    }
}

fn parse_conditions(line: &ConfigLine, keyword: &str) -> PolicyConditions {
    let mut conditions = PolicyConditions::default();
    for statement in statements(line, keyword) {
        let (condition, arg) = split_keyword(statement);
        match condition {
            "protocol" => conditions.protocols.extend(list_values(arg)),
            "family" => conditions.families.push(unquote(arg).to_string()),
            "community" => conditions.communities.extend(list_values(arg)),
            "as-path" => conditions.as_paths.extend(list_values(arg)),
            "prefix-list" => conditions.prefix_lists.extend(list_values(arg)),
            "prefix-list-filter" => conditions.prefix_list_filters.push(arg.to_string()),
            "route-filter" => conditions.route_filters.push(parse_route_filter(arg)),
            "neighbor" => conditions.neighbors.push(unquote(arg).to_string()),
            "policy" => conditions.policies.push(unquote(arg).to_string()),
            _ => {}
        }
    }
    conditions
}

fn parse_route_filter(arg: &str) -> RouteFilter {
    let (prefix, match_type) = split_keyword(arg);
    RouteFilter {
        prefix: prefix.to_string(),
        match_type: Some(match_type).filter(|m| !m.is_empty()).map(str::to_string),
    }
}

fn parse_actions(line: &ConfigLine) -> PolicyActions {
    let mut actions = PolicyActions::default();
    for statement in statements(line, "then") {
        let (action, arg) = split_keyword(statement);
        let value = || Some(unquote(arg).to_string());
        match (action, arg) {
            ("accept", "") => actions.action = Some(PolicyAction::Accept),
            ("reject", "") => actions.action = Some(PolicyAction::Reject),
            ("next", "term") => actions.action = Some(PolicyAction::NextTerm),
            ("next", "policy") => actions.action = Some(PolicyAction::NextPolicy),
            ("metric", _) => actions.metric = value(),
            ("local-preference", _) => actions.local_preference = value(),
            ("next-hop", _) => actions.next_hop = value(),
            ("as-path-prepend", _) => actions.as_path_prepend = value(),
            ("community", _) => actions.communities.extend(parse_community_action(arg)),
            _ => {}
        }
    }
    actions
}

fn parse_community_action(arg: &str) -> Option<CommunityAction> {
    let (operation, community) = split_name(arg);
    let operation = match operation {
        "add" => CommunityOperation::Add,
        "set" => CommunityOperation::Set,
        "delete" => CommunityOperation::Delete,
        _ => return None,
    };
    Some(CommunityAction {
        operation,
        community: unquote(community).to_string(),
    })
}

/// A `community` statement written either on one line (`community X members 1:1;`) or as a block.
fn parse_community(line: &ConfigLine) -> Option<Community> {
    let (name, rest) = split_name(line.arg("community")?);
    let (keyword, members) = split_keyword(rest);
    let mut community = Community {
        name: name.to_string(),
        members: if keyword == "members" {
            list_values(members)
        } else {
            Vec::new()
        },
        invert_match: false,
    };
    for child in active_children(line) {
        if let Some(members) = child.arg("members") {
            community.members.extend(list_values(members));
        } else if child.text == "invert-match" {
            community.invert_match = true;
        }
    }
    Some(community)
}

fn parse_prefix_list(name: &str, line: &ConfigLine) -> PrefixList {
    let mut list = PrefixList {
        name: name.to_string(),
        prefixes: Vec::new(),
        apply_path: None,
    };
    for child in active_children(line) {
        if let Some(path) = child.arg("apply-path") {
            list.apply_path = Some(unquote(path).to_string());
        } else if !child.text.contains(' ') {
            // Prefixes are the only statements without arguments; `apply-groups` and the like have a space.
            list.prefixes.push(child.text.clone());
        }
    }
    list
}

fn parse_as_path(line: &ConfigLine) -> Option<AsPath> {
    let (name, regex) = split_name(line.arg("as-path")?);
    Some(AsPath {
        name: name.to_string(),
        regex: unquote(regex).to_string(),
    })
}

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

    fn parse(text: &str) -> PolicyOptions {
        policy_options(&juniper::parse_braces(text)).expect("fixture has a policy-options block")
    }

    // Adapted from Juniper's BGP User Guide "Routing Policies for BGP Communities"; see the README "Sources".
    const DOC_COMMUNITY_TAG: &str = r#"
policy-options {
    policy-statement Edu-to-isis {
        term 1 {
            from {
                protocol bgp;
                community Edu;
            }
            then {
                metric 63;
                accept;
            }
        }
    }
    policy-statement send-isis-and-direct {
        term 1 {
            from {
                protocol [ isis direct ];
                route-filter 10.0.0.0/16 orlonger;
                route-filter 192.168.0.0/16 orlonger;
            }
            then accept;
        }
    }
    community Edu members 2:5;
}
"#;

    #[test]
    fn doc_term_with_from_block_and_metric() {
        let options = parse(DOC_COMMUNITY_TAG);
        assert_eq!(options.policy_statements.len(), 2);

        let policy = &options.policy_statements[0];
        assert_eq!(policy.name, "Edu-to-isis");
        let term = &policy.terms[0];
        assert_eq!(term.name.as_deref(), Some("1"));
        assert_eq!(term.from.protocols, ["bgp"]);
        assert_eq!(term.from.communities, ["Edu"]);
        assert_eq!(term.then.metric.as_deref(), Some("63"));
        assert_eq!(term.then.action, Some(PolicyAction::Accept));
    }

    #[test]
    fn doc_protocol_list_route_filters_and_leaf_then() {
        let options = parse(DOC_COMMUNITY_TAG);
        let term = &options.policy_statements[1].terms[0];
        assert_eq!(term.from.protocols, ["isis", "direct"]);
        assert_eq!(term.from.route_filters.len(), 2);
        assert_eq!(term.from.route_filters[0].prefix, "10.0.0.0/16");
        assert_eq!(term.from.route_filters[0].match_type.as_deref(), Some("orlonger"));
        assert_eq!(term.then.action, Some(PolicyAction::Accept));
    }

    #[test]
    fn doc_one_line_community() {
        let options = parse(DOC_COMMUNITY_TAG);
        assert_eq!(options.communities.len(), 1);
        assert_eq!(options.communities[0].name, "Edu");
        assert_eq!(options.communities[0].members, ["2:5"]);
        assert!(!options.communities[0].invert_match);
    }

    // Adapted from the same guide's "Configuring a Routing Policy That Removes BGP Communities" and "...Based on
    // the Number of BGP Communities" examples (Devices R1 and R2).
    const DOC_COMMUNITY_ACTIONS: &str = r#"
policy-options {
    policy-statement statics {
        from protocol static;
        then {
            community add 1;
            accept;
        }
    }
    policy-statement remove-communities {
        term 1 {
            from protocol bgp;
            then {
                community delete wild;
                accept;
            }
        }
        term 2 {
            then reject;
        }
    }
    community wild members *:*;
    community 1 members [ 2:1 2:2 2:3 ];
}
"#;

    #[test]
    fn doc_policy_without_terms_has_one_unnamed_term() {
        let options = parse(DOC_COMMUNITY_ACTIONS);
        let statics = &options.policy_statements[0];
        assert_eq!(statics.terms.len(), 1);
        let term = &statics.terms[0];
        assert_eq!(term.name, None);
        assert_eq!(term.from.protocols, ["static"]);
        assert_eq!(
            term.then.communities,
            [CommunityAction {
                operation: CommunityOperation::Add,
                community: "1".to_string()
            }]
        );
        assert_eq!(term.then.action, Some(PolicyAction::Accept));
    }

    #[test]
    fn doc_community_delete_and_final_reject_term() {
        let options = parse(DOC_COMMUNITY_ACTIONS);
        let remove = &options.policy_statements[1];
        assert_eq!(remove.terms.len(), 2);
        assert_eq!(
            remove.terms[0].then.communities[0].operation,
            CommunityOperation::Delete
        );
        assert_eq!(remove.terms[0].then.communities[0].community, "wild");
        assert_eq!(remove.terms[1].name.as_deref(), Some("2"));
        assert_eq!(remove.terms[1].then.action, Some(PolicyAction::Reject));
    }

    #[test]
    fn doc_community_members_list() {
        let options = parse(DOC_COMMUNITY_ACTIONS);
        assert_eq!(options.communities[0].members, ["*:*"]);
        assert_eq!(options.communities[1].name, "1");
        assert_eq!(options.communities[1].members, ["2:1", "2:2", "2:3"]);
    }

    // Not from documentation: covers statements the Juniper examples do not use. See the README "Sources".
    const CONFIG: &str = r#"
policy-options {
    prefix-list CUSTOMERS {
        192.0.2.0/24;
        2001:db8::/32;
    }
    prefix-list DYNAMIC {
        apply-path "protocols bgp group <*> neighbor <*>";
    }
    as-path FROM-AS65001 ".* 65001";
    as-path-group TRANSIT {
        as-path TIER1 "65100 .*";
        as-path TIER2 "65200 .*";
    }
    community BLOCK {
        invert-match;
        members [ no-export 65000:666 ];
    }
    community WILD members "* : *";
    policy-statement IMPORT {
        term FROM-CUSTOMER {
            from {
                family inet;
                neighbor 192.0.2.1;
                prefix-list CUSTOMERS;
                prefix-list-filter CUSTOMERS orlonger;
                as-path FROM-AS65001;
                route-filter 10.0.0.0/8 upto /24;
                policy SUBROUTINE;
            }
            then {
                local-preference 200;
                next-hop self;
                as-path-prepend "65000 65000";
                next policy;
            }
        }
        inactive: term DISABLED {
            then reject;
        }
        term SKIP {
            from protocol ospf;
            then next term;
        }
        then reject;
    }
}
"#;

    #[test]
    fn extracts_prefix_lists_and_as_paths() {
        let options = parse(CONFIG);
        assert_eq!(options.prefix_lists[0].name, "CUSTOMERS");
        assert_eq!(options.prefix_lists[0].prefixes, ["192.0.2.0/24", "2001:db8::/32"]);
        assert_eq!(options.prefix_lists[0].apply_path, None);
        assert!(options.prefix_lists[1].prefixes.is_empty());
        assert_eq!(
            options.prefix_lists[1].apply_path.as_deref(),
            Some("protocols bgp group <*> neighbor <*>")
        );

        assert_eq!(options.as_paths.len(), 1);
        assert_eq!(options.as_paths[0].name, "FROM-AS65001");
        assert_eq!(options.as_paths[0].regex, ".* 65001");
        let group = &options.as_path_groups[0];
        assert_eq!(group.name, "TRANSIT");
        let names: Vec<_> = group.as_paths.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(names, ["TIER1", "TIER2"]);
        assert_eq!(group.as_paths[1].regex, "65200 .*");
    }

    #[test]
    fn extracts_block_and_quoted_communities() {
        let options = parse(CONFIG);
        assert_eq!(options.communities.len(), 2);
        assert_eq!(options.communities[0].name, "BLOCK");
        assert_eq!(options.communities[0].members, ["no-export", "65000:666"]);
        assert!(options.communities[0].invert_match);
        assert_eq!(options.communities[1].members, ["* : *"]);
    }

    #[test]
    fn extracts_conditions_and_manipulation_actions() {
        let options = parse(CONFIG);
        let term = &options.policy_statements[0].terms[0];
        assert_eq!(term.name.as_deref(), Some("FROM-CUSTOMER"));
        assert_eq!(term.from.families, ["inet"]);
        assert_eq!(term.from.neighbors, ["192.0.2.1"]);
        assert_eq!(term.from.prefix_lists, ["CUSTOMERS"]);
        assert_eq!(term.from.prefix_list_filters, ["CUSTOMERS orlonger"]);
        assert_eq!(term.from.as_paths, ["FROM-AS65001"]);
        assert_eq!(term.from.route_filters[0].match_type.as_deref(), Some("upto /24"));
        assert_eq!(term.from.policies, ["SUBROUTINE"]);
        assert_eq!(term.then.local_preference.as_deref(), Some("200"));
        assert_eq!(term.then.next_hop.as_deref(), Some("self"));
        assert_eq!(term.then.as_path_prepend.as_deref(), Some("65000 65000"));
        assert_eq!(term.then.action, Some(PolicyAction::NextPolicy));
    }

    #[test]
    fn skips_inactive_terms_and_keeps_unnamed_final_term_last() {
        let options = parse(CONFIG);
        let terms = &options.policy_statements[0].terms;
        let names: Vec<_> = terms.iter().map(|t| t.name.as_deref()).collect();
        assert_eq!(names, [Some("FROM-CUSTOMER"), Some("SKIP"), None]);
        assert_eq!(terms[1].then.action, Some(PolicyAction::NextTerm));
        assert_eq!(terms[2].then.action, Some(PolicyAction::Reject));
    }

    #[test]
    fn no_policy_options_is_none() {
        assert!(policy_options(&juniper::parse_braces("system {\n host-name r1;\n}\n")).is_none());
    }
}