asterust-junos 0.4.4

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
//! `term`
//! `policy-options { policy-statement <name> { term <name> { from { ... } to { ... } then { ... } } } }`.
//!
//! A policy written without `term` statements is a single unnamed term. Each term carries `from`,
//! `to` and `then` statements.
//!
//! # See also
//!
//! - [policy-statement](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/policy-statement-edit-policy-options.html)
//! - [load-balance (ecmp)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/load-balance-edit-policy-options-policy-statement-then.html)
//! - [route-filter](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/route-filter-edit-policy-options.html)

use crate::{list_values, split_keyword, split_name, statements, unquote};
use asterust::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>,
    /// `aggregate-contributor`: routes that contribute to a configured aggregate.
    pub aggregate_contributor: bool,
    /// The OSPF `area` identifiers.
    pub areas: Vec<String>,
    /// The `as-path-group` names.
    pub as_path_groups: Vec<String>,
    /// The raw `as-path-neighbors`, `as-path-origins` and `as-path-transits` arguments, which name an AS list or an AS
    /// list group, e.g. `"as-list PEERS"` or `"as-list-group GROUP"`.
    pub as_path_neighbors: Vec<String>,
    pub as_path_origins: Vec<String>,
    pub as_path_transits: Vec<String>,
    /// Everything after `as-path-unique-count`, e.g. `"2 orhigher"`.
    pub as_path_unique_count: Option<String>,
    /// Everything after `as-path-calc-length`, e.g. `"4 equal"`.
    pub as_path_calc_length: Option<String>,
    /// Everything after `color`, e.g. `"10"` or `"10 color2 5"`.
    pub color: Option<String>,
    /// Everything after `community-count`, e.g. `"5 orlower"`.
    pub community_count: Option<String>,
    /// The `condition` names defined under `policy-options`.
    pub conditions: Vec<String>,
    /// `external`: IGP external routes. The `type` argument is in `external_type`.
    pub external: bool,
    /// The OSPF metric type after `external type`, `"1"` or `"2"`.
    pub external_type: Option<String>,
    /// `internal`: IGP internal routes.
    pub internal: bool,
    pub interfaces: Vec<String>,
    /// The IS-IS `level`.
    pub level: Option<String>,
    pub local_preference: Option<String>,
    /// Everything after `metric`, e.g. `"10"` or `"10 metric2 20"`.
    pub metric: Option<String>,
    pub mac_filter_lists: Vec<String>,
    /// Everything after `multicast-scoping`, e.g. `"link-local"` or `"4 orhigher"`.
    pub multicast_scoping: Option<String>,
    pub next_hops: Vec<String>,
    /// The `next-hop-type`, e.g. `"merged"`.
    pub next_hop_type: Option<String>,
    /// The NLRI route types, `"1"` through `"10"`.
    pub nlri_route_types: Vec<String>,
    pub origin: Option<String>,
    /// Everything after `preference`, e.g. `"10"` or `"10 preference2 20"`.
    pub preference: Option<String>,
    /// `programmed`.
    pub programmed: bool,
    /// The routing tables named by `rib`, e.g. `"vrf-a.inet.0"`.
    pub ribs: Vec<String>,
    pub route_filter_lists: Vec<String>,
    /// The `route-type`, `"external"` or `"internal"`.
    pub route_type: Option<String>,
    /// The raw `rtf-prefix-list` argument, e.g. `"LIST route-targets"`.
    pub rtf_prefix_lists: Vec<String>,
    pub source_address_filter_lists: Vec<String>,
    /// The `source-address-filter` entries, which have the same form as `route-filter`.
    pub source_address_filters: Vec<RouteFilter>,
    /// The route state, `"active"` or `"inactive"`.
    pub state: Option<String>,
    /// Everything after `tag`, e.g. `"100"` or `"100 tag2 200"`.
    pub tag: Option<String>,
    /// `traffic-engineering`.
    pub traffic_engineering: bool,
}

/// 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,
}

