asterust-junos 0.3.13

Typed Juniper JunOS config views (interfaces, OSPF, BGP, IS-IS, routing instances, policy options, firewall filters, system) extracted from an asterust config tree.
Documentation
//! `archival`
//! `system { archival { ... } }`.
//!
//! # See also
//!
//! - [archival](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/archival-edit-system.html)

use crate::{arg_of, child_block, has_leaf, secret_value, statements, unquote, value_after, Secret};
use asterust::config::ConfigLine;

/// The `configuration` block of `system archival`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ArchivalConfiguration {
    /// Archive site URLs, with any password embedded in the URL removed.
    pub archive_sites: Vec<String>,
    /// The password of each archive site, in the order of `archive_sites`: its `password` option, else the one embedded
    /// in the URL. All `None` unless the `secrets` feature is enabled.
    pub archive_site_passwords: Vec<Option<Secret>>,
    /// Minutes between transfers.
    pub transfer_interval: Option<String>,
    pub transfer_on_commit: bool,
}

/// The `system archival` configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Archival {
    pub configuration: Option<ArchivalConfiguration>,
    pub routing_instance: Option<String>,
}

pub(super) fn parse_archival(archival: &ConfigLine) -> Archival {
    Archival {
        configuration: child_block(archival, "configuration").map(|configuration| {
            let sites: Vec<&str> = statements(configuration, "archive-sites");
            ArchivalConfiguration {
                archive_sites: sites
                    .iter()
                    .filter_map(|site| site.split_whitespace().next())
                    .map(|url| redact_password(unquote(url)))
                    .collect(),
                archive_site_passwords: sites
                    .iter()
                    .filter(|site| site.split_whitespace().next().is_some())
                    .map(|site| url_statement_secret(site))
                    .collect(),
                transfer_interval: arg_of(configuration, "transfer-interval").map(str::to_string),
                transfer_on_commit: has_leaf(configuration, "transfer-on-commit"),
            }
        }),
        routing_instance: arg_of(archival, "routing-instance").map(str::to_string),
    }
}

/// The password of a `<url> [password <secret>]` statement: the option, else the one embedded in the URL.
pub(super) fn url_statement_secret(statement: &str) -> Option<Secret> {
    let words: Vec<&str> = statement.split_whitespace().collect();
    let url = unquote(words.first()?);
    let option = value_after(&words, "password");
    secret_value(option.as_deref().or_else(|| url_password(url)))
}

/// The password of a server written `<url> { password <secret>; }`: the option, else the one embedded in the URL.
pub(super) fn server_secret(server: &ConfigLine) -> Option<Secret> {
    secret_value(arg_of(server, "password")).or_else(|| url_statement_secret(&server.text))
}

/// The `password` of `scheme://user:password@host/path`.
fn url_password(url: &str) -> Option<&str> {
    let rest = url.split_once("://")?.1;
    let authority = &rest[..rest.find('/').unwrap_or(rest.len())];
    let userinfo = authority.rsplit_once('@')?.0;
    userinfo.split_once(':').map(|(_, password)| password)
}

/// Drops the `:password` from `scheme://user:password@host/path`.
pub(super) fn redact_password(url: &str) -> String {
    let Some((scheme, rest)) = url.split_once("://") else {
        return url.to_string();
    };
    let authority_end = rest.find('/').unwrap_or(rest.len());
    let (authority, path) = rest.split_at(authority_end);
    let Some((userinfo, host)) = authority.rsplit_once('@') else {
        return url.to_string();
    };
    let user = userinfo.split_once(':').map_or(userinfo, |(user, _)| user);
    format!("{scheme}://{user}@{host}{path}")
}

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

    // Not from documentation: written from the CLI Reference syntax page. See the README "Sources".
    const ARCHIVAL: &str = r#"
system {
    archival {
        configuration {
            transfer-interval 60;
            transfer-on-commit;
            archive-sites {
                "scp://backup@192.0.2.9/configs" password "$9$secret"; ## SECRET-DATA
                "ftp://svc:hunter2@192.0.2.10/configs" password "$9$other"; ## SECRET-DATA
                file:///var/tmp/archive;
            }
        }
        routing-instance mgmt_junos;
    }
}
"#;

    #[test]
    fn extracts_archival_settings() {
        let archival = system(&juniper::parse_braces(ARCHIVAL)).unwrap().archival.unwrap();
        assert_eq!(archival.routing_instance.as_deref(), Some("mgmt_junos"));
        let configuration = archival.configuration.unwrap();
        assert_eq!(configuration.transfer_interval.as_deref(), Some("60"));
        assert!(configuration.transfer_on_commit);
    }

    #[test]
    fn archive_site_passwords_prefer_the_option_over_the_url() {
        let archival = system(&juniper::parse_braces(ARCHIVAL)).unwrap().archival.unwrap();
        let configuration = archival.configuration.unwrap();
        let passwords: Vec<_> = configuration
            .archive_site_passwords
            .iter()
            .map(|p| p.as_ref().map(crate::Secret::expose))
            .collect();
        assert_eq!(
            passwords,
            [
                crate::secret::expected("$9$secret"),
                crate::secret::expected("$9$other"),
                None
            ]
        );
    }

    #[test]
    fn url_password_is_used_without_the_option() {
        let secret = super::url_statement_secret("\"ftp://svc:hunter2@192.0.2.10/configs\"");
        assert_eq!(
            secret.as_ref().map(crate::Secret::expose),
            crate::secret::expected("hunter2")
        );
        assert_eq!(super::url_statement_secret("scp://backup@192.0.2.9/configs"), None);
    }

    #[test]
    fn archive_sites_never_keep_passwords() {
        let archival = system(&juniper::parse_braces(ARCHIVAL)).unwrap().archival.unwrap();
        assert_eq!(
            archival.configuration.unwrap().archive_sites,
            [
                "scp://backup@192.0.2.9/configs",
                "ftp://svc@192.0.2.10/configs",
                "file:///var/tmp/archive",
            ]
        );
    }

    #[test]
    fn archival_without_configuration() {
        let archival = system(&juniper::parse_braces(
            "system {\n    archival {\n        routing-instance mgmt_junos;\n    }\n}\n",
        ))
        .unwrap()
        .archival
        .unwrap();
        assert!(archival.configuration.is_none());
    }

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