asterust-junos 0.1.1

Typed Juniper JunOS config views (interfaces, OSPF, BGP, IS-IS, routing instances, policy options, firewall filters, system) extracted from an asterust config tree.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! `system { ... }`.

use crate::{
    active_children, arg_of, args_of, child_block, first_word, has_leaf, list_values, named_children, split_name,
    top_level, unquote,
};
use asterust::config::{Config, ConfigLine};

/// A DNS server from `name-server`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct NameServer {
    pub address: String,
    /// Set when the server is reached through a routing instance such as `mgmt_junos`.
    pub routing_instance: Option<String>,
}

/// A `server` or `peer` entry under `ntp`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct NtpHost {
    /// Address or hostname.
    pub address: String,
    /// Authentication key number.
    pub key: Option<String>,
    pub prefer: bool,
    pub version: Option<String>,
    pub routing_instance: Option<String>,
}

/// An `authentication-key`. The key value is not extracted.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct NtpAuthenticationKey {
    pub number: String,
    /// `md5`, `sha1` or `sha256`.
    pub key_type: Option<String>,
}

/// The `system ntp` configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Ntp {
    pub boot_server: Option<String>,
    pub servers: Vec<NtpHost>,
    pub peers: Vec<NtpHost>,
    pub source_address: Option<String>,
    pub trusted_keys: Vec<String>,
    pub authentication_keys: Vec<NtpAuthenticationKey>,
    pub broadcast_client: bool,
}

/// A `<facility> <severity>` line selecting which messages go to a syslog destination.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SyslogRule {
    /// e.g. `"any"`, `"authorization"`, `"interactive-commands"`.
    pub facility: String,
    /// e.g. `"info"`, `"notice"`, `"any"`, `"none"`.
    pub severity: String,
}

/// A `host <address>` destination.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SyslogHost {
    /// Address, hostname, or `other-routing-engine`.
    pub address: String,
    pub rules: Vec<SyslogRule>,
    pub port: Option<String>,
    pub source_address: Option<String>,
    pub routing_instance: Option<String>,
    pub facility_override: Option<String>,
    pub log_prefix: Option<String>,
}

/// A `file <name>` or `user <name>` destination.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SyslogTarget {
    /// File name, or user name (`*` for all users).
    pub name: String,
    pub rules: Vec<SyslogRule>,
}

/// The `system syslog` configuration. Archive settings are not extracted.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Syslog {
    pub hosts: Vec<SyslogHost>,
    pub files: Vec<SyslogTarget>,
    pub users: Vec<SyslogTarget>,
    pub console: Vec<SyslogRule>,
    pub source_address: Option<String>,
    /// e.g. `"year millisecond"`.
    pub time_format: Option<String>,
}

/// The top-level `system` configuration.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct System {
    pub host_name: Option<String>,
    pub name_servers: Vec<NameServer>,
    pub ntp: Option<Ntp>,
    pub syslog: Option<Syslog>,
}

/// The top-level `system` block, or `None` if there is none.
pub fn system(config: &Config) -> Option<System> {
    let system = top_level(config, "system")?;
    Some(System {
        host_name: arg_of(system, "host-name").map(str::to_string),
        name_servers: name_servers(system),
        ntp: child_block(system, "ntp").map(parse_ntp),
        syslog: child_block(system, "syslog").map(parse_syslog),
    })
}

fn parse_syslog(syslog: &ConfigLine) -> Syslog {
    Syslog {
        hosts: named_children(syslog, "host")
            .map(|(address, host)| SyslogHost {
                address: address.to_string(),
                rules: syslog_rules(host),
                port: arg_of(host, "port").map(str::to_string),
                source_address: arg_of(host, "source-address").map(str::to_string),
                routing_instance: arg_of(host, "routing-instance").map(str::to_string),
                facility_override: arg_of(host, "facility-override").map(str::to_string),
                log_prefix: arg_of(host, "log-prefix").map(str::to_string),
            })
            .collect(),
        files: syslog_targets(syslog, "file"),
        users: syslog_targets(syslog, "user"),
        console: child_block(syslog, "console").map(syslog_rules).unwrap_or_default(),
        source_address: arg_of(syslog, "source-address").map(str::to_string),
        time_format: arg_of(syslog, "time-format").map(str::to_string),
    }
}

fn syslog_targets(syslog: &ConfigLine, keyword: &str) -> Vec<SyslogTarget> {
    named_children(syslog, keyword)
        .map(|(name, target)| SyslogTarget {
            name: name.to_string(),
            rules: syslog_rules(target),
        })
        .collect()
}

/// Children written `<facility> <severity>`, which tells them apart from options such as `port 514`.
fn syslog_rules(destination: &ConfigLine) -> Vec<SyslogRule> {
    const SEVERITIES: [&str; 10] = [
        "any",
        "none",
        "emergency",
        "alert",
        "critical",
        "error",
        "warning",
        "notice",
        "info",
        "debug",
    ];
    active_children(destination)
        .filter_map(|c| {
            let (facility, severity) = c.text.split_once(' ')?;
            SEVERITIES.contains(&severity).then(|| SyslogRule {
                facility: facility.to_string(),
                severity: severity.to_string(),
            })
        })
        .collect()
}

