asterust-junos 0.5.12

Typed Juniper JunOS config views (interfaces, protocols, routing instances and options, policy options, firewall filters, class of service, system, services) extracted from an asterust config tree.
Documentation
//! `ddos-protection`
//! `system { ddos-protection { global { ... } protocols { <group> { <packet-type> { ... } } } } }`.
//!
//! # See also
//!
//! - [ddos-protection](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/system-ddos-protection.html)
//! - [flow-detection (DDoS Packet Level)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/scfd-edit-system-ddos-protection.html)
//! - [flow-detection (DDoS Flow Detection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/enable-scfd-edit-system-ddos-protection.html)
//! - [flow-detection-mode (DDoS Global Flow Detection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/flow-detection-mode-edit-system-ddos-protection-global.html)
//! - [flow-level-control (DDoS Global Flow Detection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/flow-level-control-edit-system-ddos-protection-global.html)
//! - [flow-report-rate (DDoS Flow Detection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/flow-report-rate-edit-system-ddos-protection.html)
//! - [violation-report-rate (DDoS Flow Detection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/violation-report-rate-edit-system-ddos-protection.html)
//! - [flow-bandwidth (DDoS Flow Detection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/flow-bandwidth-edit-system-ddos-scfd.html)
//! - [flow-level-control (DDoS Flow Detection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/flow-control-mode-edit-system-ddos-scfd.html)
//! - [flow-level-detection (DDoS Flow Detection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/flow-operation-mode-edit-system-ddos-scfd.html)
//! - [flow-detect-time (DDoS Flow Detection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/detect-time-edit-system-ddos-scfd.html)
//! - [flow-recover-time (DDoS Flow Detection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/recover-time-edit-system-ddos-scfd.html)
//! - [flow-timeout-time (DDoS Flow Detection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/timeout-time-edit-system-ddos-scfd.html)
//! - [timeout-active-flows (DDoS Flow Detection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/enable-timeout-active-edit-system-ddos-scfd.html)
//! - [no-flow-logging (DDoS Flow Detection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/disable-flow-logging-edit-system-ddos-scfd.html)
//! - [ppp (DDoS Protection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/system-ddos-protection-protocols-ppp.html)
//! - [pppoe (DDoS Protection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/system-ddos-protection-protocols-pppoe.html)
//! - [l2tp (DDoS Protection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/system-ddos-protection-protocols-l2tp.html)
//! - [sample (DDoS Protection)](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/system-ddos-protection-protocols-sample.html)

use crate::protocols::traceoptions::{parse_traceoptions, Traceoptions};
use crate::{active_children, arg_of, child_block, has_leaf, named_children};
use asterust::config::ConfigLine;

/// The per-aggregation-level values of `flow-level-bandwidth`, `flow-level-control` and
/// `flow-level-detection`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct DdosFlowLevels {
    pub logical_interface: Option<String>,
    pub physical_interface: Option<String>,
    pub subscriber: Option<String>,
}

/// An `fpc <slot>` override of a packet type.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DdosFpc {
    pub slot: String,
    pub bandwidth_scale: Option<String>,
    pub burst_scale: Option<String>,
    pub disable_fpc: bool,
    pub hostbound_queue: Option<String>,
}

/// A packet type (or the `aggregate`) of a DDoS protocol group.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DdosPacketType {
    /// The packet type, or `aggregate`.
    pub name: String,
    /// Packets per second.
    pub bandwidth: Option<String>,
    /// Packets.
    pub burst: Option<String>,
    pub bypass_aggregate: bool,
    pub disable_fpc: bool,
    pub disable_logging: bool,
    pub disable_routing_engine: bool,
    pub fpcs: Vec<DdosFpc>,
    pub hostbound_queue: Option<String>,
    /// `high`, `medium` or `low`.
    pub priority: Option<String>,
    /// Seconds.
    pub recover_time: Option<String>,
    /// The `range` of a sampling aggregate.
    pub range: Option<String>,
    /// `automatic`, `off` or `on`.
    pub flow_detection_mode: Option<String>,
    pub flow_detect_time: Option<String>,
    pub flow_recover_time: Option<String>,
    pub flow_timeout_time: Option<String>,
    pub flow_level_bandwidth: Option<DdosFlowLevels>,
    pub flow_level_control: Option<DdosFlowLevels>,
    pub flow_level_detection: Option<DdosFlowLevels>,
    pub no_flow_logging: bool,
    pub timeout_active_flows: bool,
}

/// A protocol group of `ddos-protection protocols`, such as `pppoe` or `dhcpv4`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DdosProtocolGroup {
    pub name: String,
    /// The packet types and the `aggregate`, in the order written.
    pub packet_types: Vec<DdosPacketType>,
}

/// The `global` block of `ddos-protection`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DdosGlobal {
    pub disable_fpc: bool,
    pub disable_logging: bool,
    pub disable_routing_engine: bool,
    pub flow_detection: bool,
    pub flow_detection_mode: Option<String>,
    pub flow_level_control: Option<String>,
    /// Flow reports per second.
    pub flow_report_rate: Option<String>,
    /// Violation reports per second.
    pub violation_report_rate: Option<String>,
}