/// A `then srv6 locator <name> <sid>` action, which selects the SRv6 service SID that BGP advertises for the route.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PolicySrv6Action {
    pub locator: String,
    /// `end-dt4-sid`, `micro-dt46-sid` and the like.
    pub sid_type: Option<String>,
    /// The static SID value, if given.
    pub sid_value: Option<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>,
    /// Everything after `load-balance`, e.g. `"per-packet"`. A `load-balance { ...; }` block is not read.
    pub load_balance: Option<String>,
    /// The `resolution-map` to apply, which is defined under `policy-options`.
    pub resolution_map: Option<String>,
    pub multipath_resolve: bool,
    pub srv6: Option<PolicySrv6Action>,
}

/// 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,
}

pub(super) 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()),
            "aggregate-contributor" => conditions.aggregate_contributor = true,
            "area" => conditions.areas.push(arg.to_string()),
            "as-path-group" => conditions.as_path_groups.extend(list_values(arg)),
            "as-path-neighbors" => conditions.as_path_neighbors.push(arg.to_string()),
            "as-path-origins" => conditions.as_path_origins.push(arg.to_string()),
            "as-path-transits" => conditions.as_path_transits.push(arg.to_string()),
            "as-path-unique-count" => conditions.as_path_unique_count = rest(arg),
            "as-path-calc-length" => conditions.as_path_calc_length = rest(arg),
            "color" => conditions.color = rest(arg),
            "community-count" => conditions.community_count = rest(arg),
            "condition" => conditions.conditions.extend(list_values(arg)),
            "external" => {
                conditions.external = true;
                conditions.external_type = arg.strip_prefix("type").and_then(|t| rest(t.trim()));
            }
            "internal" => conditions.internal = true,
            "interface" => conditions.interfaces.extend(list_values(arg)),
            "level" => conditions.level = rest(arg),
            "local-preference" => conditions.local_preference = rest(arg),
            "metric" => conditions.metric = rest(arg),
            "mac-filter-list" => conditions.mac_filter_lists.extend(list_values(arg)),
            "multicast-scoping" => conditions.multicast_scoping = rest(arg),
            "next-hop" => conditions.next_hops.extend(list_values(arg)),
            "next-hop-type" => conditions.next_hop_type = rest(arg),
            "nlri-route-type" => conditions.nlri_route_types.extend(list_values(arg)),
            "origin" => conditions.origin = rest(arg),
            "preference" => conditions.preference = rest(arg),
            "programmed" => conditions.programmed = true,
            "rib" => conditions.ribs.extend(list_values(arg)),
            "route-filter-list" => conditions.route_filter_lists.extend(list_values(arg)),
            "route-type" => conditions.route_type = rest(arg),
            "rtf-prefix-list" => conditions.rtf_prefix_lists.push(arg.to_string()),
            "source-address-filter-list" => conditions.source_address_filter_lists.extend(list_values(arg)),
            "source-address-filter" => conditions.source_address_filters.push(parse_route_filter(arg)),
            "state" => conditions.state = rest(arg),
            "tag" => conditions.tag = rest(arg),
            "traffic-engineering" => conditions.traffic_engineering = true,
            _ => {}
        }
    }
    conditions
}

fn rest(arg: &str) -> Option<String> {
    Some(arg).filter(|a| !a.is_empty()).map(str::to_string)
}

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)),
            ("load-balance", _) => actions.load_balance = Some(arg.to_string()).filter(|a| !a.is_empty()),
            ("resolution-map", _) => actions.resolution_map = value(),
            ("multipath-resolve", "") => actions.multipath_resolve = true,
            ("srv6", _) => actions.srv6 = parse_srv6_action(arg),
            _ => {}
        }
    }
    actions
}

fn parse_srv6_action(arg: &str) -> Option<PolicySrv6Action> {
    let (locator, sid) = split_name(arg.strip_prefix("locator")?.trim());
    let (sid_type, sid_value) = split_keyword(sid);
    Some(PolicySrv6Action {
        locator: unquote(locator).to_string(),
        sid_type: Some(sid_type).filter(|t| !t.is_empty()).map(str::to_string),
        sid_value: Some(sid_value).filter(|v| !v.is_empty()).map(str::to_string),
    })
}

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(),
    })
}

