Skip to main content

asterust_junos/system/
archival.rs

1//! `archival`
2//! `system { archival { ... } }`.
3//!
4//! # See also
5//!
6//! - [archival](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/archival-edit-system.html)
7
8use crate::{arg_of, child_block, has_leaf, secret_value, statements, unquote, value_after, Secret};
9use asterust::config::ConfigLine;
10
11/// The `configuration` block of `system archival`.
12#[derive(Clone, Debug, PartialEq, Eq)]
13#[non_exhaustive]
14pub struct ArchivalConfiguration {
15    /// Archive site URLs, with any password embedded in the URL removed.
16    pub archive_sites: Vec<String>,
17    /// The password of each archive site, in the order of `archive_sites`: its `password` option, else the one embedded
18    /// in the URL. All `None` unless the `secrets` feature is enabled.
19    pub archive_site_passwords: Vec<Option<Secret>>,
20    /// Minutes between transfers.
21    pub transfer_interval: Option<String>,
22    pub transfer_on_commit: bool,
23}
24
25/// The `system archival` configuration.
26#[derive(Clone, Debug, PartialEq, Eq)]
27#[non_exhaustive]
28pub struct Archival {
29    pub configuration: Option<ArchivalConfiguration>,
30    pub routing_instance: Option<String>,
31}
32
33pub(super) fn parse_archival(archival: &ConfigLine) -> Archival {
34    Archival {
35        configuration: child_block(archival, "configuration").map(|configuration| {
36            let sites: Vec<&str> = statements(configuration, "archive-sites");
37            ArchivalConfiguration {
38                archive_sites: sites
39                    .iter()
40                    .filter_map(|site| site.split_whitespace().next())
41                    .map(|url| redact_password(unquote(url)))
42                    .collect(),
43                archive_site_passwords: sites
44                    .iter()
45                    .filter(|site| site.split_whitespace().next().is_some())
46                    .map(|site| url_statement_secret(site))
47                    .collect(),
48                transfer_interval: arg_of(configuration, "transfer-interval").map(str::to_string),
49                transfer_on_commit: has_leaf(configuration, "transfer-on-commit"),
50            }
51        }),
52        routing_instance: arg_of(archival, "routing-instance").map(str::to_string),
53    }
54}
55
56/// The password of a `<url> [password <secret>]` statement: the option, else the one embedded in the URL.
57pub(super) fn url_statement_secret(statement: &str) -> Option<Secret> {
58    let words: Vec<&str> = statement.split_whitespace().collect();
59    let url = unquote(words.first()?);
60    let option = value_after(&words, "password");
61    secret_value(option.as_deref().or_else(|| url_password(url)))
62}
63
64/// The password of a server written `<url> { password <secret>; }`: the option, else the one embedded in the URL.
65pub(super) fn server_secret(server: &ConfigLine) -> Option<Secret> {
66    secret_value(arg_of(server, "password")).or_else(|| url_statement_secret(&server.text))
67}
68
69/// The `password` of `scheme://user:password@host/path`.
70fn url_password(url: &str) -> Option<&str> {
71    let rest = url.split_once("://")?.1;
72    let authority = &rest[..rest.find('/').unwrap_or(rest.len())];
73    let userinfo = authority.rsplit_once('@')?.0;
74    userinfo.split_once(':').map(|(_, password)| password)
75}
76
77/// Drops the `:password` from `scheme://user:password@host/path`.
78pub(super) fn redact_password(url: &str) -> String {
79    let Some((scheme, rest)) = url.split_once("://") else {
80        return url.to_string();
81    };
82    let authority_end = rest.find('/').unwrap_or(rest.len());
83    let (authority, path) = rest.split_at(authority_end);
84    let Some((userinfo, host)) = authority.rsplit_once('@') else {
85        return url.to_string();
86    };
87    let user = userinfo.split_once(':').map_or(userinfo, |(user, _)| user);
88    format!("{scheme}://{user}@{host}{path}")
89}
90
91#[cfg(test)]
92mod tests {
93    use crate::system::system;
94    use asterust::config::juniper;
95
96    // Not from documentation: written from the CLI Reference syntax page. See the README "Sources".
97    const ARCHIVAL: &str = r#"
98system {
99    archival {
100        configuration {
101            transfer-interval 60;
102            transfer-on-commit;
103            archive-sites {
104                "scp://backup@192.0.2.9/configs" password "$9$secret"; ## SECRET-DATA
105                "ftp://svc:hunter2@192.0.2.10/configs" password "$9$other"; ## SECRET-DATA
106                file:///var/tmp/archive;
107            }
108        }
109        routing-instance mgmt_junos;
110    }
111}
112"#;
113
114    #[test]
115    fn extracts_archival_settings() {
116        let archival = system(&juniper::parse_braces(ARCHIVAL)).unwrap().archival.unwrap();
117        assert_eq!(archival.routing_instance.as_deref(), Some("mgmt_junos"));
118        let configuration = archival.configuration.unwrap();
119        assert_eq!(configuration.transfer_interval.as_deref(), Some("60"));
120        assert!(configuration.transfer_on_commit);
121    }
122
123    #[test]
124    fn archive_site_passwords_prefer_the_option_over_the_url() {
125        let archival = system(&juniper::parse_braces(ARCHIVAL)).unwrap().archival.unwrap();
126        let configuration = archival.configuration.unwrap();
127        let passwords: Vec<_> = configuration
128            .archive_site_passwords
129            .iter()
130            .map(|p| p.as_ref().map(crate::Secret::expose))
131            .collect();
132        assert_eq!(
133            passwords,
134            [
135                crate::secret::expected("$9$secret"),
136                crate::secret::expected("$9$other"),
137                None
138            ]
139        );
140    }
141
142    #[test]
143    fn url_password_is_used_without_the_option() {
144        let secret = super::url_statement_secret("\"ftp://svc:hunter2@192.0.2.10/configs\"");
145        assert_eq!(
146            secret.as_ref().map(crate::Secret::expose),
147            crate::secret::expected("hunter2")
148        );
149        assert_eq!(super::url_statement_secret("scp://backup@192.0.2.9/configs"), None);
150    }
151
152    #[test]
153    fn archive_sites_never_keep_passwords() {
154        let archival = system(&juniper::parse_braces(ARCHIVAL)).unwrap().archival.unwrap();
155        assert_eq!(
156            archival.configuration.unwrap().archive_sites,
157            [
158                "scp://backup@192.0.2.9/configs",
159                "ftp://svc@192.0.2.10/configs",
160                "file:///var/tmp/archive",
161            ]
162        );
163    }
164
165    #[test]
166    fn archival_without_configuration() {
167        let archival = system(&juniper::parse_braces(
168            "system {\n    archival {\n        routing-instance mgmt_junos;\n    }\n}\n",
169        ))
170        .unwrap()
171        .archival
172        .unwrap();
173        assert!(archival.configuration.is_none());
174    }
175
176    #[test]
177    fn no_archival_is_none() {
178        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
179        assert!(system.archival.is_none());
180    }
181}