/// The `system ddos-protection` settings.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DdosProtection {
    pub global: Option<DdosGlobal>,
    pub protocols: Vec<DdosProtocolGroup>,
    pub traceoptions: Option<Traceoptions>,
}

fn levels(parent: &ConfigLine, keyword: &str) -> Option<DdosFlowLevels> {
    let block = child_block(parent, keyword)?;
    let level = |name: &str| arg_of(block, name).map(str::to_string);
    Some(DdosFlowLevels {
        logical_interface: level("logical-interface"),
        physical_interface: level("physical-interface"),
        subscriber: level("subscriber"),
    })
}

fn parse_packet_type(name: &str, packet: &ConfigLine) -> DdosPacketType {
    // The flow detection options are written directly under the packet type, or in a
    // `flow-detection { ... }` block.
    let flow = child_block(packet, "flow-detection");
    let flow_field = |keyword: &str| {
        arg_of(packet, keyword)
            .or_else(|| flow.and_then(|f| arg_of(f, keyword)))
            .map(str::to_string)
    };
    let flow_levels = |keyword: &str| levels(packet, keyword).or_else(|| flow.and_then(|f| levels(f, keyword)));
    let flow_flag = |keyword: &str| has_leaf(packet, keyword) || flow.is_some_and(|f| has_leaf(f, keyword));
    DdosPacketType {
        name: name.to_string(),
        bandwidth: arg_of(packet, "bandwidth").map(str::to_string),
        burst: arg_of(packet, "burst").map(str::to_string),
        bypass_aggregate: has_leaf(packet, "bypass-aggregate"),
        disable_fpc: has_leaf(packet, "disable-fpc"),
        disable_logging: has_leaf(packet, "disable-logging"),
        disable_routing_engine: has_leaf(packet, "disable-routing-engine"),
        fpcs: named_children(packet, "fpc")
            .map(|(slot, fpc)| DdosFpc {
                slot: slot.to_string(),
                bandwidth_scale: arg_of(fpc, "bandwidth-scale").map(str::to_string),
                burst_scale: arg_of(fpc, "burst-scale").map(str::to_string),
                disable_fpc: has_leaf(fpc, "disable-fpc"),
                hostbound_queue: arg_of(fpc, "hostbound-queue").map(str::to_string),
            })
            .collect(),
        hostbound_queue: arg_of(packet, "hostbound-queue").map(str::to_string),
        priority: arg_of(packet, "priority").map(str::to_string),
        recover_time: arg_of(packet, "recover-time").map(str::to_string),
        range: arg_of(packet, "range").map(str::to_string),
        flow_detection_mode: flow_field("flow-detection-mode"),
        flow_detect_time: flow_field("flow-detect-time"),
        flow_recover_time: flow_field("flow-recover-time"),
        flow_timeout_time: flow_field("flow-timeout-time"),
        flow_level_bandwidth: flow_levels("flow-level-bandwidth"),
        flow_level_control: flow_levels("flow-level-control"),
        flow_level_detection: flow_levels("flow-level-detection"),
        no_flow_logging: flow_flag("no-flow-logging"),
        timeout_active_flows: flow_flag("timeout-active-flows"),
    }
}

