Skip to main content

asterust_junos/policy_options/policy_statement/
term.rs

1//! `term`
2//! `policy-options { policy-statement <name> { term <name> { from { ... } to { ... } then { ... } } } }`.
3//!
4//! A policy written without `term` statements is a single unnamed term. Each term carries `from`,
5//! `to` and `then` statements.
6//!
7//! # See also
8//!
9//! - [policy-statement](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/policy-statement-edit-policy-options.html)
10//! - [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)
11//! - [route-filter](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/route-filter-edit-policy-options.html)
12
13use crate::{
14    active_children, arg_of, child_block, has_leaf, list_values, split_keyword, split_name, statements, unquote,
15};
16use asterust::config::ConfigLine;
17
18/// A `route-filter <prefix> <match-type>` condition.
19#[derive(Clone, Debug, PartialEq, Eq)]
20#[non_exhaustive]
21pub struct RouteFilter {
22    pub prefix: String,
23    /// Everything after the prefix, e.g. `"exact"`, `"orlonger"`, `"upto /24"`.
24    pub match_type: Option<String>,
25}
26
27/// A `database <name>` entry of a `validation-database-instance`, with the validation state it matches.
28#[derive(Clone, Debug, PartialEq, Eq)]
29#[non_exhaustive]
30pub struct ValidationDatabaseMatch {
31    pub name: String,
32    /// `"valid"`, `"invalid"` or `"unknown"`.
33    pub state: Option<String>,
34}
35
36/// The `validation-database-instance` condition of Junos OS Evolved.
37#[derive(Clone, Debug, Default, PartialEq, Eq)]
38#[non_exhaustive]
39pub struct ValidationDatabaseInstance {
40    /// The `state` that applies whichever database matched: `"valid"`, `"invalid"` or `"unknown"`.
41    pub state: Option<String>,
42    pub databases: Vec<ValidationDatabaseMatch>,
43}
44
45/// The match conditions of a term's `from` or `to` statement. Conditions not listed here are
46/// ignored.
47#[derive(Clone, Debug, Default, PartialEq, Eq)]
48#[non_exhaustive]
49pub struct PolicyConditions {
50    pub protocols: Vec<String>,
51    pub families: Vec<String>,
52    pub communities: Vec<String>,
53    pub as_paths: Vec<String>,
54    pub prefix_lists: Vec<String>,
55    /// The raw `prefix-list-filter` argument, e.g. `"CUSTOMERS orlonger"`.
56    pub prefix_list_filters: Vec<String>,
57    pub route_filters: Vec<RouteFilter>,
58    pub neighbors: Vec<String>,
59    /// Subroutine policies from `policy`.
60    pub policies: Vec<String>,
61    /// `aggregate-contributor`: routes that contribute to a configured aggregate.
62    pub aggregate_contributor: bool,
63    /// The OSPF `area` identifiers.
64    pub areas: Vec<String>,
65    /// The `as-path-group` names.
66    pub as_path_groups: Vec<String>,
67    /// The raw `as-path-neighbors`, `as-path-origins` and `as-path-transits` arguments, which name an AS list or an AS
68    /// list group, e.g. `"as-list PEERS"` or `"as-list-group GROUP"`.
69    pub as_path_neighbors: Vec<String>,
70    pub as_path_origins: Vec<String>,
71    pub as_path_transits: Vec<String>,
72    /// Everything after `as-path-unique-count`, e.g. `"2 orhigher"`.
73    pub as_path_unique_count: Option<String>,
74    /// Everything after `as-path-calc-length`, e.g. `"4 equal"`.
75    pub as_path_calc_length: Option<String>,
76    /// Everything after `color`, e.g. `"10"` or `"10 color2 5"`.
77    pub color: Option<String>,
78    /// Everything after `community-count`, e.g. `"5 orlower"`.
79    pub community_count: Option<String>,
80    /// The `condition` names defined under `policy-options`.
81    pub conditions: Vec<String>,
82    /// `external`: IGP external routes. The `type` argument is in `external_type`.
83    pub external: bool,
84    /// The OSPF metric type after `external type`, `"1"` or `"2"`.
85    pub external_type: Option<String>,
86    /// `internal`: IGP internal routes.
87    pub internal: bool,
88    pub interfaces: Vec<String>,
89    /// The IS-IS `level`.
90    pub level: Option<String>,
91    pub local_preference: Option<String>,
92    /// Everything after `metric`, e.g. `"10"` or `"10 metric2 20"`.
93    pub metric: Option<String>,
94    pub mac_filter_lists: Vec<String>,
95    /// Everything after `multicast-scoping`, e.g. `"link-local"` or `"4 orhigher"`.
96    pub multicast_scoping: Option<String>,
97    pub next_hops: Vec<String>,
98    /// The `next-hop-type`, e.g. `"merged"`.
99    pub next_hop_type: Option<String>,
100    /// The NLRI route types, `"1"` through `"10"`.
101    pub nlri_route_types: Vec<String>,
102    pub origin: Option<String>,
103    /// Everything after `preference`, e.g. `"10"` or `"10 preference2 20"`.
104    pub preference: Option<String>,
105    /// `programmed`.
106    pub programmed: bool,
107    /// The routing tables named by `rib`, e.g. `"vrf-a.inet.0"`.
108    pub ribs: Vec<String>,
109    pub route_filter_lists: Vec<String>,
110    /// The `route-type`, `"external"` or `"internal"`.
111    pub route_type: Option<String>,
112    /// The raw `rtf-prefix-list` argument, e.g. `"LIST route-targets"`.
113    pub rtf_prefix_lists: Vec<String>,
114    pub source_address_filter_lists: Vec<String>,
115    /// The `source-address-filter` entries, which have the same form as `route-filter`.
116    pub source_address_filters: Vec<RouteFilter>,
117    /// The route state, `"active"` or `"inactive"`.
118    pub state: Option<String>,
119    /// Everything after `tag`, e.g. `"100"` or `"100 tag2 200"`.
120    pub tag: Option<String>,
121    /// `traffic-engineering`.
122    pub traffic_engineering: bool,
123    /// The `validation-database` match: `"valid"`, `"invalid"` or `"unknown"`, the origin validation state of the route.
124    pub validation_database: Option<String>,
125    /// The `validation-database-instance` block of Junos OS Evolved.
126    pub validation_database_instance: Option<ValidationDatabaseInstance>,
127}
128
129/// The flow-control action ending a term.
130#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131#[non_exhaustive]
132pub enum PolicyAction {
133    Accept,
134    Reject,
135    NextTerm,
136    NextPolicy,
137}
138
139/// How a `then community` action changes the route's communities.
140#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141#[non_exhaustive]
142pub enum CommunityOperation {
143    Add,
144    Set,
145    Delete,
146}
147
148/// A `then community (add | set | delete) <name>` action.
149#[derive(Clone, Debug, PartialEq, Eq)]
150#[non_exhaustive]
151pub struct CommunityAction {
152    pub operation: CommunityOperation,
153    pub community: String,
154}
155
156/// A `then srv6 locator <name> <sid>` action, which selects the SRv6 service SID that BGP advertises for the route.
157#[derive(Clone, Debug, PartialEq, Eq)]
158#[non_exhaustive]
159pub struct PolicySrv6Action {
160    pub locator: String,
161    /// `end-dt4-sid`, `micro-dt46-sid` and the like.
162    pub sid_type: Option<String>,
163    /// The static SID value, if given.
164    pub sid_value: Option<String>,
165}
166
167/// The `prefix-segment` action: the SID index of a prefix and whether it is a node segment.
168#[derive(Clone, Debug, Default, PartialEq, Eq)]
169#[non_exhaustive]
170pub struct PolicyPrefixSegment {
171    pub index: Option<String>,
172    pub node_segment: bool,
173}
174
175/// The actions of a term's `then` statement. Actions not listed here are ignored.
176#[derive(Clone, Debug, Default, PartialEq, Eq)]
177#[non_exhaustive]
178pub struct PolicyActions {
179    pub action: Option<PolicyAction>,
180    /// Everything after `metric`, e.g. `"63"` or `"add 10"`.
181    pub metric: Option<String>,
182    pub local_preference: Option<String>,
183    pub next_hop: Option<String>,
184    pub as_path_prepend: Option<String>,
185    pub communities: Vec<CommunityAction>,
186    /// Everything after `load-balance`, e.g. `"per-packet"`. A `load-balance { ...; }` block is not read.
187    pub load_balance: Option<String>,
188    /// The `resolution-map` to apply, which is defined under `policy-options`.
189    pub resolution_map: Option<String>,
190    pub multipath_resolve: bool,
191    pub srv6: Option<PolicySrv6Action>,
192    /// The action the policy takes when no term matches, from `default-action`.
193    pub default_action: Option<PolicyAction>,
194    /// Everything after `add-path`, e.g. `"send-count 16"`.
195    pub add_path: Option<String>,
196    pub advertise_locator: bool,
197    pub aggregate_bandwidth: bool,
198    /// The `multiplier` of the `aggregate-weight` block.
199    pub aggregate_weight: Option<String>,
200    /// `aigp-originate`; the value after `distance` is in `aigp_distance`.
201    pub aigp_originate: bool,
202    pub aigp_distance: Option<String>,
203    /// Everything after `as-path-expand`, e.g. `"2"` or `"last-as count 2"`.
204    pub as_path_expand: Option<String>,
205    /// Everything after `assisted-replication`.
206    pub assisted_replication: Option<String>,
207    pub bgp_output_queue_priority: Option<String>,
208    /// The `class` that the route is placed in.
209    pub class: Option<String>,
210    /// Everything after `color`, e.g. `"10"` or `"add 5"`.
211    pub color: Option<String>,
212    pub cos_next_hop_map: Option<String>,
213    /// The `damping` parameters to apply, named under `policy-options damping`.
214    pub damping: Option<String>,
215    pub destination_class: Option<String>,
216    pub dynamic_tunnel_attributes: Option<String>,
217    /// Everything after `external`, e.g. `"type 2 metric 10"`.
218    pub external: Option<String>,
219    pub forwarding_class: Option<String>,
220    /// Everything after `install-nexthop`, e.g. `"strict lsp LSP1"`.
221    pub install_nexthop: Option<String>,
222    /// `Some(true)` for `install-to-fib`, `Some(false)` for `no-install-to-fib`.
223    pub install_to_fib: Option<bool>,
224    pub limit_bandwidth: Option<String>,
225    pub map_to_interface: Option<String>,
226    pub no_entropy_label_capability: bool,
227    pub origin: Option<String>,
228    /// Everything after `preference`, e.g. `"10"` or `"add 5"`.
229    pub preference: Option<String>,
230    pub prefix_attribute_flags: bool,
231    pub prefix_segment: Option<PolicyPrefixSegment>,
232    /// `"high"`, `"medium"` or `"low"`.
233    pub priority: Option<String>,
234    pub set_down_bit: bool,
235    pub source_class: Option<String>,
236    pub sr_te_template: Option<String>,
237    pub ssm_sources: Vec<String>,
238    /// Everything after `tag`, e.g. `"100"` or `"add 5"`.
239    pub tag: Option<String>,
240    /// `"valid"`, `"invalid"` or `"unknown"`.
241    pub validation_state: Option<String>,
242}
243
244/// One term of a policy statement.
245#[derive(Clone, Debug, PartialEq, Eq)]
246#[non_exhaustive]
247pub struct PolicyTerm {
248    /// `None` for the unnamed term, which is the only one in a policy written without `term`
249    /// statements.
250    pub name: Option<String>,
251    pub from: PolicyConditions,
252    pub to: PolicyConditions,
253    pub then: PolicyActions,
254}
255
256pub(super) fn parse_term(name: Option<&str>, line: &ConfigLine) -> PolicyTerm {
257    PolicyTerm {
258        name: name.map(str::to_string),
259        from: parse_conditions(line, "from"),
260        to: parse_conditions(line, "to"),
261        then: parse_actions(line),
262    }
263}
264
265fn parse_conditions(line: &ConfigLine, keyword: &str) -> PolicyConditions {
266    let mut conditions = PolicyConditions {
267        validation_database_instance: active_children(line)
268            .filter(|c| c.text == keyword)
269            .find_map(|block| child_block(block, "validation-database-instance"))
270            .map(parse_validation_database_instance),
271        ..PolicyConditions::default()
272    };
273    for statement in statements(line, keyword) {
274        let (condition, arg) = split_keyword(statement);
275        match condition {
276            "protocol" => conditions.protocols.extend(list_values(arg)),
277            "family" => conditions.families.push(unquote(arg).to_string()),
278            "community" => conditions.communities.extend(list_values(arg)),
279            "as-path" => conditions.as_paths.extend(list_values(arg)),
280            "prefix-list" => conditions.prefix_lists.extend(list_values(arg)),
281            "prefix-list-filter" => conditions.prefix_list_filters.push(arg.to_string()),
282            "route-filter" => conditions.route_filters.push(parse_route_filter(arg)),
283            "neighbor" => conditions.neighbors.push(unquote(arg).to_string()),
284            "policy" => conditions.policies.push(unquote(arg).to_string()),
285            "aggregate-contributor" => conditions.aggregate_contributor = true,
286            "area" => conditions.areas.push(arg.to_string()),
287            "as-path-group" => conditions.as_path_groups.extend(list_values(arg)),
288            "as-path-neighbors" => conditions.as_path_neighbors.push(arg.to_string()),
289            "as-path-origins" => conditions.as_path_origins.push(arg.to_string()),
290            "as-path-transits" => conditions.as_path_transits.push(arg.to_string()),
291            "as-path-unique-count" => conditions.as_path_unique_count = rest(arg),
292            "as-path-calc-length" => conditions.as_path_calc_length = rest(arg),
293            "color" => conditions.color = rest(arg),
294            "community-count" => conditions.community_count = rest(arg),
295            "condition" => conditions.conditions.extend(list_values(arg)),
296            "external" => {
297                conditions.external = true;
298                conditions.external_type = arg.strip_prefix("type").and_then(|t| rest(t.trim()));
299            }
300            "internal" => conditions.internal = true,
301            "interface" => conditions.interfaces.extend(list_values(arg)),
302            "level" => conditions.level = rest(arg),
303            "local-preference" => conditions.local_preference = rest(arg),
304            "metric" => conditions.metric = rest(arg),
305            "mac-filter-list" => conditions.mac_filter_lists.extend(list_values(arg)),
306            "multicast-scoping" => conditions.multicast_scoping = rest(arg),
307            "next-hop" => conditions.next_hops.extend(list_values(arg)),
308            "next-hop-type" => conditions.next_hop_type = rest(arg),
309            "nlri-route-type" => conditions.nlri_route_types.extend(list_values(arg)),
310            "origin" => conditions.origin = rest(arg),
311            "preference" => conditions.preference = rest(arg),
312            "programmed" => conditions.programmed = true,
313            "rib" => conditions.ribs.extend(list_values(arg)),
314            "route-filter-list" => conditions.route_filter_lists.extend(list_values(arg)),
315            "route-type" => conditions.route_type = rest(arg),
316            "rtf-prefix-list" => conditions.rtf_prefix_lists.push(arg.to_string()),
317            "source-address-filter-list" => conditions.source_address_filter_lists.extend(list_values(arg)),
318            "source-address-filter" => conditions.source_address_filters.push(parse_route_filter(arg)),
319            "state" => conditions.state = rest(arg),
320            "tag" => conditions.tag = rest(arg),
321            "traffic-engineering" => conditions.traffic_engineering = true,
322            "validation-database" => conditions.validation_database = rest(arg),
323            _ => {}
324        }
325    }
326    conditions
327}
328
329fn parse_validation_database_instance(line: &ConfigLine) -> ValidationDatabaseInstance {
330    ValidationDatabaseInstance {
331        state: arg_of(line, "state").map(str::to_string),
332        databases: active_children(line)
333            .filter_map(|c| c.arg("database"))
334            .map(|arg| {
335                let (name, after) = split_name(arg);
336                ValidationDatabaseMatch {
337                    name: unquote(name).to_string(),
338                    state: after.strip_prefix("state").and_then(|s| rest(s.trim())),
339                }
340            })
341            .collect(),
342    }
343}
344
345fn rest(arg: &str) -> Option<String> {
346    Some(arg).filter(|a| !a.is_empty()).map(str::to_string)
347}
348
349fn parse_route_filter(arg: &str) -> RouteFilter {
350    let (prefix, match_type) = split_keyword(arg);
351    RouteFilter {
352        prefix: prefix.to_string(),
353        match_type: Some(match_type).filter(|m| !m.is_empty()).map(str::to_string),
354    }
355}
356
357fn parse_actions(line: &ConfigLine) -> PolicyActions {
358    let mut actions = PolicyActions::default();
359    for statement in statements(line, "then") {
360        let (action, arg) = split_keyword(statement);
361        let value = || Some(unquote(arg).to_string());
362        match (action, arg) {
363            ("accept", "") => actions.action = Some(PolicyAction::Accept),
364            ("reject", "") => actions.action = Some(PolicyAction::Reject),
365            ("next", "term") => actions.action = Some(PolicyAction::NextTerm),
366            ("next", "policy") => actions.action = Some(PolicyAction::NextPolicy),
367            ("metric", _) => actions.metric = value(),
368            ("local-preference", _) => actions.local_preference = value(),
369            ("next-hop", _) => actions.next_hop = value(),
370            ("as-path-prepend", _) => actions.as_path_prepend = value(),
371            ("community", _) => actions.communities.extend(parse_community_actions(arg)),
372            ("load-balance", _) => actions.load_balance = Some(arg.to_string()).filter(|a| !a.is_empty()),
373            ("resolution-map", _) => actions.resolution_map = value(),
374            ("multipath-resolve", "") => actions.multipath_resolve = true,
375            ("srv6", _) => actions.srv6 = parse_srv6_action(arg),
376            ("default-action", "accept") => actions.default_action = Some(PolicyAction::Accept),
377            ("default-action", "reject") => actions.default_action = Some(PolicyAction::Reject),
378            ("add-path", _) => actions.add_path = value(),
379            ("advertise-locator", "") => actions.advertise_locator = true,
380            ("aggregate-bandwidth", "") => actions.aggregate_bandwidth = true,
381            ("aigp-originate", _) => {
382                actions.aigp_originate = true;
383                actions.aigp_distance = arg.strip_prefix("distance").map(|d| d.trim().to_string());
384            }
385            ("as-path-expand", _) => actions.as_path_expand = value(),
386            ("assisted-replication", _) => actions.assisted_replication = value(),
387            ("bgp-output-queue-priority", _) => actions.bgp_output_queue_priority = value(),
388            ("class", _) => actions.class = value(),
389            ("color", _) => actions.color = value(),
390            ("cos-next-hop-map", _) => actions.cos_next_hop_map = value(),
391            ("damping", _) => actions.damping = value(),
392            ("destination-class", _) => actions.destination_class = value(),
393            ("dynamic-tunnel-attributes", _) => actions.dynamic_tunnel_attributes = value(),
394            ("external", _) => actions.external = value(),
395            ("forwarding-class", _) => actions.forwarding_class = value(),
396            ("install-nexthop", _) => actions.install_nexthop = value(),
397            ("install-to-fib", "") => actions.install_to_fib = Some(true),
398            ("no-install-to-fib", "") => actions.install_to_fib = Some(false),
399            ("limit-bandwidth", _) => actions.limit_bandwidth = value(),
400            ("map-to-interface", _) => actions.map_to_interface = value(),
401            ("no-entropy-label-capability", "") => actions.no_entropy_label_capability = true,
402            ("origin", _) => actions.origin = value(),
403            ("preference", _) => actions.preference = value(),
404            ("prefix-attribute-flags", "") => actions.prefix_attribute_flags = true,
405            ("priority", _) => actions.priority = value(),
406            ("set-down-bit", "") => actions.set_down_bit = true,
407            ("source-class", _) => actions.source_class = value(),
408            ("sr-te-template", _) => actions.sr_te_template = value(),
409            ("ssm-source", _) => actions.ssm_sources.extend(list_values(arg)),
410            ("tag", _) => actions.tag = value(),
411            ("validation-state", _) => actions.validation_state = value(),
412            _ => {}
413        }
414    }
415    for block in active_children(line).filter(|c| c.text == "then") {
416        if let Some(weight) = child_block(block, "aggregate-weight") {
417            actions.aggregate_weight = arg_of(weight, "multiplier").map(str::to_string);
418        }
419        if let Some(segment) = child_block(block, "prefix-segment") {
420            actions.prefix_segment = Some(PolicyPrefixSegment {
421                index: arg_of(segment, "index").map(str::to_string),
422                node_segment: has_leaf(segment, "node-segment"),
423            });
424        }
425    }
426    actions
427}
428
429fn parse_srv6_action(arg: &str) -> Option<PolicySrv6Action> {
430    let (locator, sid) = split_name(arg.strip_prefix("locator")?.trim());
431    let (sid_type, sid_value) = split_keyword(sid);
432    Some(PolicySrv6Action {
433        locator: unquote(locator).to_string(),
434        sid_type: Some(sid_type).filter(|t| !t.is_empty()).map(str::to_string),
435        sid_value: Some(sid_value).filter(|v| !v.is_empty()).map(str::to_string),
436    })
437}
438
439fn parse_community_actions(arg: &str) -> Vec<CommunityAction> {
440    let (operation, communities) = split_name(arg);
441    let operation = match operation {
442        "add" | "+" => CommunityOperation::Add,
443        "set" | "=" => CommunityOperation::Set,
444        "delete" | "-" => CommunityOperation::Delete,
445        _ => return Vec::new(),
446    };
447    list_values(communities)
448        .into_iter()
449        .map(|community| CommunityAction { operation, community })
450        .collect()
451}
452
453#[cfg(test)]
454mod tests {
455    use crate::policy_options::{
456        policy_options, CommunityOperation, PolicyAction, PolicyActions, PolicyConditions, PolicyOptions,
457    };
458    use asterust::config::juniper;
459
460    fn parse(text: &str) -> PolicyOptions {
461        policy_options(&juniper::parse_braces(text)).expect("fixture has a policy-options block")
462    }
463
464    fn from_of(options: &PolicyOptions, policy: usize, term: usize) -> &PolicyConditions {
465        &options.policy_statements[policy].terms[term].from
466    }
467
468    // Adapted from the Routing Policies, Firewall Filters, and Traffic Policers User Guide: the `show policy-options`
469    // output of Example: Configuring BGP Import Policy Based on Community Count, the source address filter examples
470    // of Configuring Route Lists for Use in Routing Policy Match Conditions, the route filter list example, the
471    // conditional prefix example, the `next-table` example of the actions page and the MVPN damping example. The
472    // `set` examples are written in brace form. See the README "Sources".
473    const DOC_CONDITIONS: &str = r#"
474policy-options {
475    policy-statement import-communities {
476        term 1 {
477            from {
478                protocol bgp;
479                community-count 5 orlower;
480            }
481            then accept;
482        }
483        term 2 {
484            then reject;
485        }
486    }
487    policy-statement join-filter {
488        from {
489            neighbor 10.14.12.20;
490            source-address-filter 10.83.0.0/16 orlonger;
491        }
492        then reject;
493    }
494    policy-statement join-filter-interface {
495        from {
496            interface so-1/0/0.0;
497            source-address-filter 10.83.0.0/16 orlonger;
498        }
499        then reject;
500    }
501    policy-statement as-list-match {
502        term neighbor-match {
503            from as-path-neighbors as-list peer-match;
504        }
505        term group-match {
506            from as-path-origins as-list-group origin_group;
507        }
508    }
509    policy-statement rf-test-policy {
510        term term2 {
511            from route-filter-list rf-list-1;
512        }
513    }
514    policy-statement conditional-export-bgp {
515        term conditional-default {
516            from {
517                condition prefix_11;
518                route-filter 0.0.0.0/0 exact;
519            }
520            then accept;
521        }
522    }
523    policy-statement dampPolicy {
524        term term1 {
525            from nlri-route-type [ 3 4 5 ];
526        }
527    }
528    policy-statement vrf-leak {
529        term 1 {
530            from {
531                protocol bgp;
532                rib vrf-customer2.inet.0;
533                community customer;
534            }
535        }
536    }
537}
538"#;
539
540    #[test]
541    fn reads_the_guide_community_count() {
542        let options = parse(DOC_CONDITIONS);
543        let from = from_of(&options, 0, 0);
544        assert_eq!(from.protocols, ["bgp"]);
545        assert_eq!(from.community_count.as_deref(), Some("5 orlower"));
546        assert_eq!(from_of(&options, 0, 1).community_count, None);
547    }
548
549    #[test]
550    fn reads_the_guide_source_address_filters() {
551        let options = parse(DOC_CONDITIONS);
552        let from = from_of(&options, 1, 0);
553        assert_eq!(from.neighbors, ["10.14.12.20"]);
554        assert_eq!(from.source_address_filters.len(), 1);
555        assert_eq!(from.source_address_filters[0].prefix, "10.83.0.0/16");
556        assert_eq!(from.source_address_filters[0].match_type.as_deref(), Some("orlonger"));
557
558        let from = from_of(&options, 2, 0);
559        assert_eq!(from.interfaces, ["so-1/0/0.0"]);
560    }
561
562    #[test]
563    fn reads_the_guide_as_lists() {
564        let options = parse(DOC_CONDITIONS);
565        assert_eq!(from_of(&options, 3, 0).as_path_neighbors, ["as-list peer-match"]);
566        assert_eq!(from_of(&options, 3, 1).as_path_origins, ["as-list-group origin_group"]);
567    }
568
569    #[test]
570    fn reads_the_guide_lists_and_conditions() {
571        let options = parse(DOC_CONDITIONS);
572        assert_eq!(from_of(&options, 4, 0).route_filter_lists, ["rf-list-1"]);
573
574        let from = from_of(&options, 5, 0);
575        assert_eq!(from.conditions, ["prefix_11"]);
576        assert_eq!(from.route_filters[0].prefix, "0.0.0.0/0");
577    }
578
579    #[test]
580    fn reads_the_guide_nlri_route_types_and_rib() {
581        let options = parse(DOC_CONDITIONS);
582        assert_eq!(from_of(&options, 6, 0).nlri_route_types, ["3", "4", "5"]);
583
584        let from = from_of(&options, 7, 0);
585        assert_eq!(from.ribs, ["vrf-customer2.inet.0"]);
586        assert_eq!(from.communities, ["customer"]);
587    }
588
589    // Not from documentation: written from the match condition tables of the Routing Policies, Firewall Filters, and
590    // Traffic Policers User Guide. See the README "Sources".
591    #[test]
592    fn reads_the_other_match_conditions() {
593        let options = parse(
594            r#"
595policy-options {
596    policy-statement igp {
597        term ospf {
598            from {
599                protocol ospf;
600                area 0.0.0.0;
601                external type 2;
602                level 2;
603                tag 100 tag2 200;
604                state active;
605                aggregate-contributor;
606                programmed;
607                traffic-engineering;
608            }
609        }
610        term internal {
611            from {
612                internal;
613                route-type external;
614                color 10 color2 5;
615                metric 20 metric2 30;
616                preference 100 preference2 200;
617                local-preference 150;
618                origin igp;
619                next-hop [ 192.0.2.1 192.0.2.2 ];
620                next-hop-type merged;
621                as-path-group TRANSIT;
622                as-path-unique-count 2 orhigher;
623                as-path-calc-length 4 equal;
624                mac-filter-list MACS;
625                multicast-scoping link-local;
626                rtf-prefix-list RTF route-targets;
627                source-address-filter-list SOURCES;
628            }
629        }
630        term bare {
631            from external;
632        }
633    }
634}
635"#,
636        );
637        let ospf = from_of(&options, 0, 0);
638        assert_eq!(ospf.areas, ["0.0.0.0"]);
639        assert!(ospf.external);
640        assert_eq!(ospf.external_type.as_deref(), Some("2"));
641        assert_eq!(ospf.level.as_deref(), Some("2"));
642        assert_eq!(ospf.tag.as_deref(), Some("100 tag2 200"));
643        assert_eq!(ospf.state.as_deref(), Some("active"));
644        assert!(ospf.aggregate_contributor && ospf.programmed && ospf.traffic_engineering);
645        assert!(!ospf.internal);
646
647        let other = from_of(&options, 0, 1);
648        assert!(other.internal && !other.external);
649        assert_eq!(other.route_type.as_deref(), Some("external"));
650        assert_eq!(other.color.as_deref(), Some("10 color2 5"));
651        assert_eq!(other.metric.as_deref(), Some("20 metric2 30"));
652        assert_eq!(other.preference.as_deref(), Some("100 preference2 200"));
653        assert_eq!(other.local_preference.as_deref(), Some("150"));
654        assert_eq!(other.origin.as_deref(), Some("igp"));
655        assert_eq!(other.next_hops, ["192.0.2.1", "192.0.2.2"]);
656        assert_eq!(other.next_hop_type.as_deref(), Some("merged"));
657        assert_eq!(other.as_path_groups, ["TRANSIT"]);
658        assert_eq!(other.as_path_unique_count.as_deref(), Some("2 orhigher"));
659        assert_eq!(other.as_path_calc_length.as_deref(), Some("4 equal"));
660        assert_eq!(other.mac_filter_lists, ["MACS"]);
661        assert_eq!(other.multicast_scoping.as_deref(), Some("link-local"));
662        assert_eq!(other.rtf_prefix_lists, ["RTF route-targets"]);
663        assert_eq!(other.source_address_filter_lists, ["SOURCES"]);
664
665        let bare = from_of(&options, 0, 2);
666        assert!(bare.external);
667        assert_eq!(bare.external_type, None);
668    }
669
670    #[test]
671    fn reads_to_conditions_with_the_same_statements() {
672        let options = parse(
673            "policy-options {\n    policy-statement export {\n        to {\n            level 1;\n            interface ge-0/0/0.0;\n        }\n    }\n}\n",
674        );
675        let to = &options.policy_statements[0].terms[0].to;
676        assert_eq!(to.level.as_deref(), Some("1"));
677        assert_eq!(to.interfaces, ["ge-0/0/0.0"]);
678    }
679
680    // Adapted from the BGP User Guide, Example: Configuring Origin Validation for BGP (Device R0 `show policy-options`
681    // and the validation-database import policy of Understanding Origin Validation for BGP); see the README "Sources".
682    const DOC_VALIDATION: &str = r#"
683policy-options {
684    policy-statement validation {
685        term valid {
686            from {
687                protocol bgp;
688                validation-database valid;
689            }
690            then {
691                validation-state valid;
692                community add origin-validation-state-valid;
693                accept;
694            }
695        }
696        term invalid {
697            from {
698                protocol bgp;
699                validation-database invalid;
700            }
701            then reject;
702        }
703        term unknown {
704            from protocol bgp;
705            then accept;
706        }
707    }
708}
709"#;
710
711    #[test]
712    fn reads_the_guide_validation_database() {
713        let options = parse(DOC_VALIDATION);
714        assert_eq!(from_of(&options, 0, 0).protocols, ["bgp"]);
715        assert_eq!(from_of(&options, 0, 0).validation_database.as_deref(), Some("valid"));
716        assert_eq!(from_of(&options, 0, 1).validation_database.as_deref(), Some("invalid"));
717        assert_eq!(from_of(&options, 0, 2).validation_database, None);
718        assert_eq!(from_of(&options, 0, 0).validation_database_instance, None);
719    }
720
721    // Not from documentation: written from the `validation-database-instance` syntax of the policy-statement CLI
722    // Reference page (Junos OS Evolved). See the README "Sources".
723    #[test]
724    fn reads_the_validation_database_instance() {
725        let options = parse(
726            r#"
727policy-options {
728    policy-statement rpki {
729        term t {
730            from {
731                validation-database-instance {
732                    database RPKI1 state valid;
733                    database "RPKI 2";
734                    state invalid;
735                }
736            }
737        }
738        term inline {
739            from validation-database valid;
740        }
741    }
742}
743"#,
744        );
745        let instance = from_of(&options, 0, 0).validation_database_instance.as_ref().unwrap();
746        assert_eq!(instance.state.as_deref(), Some("invalid"));
747        assert_eq!(instance.databases.len(), 2);
748        assert_eq!(instance.databases[0].name, "RPKI1");
749        assert_eq!(instance.databases[0].state.as_deref(), Some("valid"));
750        assert_eq!(instance.databases[1].name, "RPKI 2");
751        assert_eq!(instance.databases[1].state, None);
752        assert_eq!(from_of(&options, 0, 1).validation_database_instance, None);
753    }
754
755    fn then_of(options: &PolicyOptions, policy: usize, term: usize) -> &PolicyActions {
756        &options.policy_statements[policy].terms[term].then
757    }
758
759    // Adapted from the BGP User Guide: the `show policy-options` output of Understanding Load Balancing Using BGP
760    // Add-Path and Multipath (`aggregate-bandwidth`, `as-path-expand`), the AIGP example of Autonomous Systems, the
761    // damping examples of BGP Session Flaps, and the PTX default policy of Basic Routing Policies; see the README
762    // "Sources".
763    const DOC_THEN_ACTIONS: &str = r#"
764policy-options {
765    policy-statement aggregate_bw_and_limit_capacity {
766        then {
767            aggregate-bandwidth;
768            limit-bandwidth 80000000;
769            accept;
770        }
771    }
772    policy-statement s2b {
773        from protocol [ static direct ];
774        then {
775            as-path-expand 2;
776            accept;
777        }
778    }
779    policy-statement aigp {
780        term 10 {
781            from {
782                protocol static;
783                route-filter 44.0.0.0/24 exact;
784            }
785            then {
786                aigp-originate distance 200;
787                next-hop 10.100.1.4;
788                accept;
789            }
790        }
791    }
792    policy-statement dampPolicy {
793        term term1 {
794            from {
795                family inet-mvpn;
796                nlri-route-type [ 3 4 5 ];
797            }
798            then accept;
799        }
800        then {
801            damping no-damp;
802            accept;
803        }
804    }
805    policy-statement override-ptx-series-default {
806        term 1 {
807            from {
808                prefix-list install-bgp;
809            }
810            then {
811                load-balance per-prefix;
812                install-to-fib;
813            }
814        }
815    }
816    policy-statement junos-ptx-series-default {
817        term t1 {
818            from {
819                protocol bgp;
820                rib inet.0;
821            }
822            then no-install-to-fib;
823        }
824    }
825    policy-statement damp {
826        term 1 {
827            from {
828                route-filter 10.128.0.0/9 exact damping dry;
829                route-filter 0.0.0.0/0 prefix-length-range /17-/32 damping aggressive;
830            }
831        }
832    }
833}
834"#;
835
836    #[test]
837    fn reads_the_guide_bandwidth_and_expand_actions() {
838        let options = parse(DOC_THEN_ACTIONS);
839        let bandwidth = then_of(&options, 0, 0);
840        assert!(bandwidth.aggregate_bandwidth);
841        assert_eq!(bandwidth.limit_bandwidth.as_deref(), Some("80000000"));
842        assert_eq!(bandwidth.action, Some(PolicyAction::Accept));
843
844        let expand = then_of(&options, 1, 0);
845        assert_eq!(expand.as_path_expand.as_deref(), Some("2"));
846        assert!(!expand.aggregate_bandwidth);
847    }
848
849    #[test]
850    fn reads_the_guide_aigp_originate() {
851        let options = parse(DOC_THEN_ACTIONS);
852        let then = then_of(&options, 2, 0);
853        assert!(then.aigp_originate);
854        assert_eq!(then.aigp_distance.as_deref(), Some("200"));
855        assert_eq!(then.next_hop.as_deref(), Some("10.100.1.4"));
856    }
857
858    #[test]
859    fn reads_the_guide_damping() {
860        let options = parse(DOC_THEN_ACTIONS);
861        let policy = &options.policy_statements[3];
862        assert_eq!(policy.terms.len(), 2);
863        assert_eq!(policy.terms[0].name.as_deref(), Some("term1"));
864        assert_eq!(policy.terms[1].name, None);
865        assert_eq!(policy.terms[1].then.damping.as_deref(), Some("no-damp"));
866        assert_eq!(policy.terms[1].then.action, Some(PolicyAction::Accept));
867
868        let filters = &from_of(&options, 6, 0).route_filters;
869        assert_eq!(filters[0].match_type.as_deref(), Some("exact damping dry"));
870        assert_eq!(
871            filters[1].match_type.as_deref(),
872            Some("prefix-length-range /17-/32 damping aggressive")
873        );
874    }
875
876    #[test]
877    fn reads_the_guide_install_to_fib() {
878        let options = parse(DOC_THEN_ACTIONS);
879        let override_default = then_of(&options, 4, 0);
880        assert_eq!(override_default.load_balance.as_deref(), Some("per-prefix"));
881        assert_eq!(override_default.install_to_fib, Some(true));
882        assert_eq!(then_of(&options, 5, 0).install_to_fib, Some(false));
883        assert_eq!(then_of(&options, 0, 0).install_to_fib, None);
884    }
885
886    // Not from documentation: written from the action table of the Routing Policies, Firewall Filters, and Traffic
887    // Policers User Guide and the policy-statement CLI Reference page. See the README "Sources".
888    #[test]
889    fn reads_the_other_actions() {
890        let options = parse(
891            r#"
892policy-options {
893    policy-statement actions {
894        term a {
895            then {
896                default-action reject;
897                add-path send-count 4;
898                advertise-locator;
899                aggregate-weight {
900                    multiplier 2;
901                }
902                as-path-expand last-as count 3;
903                assisted-replication replicator-ip 192.0.2.1 strict;
904                bgp-output-queue-priority 5;
905                class gold;
906                color 10 color2 20;
907                cos-next-hop-map MAP;
908                destination-class DC;
909                dynamic-tunnel-attributes TUNNEL;
910                external type 2 metric 10;
911                forwarding-class expedited-forwarding;
912                install-nexthop strict lsp LSP1;
913                map-to-interface self;
914                no-entropy-label-capability;
915                origin igp;
916                preference add 5;
917                prefix-attribute-flags;
918                prefix-segment {
919                    index 100;
920                    node-segment;
921                }
922                priority high;
923                set-down-bit;
924                source-class SC;
925                sr-te-template TEMPLATE;
926                ssm-source [ 192.0.2.1 192.0.2.2 ];
927                tag 100 tag2 200;
928                validation-state valid;
929            }
930        }
931    }
932}
933"#,
934        );
935        let then = then_of(&options, 0, 0);
936        assert_eq!(then.default_action, Some(PolicyAction::Reject));
937        assert_eq!(then.add_path.as_deref(), Some("send-count 4"));
938        assert!(then.advertise_locator);
939        assert_eq!(then.aggregate_weight.as_deref(), Some("2"));
940        assert!(!then.aigp_originate);
941        assert_eq!(then.as_path_expand.as_deref(), Some("last-as count 3"));
942        assert_eq!(
943            then.assisted_replication.as_deref(),
944            Some("replicator-ip 192.0.2.1 strict")
945        );
946        assert_eq!(then.bgp_output_queue_priority.as_deref(), Some("5"));
947        assert_eq!(then.class.as_deref(), Some("gold"));
948        assert_eq!(then.color.as_deref(), Some("10 color2 20"));
949        assert_eq!(then.cos_next_hop_map.as_deref(), Some("MAP"));
950        assert_eq!(then.destination_class.as_deref(), Some("DC"));
951        assert_eq!(then.dynamic_tunnel_attributes.as_deref(), Some("TUNNEL"));
952        assert_eq!(then.external.as_deref(), Some("type 2 metric 10"));
953        assert_eq!(then.forwarding_class.as_deref(), Some("expedited-forwarding"));
954        assert_eq!(then.install_nexthop.as_deref(), Some("strict lsp LSP1"));
955        assert_eq!(then.map_to_interface.as_deref(), Some("self"));
956        assert!(then.no_entropy_label_capability);
957        assert_eq!(then.origin.as_deref(), Some("igp"));
958        assert_eq!(then.preference.as_deref(), Some("add 5"));
959        assert!(then.prefix_attribute_flags);
960        let segment = then.prefix_segment.as_ref().unwrap();
961        assert_eq!(segment.index.as_deref(), Some("100"));
962        assert!(segment.node_segment);
963        assert_eq!(then.priority.as_deref(), Some("high"));
964        assert!(then.set_down_bit);
965        assert_eq!(then.source_class.as_deref(), Some("SC"));
966        assert_eq!(then.sr_te_template.as_deref(), Some("TEMPLATE"));
967        assert_eq!(then.ssm_sources, ["192.0.2.1", "192.0.2.2"]);
968        assert_eq!(then.tag.as_deref(), Some("100 tag2 200"));
969        assert_eq!(then.validation_state.as_deref(), Some("valid"));
970    }
971
972    // Not from documentation: the list and symbol forms of the `community` action on the actions page.
973    #[test]
974    fn reads_community_lists_and_symbols() {
975        let options = parse(
976            "policy-options {\n    policy-statement c {\n        then {\n            community add [ a b ];\n            community - old;\n            community = only;\n        }\n    }\n}\n",
977        );
978        let communities: Vec<_> = then_of(&options, 0, 0)
979            .communities
980            .iter()
981            .map(|c| (c.operation, c.community.as_str()))
982            .collect();
983        assert_eq!(
984            communities,
985            [
986                (CommunityOperation::Add, "a"),
987                (CommunityOperation::Add, "b"),
988                (CommunityOperation::Delete, "old"),
989                (CommunityOperation::Set, "only"),
990            ]
991        );
992    }
993}