Skip to main content

asterust_junos/
system.rs

1//! `system { ... }`.
2
3use crate::{
4    active_children, arg_of, args_of, child_block, first_word, has_leaf, list_values, named_children, split_name,
5    top_level, unquote,
6};
7use asterust::config::{Config, ConfigLine};
8
9/// A DNS server from `name-server`.
10#[derive(Clone, Debug, PartialEq, Eq)]
11#[non_exhaustive]
12pub struct NameServer {
13    pub address: String,
14    /// Set when the server is reached through a routing instance such as `mgmt_junos`.
15    pub routing_instance: Option<String>,
16}
17
18/// A `server` or `peer` entry under `ntp`.
19#[derive(Clone, Debug, PartialEq, Eq)]
20#[non_exhaustive]
21pub struct NtpHost {
22    /// Address or hostname.
23    pub address: String,
24    /// Authentication key number.
25    pub key: Option<String>,
26    pub prefer: bool,
27    pub version: Option<String>,
28    pub routing_instance: Option<String>,
29}
30
31/// An `authentication-key`. The key value is not extracted.
32#[derive(Clone, Debug, PartialEq, Eq)]
33#[non_exhaustive]
34pub struct NtpAuthenticationKey {
35    pub number: String,
36    /// `md5`, `sha1` or `sha256`.
37    pub key_type: Option<String>,
38}
39
40/// The `system ntp` configuration.
41#[derive(Clone, Debug, PartialEq, Eq)]
42#[non_exhaustive]
43pub struct Ntp {
44    pub boot_server: Option<String>,
45    pub servers: Vec<NtpHost>,
46    pub peers: Vec<NtpHost>,
47    pub source_address: Option<String>,
48    pub trusted_keys: Vec<String>,
49    pub authentication_keys: Vec<NtpAuthenticationKey>,
50    pub broadcast_client: bool,
51}
52
53/// A `<facility> <severity>` line selecting which messages go to a syslog destination.
54#[derive(Clone, Debug, PartialEq, Eq)]
55#[non_exhaustive]
56pub struct SyslogRule {
57    /// e.g. `"any"`, `"authorization"`, `"interactive-commands"`.
58    pub facility: String,
59    /// e.g. `"info"`, `"notice"`, `"any"`, `"none"`.
60    pub severity: String,
61}
62
63/// A `host <address>` destination.
64#[derive(Clone, Debug, PartialEq, Eq)]
65#[non_exhaustive]
66pub struct SyslogHost {
67    /// Address, hostname, or `other-routing-engine`.
68    pub address: String,
69    pub rules: Vec<SyslogRule>,
70    pub port: Option<String>,
71    pub source_address: Option<String>,
72    pub routing_instance: Option<String>,
73    pub facility_override: Option<String>,
74    pub log_prefix: Option<String>,
75}
76
77/// A syslog `archive` statement. `archive-sites`, `start-time` and `transfer-interval` are not extracted.
78#[derive(Clone, Debug, Default, PartialEq, Eq)]
79#[non_exhaustive]
80pub struct SyslogArchive {
81    /// Maximum number of archived files.
82    pub files: Option<String>,
83    /// Maximum file size, e.g. `"1m"`.
84    pub size: Option<String>,
85    /// `Some(true)` for `world-readable`, `Some(false)` for `no-world-readable`.
86    pub world_readable: Option<bool>,
87}
88
89/// A `file <name>` or `user <name>` destination.
90#[derive(Clone, Debug, PartialEq, Eq)]
91#[non_exhaustive]
92pub struct SyslogTarget {
93    /// File name, or user name (`*` for all users).
94    pub name: String,
95    pub rules: Vec<SyslogRule>,
96    /// Only files have an archive.
97    pub archive: Option<SyslogArchive>,
98}
99
100/// The `system syslog` configuration.
101#[derive(Clone, Debug, PartialEq, Eq)]
102#[non_exhaustive]
103pub struct Syslog {
104    pub hosts: Vec<SyslogHost>,
105    pub files: Vec<SyslogTarget>,
106    pub users: Vec<SyslogTarget>,
107    pub console: Vec<SyslogRule>,
108    pub source_address: Option<String>,
109    /// e.g. `"year millisecond"`.
110    pub time_format: Option<String>,
111    /// The default archive settings that files inherit.
112    pub archive: Option<SyslogArchive>,
113}
114
115/// A login `class`.
116#[derive(Clone, Debug, PartialEq, Eq)]
117#[non_exhaustive]
118pub struct LoginClass {
119    pub name: String,
120    pub permissions: Vec<String>,
121    /// Minutes.
122    pub idle_timeout: Option<String>,
123    /// The regular expressions as written, e.g. `"(show)|(ping)"`.
124    pub allow_commands: Option<String>,
125    pub deny_commands: Option<String>,
126    pub allow_configuration: Option<String>,
127    pub deny_configuration: Option<String>,
128}
129
130/// A login `user`. Passwords and keys are not extracted, only which authentication methods are present.
131#[derive(Clone, Debug, PartialEq, Eq)]
132#[non_exhaustive]
133pub struct LoginUser {
134    pub name: String,
135    pub class: Option<String>,
136    pub uid: Option<String>,
137    pub full_name: Option<String>,
138    /// One entry per authentication statement, e.g. `"encrypted-password"`, `"ssh-rsa"`.
139    pub authentication_methods: Vec<String>,
140}
141
142/// The `system login` configuration.
143#[derive(Clone, Debug, PartialEq, Eq)]
144#[non_exhaustive]
145pub struct Login {
146    /// The banner shown before login.
147    pub message: Option<String>,
148    /// The text shown after login.
149    pub announcement: Option<String>,
150    pub classes: Vec<LoginClass>,
151    pub users: Vec<LoginUser>,
152}
153
154/// The `system services ssh` settings; every field is `None` or empty when only `ssh;` is written.
155#[derive(Clone, Debug, Default, PartialEq, Eq)]
156#[non_exhaustive]
157pub struct SshService {
158    /// `allow`, `deny` or `deny-password`.
159    pub root_login: Option<String>,
160    pub protocol_versions: Vec<String>,
161    pub port: Option<String>,
162    pub connection_limit: Option<String>,
163    pub rate_limit: Option<String>,
164    pub ciphers: Vec<String>,
165    pub sftp_server: bool,
166}
167
168/// An `address` of an outbound-ssh client.
169#[derive(Clone, Debug, PartialEq, Eq)]
170#[non_exhaustive]
171pub struct OutboundSshServer {
172    pub address: String,
173    pub port: Option<String>,
174    pub retry: Option<String>,
175    pub timeout: Option<String>,
176}
177
178/// An `outbound-ssh client <id>`. The `secret` is not extracted.
179#[derive(Clone, Debug, PartialEq, Eq)]
180#[non_exhaustive]
181pub struct OutboundSshClient {
182    pub id: String,
183    pub device_id: Option<String>,
184    pub servers: Vec<OutboundSshServer>,
185    /// e.g. `"netconf"`.
186    pub services: Vec<String>,
187    /// `in-order` or `sticky`.
188    pub reconnect_strategy: Option<String>,
189    pub routing_instance: Option<String>,
190}
191
192/// The `system services` configuration. Services other than those listed are not extracted.
193#[derive(Clone, Debug, PartialEq, Eq)]
194#[non_exhaustive]
195pub struct Services {
196    pub ssh: Option<SshService>,
197    pub telnet: bool,
198    pub ftp: bool,
199    /// `netconf { ssh; }`.
200    pub netconf_ssh: bool,
201    /// `web-management { http; }`.
202    pub http: bool,
203    /// `web-management { https; }`.
204    pub https: bool,
205    pub outbound_ssh: Vec<OutboundSshClient>,
206}
207
208/// The `system root-authentication` methods. Passwords and keys are not extracted.
209#[derive(Clone, Debug, PartialEq, Eq)]
210#[non_exhaustive]
211pub struct RootAuthentication {
212    /// One entry per statement, e.g. `"encrypted-password"`, `"ssh-rsa"`, `"no-public-keys"`.
213    pub methods: Vec<String>,
214}
215
216/// A `static-host-mapping <hostname>` entry.
217#[derive(Clone, Debug, PartialEq, Eq)]
218#[non_exhaustive]
219pub struct StaticHostMapping {
220    pub hostname: String,
221    pub aliases: Vec<String>,
222    pub inet: Vec<String>,
223    pub inet6: Vec<String>,
224    /// The ISO system identifier, e.g. `0100.2550.0001`.
225    pub sysid: Option<String>,
226}
227
228/// A `backup-router` or `inet6-backup-router`.
229#[derive(Clone, Debug, PartialEq, Eq)]
230#[non_exhaustive]
231pub struct BackupRouter {
232    pub address: String,
233    /// Empty when the router is reachable for all destinations.
234    pub destinations: Vec<String>,
235}
236
237/// A `radius-server <address>`. The `secret` is not extracted.
238#[derive(Clone, Debug, PartialEq, Eq)]
239#[non_exhaustive]
240pub struct RadiusServer {
241    pub address: String,
242    pub port: Option<String>,
243    pub accounting_port: Option<String>,
244    pub retry: Option<String>,
245    pub timeout: Option<String>,
246    pub source_address: Option<String>,
247    pub routing_instance: Option<String>,
248}
249
250/// A `tacplus-server <address>`. The `secret` is not extracted.
251#[derive(Clone, Debug, PartialEq, Eq)]
252#[non_exhaustive]
253pub struct TacplusServer {
254    pub address: String,
255    pub port: Option<String>,
256    pub timeout: Option<String>,
257    pub source_address: Option<String>,
258    pub routing_instance: Option<String>,
259    pub single_connection: bool,
260}
261
262/// A `system location` block. The Bellcore coordinates (`hcoord`, `vcoord`, `lata`, `npa-nxx`) are not extracted.
263#[derive(Clone, Debug, PartialEq, Eq)]
264#[non_exhaustive]
265pub struct Location {
266    pub building: Option<String>,
267    pub floor: Option<String>,
268    pub rack: Option<String>,
269    pub country_code: Option<String>,
270    pub postal_code: Option<String>,
271    pub latitude: Option<String>,
272    pub longitude: Option<String>,
273    /// Feet above sea level.
274    pub altitude: Option<String>,
275}
276
277/// A `system ports console` or `auxiliary` block.
278#[derive(Clone, Debug, PartialEq, Eq)]
279#[non_exhaustive]
280pub struct SerialPort {
281    pub disable: bool,
282    pub insecure: bool,
283    pub log_out_on_disconnect: bool,
284    /// From `type`, e.g. `vt100`.
285    pub terminal_type: Option<String>,
286    /// `mini-usb` or `rj45`; only on the auxiliary port.
287    pub port_type: Option<String>,
288}
289
290/// The `system ports` configuration.
291#[derive(Clone, Debug, PartialEq, Eq)]
292#[non_exhaustive]
293pub struct Ports {
294    pub console: Option<SerialPort>,
295    pub auxiliary: Option<SerialPort>,
296}
297
298/// The top-level `system` configuration.
299#[derive(Clone, Debug, PartialEq, Eq)]
300#[non_exhaustive]
301pub struct System {
302    pub host_name: Option<String>,
303    pub domain_name: Option<String>,
304    /// e.g. `"UTC"` or `"America/New_York"`.
305    pub time_zone: Option<String>,
306    pub domain_search: Vec<String>,
307    pub static_host_mappings: Vec<StaticHostMapping>,
308    pub backup_router: Option<BackupRouter>,
309    pub inet6_backup_router: Option<BackupRouter>,
310    /// Methods in the order tried: `password`, `radius`, `tacplus`.
311    pub authentication_order: Vec<String>,
312    pub radius_servers: Vec<RadiusServer>,
313    pub tacplus_servers: Vec<TacplusServer>,
314    pub location: Option<Location>,
315    pub ports: Option<Ports>,
316    pub max_configurations_on_flash: Option<String>,
317    pub max_configuration_rollbacks: Option<String>,
318    pub no_redirects: bool,
319    pub root_authentication: Option<RootAuthentication>,
320    pub name_servers: Vec<NameServer>,
321    pub ntp: Option<Ntp>,
322    pub syslog: Option<Syslog>,
323    pub login: Option<Login>,
324    pub services: Option<Services>,
325}
326
327/// The top-level `system` block, or `None` if there is none.
328pub fn system(config: &Config) -> Option<System> {
329    let system = top_level(config, "system")?;
330    Some(System {
331        host_name: arg_of(system, "host-name").map(str::to_string),
332        domain_name: arg_of(system, "domain-name").map(str::to_string),
333        time_zone: arg_of(system, "time-zone").map(str::to_string),
334        domain_search: args_of(system, "domain-search")
335            .into_iter()
336            .flat_map(list_values)
337            .collect(),
338        static_host_mappings: child_block(system, "static-host-mapping")
339            .map(|mappings| active_children(mappings).map(parse_static_host_mapping).collect())
340            .unwrap_or_default(),
341        backup_router: arg_of(system, "backup-router").map(parse_backup_router),
342        inet6_backup_router: arg_of(system, "inet6-backup-router").map(parse_backup_router),
343        authentication_order: args_of(system, "authentication-order")
344            .into_iter()
345            .flat_map(list_values)
346            .collect(),
347        radius_servers: servers(system, "radius-server")
348            .into_iter()
349            .map(|(address, server)| RadiusServer {
350                address: address.to_string(),
351                port: arg_of(server, "port").map(str::to_string),
352                accounting_port: arg_of(server, "accounting-port").map(str::to_string),
353                retry: arg_of(server, "retry").map(str::to_string),
354                timeout: arg_of(server, "timeout").map(str::to_string),
355                source_address: arg_of(server, "source-address").map(str::to_string),
356                routing_instance: arg_of(server, "routing-instance").map(str::to_string),
357            })
358            .collect(),
359        tacplus_servers: servers(system, "tacplus-server")
360            .into_iter()
361            .map(|(address, server)| TacplusServer {
362                address: address.to_string(),
363                port: arg_of(server, "port").map(str::to_string),
364                timeout: arg_of(server, "timeout").map(str::to_string),
365                source_address: arg_of(server, "source-address").map(str::to_string),
366                routing_instance: arg_of(server, "routing-instance").map(str::to_string),
367                single_connection: has_leaf(server, "single-connection"),
368            })
369            .collect(),
370        location: child_block(system, "location").map(parse_location),
371        ports: child_block(system, "ports").map(|ports| Ports {
372            console: child_block(ports, "console").map(parse_serial_port),
373            auxiliary: child_block(ports, "auxiliary").map(parse_serial_port),
374        }),
375        max_configurations_on_flash: arg_of(system, "max-configurations-on-flash").map(str::to_string),
376        max_configuration_rollbacks: arg_of(system, "max-configuration-rollbacks").map(str::to_string),
377        no_redirects: has_leaf(system, "no-redirects"),
378        root_authentication: child_block(system, "root-authentication").map(|auth| RootAuthentication {
379            methods: authentication_methods(auth),
380        }),
381        name_servers: name_servers(system),
382        ntp: child_block(system, "ntp").map(parse_ntp),
383        syslog: child_block(system, "syslog").map(parse_syslog),
384        login: child_block(system, "login").map(parse_login),
385        services: child_block(system, "services").map(parse_services),
386    })
387}
388
389fn parse_location(location: &ConfigLine) -> Location {
390    let field = |keyword: &str| arg_of(location, keyword).map(str::to_string);
391    Location {
392        building: field("building"),
393        floor: field("floor"),
394        rack: field("rack"),
395        country_code: field("country-code"),
396        postal_code: field("postal-code"),
397        latitude: field("latitude"),
398        longitude: field("longitude"),
399        altitude: field("altitude"),
400    }
401}
402
403fn parse_serial_port(port: &ConfigLine) -> SerialPort {
404    SerialPort {
405        disable: has_leaf(port, "disable"),
406        insecure: has_leaf(port, "insecure"),
407        log_out_on_disconnect: has_leaf(port, "log-out-on-disconnect"),
408        terminal_type: arg_of(port, "type").map(str::to_string),
409        port_type: arg_of(port, "port-type").map(str::to_string),
410    }
411}
412
413/// Servers written as `<keyword> <address> { ... }`, or as `<keyword> { <address> { ... } }`, with their option lines.
414fn servers<'a>(system: &'a ConfigLine, keyword: &str) -> Vec<(&'a str, &'a ConfigLine)> {
415    let mut found = Vec::new();
416    for child in active_children(system) {
417        if child.text == keyword {
418            found.extend(active_children(child).map(|server| (unquote(&server.text), server)));
419        } else if let Some(arg) = child.arg(keyword) {
420            found.push((split_name(arg).0, child));
421        }
422    }
423    found
424}
425
426fn parse_static_host_mapping(mapping: &ConfigLine) -> StaticHostMapping {
427    let list = |keyword: &str| args_of(mapping, keyword).into_iter().flat_map(list_values).collect();
428    StaticHostMapping {
429        hostname: unquote(&mapping.text).to_string(),
430        aliases: list("alias"),
431        inet: list("inet"),
432        inet6: list("inet6"),
433        sysid: arg_of(mapping, "sysid").map(str::to_string),
434    }
435}
436
437/// `<address> [destination <prefix | [ prefixes ]>]`.
438fn parse_backup_router(arg: &str) -> BackupRouter {
439    let (address, rest) = split_name(arg);
440    BackupRouter {
441        address: address.to_string(),
442        destinations: rest.strip_prefix("destination").map(list_values).unwrap_or_default(),
443    }
444}
445
446fn parse_services(services: &ConfigLine) -> Services {
447    let web = child_block(services, "web-management");
448    let netconf = child_block(services, "netconf");
449    Services {
450        ssh: child_block(services, "ssh").map(parse_ssh),
451        telnet: child_block(services, "telnet").is_some(),
452        ftp: child_block(services, "ftp").is_some(),
453        netconf_ssh: netconf.is_some_and(|n| child_block(n, "ssh").is_some()),
454        http: web.is_some_and(|w| child_block(w, "http").is_some()),
455        https: web.is_some_and(|w| child_block(w, "https").is_some()),
456        outbound_ssh: child_block(services, "outbound-ssh")
457            .map(|outbound| {
458                named_children(outbound, "client")
459                    .map(|(id, client)| parse_outbound_client(id, client))
460                    .collect()
461            })
462            .unwrap_or_default(),
463    }
464}
465
466fn parse_outbound_client(id: &str, client: &ConfigLine) -> OutboundSshClient {
467    OutboundSshClient {
468        id: id.to_string(),
469        device_id: arg_of(client, "device-id").map(str::to_string),
470        servers: active_children(client)
471            // Servers are the children written as a bare address; the single-word blocks are other options.
472            .filter(|c| !c.text.contains(' ') && !matches!(c.text.as_str(), "keep-alive" | "proxy-server"))
473            .map(|server| OutboundSshServer {
474                address: server.text.clone(),
475                port: arg_of(server, "port").map(str::to_string),
476                retry: arg_of(server, "retry").map(str::to_string),
477                timeout: arg_of(server, "timeout").map(str::to_string),
478            })
479            .collect(),
480        services: args_of(client, "services").into_iter().flat_map(list_values).collect(),
481        reconnect_strategy: arg_of(client, "reconnect-strategy").map(str::to_string),
482        routing_instance: arg_of(client, "routing-instance").map(str::to_string),
483    }
484}
485
486fn parse_ssh(ssh: &ConfigLine) -> SshService {
487    let list = |keyword: &str| args_of(ssh, keyword).into_iter().flat_map(list_values).collect();
488    SshService {
489        root_login: arg_of(ssh, "root-login").map(str::to_string),
490        protocol_versions: list("protocol-version"),
491        port: arg_of(ssh, "port").map(str::to_string),
492        connection_limit: arg_of(ssh, "connection-limit").map(str::to_string),
493        rate_limit: arg_of(ssh, "rate-limit").map(str::to_string),
494        ciphers: list("ciphers"),
495        sftp_server: has_leaf(ssh, "sftp-server"),
496    }
497}
498
499/// The name of each statement in an `authentication` block. Secrets can carry a trailing `## SECRET-DATA` marker,
500/// so only the first word is kept.
501fn authentication_methods(auth: &ConfigLine) -> Vec<String> {
502    active_children(auth)
503        .filter_map(|c| c.text.split_whitespace().next())
504        .map(str::to_string)
505        .collect()
506}
507
508fn parse_login(login: &ConfigLine) -> Login {
509    Login {
510        message: arg_of(login, "message").map(str::to_string),
511        announcement: arg_of(login, "announcement").map(str::to_string),
512        classes: named_children(login, "class")
513            .map(|(name, class)| LoginClass {
514                name: name.to_string(),
515                permissions: args_of(class, "permissions")
516                    .into_iter()
517                    .flat_map(list_values)
518                    .collect(),
519                idle_timeout: arg_of(class, "idle-timeout").map(str::to_string),
520                allow_commands: arg_of(class, "allow-commands").map(str::to_string),
521                deny_commands: arg_of(class, "deny-commands").map(str::to_string),
522                allow_configuration: arg_of(class, "allow-configuration").map(str::to_string),
523                deny_configuration: arg_of(class, "deny-configuration").map(str::to_string),
524            })
525            .collect(),
526        users: named_children(login, "user")
527            .map(|(name, user)| LoginUser {
528                name: name.to_string(),
529                class: arg_of(user, "class").map(str::to_string),
530                uid: arg_of(user, "uid").map(str::to_string),
531                full_name: arg_of(user, "full-name").map(str::to_string),
532                authentication_methods: child_block(user, "authentication")
533                    .map(authentication_methods)
534                    .unwrap_or_default(),
535            })
536            .collect(),
537    }
538}
539
540fn parse_syslog(syslog: &ConfigLine) -> Syslog {
541    Syslog {
542        hosts: named_children(syslog, "host")
543            .map(|(address, host)| SyslogHost {
544                address: address.to_string(),
545                rules: syslog_rules(host),
546                port: arg_of(host, "port").map(str::to_string),
547                source_address: arg_of(host, "source-address").map(str::to_string),
548                routing_instance: arg_of(host, "routing-instance").map(str::to_string),
549                facility_override: arg_of(host, "facility-override").map(str::to_string),
550                log_prefix: arg_of(host, "log-prefix").map(str::to_string),
551            })
552            .collect(),
553        files: syslog_targets(syslog, "file"),
554        users: syslog_targets(syslog, "user"),
555        console: child_block(syslog, "console").map(syslog_rules).unwrap_or_default(),
556        source_address: arg_of(syslog, "source-address").map(str::to_string),
557        time_format: arg_of(syslog, "time-format").map(str::to_string),
558        archive: syslog_archive(syslog),
559    }
560}
561
562fn syslog_targets(syslog: &ConfigLine, keyword: &str) -> Vec<SyslogTarget> {
563    named_children(syslog, keyword)
564        .map(|(name, target)| SyslogTarget {
565            name: name.to_string(),
566            rules: syslog_rules(target),
567            archive: syslog_archive(target),
568        })
569        .collect()
570}
571
572/// An `archive` written as a block or on one line (`archive size 1m files 5 world-readable;`).
573fn syslog_archive(parent: &ConfigLine) -> Option<SyslogArchive> {
574    let archive = active_children(parent).find(|c| c.text == "archive" || c.arg("archive").is_some())?;
575    // Both forms reduce to one stream of words: the options on the line itself, then one statement per child.
576    let mut words = archive
577        .text
578        .split_whitespace()
579        .skip(1)
580        .chain(active_children(archive).flat_map(|c| c.text.split_whitespace()));
581    let mut settings = SyslogArchive::default();
582    while let Some(word) = words.next() {
583        match word {
584            "files" => settings.files = words.next().map(str::to_string),
585            "size" => settings.size = words.next().map(str::to_string),
586            "world-readable" => settings.world_readable = Some(true),
587            "no-world-readable" => settings.world_readable = Some(false),
588            _ => {}
589        }
590    }
591    Some(settings)
592}
593
594/// Children written `<facility> <severity>`, which tells them apart from options such as `port 514`.
595fn syslog_rules(destination: &ConfigLine) -> Vec<SyslogRule> {
596    const SEVERITIES: [&str; 10] = [
597        "any",
598        "none",
599        "emergency",
600        "alert",
601        "critical",
602        "error",
603        "warning",
604        "notice",
605        "info",
606        "debug",
607    ];
608    active_children(destination)
609        .filter_map(|c| {
610            let (facility, severity) = c.text.split_once(' ')?;
611            SEVERITIES.contains(&severity).then(|| SyslogRule {
612                facility: facility.to_string(),
613                severity: severity.to_string(),
614            })
615        })
616        .collect()
617}
618
619fn parse_ntp(ntp: &ConfigLine) -> Ntp {
620    let hosts = |keyword: &str| -> Vec<NtpHost> {
621        active_children(ntp)
622            .filter_map(|c| Some(ntp_host(c.arg(keyword)?, c)))
623            .collect()
624    };
625    Ntp {
626        boot_server: arg_of(ntp, "boot-server").map(str::to_string),
627        servers: hosts("server"),
628        peers: hosts("peer"),
629        source_address: arg_of(ntp, "source-address").and_then(first_word).map(str::to_string),
630        trusted_keys: args_of(ntp, "trusted-key").into_iter().flat_map(list_values).collect(),
631        authentication_keys: args_of(ntp, "authentication-key")
632            .into_iter()
633            .filter_map(ntp_authentication_key)
634            .collect(),
635        broadcast_client: has_leaf(ntp, "broadcast-client"),
636    }
637}
638
639/// A host written `<address> [key n] [prefer] [version n] [routing-instance x]`, with the options on the line
640/// or in a block.
641fn ntp_host(arg: &str, line: &ConfigLine) -> NtpHost {
642    let (address, options) = split_name(arg);
643    let mut words = options.split_whitespace();
644    let mut host = NtpHost {
645        address: address.to_string(),
646        key: arg_of(line, "key").map(str::to_string),
647        prefer: has_leaf(line, "prefer"),
648        version: arg_of(line, "version").map(str::to_string),
649        routing_instance: arg_of(line, "routing-instance").map(str::to_string),
650    };
651    while let Some(word) = words.next() {
652        match word {
653            "prefer" => host.prefer = true,
654            "key" => host.key = words.next().map(str::to_string),
655            "version" => host.version = words.next().map(str::to_string),
656            "routing-instance" => host.routing_instance = words.next().map(str::to_string),
657            _ => {}
658        }
659    }
660    host
661}
662
663/// `<number> type <type> value <secret>`; the secret is dropped.
664fn ntp_authentication_key(arg: &str) -> Option<NtpAuthenticationKey> {
665    let mut words = arg.split_whitespace();
666    let number = words.next()?.to_string();
667    let key_type = words.skip_while(|w| *w != "type").nth(1).map(str::to_string);
668    Some(NtpAuthenticationKey { number, key_type })
669}
670
671/// Servers written as a `name-server { <address>; ... }` block, or one per `name-server <address>` line.
672fn name_servers(system: &ConfigLine) -> Vec<NameServer> {
673    let mut found = Vec::new();
674    for child in active_children(system) {
675        if child.text == "name-server" {
676            found.extend(active_children(child).map(|server| name_server(&server.text, server)));
677        } else if let Some(address) = child.arg("name-server") {
678            found.push(name_server(address, child));
679        }
680    }
681    found
682}
683
684fn name_server(address: &str, line: &ConfigLine) -> NameServer {
685    NameServer {
686        address: unquote(address).to_string(),
687        routing_instance: arg_of(line, "routing-instance").map(str::to_string),
688    }
689}
690
691#[cfg(test)]
692mod tests {
693    use super::*;
694    use asterust::config::juniper;
695
696    // Not from documentation: written from the CLI Reference syntax pages. See the README "Sources".
697    #[test]
698    fn extracts_host_name() {
699        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
700        assert_eq!(system.host_name.as_deref(), Some("pe1"));
701    }
702
703    #[test]
704    fn host_name_is_optional() {
705        let system = system(&juniper::parse_braces("system {\n    domain-name example.net;\n}\n")).unwrap();
706        assert_eq!(system.host_name, None);
707    }
708
709    #[test]
710    fn skips_inactive_host_name() {
711        let system = system(&juniper::parse_braces("system {\n    inactive: host-name pe1;\n}\n")).unwrap();
712        assert_eq!(system.host_name, None);
713    }
714
715    #[test]
716    fn extracts_name_server_block() {
717        let system = system(&juniper::parse_braces(
718            "system {\n    name-server {\n        192.0.2.53;\n        2001:db8::53;\n    }\n}\n",
719        ))
720        .unwrap();
721        let addresses: Vec<_> = system.name_servers.iter().map(|s| s.address.as_str()).collect();
722        assert_eq!(addresses, ["192.0.2.53", "2001:db8::53"]);
723        assert_eq!(system.name_servers[0].routing_instance, None);
724    }
725
726    #[test]
727    fn name_server_in_management_instance() {
728        let system = system(&juniper::parse_braces(
729            "system {\n    name-server {\n        192.0.2.53 {\n            routing-instance mgmt_junos;\n        }\n    }\n}\n",
730        ))
731        .unwrap();
732        assert_eq!(system.name_servers[0].address, "192.0.2.53");
733        assert_eq!(system.name_servers[0].routing_instance.as_deref(), Some("mgmt_junos"));
734    }
735
736    #[test]
737    fn extracts_one_line_name_servers_and_skips_inactive() {
738        let system = system(&juniper::parse_braces(
739            "system {\n    name-server 192.0.2.53;\n    name-server 192.0.2.54;\n    inactive: name-server 192.0.2.55;\n}\n",
740        ))
741        .unwrap();
742        let addresses: Vec<_> = system.name_servers.iter().map(|s| s.address.as_str()).collect();
743        assert_eq!(addresses, ["192.0.2.53", "192.0.2.54"]);
744    }
745
746    const NTP: &str = r#"
747system {
748    ntp {
749        boot-server 192.0.2.10;
750        source-address 192.0.2.1;
751        authentication-key 1 type md5 value "$9$secret";
752        authentication-key 2 type sha256 value "$9$other";
753        trusted-key [ 1 2 ];
754        server 192.0.2.10 key 1 prefer version 4;
755        server 192.0.2.11;
756        server ntp.example.net {
757            key 2;
758            prefer;
759            version 3;
760            routing-instance mgmt_junos;
761        }
762        inactive: server 192.0.2.12;
763        peer 192.0.2.20 key 1;
764        broadcast-client;
765    }
766}
767"#;
768
769    #[test]
770    fn extracts_ntp_servers_in_line_and_block_form() {
771        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
772        let addresses: Vec<_> = ntp.servers.iter().map(|s| s.address.as_str()).collect();
773        assert_eq!(addresses, ["192.0.2.10", "192.0.2.11", "ntp.example.net"]);
774
775        let line = &ntp.servers[0];
776        assert_eq!(line.key.as_deref(), Some("1"));
777        assert!(line.prefer);
778        assert_eq!(line.version.as_deref(), Some("4"));
779
780        assert_eq!(ntp.servers[1].key, None);
781        assert!(!ntp.servers[1].prefer);
782
783        let block = &ntp.servers[2];
784        assert_eq!(block.key.as_deref(), Some("2"));
785        assert!(block.prefer);
786        assert_eq!(block.version.as_deref(), Some("3"));
787        assert_eq!(block.routing_instance.as_deref(), Some("mgmt_junos"));
788    }
789
790    #[test]
791    fn extracts_ntp_peers_keys_and_global_settings() {
792        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
793        assert_eq!(ntp.peers.len(), 1);
794        assert_eq!(ntp.peers[0].address, "192.0.2.20");
795        assert_eq!(ntp.peers[0].key.as_deref(), Some("1"));
796        assert_eq!(ntp.boot_server.as_deref(), Some("192.0.2.10"));
797        assert_eq!(ntp.source_address.as_deref(), Some("192.0.2.1"));
798        assert_eq!(ntp.trusted_keys, ["1", "2"]);
799        assert!(ntp.broadcast_client);
800    }
801
802    #[test]
803    fn ntp_authentication_keys_omit_the_secret() {
804        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
805        assert_eq!(ntp.authentication_keys.len(), 2);
806        assert_eq!(ntp.authentication_keys[0].number, "1");
807        assert_eq!(ntp.authentication_keys[0].key_type.as_deref(), Some("md5"));
808        assert_eq!(ntp.authentication_keys[1].key_type.as_deref(), Some("sha256"));
809    }
810
811    #[test]
812    fn no_ntp_is_none() {
813        assert!(system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n"))
814            .unwrap()
815            .ntp
816            .is_none());
817    }
818
819    const SYSLOG: &str = r#"
820system {
821    syslog {
822        user * {
823            any emergency;
824        }
825        host 192.0.2.5 {
826            any notice;
827            authorization info;
828            port 514;
829            source-address 192.0.2.1;
830            routing-instance mgmt_junos;
831            facility-override local3;
832            log-prefix pe1;
833        }
834        host other-routing-engine {
835            any critical;
836        }
837        file messages {
838            any notice;
839            authorization info;
840            explicit-priority;
841        }
842        file interactive-commands {
843            interactive-commands any;
844        }
845        inactive: file debug {
846            any debug;
847        }
848        console {
849            any critical;
850        }
851        source-address 192.0.2.1;
852        time-format year millisecond;
853    }
854}
855"#;
856
857    #[test]
858    fn extracts_syslog_hosts() {
859        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
860        let addresses: Vec<_> = syslog.hosts.iter().map(|h| h.address.as_str()).collect();
861        assert_eq!(addresses, ["192.0.2.5", "other-routing-engine"]);
862
863        let host = &syslog.hosts[0];
864        assert_eq!(host.rules.len(), 2);
865        assert_eq!(host.rules[1].facility, "authorization");
866        assert_eq!(host.rules[1].severity, "info");
867        assert_eq!(host.port.as_deref(), Some("514"));
868        assert_eq!(host.source_address.as_deref(), Some("192.0.2.1"));
869        assert_eq!(host.routing_instance.as_deref(), Some("mgmt_junos"));
870        assert_eq!(host.facility_override.as_deref(), Some("local3"));
871        assert_eq!(host.log_prefix.as_deref(), Some("pe1"));
872    }
873
874    #[test]
875    fn extracts_syslog_files_users_and_console() {
876        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
877
878        let files: Vec<_> = syslog.files.iter().map(|f| f.name.as_str()).collect();
879        assert_eq!(files, ["messages", "interactive-commands"]);
880        // `explicit-priority` is an option, not a facility/severity rule.
881        assert_eq!(syslog.files[0].rules.len(), 2);
882        assert_eq!(syslog.files[1].rules[0].facility, "interactive-commands");
883        assert_eq!(syslog.files[1].rules[0].severity, "any");
884
885        assert_eq!(syslog.users[0].name, "*");
886        assert_eq!(syslog.users[0].rules[0].severity, "emergency");
887        assert_eq!(syslog.console[0].facility, "any");
888        assert_eq!(syslog.console[0].severity, "critical");
889    }
890
891    #[test]
892    fn extracts_syslog_global_settings() {
893        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
894        assert_eq!(syslog.source_address.as_deref(), Some("192.0.2.1"));
895        assert_eq!(syslog.time_format.as_deref(), Some("year millisecond"));
896    }
897
898    #[test]
899    fn extracts_syslog_archive_in_line_and_block_form() {
900        let syslog = system(&juniper::parse_braces(
901            r#"
902system {
903    syslog {
904        archive {
905            files 20;
906            size 5m;
907            world-readable;
908        }
909        file messages {
910            any notice;
911            archive size 100k files 10 no-world-readable;
912        }
913        file plain {
914            any info;
915        }
916    }
917}
918"#,
919        ))
920        .unwrap()
921        .syslog
922        .unwrap();
923
924        let default = syslog.archive.unwrap();
925        assert_eq!(default.files.as_deref(), Some("20"));
926        assert_eq!(default.size.as_deref(), Some("5m"));
927        assert_eq!(default.world_readable, Some(true));
928
929        let messages = syslog.files[0].archive.as_ref().unwrap();
930        assert_eq!(messages.files.as_deref(), Some("10"));
931        assert_eq!(messages.size.as_deref(), Some("100k"));
932        assert_eq!(messages.world_readable, Some(false));
933
934        assert_eq!(syslog.files[1].archive, None);
935    }
936
937    #[test]
938    fn no_syslog_is_none() {
939        assert!(system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n"))
940            .unwrap()
941            .syslog
942            .is_none());
943    }
944
945    const LOGIN: &str = r#"
946system {
947    login {
948        message "Authorized access only";
949        announcement "Maintenance window Sunday";
950        class NOC {
951            permissions [ view view-configuration ];
952            idle-timeout 15;
953            allow-commands "(ping)|(traceroute)";
954            deny-configuration ".*";
955        }
956        class OPS {
957            permissions all;
958            deny-commands "(request system)";
959            allow-configuration "(interfaces)|(protocols)";
960        }
961        user admin {
962            uid 2000;
963            class super-user;
964            full-name "Network Admin";
965            authentication {
966                encrypted-password "$6$salt$hash"; ## SECRET-DATA
967                ssh-ed25519 "ssh-ed25519 AAAAC3Nza admin@host"; ## SECRET-DATA
968            }
969        }
970        user monitor {
971            class NOC;
972        }
973    }
974}
975"#;
976
977    #[test]
978    fn extracts_login_banner_and_classes() {
979        let login = system(&juniper::parse_braces(LOGIN)).unwrap().login.unwrap();
980        assert_eq!(login.message.as_deref(), Some("Authorized access only"));
981        assert_eq!(login.announcement.as_deref(), Some("Maintenance window Sunday"));
982
983        assert_eq!(login.classes.len(), 2);
984        let noc = &login.classes[0];
985        assert_eq!(noc.name, "NOC");
986        assert_eq!(noc.permissions, ["view", "view-configuration"]);
987        assert_eq!(noc.idle_timeout.as_deref(), Some("15"));
988        assert_eq!(noc.allow_commands.as_deref(), Some("(ping)|(traceroute)"));
989        assert_eq!(noc.deny_configuration.as_deref(), Some(".*"));
990        assert_eq!(noc.deny_commands, None);
991
992        let ops = &login.classes[1];
993        assert_eq!(ops.permissions, ["all"]);
994        assert_eq!(ops.deny_commands.as_deref(), Some("(request system)"));
995        assert_eq!(ops.allow_configuration.as_deref(), Some("(interfaces)|(protocols)"));
996    }
997
998    #[test]
999    fn extracts_login_users_without_secrets() {
1000        let login = system(&juniper::parse_braces(LOGIN)).unwrap().login.unwrap();
1001        assert_eq!(login.users.len(), 2);
1002
1003        let admin = &login.users[0];
1004        assert_eq!(admin.name, "admin");
1005        assert_eq!(admin.class.as_deref(), Some("super-user"));
1006        assert_eq!(admin.uid.as_deref(), Some("2000"));
1007        assert_eq!(admin.full_name.as_deref(), Some("Network Admin"));
1008        assert_eq!(admin.authentication_methods, ["encrypted-password", "ssh-ed25519"]);
1009
1010        let monitor = &login.users[1];
1011        assert_eq!(monitor.class.as_deref(), Some("NOC"));
1012        assert!(monitor.authentication_methods.is_empty());
1013    }
1014
1015    #[test]
1016    fn no_login_is_none() {
1017        assert!(system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n"))
1018            .unwrap()
1019            .login
1020            .is_none());
1021    }
1022
1023    const SERVICES: &str = r#"
1024system {
1025    services {
1026        ssh {
1027            root-login deny;
1028            protocol-version v2;
1029            port 2222;
1030            connection-limit 10;
1031            rate-limit 5;
1032            ciphers [ aes256-ctr aes128-ctr ];
1033            sftp-server;
1034        }
1035        netconf {
1036            ssh;
1037        }
1038        web-management {
1039            https {
1040                system-generated-certificate;
1041            }
1042        }
1043        telnet;
1044    }
1045}
1046"#;
1047
1048    #[test]
1049    fn extracts_ssh_service_settings() {
1050        let services = system(&juniper::parse_braces(SERVICES)).unwrap().services.unwrap();
1051        let ssh = services.ssh.unwrap();
1052        assert_eq!(ssh.root_login.as_deref(), Some("deny"));
1053        assert_eq!(ssh.protocol_versions, ["v2"]);
1054        assert_eq!(ssh.port.as_deref(), Some("2222"));
1055        assert_eq!(ssh.connection_limit.as_deref(), Some("10"));
1056        assert_eq!(ssh.rate_limit.as_deref(), Some("5"));
1057        assert_eq!(ssh.ciphers, ["aes256-ctr", "aes128-ctr"]);
1058        assert!(ssh.sftp_server);
1059    }
1060
1061    #[test]
1062    fn extracts_enabled_services() {
1063        let services = system(&juniper::parse_braces(SERVICES)).unwrap().services.unwrap();
1064        assert!(services.telnet);
1065        assert!(services.netconf_ssh);
1066        assert!(services.https);
1067        assert!(!services.http);
1068        assert!(!services.ftp);
1069    }
1070
1071    #[test]
1072    fn bare_service_statements_enable_with_defaults() {
1073        let services = system(&juniper::parse_braces(
1074            "system {\n    services {\n        ssh;\n        ftp;\n        web-management {\n            http;\n        }\n    }\n}\n",
1075        ))
1076        .unwrap()
1077        .services
1078        .unwrap();
1079        assert_eq!(services.ssh, Some(SshService::default()));
1080        assert!(services.ftp);
1081        assert!(services.http);
1082        assert!(!services.telnet);
1083        assert!(!services.netconf_ssh);
1084    }
1085
1086    #[test]
1087    fn disabled_service_is_not_reported() {
1088        let services = system(&juniper::parse_braces(
1089            "system {\n    services {\n        inactive: telnet;\n        ssh;\n    }\n}\n",
1090        ))
1091        .unwrap()
1092        .services
1093        .unwrap();
1094        assert!(!services.telnet);
1095    }
1096
1097    #[test]
1098    fn extracts_outbound_ssh_clients() {
1099        let services = system(&juniper::parse_braces(
1100            r#"
1101system {
1102    services {
1103        outbound-ssh {
1104            client mgmt {
1105                device-id pe1;
1106                secret "$9$secret"; ## SECRET-DATA
1107                reconnect-strategy sticky;
1108                routing-instance mgmt_junos;
1109                services netconf;
1110                192.0.2.50 {
1111                    port 7804;
1112                    retry 5;
1113                    timeout 20;
1114                }
1115            }
1116            client backup {
1117                192.0.2.60;
1118                keep-alive {
1119                    retry 3;
1120                    timeout 15;
1121                }
1122            }
1123        }
1124    }
1125}
1126"#,
1127        ))
1128        .unwrap()
1129        .services
1130        .unwrap();
1131        assert_eq!(services.outbound_ssh.len(), 2);
1132
1133        let mgmt = &services.outbound_ssh[0];
1134        assert_eq!(mgmt.id, "mgmt");
1135        assert_eq!(mgmt.device_id.as_deref(), Some("pe1"));
1136        assert_eq!(mgmt.reconnect_strategy.as_deref(), Some("sticky"));
1137        assert_eq!(mgmt.routing_instance.as_deref(), Some("mgmt_junos"));
1138        assert_eq!(mgmt.services, ["netconf"]);
1139        assert_eq!(mgmt.servers.len(), 1);
1140        assert_eq!(mgmt.servers[0].address, "192.0.2.50");
1141        assert_eq!(mgmt.servers[0].port.as_deref(), Some("7804"));
1142        assert_eq!(mgmt.servers[0].retry.as_deref(), Some("5"));
1143        assert_eq!(mgmt.servers[0].timeout.as_deref(), Some("20"));
1144
1145        let backup = &services.outbound_ssh[1];
1146        assert_eq!(backup.id, "backup");
1147        // `keep-alive` is an option block, not a server.
1148        assert_eq!(backup.servers.len(), 1);
1149        assert_eq!(backup.servers[0].address, "192.0.2.60");
1150        assert_eq!(backup.servers[0].port, None);
1151    }
1152
1153    #[test]
1154    fn no_outbound_ssh_is_empty() {
1155        let services = system(&juniper::parse_braces(
1156            "system {\n    services {\n        ssh;\n    }\n}\n",
1157        ))
1158        .unwrap()
1159        .services
1160        .unwrap();
1161        assert!(services.outbound_ssh.is_empty());
1162    }
1163
1164    #[test]
1165    fn no_services_is_none() {
1166        assert!(system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n"))
1167            .unwrap()
1168            .services
1169            .is_none());
1170    }
1171
1172    #[test]
1173    fn extracts_domain_name() {
1174        let system = system(&juniper::parse_braces(
1175            "system {\n    host-name pe1;\n    domain-name example.net;\n}\n",
1176        ))
1177        .unwrap();
1178        assert_eq!(system.domain_name.as_deref(), Some("example.net"));
1179    }
1180
1181    #[test]
1182    fn domain_name_is_optional() {
1183        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
1184        assert_eq!(system.domain_name, None);
1185    }
1186
1187    #[test]
1188    fn extracts_time_zone() {
1189        let system = system(&juniper::parse_braces("system {\n    time-zone America/New_York;\n}\n")).unwrap();
1190        assert_eq!(system.time_zone.as_deref(), Some("America/New_York"));
1191    }
1192
1193    #[test]
1194    fn time_zone_is_optional() {
1195        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
1196        assert_eq!(system.time_zone, None);
1197    }
1198
1199    #[test]
1200    fn extracts_root_authentication_methods_without_secrets() {
1201        let system = system(&juniper::parse_braces(
1202            r#"
1203system {
1204    root-authentication {
1205        encrypted-password "$6$salt$hash"; ## SECRET-DATA
1206        ssh-rsa "ssh-rsa AAAAB3Nza root@host"; ## SECRET-DATA
1207        ssh-rsa "ssh-rsa AAAAB3Nzb ops@host" {
1208            from 192.0.2.0/24;
1209        }
1210    }
1211}
1212"#,
1213        ))
1214        .unwrap();
1215        let root = system.root_authentication.unwrap();
1216        assert_eq!(root.methods, ["encrypted-password", "ssh-rsa", "ssh-rsa"]);
1217    }
1218
1219    #[test]
1220    fn root_authentication_can_disable_public_keys() {
1221        let system = system(&juniper::parse_braces(
1222            "system {\n    root-authentication {\n        no-public-keys;\n    }\n}\n",
1223        ))
1224        .unwrap();
1225        assert_eq!(system.root_authentication.unwrap().methods, ["no-public-keys"]);
1226    }
1227
1228    #[test]
1229    fn no_root_authentication_is_none() {
1230        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
1231        assert!(system.root_authentication.is_none());
1232    }
1233
1234    #[test]
1235    fn extracts_domain_search_list() {
1236        let system = system(&juniper::parse_braces(
1237            "system {\n    domain-search [ example.net lab.example.net ];\n}\n",
1238        ))
1239        .unwrap();
1240        assert_eq!(system.domain_search, ["example.net", "lab.example.net"]);
1241    }
1242
1243    #[test]
1244    fn extracts_static_host_mappings() {
1245        let system = system(&juniper::parse_braces(
1246            r#"
1247system {
1248    static-host-mapping {
1249        p1.example.net {
1250            inet [ 10.255.0.2 10.255.1.2 ];
1251            inet6 2001:db8::2;
1252            alias [ p1 core1 ];
1253            sysid 0100.2550.0002;
1254        }
1255        p2.example.net {
1256            inet 10.255.0.3;
1257        }
1258    }
1259}
1260"#,
1261        ))
1262        .unwrap();
1263        assert_eq!(system.static_host_mappings.len(), 2);
1264
1265        let p1 = &system.static_host_mappings[0];
1266        assert_eq!(p1.hostname, "p1.example.net");
1267        assert_eq!(p1.inet, ["10.255.0.2", "10.255.1.2"]);
1268        assert_eq!(p1.inet6, ["2001:db8::2"]);
1269        assert_eq!(p1.aliases, ["p1", "core1"]);
1270        assert_eq!(p1.sysid.as_deref(), Some("0100.2550.0002"));
1271
1272        let p2 = &system.static_host_mappings[1];
1273        assert_eq!(p2.inet, ["10.255.0.3"]);
1274        assert!(p2.aliases.is_empty());
1275        assert_eq!(p2.sysid, None);
1276    }
1277
1278    #[test]
1279    fn extracts_backup_routers() {
1280        let system = system(&juniper::parse_braces(
1281            "system {\n    backup-router 192.0.2.1 destination [ 10.0.0.0/8 172.16.0.0/12 ];\n    inet6-backup-router 2001:db8::1;\n}\n",
1282        ))
1283        .unwrap();
1284        let backup = system.backup_router.unwrap();
1285        assert_eq!(backup.address, "192.0.2.1");
1286        assert_eq!(backup.destinations, ["10.0.0.0/8", "172.16.0.0/12"]);
1287
1288        let backup6 = system.inet6_backup_router.unwrap();
1289        assert_eq!(backup6.address, "2001:db8::1");
1290        assert!(backup6.destinations.is_empty());
1291    }
1292
1293    #[test]
1294    fn single_destination_backup_router() {
1295        let system = system(&juniper::parse_braces(
1296            "system {\n    backup-router 192.0.2.1 destination 10.0.0.0/8;\n}\n",
1297        ))
1298        .unwrap();
1299        assert_eq!(system.backup_router.unwrap().destinations, ["10.0.0.0/8"]);
1300    }
1301
1302    #[test]
1303    fn addressing_settings_are_optional() {
1304        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
1305        assert!(system.domain_search.is_empty());
1306        assert!(system.static_host_mappings.is_empty());
1307        assert!(system.backup_router.is_none());
1308        assert!(system.inet6_backup_router.is_none());
1309    }
1310
1311    #[test]
1312    fn extracts_authentication_order() {
1313        let system = system(&juniper::parse_braces(
1314            "system {\n    authentication-order [ tacplus radius password ];\n}\n",
1315        ))
1316        .unwrap();
1317        assert_eq!(system.authentication_order, ["tacplus", "radius", "password"]);
1318    }
1319
1320    #[test]
1321    fn extracts_radius_servers_without_secrets() {
1322        let system = system(&juniper::parse_braces(
1323            r#"
1324system {
1325    radius-server 192.0.2.10 {
1326        secret "$9$secret"; ## SECRET-DATA
1327        port 1812;
1328        accounting-port 1813;
1329        retry 5;
1330        timeout 10;
1331        source-address 192.0.2.1;
1332        routing-instance mgmt_junos;
1333    }
1334    radius-server 192.0.2.11 {
1335        secret "$9$other"; ## SECRET-DATA
1336    }
1337}
1338"#,
1339        ))
1340        .unwrap();
1341        assert_eq!(system.radius_servers.len(), 2);
1342
1343        let first = &system.radius_servers[0];
1344        assert_eq!(first.address, "192.0.2.10");
1345        assert_eq!(first.port.as_deref(), Some("1812"));
1346        assert_eq!(first.accounting_port.as_deref(), Some("1813"));
1347        assert_eq!(first.retry.as_deref(), Some("5"));
1348        assert_eq!(first.timeout.as_deref(), Some("10"));
1349        assert_eq!(first.source_address.as_deref(), Some("192.0.2.1"));
1350        assert_eq!(first.routing_instance.as_deref(), Some("mgmt_junos"));
1351
1352        assert_eq!(system.radius_servers[1].address, "192.0.2.11");
1353        assert_eq!(system.radius_servers[1].port, None);
1354    }
1355
1356    #[test]
1357    fn extracts_radius_servers_in_nested_block_form() {
1358        let system = system(&juniper::parse_braces(
1359            "system {\n    radius-server {\n        192.0.2.10 {\n            port 1645;\n        }\n    }\n}\n",
1360        ))
1361        .unwrap();
1362        assert_eq!(system.radius_servers[0].address, "192.0.2.10");
1363        assert_eq!(system.radius_servers[0].port.as_deref(), Some("1645"));
1364    }
1365
1366    #[test]
1367    fn extracts_tacplus_servers_without_secrets() {
1368        let system = system(&juniper::parse_braces(
1369            r#"
1370system {
1371    tacplus-server 192.0.2.20 {
1372        port 49;
1373        secret "$9$secret"; ## SECRET-DATA
1374        single-connection;
1375        source-address 192.0.2.1;
1376        timeout 5;
1377    }
1378    inactive: tacplus-server 192.0.2.21 {
1379        secret "$9$other"; ## SECRET-DATA
1380    }
1381}
1382"#,
1383        ))
1384        .unwrap();
1385        assert_eq!(system.tacplus_servers.len(), 1);
1386        let server = &system.tacplus_servers[0];
1387        assert_eq!(server.address, "192.0.2.20");
1388        assert_eq!(server.port.as_deref(), Some("49"));
1389        assert_eq!(server.timeout.as_deref(), Some("5"));
1390        assert_eq!(server.source_address.as_deref(), Some("192.0.2.1"));
1391        assert!(server.single_connection);
1392        assert_eq!(server.routing_instance, None);
1393    }
1394
1395    #[test]
1396    fn authentication_settings_are_optional() {
1397        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
1398        assert!(system.authentication_order.is_empty());
1399        assert!(system.radius_servers.is_empty());
1400        assert!(system.tacplus_servers.is_empty());
1401    }
1402
1403    #[test]
1404    fn extracts_location() {
1405        let system = system(&juniper::parse_braces(
1406            r#"
1407system {
1408    location {
1409        building "DC East";
1410        floor 2;
1411        rack 14;
1412        country-code US;
1413        postal-code 10001;
1414        latitude 40.7128;
1415        longitude -74.006;
1416        altitude 33;
1417    }
1418}
1419"#,
1420        ))
1421        .unwrap();
1422        let location = system.location.unwrap();
1423        assert_eq!(location.building.as_deref(), Some("DC East"));
1424        assert_eq!(location.floor.as_deref(), Some("2"));
1425        assert_eq!(location.rack.as_deref(), Some("14"));
1426        assert_eq!(location.country_code.as_deref(), Some("US"));
1427        assert_eq!(location.postal_code.as_deref(), Some("10001"));
1428        assert_eq!(location.latitude.as_deref(), Some("40.7128"));
1429        assert_eq!(location.longitude.as_deref(), Some("-74.006"));
1430        assert_eq!(location.altitude.as_deref(), Some("33"));
1431    }
1432
1433    #[test]
1434    fn extracts_console_and_auxiliary_ports() {
1435        let system = system(&juniper::parse_braces(
1436            r#"
1437system {
1438    ports {
1439        console {
1440            log-out-on-disconnect;
1441            type vt100;
1442            insecure;
1443        }
1444        auxiliary {
1445            disable;
1446            port-type rj45;
1447        }
1448    }
1449}
1450"#,
1451        ))
1452        .unwrap();
1453        let ports = system.ports.unwrap();
1454
1455        let console = ports.console.unwrap();
1456        assert!(console.log_out_on_disconnect);
1457        assert!(console.insecure);
1458        assert!(!console.disable);
1459        assert_eq!(console.terminal_type.as_deref(), Some("vt100"));
1460        assert_eq!(console.port_type, None);
1461
1462        let auxiliary = ports.auxiliary.unwrap();
1463        assert!(auxiliary.disable);
1464        assert_eq!(auxiliary.port_type.as_deref(), Some("rj45"));
1465    }
1466
1467    #[test]
1468    fn extracts_configuration_limits_and_no_redirects() {
1469        let system = system(&juniper::parse_braces(
1470            "system {\n    max-configurations-on-flash 5;\n    max-configuration-rollbacks 20;\n    no-redirects;\n}\n",
1471        ))
1472        .unwrap();
1473        assert_eq!(system.max_configurations_on_flash.as_deref(), Some("5"));
1474        assert_eq!(system.max_configuration_rollbacks.as_deref(), Some("20"));
1475        assert!(system.no_redirects);
1476    }
1477
1478    #[test]
1479    fn device_settings_are_optional() {
1480        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
1481        assert!(system.location.is_none());
1482        assert!(system.ports.is_none());
1483        assert_eq!(system.max_configurations_on_flash, None);
1484        assert_eq!(system.max_configuration_rollbacks, None);
1485        assert!(!system.no_redirects);
1486    }
1487
1488    #[test]
1489    fn no_system_is_none() {
1490        assert!(system(&juniper::parse_braces("interfaces {\n    lo0;\n}\n")).is_none());
1491    }
1492}