pub(super) fn parse_ddos_protection(ddos: &ConfigLine) -> DdosProtection {
    DdosProtection {
        global: child_block(ddos, "global").map(|global| DdosGlobal {
            disable_fpc: has_leaf(global, "disable-fpc"),
            disable_logging: has_leaf(global, "disable-logging"),
            disable_routing_engine: has_leaf(global, "disable-routing-engine"),
            flow_detection: has_leaf(global, "flow-detection"),
            flow_detection_mode: arg_of(global, "flow-detection-mode").map(str::to_string),
            flow_level_control: arg_of(global, "flow-level-control").map(str::to_string),
            flow_report_rate: arg_of(global, "flow-report-rate").map(str::to_string),
            violation_report_rate: arg_of(global, "violation-report-rate").map(str::to_string),
        }),
        protocols: child_block(ddos, "protocols")
            .map(|protocols| {
                active_children(protocols)
                    .map(|group| DdosProtocolGroup {
                        name: group.text.clone(),
                        packet_types: active_children(group)
                            .map(|packet| parse_packet_type(&packet.text, packet))
                            .collect(),
                    })
                    .collect()
            })
            .unwrap_or_default(),
        traceoptions: parse_traceoptions(ddos),
    }
}

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

    // Not from documentation: written from the CLI Reference syntax pages. See the README "Sources".
    #[test]
    fn extracts_the_global_settings() {
        let ddos = system(&juniper::parse_braces(
            r#"
system {
    ddos-protection {
        global {
            disable-fpc;
            disable-logging;
            disable-routing-engine;
            flow-detection;
            flow-detection-mode automatic;
            flow-level-control police;
            flow-report-rate 50;
            violation-report-rate 200;
        }
        traceoptions {
            file ddos.log;
            flag all;
        }
    }
}
"#,
        ))
        .unwrap()
        .ddos_protection
        .unwrap();
        let global = ddos.global.unwrap();
        assert!(global.disable_fpc);
        assert!(global.disable_logging);
        assert!(global.disable_routing_engine);
        assert!(global.flow_detection);
        assert_eq!(global.flow_detection_mode.as_deref(), Some("automatic"));
        assert_eq!(global.flow_level_control.as_deref(), Some("police"));
        assert_eq!(global.flow_report_rate.as_deref(), Some("50"));
        assert_eq!(global.violation_report_rate.as_deref(), Some("200"));
        assert_eq!(ddos.traceoptions.unwrap().file.as_deref(), Some("ddos.log"));
        assert!(ddos.protocols.is_empty());
    }

    #[test]
    fn extracts_protocol_groups_and_packet_types() {
        let ddos = system(&juniper::parse_braces(
            r#"
system {
    ddos-protection {
        protocols {
            pppoe {
                aggregate {
                    bandwidth 8000;
                    burst 2000;
                    recover-time 120;
                    fpc 2 {
                        bandwidth-scale 50;
                        burst-scale 25;
                        disable-fpc;
                    }
                }
                padi {
                    bandwidth 500;
                    bypass-aggregate;
                    disable-logging;
                    priority medium;
                    hostbound-queue 3;
                    flow-detection-mode on;
                    flow-detect-time 5;
                    flow-recover-time 90;
                    flow-timeout-time 600;
                    no-flow-logging;
                    timeout-active-flows;
                    flow-level-bandwidth {
                        logical-interface 100;
                        subscriber 10;
                    }
                    flow-level-control {
                        physical-interface drop;
                    }
                    flow-level-detection {
                        subscriber off;
                    }
                }
            }
            sample {
                aggregate {
                    range 5000;
                }
            }
        }
    }
}
"#,
        ))
        .unwrap()
        .ddos_protection
        .unwrap();
        assert_eq!(ddos.protocols.len(), 2);
        let pppoe = &ddos.protocols[0];
        assert_eq!(pppoe.name, "pppoe");
        assert_eq!(pppoe.packet_types.len(), 2);

        let aggregate = &pppoe.packet_types[0];
        assert_eq!(aggregate.name, "aggregate");
        assert_eq!(aggregate.bandwidth.as_deref(), Some("8000"));
        assert_eq!(aggregate.burst.as_deref(), Some("2000"));
        assert_eq!(aggregate.recover_time.as_deref(), Some("120"));
        assert_eq!(aggregate.fpcs[0].slot, "2");
        assert_eq!(aggregate.fpcs[0].bandwidth_scale.as_deref(), Some("50"));
        assert_eq!(aggregate.fpcs[0].burst_scale.as_deref(), Some("25"));
        assert!(aggregate.fpcs[0].disable_fpc);

        let padi = &pppoe.packet_types[1];
        assert_eq!(padi.name, "padi");
        assert!(padi.bypass_aggregate);
        assert!(padi.disable_logging);
        assert_eq!(padi.priority.as_deref(), Some("medium"));
        assert_eq!(padi.hostbound_queue.as_deref(), Some("3"));
        assert_eq!(padi.flow_detection_mode.as_deref(), Some("on"));
        assert_eq!(padi.flow_detect_time.as_deref(), Some("5"));
        assert_eq!(padi.flow_recover_time.as_deref(), Some("90"));
        assert_eq!(padi.flow_timeout_time.as_deref(), Some("600"));
        assert!(padi.no_flow_logging);
        assert!(padi.timeout_active_flows);
        let bandwidth = padi.flow_level_bandwidth.as_ref().unwrap();
        assert_eq!(bandwidth.logical_interface.as_deref(), Some("100"));
        assert_eq!(bandwidth.subscriber.as_deref(), Some("10"));
        assert_eq!(bandwidth.physical_interface, None);
        assert_eq!(
            padi.flow_level_control.as_ref().unwrap().physical_interface.as_deref(),
            Some("drop")
        );
        assert_eq!(
            padi.flow_level_detection.as_ref().unwrap().subscriber.as_deref(),
            Some("off")
        );

        assert_eq!(ddos.protocols[1].packet_types[0].range.as_deref(), Some("5000"));
    }

    #[test]
    fn reads_flow_detection_written_as_a_block() {
        let ddos = system(&juniper::parse_braces(
            r#"
system {
    ddos-protection {
        protocols {
            dhcpv4 {
                discover {
                    flow-detection {
                        flow-detect-time 4;
                        no-flow-logging;
                        flow-level-bandwidth {
                            subscriber 20;
                        }
                    }
                }
            }
        }
    }
}
"#,
        ))
        .unwrap()
        .ddos_protection
        .unwrap();
        let discover = &ddos.protocols[0].packet_types[0];
        assert_eq!(discover.flow_detect_time.as_deref(), Some("4"));
        assert!(discover.no_flow_logging);
        assert_eq!(
            discover.flow_level_bandwidth.as_ref().unwrap().subscriber.as_deref(),
            Some("20")
        );
        assert_eq!(discover.bandwidth, None);
    }

    #[test]
    fn no_ddos_protection_is_none() {
        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
        assert!(system.ddos_protection.is_none());
    }
}