fn parse_ntp(ntp: &ConfigLine) -> Ntp {
    let hosts = |keyword: &str| -> Vec<NtpHost> {
        active_children(ntp)
            .filter_map(|c| Some(ntp_host(c.arg(keyword)?, c)))
            .collect()
    };
    Ntp {
        boot_server: arg_of(ntp, "boot-server").map(str::to_string),
        servers: hosts("server"),
        peers: hosts("peer"),
        source_address: arg_of(ntp, "source-address").and_then(first_word).map(str::to_string),
        trusted_keys: args_of(ntp, "trusted-key").into_iter().flat_map(list_values).collect(),
        authentication_keys: args_of(ntp, "authentication-key")
            .into_iter()
            .filter_map(ntp_authentication_key)
            .collect(),
        broadcast_client: has_leaf(ntp, "broadcast-client"),
    }
}

/// A host written `<address> [key n] [prefer] [version n] [routing-instance x]`, with the options on the line
/// or in a block.
fn ntp_host(arg: &str, line: &ConfigLine) -> NtpHost {
    let (address, options) = split_name(arg);
    let mut words = options.split_whitespace();
    let mut host = NtpHost {
        address: address.to_string(),
        key: arg_of(line, "key").map(str::to_string),
        prefer: has_leaf(line, "prefer"),
        version: arg_of(line, "version").map(str::to_string),
        routing_instance: arg_of(line, "routing-instance").map(str::to_string),
    };
    while let Some(word) = words.next() {
        match word {
            "prefer" => host.prefer = true,
            "key" => host.key = words.next().map(str::to_string),
            "version" => host.version = words.next().map(str::to_string),
            "routing-instance" => host.routing_instance = words.next().map(str::to_string),
            _ => {}
        }
    }
    host
}

/// `<number> type <type> value <secret>`; the secret is dropped.
fn ntp_authentication_key(arg: &str) -> Option<NtpAuthenticationKey> {
    let mut words = arg.split_whitespace();
    let number = words.next()?.to_string();
    let key_type = words.skip_while(|w| *w != "type").nth(1).map(str::to_string);
    Some(NtpAuthenticationKey { number, key_type })
}

/// Servers written as a `name-server { <address>; ... }` block, or one per `name-server <address>` line.
fn name_servers(system: &ConfigLine) -> Vec<NameServer> {
    let mut found = Vec::new();
    for child in active_children(system) {
        if child.text == "name-server" {
            found.extend(active_children(child).map(|server| name_server(&server.text, server)));
        } else if let Some(address) = child.arg("name-server") {
            found.push(name_server(address, child));
        }
    }
    found
}

fn name_server(address: &str, line: &ConfigLine) -> NameServer {
    NameServer {
        address: unquote(address).to_string(),
        routing_instance: arg_of(line, "routing-instance").map(str::to_string),
    }
}

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

    // Not from documentation: written from the CLI Reference syntax pages. See the README "Sources".
    #[test]
    fn extracts_host_name() {
        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
        assert_eq!(system.host_name.as_deref(), Some("pe1"));
    }

    #[test]
    fn host_name_is_optional() {
        let system = system(&juniper::parse_braces("system {\n    domain-name example.net;\n}\n")).unwrap();
        assert_eq!(system.host_name, None);
    }

    #[test]
    fn skips_inactive_host_name() {
        let system = system(&juniper::parse_braces("system {\n    inactive: host-name pe1;\n}\n")).unwrap();
        assert_eq!(system.host_name, None);
    }

    #[test]
    fn extracts_name_server_block() {
        let system = system(&juniper::parse_braces(
            "system {\n    name-server {\n        192.0.2.53;\n        2001:db8::53;\n    }\n}\n",
        ))
        .unwrap();
        let addresses: Vec<_> = system.name_servers.iter().map(|s| s.address.as_str()).collect();
        assert_eq!(addresses, ["192.0.2.53", "2001:db8::53"]);
        assert_eq!(system.name_servers[0].routing_instance, None);
    }

    #[test]
    fn name_server_in_management_instance() {
        let system = system(&juniper::parse_braces(
            "system {\n    name-server {\n        192.0.2.53 {\n            routing-instance mgmt_junos;\n        }\n    }\n}\n",
        ))
        .unwrap();
        assert_eq!(system.name_servers[0].address, "192.0.2.53");
        assert_eq!(system.name_servers[0].routing_instance.as_deref(), Some("mgmt_junos"));
    }

    #[test]
    fn extracts_one_line_name_servers_and_skips_inactive() {
        let system = system(&juniper::parse_braces(
            "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",
        ))
        .unwrap();
        let addresses: Vec<_> = system.name_servers.iter().map(|s| s.address.as_str()).collect();
        assert_eq!(addresses, ["192.0.2.53", "192.0.2.54"]);
    }

    const NTP: &str = r#"
