asterust-junos 0.3.17

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
//! `policy-options`
//! `policy-options { ... }`.
//!
//! # See also
//!
//! - [`[edit policy-options]` hierarchy](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/topic-map/hierarchy-edit-policy-options.html)

mod as_path;
mod as_path_group;
mod community;
mod policy_statement;
mod prefix_list;
mod resolution_map;

pub use as_path::AsPath;
pub use as_path_group::AsPathGroup;
pub use community::Community;
pub use policy_statement::{
    CommunityAction, CommunityOperation, PolicyAction, PolicyActions, PolicyConditions, PolicySrv6Action,
    PolicyStatement, PolicyTerm, RouteFilter,
};
pub use prefix_list::PrefixList;
pub use resolution_map::ResolutionMap;

use crate::{active_children, named_children, top_level};
use as_path::parse_as_path;
use as_path_group::parse_as_path_group;
use asterust::config::Config;
use community::parse_community;
use policy_statement::parse_policy;
use prefix_list::parse_prefix_list;
use resolution_map::parse_resolution_map;

/// 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>,
    pub resolution_maps: Vec<ResolutionMap>,
}

/// Returns the top-level `policy-options` block, or `None` if there is none.
///
/// # Examples
///
/// ```
/// use asterust::config::juniper;
/// use asterust_junos::policy_options::policy_options;
///
/// let config = juniper::parse_braces("policy-options {\n    prefix-list CUSTOMERS {\n        192.0.2.0/24;\n    }\n}\n");
/// let options = policy_options(&config).unwrap();
/// assert_eq!(options.prefix_lists[0].name, "CUSTOMERS");
/// assert_eq!(options.prefix_lists[0].prefixes, ["192.0.2.0/24"]);
/// ```
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)| parse_as_path_group(name, line))
            .collect(),
        resolution_maps: named_children(root, "resolution-map")
            .map(|(name, line)| parse_resolution_map(name, line))
            .collect(),
    })
}

#[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());
    }

    // Device R1 `show policy-options` of "Example: Configuring Static SR-TE Policy for an SRv6 Tunnel" (BGP User Guide,
    // BGP Egress Traffic Engineering), with the guide's column padding removed; see the README "Sources".
    const DOC_SRV6_TE: &str = r#"
policy-options {
    policy-statement LBPP {
        term 1 {
            then {
                load-balance per-packet;
            }
        }
    }
    policy-statement mpath-resolve {
        then multipath-resolve;
    }
    policy-statement v4vpn1_res_map1 {
        term 1 {
            from protocol bgp;
            then {
                accept;
                resolution-map map1;
            }
        }
    }
    policy-statement v6vpn1_res_map1 {
        term 1 {
            from {
                family inet6-vpn;
                protocol bgp;
            }
            then {
                accept;
                resolution-map map1;
            }
        }
    }
    community to_CE0_community members target:65500:1;
    resolution-map map1 {
        mode ip-color;
    }
}
"#;

    // Not from documentation: the `srv6` action is written from the uSID example at srv6.md and the `resolution-map`
    // list from the CLI Reference. See the README "Sources".
    const SRV6_ACTION: &str = r#"
policy-options {
    policy-statement LL-PREFIXES {
        term VOICE {
            from community VOICE;
            then {
                srv6 locator LOC128 micro-dt46-sid;
                accept;
            }
        }
        term STATIC {
            then srv6 locator LOC1 end-dt4-sid 3001::4;
        }
        term PLAIN {
            then srv6 locator LOC2;
        }
    }
    resolution-map map2 {
        mode [ color-only ip-color ];
    }
}
"#;

    #[test]
    fn doc_load_balance_and_multipath_resolve() {
        let options = parse(DOC_SRV6_TE);
        let balance = &options.policy_statements[0].terms[0].then;
        assert_eq!(balance.load_balance.as_deref(), Some("per-packet"));
        assert!(!balance.multipath_resolve);

        let resolve = &options.policy_statements[1].terms[0].then;
        assert!(resolve.multipath_resolve);
        assert_eq!(resolve.load_balance, None);
    }

    #[test]
    fn doc_resolution_map_action_and_definition() {
        let options = parse(DOC_SRV6_TE);
        let term = &options.policy_statements[3].terms[0];
        assert_eq!(term.from.families, ["inet6-vpn"]);
        assert_eq!(term.then.resolution_map.as_deref(), Some("map1"));
        assert_eq!(term.then.action, Some(PolicyAction::Accept));

        assert_eq!(options.resolution_maps.len(), 1);
        assert_eq!(options.resolution_maps[0].name, "map1");
        assert_eq!(options.resolution_maps[0].modes, ["ip-color"]);
    }

    #[test]
    fn srv6_actions() {
        let options = parse(SRV6_ACTION);
        let terms = &options.policy_statements[0].terms;

        let dynamic = terms[0].then.srv6.as_ref().unwrap();
        assert_eq!(dynamic.locator, "LOC128");
        assert_eq!(dynamic.sid_type.as_deref(), Some("micro-dt46-sid"));
        assert_eq!(dynamic.sid_value, None);
        assert_eq!(terms[0].then.action, Some(PolicyAction::Accept));

        let fixed = terms[1].then.srv6.as_ref().unwrap();
        assert_eq!(fixed.locator, "LOC1");
        assert_eq!(fixed.sid_type.as_deref(), Some("end-dt4-sid"));
        assert_eq!(fixed.sid_value.as_deref(), Some("3001::4"));

        let bare = terms[2].then.srv6.as_ref().unwrap();
        assert_eq!(bare.locator, "LOC2");
        assert_eq!(bare.sid_type, None);

        assert_eq!(options.resolution_maps[0].modes, ["color-only", "ip-color"]);
    }
}