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 `file <name>` or `user <name>` destination.
78#[derive(Clone, Debug, PartialEq, Eq)]
79#[non_exhaustive]
80pub struct SyslogTarget {
81    /// File name, or user name (`*` for all users).
82    pub name: String,
83    pub rules: Vec<SyslogRule>,
84}
85
86/// The `system syslog` configuration. Archive settings are not extracted.
87#[derive(Clone, Debug, PartialEq, Eq)]
88#[non_exhaustive]
89pub struct Syslog {
90    pub hosts: Vec<SyslogHost>,
91    pub files: Vec<SyslogTarget>,
92    pub users: Vec<SyslogTarget>,
93    pub console: Vec<SyslogRule>,
94    pub source_address: Option<String>,
95    /// e.g. `"year millisecond"`.
96    pub time_format: Option<String>,
97}
98
99/// A login `class`.
100#[derive(Clone, Debug, PartialEq, Eq)]
101#[non_exhaustive]
102pub struct LoginClass {
103    pub name: String,
104    pub permissions: Vec<String>,
105    /// Minutes.
106    pub idle_timeout: Option<String>,
107    /// The regular expressions as written, e.g. `"(show)|(ping)"`.
108    pub allow_commands: Option<String>,
109    pub deny_commands: Option<String>,
110    pub allow_configuration: Option<String>,
111    pub deny_configuration: Option<String>,
112}
113
114/// A login `user`. Passwords and keys are not extracted, only which authentication methods are present.
115#[derive(Clone, Debug, PartialEq, Eq)]
116#[non_exhaustive]
117pub struct LoginUser {
118    pub name: String,
119    pub class: Option<String>,
120    pub uid: Option<String>,
121    pub full_name: Option<String>,
122    /// One entry per authentication statement, e.g. `"encrypted-password"`, `"ssh-rsa"`.
123    pub authentication_methods: Vec<String>,
124}
125
126/// The `system login` configuration.
127#[derive(Clone, Debug, PartialEq, Eq)]
128#[non_exhaustive]
129pub struct Login {
130    /// The banner shown before login.
131    pub message: Option<String>,
132    /// The text shown after login.
133    pub announcement: Option<String>,
134    pub classes: Vec<LoginClass>,
135    pub users: Vec<LoginUser>,
136}
137
138/// The `system services ssh` settings; every field is `None` or empty when only `ssh;` is written.
139#[derive(Clone, Debug, Default, PartialEq, Eq)]
140#[non_exhaustive]
141pub struct SshService {
142    /// `allow`, `deny` or `deny-password`.
143    pub root_login: Option<String>,
144    pub protocol_versions: Vec<String>,
145    pub port: Option<String>,
146    pub connection_limit: Option<String>,
147    pub rate_limit: Option<String>,
148    pub ciphers: Vec<String>,
149    pub sftp_server: bool,
150}
151
152/// The `system services` configuration. Services other than those listed are not extracted.
153#[derive(Clone, Debug, PartialEq, Eq)]
154#[non_exhaustive]
155pub struct Services {
156    pub ssh: Option<SshService>,
157    pub telnet: bool,
158    pub ftp: bool,
159    /// `netconf { ssh; }`.
160    pub netconf_ssh: bool,
161    /// `web-management { http; }`.
162    pub http: bool,
163    /// `web-management { https; }`.
164    pub https: bool,
165}
166
167/// The top-level `system` configuration.
168#[derive(Clone, Debug, PartialEq, Eq)]
169#[non_exhaustive]
170pub struct System {
171    pub host_name: Option<String>,
172    pub name_servers: Vec<NameServer>,
173    pub ntp: Option<Ntp>,
174    pub syslog: Option<Syslog>,
175    pub login: Option<Login>,
176    pub services: Option<Services>,
177}
178
179/// The top-level `system` block, or `None` if there is none.
180pub fn system(config: &Config) -> Option<System> {
181    let system = top_level(config, "system")?;
182    Some(System {
183        host_name: arg_of(system, "host-name").map(str::to_string),
184        name_servers: name_servers(system),
185        ntp: child_block(system, "ntp").map(parse_ntp),
186        syslog: child_block(system, "syslog").map(parse_syslog),
187        login: child_block(system, "login").map(parse_login),
188        services: child_block(system, "services").map(parse_services),
189    })
190}
191
192fn parse_services(services: &ConfigLine) -> Services {
193    let web = child_block(services, "web-management");
194    let netconf = child_block(services, "netconf");
195    Services {
196        ssh: child_block(services, "ssh").map(parse_ssh),
197        telnet: child_block(services, "telnet").is_some(),
198        ftp: child_block(services, "ftp").is_some(),
199        netconf_ssh: netconf.is_some_and(|n| child_block(n, "ssh").is_some()),
200        http: web.is_some_and(|w| child_block(w, "http").is_some()),
201        https: web.is_some_and(|w| child_block(w, "https").is_some()),
202    }
203}
204
205fn parse_ssh(ssh: &ConfigLine) -> SshService {
206    let list = |keyword: &str| args_of(ssh, keyword).into_iter().flat_map(list_values).collect();
207    SshService {
208        root_login: arg_of(ssh, "root-login").map(str::to_string),
209        protocol_versions: list("protocol-version"),
210        port: arg_of(ssh, "port").map(str::to_string),
211        connection_limit: arg_of(ssh, "connection-limit").map(str::to_string),
212        rate_limit: arg_of(ssh, "rate-limit").map(str::to_string),
213        ciphers: list("ciphers"),
214        sftp_server: has_leaf(ssh, "sftp-server"),
215    }
216}
217
218fn parse_login(login: &ConfigLine) -> Login {
219    Login {
220        message: arg_of(login, "message").map(str::to_string),
221        announcement: arg_of(login, "announcement").map(str::to_string),
222        classes: named_children(login, "class")
223            .map(|(name, class)| LoginClass {
224                name: name.to_string(),
225                permissions: args_of(class, "permissions")
226                    .into_iter()
227                    .flat_map(list_values)
228                    .collect(),
229                idle_timeout: arg_of(class, "idle-timeout").map(str::to_string),
230                allow_commands: arg_of(class, "allow-commands").map(str::to_string),
231                deny_commands: arg_of(class, "deny-commands").map(str::to_string),
232                allow_configuration: arg_of(class, "allow-configuration").map(str::to_string),
233                deny_configuration: arg_of(class, "deny-configuration").map(str::to_string),
234            })
235            .collect(),
236        users: named_children(login, "user")
237            .map(|(name, user)| LoginUser {
238                name: name.to_string(),
239                class: arg_of(user, "class").map(str::to_string),
240                uid: arg_of(user, "uid").map(str::to_string),
241                full_name: arg_of(user, "full-name").map(str::to_string),
242                authentication_methods: child_block(user, "authentication")
243                    .map(|auth| {
244                        // Secrets may carry a trailing `## SECRET-DATA` marker; only the method name is kept.
245                        active_children(auth)
246                            .filter_map(|c| c.text.split_whitespace().next())
247                            .map(str::to_string)
248                            .collect()
249                    })
250                    .unwrap_or_default(),
251            })
252            .collect(),
253    }
254}
255
256fn parse_syslog(syslog: &ConfigLine) -> Syslog {
257    Syslog {
258        hosts: named_children(syslog, "host")
259            .map(|(address, host)| SyslogHost {
260                address: address.to_string(),
261                rules: syslog_rules(host),
262                port: arg_of(host, "port").map(str::to_string),
263                source_address: arg_of(host, "source-address").map(str::to_string),
264                routing_instance: arg_of(host, "routing-instance").map(str::to_string),
265                facility_override: arg_of(host, "facility-override").map(str::to_string),
266                log_prefix: arg_of(host, "log-prefix").map(str::to_string),
267            })
268            .collect(),
269        files: syslog_targets(syslog, "file"),
270        users: syslog_targets(syslog, "user"),
271        console: child_block(syslog, "console").map(syslog_rules).unwrap_or_default(),
272        source_address: arg_of(syslog, "source-address").map(str::to_string),
273        time_format: arg_of(syslog, "time-format").map(str::to_string),
274    }
275}
276
277fn syslog_targets(syslog: &ConfigLine, keyword: &str) -> Vec<SyslogTarget> {
278    named_children(syslog, keyword)
279        .map(|(name, target)| SyslogTarget {
280            name: name.to_string(),
281            rules: syslog_rules(target),
282        })
283        .collect()
284}
285
286/// Children written `<facility> <severity>`, which tells them apart from options such as `port 514`.
287fn syslog_rules(destination: &ConfigLine) -> Vec<SyslogRule> {
288    const SEVERITIES: [&str; 10] = [
289        "any",
290        "none",
291        "emergency",
292        "alert",
293        "critical",
294        "error",
295        "warning",
296        "notice",
297        "info",
298        "debug",
299    ];
300    active_children(destination)
301        .filter_map(|c| {
302            let (facility, severity) = c.text.split_once(' ')?;
303            SEVERITIES.contains(&severity).then(|| SyslogRule {
304                facility: facility.to_string(),
305                severity: severity.to_string(),
306            })
307        })
308        .collect()
309}
310
311fn parse_ntp(ntp: &ConfigLine) -> Ntp {
312    let hosts = |keyword: &str| -> Vec<NtpHost> {
313        active_children(ntp)
314            .filter_map(|c| Some(ntp_host(c.arg(keyword)?, c)))
315            .collect()
316    };
317    Ntp {
318        boot_server: arg_of(ntp, "boot-server").map(str::to_string),
319        servers: hosts("server"),
320        peers: hosts("peer"),
321        source_address: arg_of(ntp, "source-address").and_then(first_word).map(str::to_string),
322        trusted_keys: args_of(ntp, "trusted-key").into_iter().flat_map(list_values).collect(),
323        authentication_keys: args_of(ntp, "authentication-key")
324            .into_iter()
325            .filter_map(ntp_authentication_key)
326            .collect(),
327        broadcast_client: has_leaf(ntp, "broadcast-client"),
328    }
329}
330
331/// A host written `<address> [key n] [prefer] [version n] [routing-instance x]`, with the options on the line
332/// or in a block.
333fn ntp_host(arg: &str, line: &ConfigLine) -> NtpHost {
334    let (address, options) = split_name(arg);
335    let mut words = options.split_whitespace();
336    let mut host = NtpHost {
337        address: address.to_string(),
338        key: arg_of(line, "key").map(str::to_string),
339        prefer: has_leaf(line, "prefer"),
340        version: arg_of(line, "version").map(str::to_string),
341        routing_instance: arg_of(line, "routing-instance").map(str::to_string),
342    };
343    while let Some(word) = words.next() {
344        match word {
345            "prefer" => host.prefer = true,
346            "key" => host.key = words.next().map(str::to_string),
347            "version" => host.version = words.next().map(str::to_string),
348            "routing-instance" => host.routing_instance = words.next().map(str::to_string),
349            _ => {}
350        }
351    }
352    host
353}
354
355/// `<number> type <type> value <secret>`; the secret is dropped.
356fn ntp_authentication_key(arg: &str) -> Option<NtpAuthenticationKey> {
357    let mut words = arg.split_whitespace();
358    let number = words.next()?.to_string();
359    let key_type = words.skip_while(|w| *w != "type").nth(1).map(str::to_string);
360    Some(NtpAuthenticationKey { number, key_type })
361}
362
363/// Servers written as a `name-server { <address>; ... }` block, or one per `name-server <address>` line.
364fn name_servers(system: &ConfigLine) -> Vec<NameServer> {
365    let mut found = Vec::new();
366    for child in active_children(system) {
367        if child.text == "name-server" {
368            found.extend(active_children(child).map(|server| name_server(&server.text, server)));
369        } else if let Some(address) = child.arg("name-server") {
370            found.push(name_server(address, child));
371        }
372    }
373    found
374}
375
376fn name_server(address: &str, line: &ConfigLine) -> NameServer {
377    NameServer {
378        address: unquote(address).to_string(),
379        routing_instance: arg_of(line, "routing-instance").map(str::to_string),
380    }
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386    use asterust::config::juniper;
387
388    // Not from documentation: written from the CLI Reference syntax pages. See the README "Sources".
389    #[test]
390    fn extracts_host_name() {
391        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
392        assert_eq!(system.host_name.as_deref(), Some("pe1"));
393    }
394
395    #[test]
396    fn host_name_is_optional() {
397        let system = system(&juniper::parse_braces("system {\n    domain-name example.net;\n}\n")).unwrap();
398        assert_eq!(system.host_name, None);
399    }
400
401    #[test]
402    fn skips_inactive_host_name() {
403        let system = system(&juniper::parse_braces("system {\n    inactive: host-name pe1;\n}\n")).unwrap();
404        assert_eq!(system.host_name, None);
405    }
406
407    #[test]
408    fn extracts_name_server_block() {
409        let system = system(&juniper::parse_braces(
410            "system {\n    name-server {\n        192.0.2.53;\n        2001:db8::53;\n    }\n}\n",
411        ))
412        .unwrap();
413        let addresses: Vec<_> = system.name_servers.iter().map(|s| s.address.as_str()).collect();
414        assert_eq!(addresses, ["192.0.2.53", "2001:db8::53"]);
415        assert_eq!(system.name_servers[0].routing_instance, None);
416    }
417
418    #[test]
419    fn name_server_in_management_instance() {
420        let system = system(&juniper::parse_braces(
421            "system {\n    name-server {\n        192.0.2.53 {\n            routing-instance mgmt_junos;\n        }\n    }\n}\n",
422        ))
423        .unwrap();
424        assert_eq!(system.name_servers[0].address, "192.0.2.53");
425        assert_eq!(system.name_servers[0].routing_instance.as_deref(), Some("mgmt_junos"));
426    }
427
428    #[test]
429    fn extracts_one_line_name_servers_and_skips_inactive() {
430        let system = system(&juniper::parse_braces(
431            "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",
432        ))
433        .unwrap();
434        let addresses: Vec<_> = system.name_servers.iter().map(|s| s.address.as_str()).collect();
435        assert_eq!(addresses, ["192.0.2.53", "192.0.2.54"]);
436    }
437
438    const NTP: &str = r#"
439system {
440    ntp {
441        boot-server 192.0.2.10;
442        source-address 192.0.2.1;
443        authentication-key 1 type md5 value "$9$secret";
444        authentication-key 2 type sha256 value "$9$other";
445        trusted-key [ 1 2 ];
446        server 192.0.2.10 key 1 prefer version 4;
447        server 192.0.2.11;
448        server ntp.example.net {
449            key 2;
450            prefer;
451            version 3;
452            routing-instance mgmt_junos;
453        }
454        inactive: server 192.0.2.12;
455        peer 192.0.2.20 key 1;
456        broadcast-client;
457    }
458}
459"#;
460
461    #[test]
462    fn extracts_ntp_servers_in_line_and_block_form() {
463        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
464        let addresses: Vec<_> = ntp.servers.iter().map(|s| s.address.as_str()).collect();
465        assert_eq!(addresses, ["192.0.2.10", "192.0.2.11", "ntp.example.net"]);
466
467        let line = &ntp.servers[0];
468        assert_eq!(line.key.as_deref(), Some("1"));
469        assert!(line.prefer);
470        assert_eq!(line.version.as_deref(), Some("4"));
471
472        assert_eq!(ntp.servers[1].key, None);
473        assert!(!ntp.servers[1].prefer);
474
475        let block = &ntp.servers[2];
476        assert_eq!(block.key.as_deref(), Some("2"));
477        assert!(block.prefer);
478        assert_eq!(block.version.as_deref(), Some("3"));
479        assert_eq!(block.routing_instance.as_deref(), Some("mgmt_junos"));
480    }
481
482    #[test]
483    fn extracts_ntp_peers_keys_and_global_settings() {
484        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
485        assert_eq!(ntp.peers.len(), 1);
486        assert_eq!(ntp.peers[0].address, "192.0.2.20");
487        assert_eq!(ntp.peers[0].key.as_deref(), Some("1"));
488        assert_eq!(ntp.boot_server.as_deref(), Some("192.0.2.10"));
489        assert_eq!(ntp.source_address.as_deref(), Some("192.0.2.1"));
490        assert_eq!(ntp.trusted_keys, ["1", "2"]);
491        assert!(ntp.broadcast_client);
492    }
493
494    #[test]
495    fn ntp_authentication_keys_omit_the_secret() {
496        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
497        assert_eq!(ntp.authentication_keys.len(), 2);
498        assert_eq!(ntp.authentication_keys[0].number, "1");
499        assert_eq!(ntp.authentication_keys[0].key_type.as_deref(), Some("md5"));
500        assert_eq!(ntp.authentication_keys[1].key_type.as_deref(), Some("sha256"));
501    }
502
503    #[test]
504    fn no_ntp_is_none() {
505        assert!(system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n"))
506            .unwrap()
507            .ntp
508            .is_none());
509    }
510
511    const SYSLOG: &str = r#"
512system {
513    syslog {
514        user * {
515            any emergency;
516        }
517        host 192.0.2.5 {
518            any notice;
519            authorization info;
520            port 514;
521            source-address 192.0.2.1;
522            routing-instance mgmt_junos;
523            facility-override local3;
524            log-prefix pe1;
525        }
526        host other-routing-engine {
527            any critical;
528        }
529        file messages {
530            any notice;
531            authorization info;
532            explicit-priority;
533        }
534        file interactive-commands {
535            interactive-commands any;
536        }
537        inactive: file debug {
538            any debug;
539        }
540        console {
541            any critical;
542        }
543        source-address 192.0.2.1;
544        time-format year millisecond;
545    }
546}
547"#;
548
549    #[test]
550    fn extracts_syslog_hosts() {
551        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
552        let addresses: Vec<_> = syslog.hosts.iter().map(|h| h.address.as_str()).collect();
553        assert_eq!(addresses, ["192.0.2.5", "other-routing-engine"]);
554
555        let host = &syslog.hosts[0];
556        assert_eq!(host.rules.len(), 2);
557        assert_eq!(host.rules[1].facility, "authorization");
558        assert_eq!(host.rules[1].severity, "info");
559        assert_eq!(host.port.as_deref(), Some("514"));
560        assert_eq!(host.source_address.as_deref(), Some("192.0.2.1"));
561        assert_eq!(host.routing_instance.as_deref(), Some("mgmt_junos"));
562        assert_eq!(host.facility_override.as_deref(), Some("local3"));
563        assert_eq!(host.log_prefix.as_deref(), Some("pe1"));
564    }
565
566    #[test]
567    fn extracts_syslog_files_users_and_console() {
568        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
569
570        let files: Vec<_> = syslog.files.iter().map(|f| f.name.as_str()).collect();
571        assert_eq!(files, ["messages", "interactive-commands"]);
572        // `explicit-priority` is an option, not a facility/severity rule.
573        assert_eq!(syslog.files[0].rules.len(), 2);
574        assert_eq!(syslog.files[1].rules[0].facility, "interactive-commands");
575        assert_eq!(syslog.files[1].rules[0].severity, "any");
576
577        assert_eq!(syslog.users[0].name, "*");
578        assert_eq!(syslog.users[0].rules[0].severity, "emergency");
579        assert_eq!(syslog.console[0].facility, "any");
580        assert_eq!(syslog.console[0].severity, "critical");
581    }
582
583    #[test]
584    fn extracts_syslog_global_settings() {
585        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
586        assert_eq!(syslog.source_address.as_deref(), Some("192.0.2.1"));
587        assert_eq!(syslog.time_format.as_deref(), Some("year millisecond"));
588    }
589
590    #[test]
591    fn no_syslog_is_none() {
592        assert!(system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n"))
593            .unwrap()
594            .syslog
595            .is_none());
596    }
597
598    const LOGIN: &str = r#"
599system {
600    login {
601        message "Authorized access only";
602        announcement "Maintenance window Sunday";
603        class NOC {
604            permissions [ view view-configuration ];
605            idle-timeout 15;
606            allow-commands "(ping)|(traceroute)";
607            deny-configuration ".*";
608        }
609        class OPS {
610            permissions all;
611            deny-commands "(request system)";
612            allow-configuration "(interfaces)|(protocols)";
613        }
614        user admin {
615            uid 2000;
616            class super-user;
617            full-name "Network Admin";
618            authentication {
619                encrypted-password "$6$salt$hash"; ## SECRET-DATA
620                ssh-ed25519 "ssh-ed25519 AAAAC3Nza admin@host"; ## SECRET-DATA
621            }
622        }
623        user monitor {
624            class NOC;
625        }
626    }
627}
628"#;
629
630    #[test]
631    fn extracts_login_banner_and_classes() {
632        let login = system(&juniper::parse_braces(LOGIN)).unwrap().login.unwrap();
633        assert_eq!(login.message.as_deref(), Some("Authorized access only"));
634        assert_eq!(login.announcement.as_deref(), Some("Maintenance window Sunday"));
635
636        assert_eq!(login.classes.len(), 2);
637        let noc = &login.classes[0];
638        assert_eq!(noc.name, "NOC");
639        assert_eq!(noc.permissions, ["view", "view-configuration"]);
640        assert_eq!(noc.idle_timeout.as_deref(), Some("15"));
641        assert_eq!(noc.allow_commands.as_deref(), Some("(ping)|(traceroute)"));
642        assert_eq!(noc.deny_configuration.as_deref(), Some(".*"));
643        assert_eq!(noc.deny_commands, None);
644
645        let ops = &login.classes[1];
646        assert_eq!(ops.permissions, ["all"]);
647        assert_eq!(ops.deny_commands.as_deref(), Some("(request system)"));
648        assert_eq!(ops.allow_configuration.as_deref(), Some("(interfaces)|(protocols)"));
649    }
650
651    #[test]
652    fn extracts_login_users_without_secrets() {
653        let login = system(&juniper::parse_braces(LOGIN)).unwrap().login.unwrap();
654        assert_eq!(login.users.len(), 2);
655
656        let admin = &login.users[0];
657        assert_eq!(admin.name, "admin");
658        assert_eq!(admin.class.as_deref(), Some("super-user"));
659        assert_eq!(admin.uid.as_deref(), Some("2000"));
660        assert_eq!(admin.full_name.as_deref(), Some("Network Admin"));
661        assert_eq!(admin.authentication_methods, ["encrypted-password", "ssh-ed25519"]);
662
663        let monitor = &login.users[1];
664        assert_eq!(monitor.class.as_deref(), Some("NOC"));
665        assert!(monitor.authentication_methods.is_empty());
666    }
667
668    #[test]
669    fn no_login_is_none() {
670        assert!(system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n"))
671            .unwrap()
672            .login
673            .is_none());
674    }
675
676    const SERVICES: &str = r#"
677system {
678    services {
679        ssh {
680            root-login deny;
681            protocol-version v2;
682            port 2222;
683            connection-limit 10;
684            rate-limit 5;
685            ciphers [ aes256-ctr aes128-ctr ];
686            sftp-server;
687        }
688        netconf {
689            ssh;
690        }
691        web-management {
692            https {
693                system-generated-certificate;
694            }
695        }
696        telnet;
697    }
698}
699"#;
700
701    #[test]
702    fn extracts_ssh_service_settings() {
703        let services = system(&juniper::parse_braces(SERVICES)).unwrap().services.unwrap();
704        let ssh = services.ssh.unwrap();
705        assert_eq!(ssh.root_login.as_deref(), Some("deny"));
706        assert_eq!(ssh.protocol_versions, ["v2"]);
707        assert_eq!(ssh.port.as_deref(), Some("2222"));
708        assert_eq!(ssh.connection_limit.as_deref(), Some("10"));
709        assert_eq!(ssh.rate_limit.as_deref(), Some("5"));
710        assert_eq!(ssh.ciphers, ["aes256-ctr", "aes128-ctr"]);
711        assert!(ssh.sftp_server);
712    }
713
714    #[test]
715    fn extracts_enabled_services() {
716        let services = system(&juniper::parse_braces(SERVICES)).unwrap().services.unwrap();
717        assert!(services.telnet);
718        assert!(services.netconf_ssh);
719        assert!(services.https);
720        assert!(!services.http);
721        assert!(!services.ftp);
722    }
723
724    #[test]
725    fn bare_service_statements_enable_with_defaults() {
726        let services = system(&juniper::parse_braces(
727            "system {\n    services {\n        ssh;\n        ftp;\n        web-management {\n            http;\n        }\n    }\n}\n",
728        ))
729        .unwrap()
730        .services
731        .unwrap();
732        assert_eq!(services.ssh, Some(SshService::default()));
733        assert!(services.ftp);
734        assert!(services.http);
735        assert!(!services.telnet);
736        assert!(!services.netconf_ssh);
737    }
738
739    #[test]
740    fn disabled_service_is_not_reported() {
741        let services = system(&juniper::parse_braces(
742            "system {\n    services {\n        inactive: telnet;\n        ssh;\n    }\n}\n",
743        ))
744        .unwrap()
745        .services
746        .unwrap();
747        assert!(!services.telnet);
748    }
749
750    #[test]
751    fn no_services_is_none() {
752        assert!(system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n"))
753            .unwrap()
754            .services
755            .is_none());
756    }
757
758    #[test]
759    fn no_system_is_none() {
760        assert!(system(&juniper::parse_braces("interfaces {\n    lo0;\n}\n")).is_none());
761    }
762}