system {
    ntp {
        boot-server 192.0.2.10;
        source-address 192.0.2.1;
        authentication-key 1 type md5 value "$9$secret";
        authentication-key 2 type sha256 value "$9$other";
        trusted-key [ 1 2 ];
        server 192.0.2.10 key 1 prefer version 4;
        server 192.0.2.11;
        server ntp.example.net {
            key 2;
            prefer;
            version 3;
            routing-instance mgmt_junos;
        }
        inactive: server 192.0.2.12;
        peer 192.0.2.20 key 1;
        broadcast-client;
    }
}
"#;

    #[test]
    fn extracts_ntp_servers_in_line_and_block_form() {
        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
        let addresses: Vec<_> = ntp.servers.iter().map(|s| s.address.as_str()).collect();
        assert_eq!(addresses, ["192.0.2.10", "192.0.2.11", "ntp.example.net"]);

        let line = &ntp.servers[0];
        assert_eq!(line.key.as_deref(), Some("1"));
        assert!(line.prefer);
        assert_eq!(line.version.as_deref(), Some("4"));

        assert_eq!(ntp.servers[1].key, None);
        assert!(!ntp.servers[1].prefer);

        let block = &ntp.servers[2];
        assert_eq!(block.key.as_deref(), Some("2"));
        assert!(block.prefer);
        assert_eq!(block.version.as_deref(), Some("3"));
        assert_eq!(block.routing_instance.as_deref(), Some("mgmt_junos"));
    }

    #[test]
    fn extracts_ntp_peers_keys_and_global_settings() {
        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
        assert_eq!(ntp.peers.len(), 1);
        assert_eq!(ntp.peers[0].address, "192.0.2.20");
        assert_eq!(ntp.peers[0].key.as_deref(), Some("1"));
        assert_eq!(ntp.boot_server.as_deref(), Some("192.0.2.10"));
        assert_eq!(ntp.source_address.as_deref(), Some("192.0.2.1"));
        assert_eq!(ntp.trusted_keys, ["1", "2"]);
        assert!(ntp.broadcast_client);
    }

    #[test]
    fn ntp_authentication_keys_omit_the_secret() {
        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
        assert_eq!(ntp.authentication_keys.len(), 2);
        assert_eq!(ntp.authentication_keys[0].number, "1");
        assert_eq!(ntp.authentication_keys[0].key_type.as_deref(), Some("md5"));
        assert_eq!(ntp.authentication_keys[1].key_type.as_deref(), Some("sha256"));
    }

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

    const SYSLOG: &str = r#"
system {
    syslog {
        user * {
            any emergency;
        }
        host 192.0.2.5 {
            any notice;
            authorization info;
            port 514;
            source-address 192.0.2.1;
            routing-instance mgmt_junos;
            facility-override local3;
            log-prefix pe1;
        }
        host other-routing-engine {
            any critical;
        }
        file messages {
            any notice;
            authorization info;
            explicit-priority;
        }
        file interactive-commands {
            interactive-commands any;
        }
        inactive: file debug {
            any debug;
        }
        console {
            any critical;
        }
        source-address 192.0.2.1;
        time-format year millisecond;
    }
}
"#;

    #[test]
    fn extracts_syslog_hosts() {
        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
        let addresses: Vec<_> = syslog.hosts.iter().map(|h| h.address.as_str()).collect();
        assert_eq!(addresses, ["192.0.2.5", "other-routing-engine"]);

        let host = &syslog.hosts[0];
        assert_eq!(host.rules.len(), 2);
        assert_eq!(host.rules[1].facility, "authorization");
        assert_eq!(host.rules[1].severity, "info");
        assert_eq!(host.port.as_deref(), Some("514"));
        assert_eq!(host.source_address.as_deref(), Some("192.0.2.1"));
        assert_eq!(host.routing_instance.as_deref(), Some("mgmt_junos"));
        assert_eq!(host.facility_override.as_deref(), Some("local3"));
        assert_eq!(host.log_prefix.as_deref(), Some("pe1"));
    }

    #[test]
    fn extracts_syslog_files_users_and_console() {
        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();

        let files: Vec<_> = syslog.files.iter().map(|f| f.name.as_str()).collect();
        assert_eq!(files, ["messages", "interactive-commands"]);
        // `explicit-priority` is an option, not a facility/severity rule.
        assert_eq!(syslog.files[0].rules.len(), 2);
        assert_eq!(syslog.files[1].rules[0].facility, "interactive-commands");
        assert_eq!(syslog.files[1].rules[0].severity, "any");

        assert_eq!(syslog.users[0].name, "*");
        assert_eq!(syslog.users[0].rules[0].severity, "emergency");
        assert_eq!(syslog.console[0].facility, "any");
        assert_eq!(syslog.console[0].severity, "critical");
    }

    #[test]
    fn extracts_syslog_global_settings() {
        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
        assert_eq!(syslog.source_address.as_deref(), Some("192.0.2.1"));
        assert_eq!(syslog.time_format.as_deref(), Some("year millisecond"));
    }

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

    #[test]
    fn no_system_is_none() {
        assert!(system(&juniper::parse_braces("interfaces {\n    lo0;\n}\n")).is_none());
    }
}