#[cfg(test)]
mod tests {
    use crate::policy_options::{policy_options, PolicyConditions, PolicyOptions};
    use asterust::config::juniper;

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

    fn from_of(options: &PolicyOptions, policy: usize, term: usize) -> &PolicyConditions {
        &options.policy_statements[policy].terms[term].from
    }

    // Adapted from the Routing Policies, Firewall Filters, and Traffic Policers User Guide: the `show policy-options`
    // output of Example: Configuring BGP Import Policy Based on Community Count, the source address filter examples
    // of Configuring Route Lists for Use in Routing Policy Match Conditions, the route filter list example, the
    // conditional prefix example, the `next-table` example of the actions page and the MVPN damping example. The
    // `set` examples are written in brace form. See the README "Sources".
    const DOC_CONDITIONS: &str = r#"
policy-options {
    policy-statement import-communities {
        term 1 {
            from {
                protocol bgp;
                community-count 5 orlower;
            }
            then accept;
        }
        term 2 {
            then reject;
        }
    }
    policy-statement join-filter {
        from {
            neighbor 10.14.12.20;
            source-address-filter 10.83.0.0/16 orlonger;
        }
        then reject;
    }
    policy-statement join-filter-interface {
        from {
            interface so-1/0/0.0;
            source-address-filter 10.83.0.0/16 orlonger;
        }
        then reject;
    }
    policy-statement as-list-match {
        term neighbor-match {
            from as-path-neighbors as-list peer-match;
        }
        term group-match {
            from as-path-origins as-list-group origin_group;
        }
    }
    policy-statement rf-test-policy {
        term term2 {
            from route-filter-list rf-list-1;
        }
    }
    policy-statement conditional-export-bgp {
        term conditional-default {
            from {
                condition prefix_11;
                route-filter 0.0.0.0/0 exact;
            }
            then accept;
        }
    }
    policy-statement dampPolicy {
        term term1 {
            from nlri-route-type [ 3 4 5 ];
        }
    }
    policy-statement vrf-leak {
        term 1 {
            from {
                protocol bgp;
                rib vrf-customer2.inet.0;
                community customer;
            }
        }
    }
}
"#;

    #[test]
    fn reads_the_guide_community_count() {
        let options = parse(DOC_CONDITIONS);
        let from = from_of(&options, 0, 0);
        assert_eq!(from.protocols, ["bgp"]);
        assert_eq!(from.community_count.as_deref(), Some("5 orlower"));
        assert_eq!(from_of(&options, 0, 1).community_count, None);
    }

    #[test]
    fn reads_the_guide_source_address_filters() {
        let options = parse(DOC_CONDITIONS);
        let from = from_of(&options, 1, 0);
        assert_eq!(from.neighbors, ["10.14.12.20"]);
        assert_eq!(from.source_address_filters.len(), 1);
        assert_eq!(from.source_address_filters[0].prefix, "10.83.0.0/16");
        assert_eq!(from.source_address_filters[0].match_type.as_deref(), Some("orlonger"));

        let from = from_of(&options, 2, 0);
        assert_eq!(from.interfaces, ["so-1/0/0.0"]);
    }

    #[test]
    fn reads_the_guide_as_lists() {
        let options = parse(DOC_CONDITIONS);
        assert_eq!(from_of(&options, 3, 0).as_path_neighbors, ["as-list peer-match"]);
        assert_eq!(from_of(&options, 3, 1).as_path_origins, ["as-list-group origin_group"]);
    }

    #[test]
    fn reads_the_guide_lists_and_conditions() {
        let options = parse(DOC_CONDITIONS);
        assert_eq!(from_of(&options, 4, 0).route_filter_lists, ["rf-list-1"]);

        let from = from_of(&options, 5, 0);
        assert_eq!(from.conditions, ["prefix_11"]);
        assert_eq!(from.route_filters[0].prefix, "0.0.0.0/0");
    }

    #[test]
    fn reads_the_guide_nlri_route_types_and_rib() {
        let options = parse(DOC_CONDITIONS);
        assert_eq!(from_of(&options, 6, 0).nlri_route_types, ["3", "4", "5"]);

        let from = from_of(&options, 7, 0);
        assert_eq!(from.ribs, ["vrf-customer2.inet.0"]);
        assert_eq!(from.communities, ["customer"]);
    }

    // Not from documentation: written from the match condition tables of the Routing Policies, Firewall Filters, and
    // Traffic Policers User Guide. See the README "Sources".
    #[test]
    fn reads_the_other_match_conditions() {
        let options = parse(
            r#"
policy-options {
    policy-statement igp {
        term ospf {
            from {
                protocol ospf;
                area 0.0.0.0;
                external type 2;
                level 2;
                tag 100 tag2 200;
                state active;
                aggregate-contributor;
                programmed;
                traffic-engineering;
            }
        }
        term internal {
            from {
                internal;
                route-type external;
                color 10 color2 5;
                metric 20 metric2 30;
                preference 100 preference2 200;
                local-preference 150;
                origin igp;
                next-hop [ 192.0.2.1 192.0.2.2 ];
                next-hop-type merged;
                as-path-group TRANSIT;
                as-path-unique-count 2 orhigher;
                as-path-calc-length 4 equal;
                mac-filter-list MACS;
                multicast-scoping link-local;
                rtf-prefix-list RTF route-targets;
                source-address-filter-list SOURCES;
            }
        }
        term bare {
            from external;
        }
    }
}
"#,
        );
        let ospf = from_of(&options, 0, 0);
        assert_eq!(ospf.areas, ["0.0.0.0"]);
        assert!(ospf.external);
        assert_eq!(ospf.external_type.as_deref(), Some("2"));
        assert_eq!(ospf.level.as_deref(), Some("2"));
        assert_eq!(ospf.tag.as_deref(), Some("100 tag2 200"));
        assert_eq!(ospf.state.as_deref(), Some("active"));
        assert!(ospf.aggregate_contributor && ospf.programmed && ospf.traffic_engineering);
        assert!(!ospf.internal);

        let other = from_of(&options, 0, 1);
        assert!(other.internal && !other.external);
        assert_eq!(other.route_type.as_deref(), Some("external"));
        assert_eq!(other.color.as_deref(), Some("10 color2 5"));
        assert_eq!(other.metric.as_deref(), Some("20 metric2 30"));
        assert_eq!(other.preference.as_deref(), Some("100 preference2 200"));
        assert_eq!(other.local_preference.as_deref(), Some("150"));
        assert_eq!(other.origin.as_deref(), Some("igp"));
        assert_eq!(other.next_hops, ["192.0.2.1", "192.0.2.2"]);
        assert_eq!(other.next_hop_type.as_deref(), Some("merged"));
        assert_eq!(other.as_path_groups, ["TRANSIT"]);
        assert_eq!(other.as_path_unique_count.as_deref(), Some("2 orhigher"));
        assert_eq!(other.as_path_calc_length.as_deref(), Some("4 equal"));
        assert_eq!(other.mac_filter_lists, ["MACS"]);
        assert_eq!(other.multicast_scoping.as_deref(), Some("link-local"));
        assert_eq!(other.rtf_prefix_lists, ["RTF route-targets"]);
        assert_eq!(other.source_address_filter_lists, ["SOURCES"]);

        let bare = from_of(&options, 0, 2);
        assert!(bare.external);
        assert_eq!(bare.external_type, None);
    }

    #[test]
    fn reads_to_conditions_with_the_same_statements() {
        let options = parse(
            "policy-options {\n    policy-statement export {\n        to {\n            level 1;\n            interface ge-0/0/0.0;\n        }\n    }\n}\n",
        );
        let to = &options.policy_statements[0].terms[0].to;
        assert_eq!(to.level.as_deref(), Some("1"));
        assert_eq!(to.interfaces, ["ge-0/0/0.0"]);
    }
}