Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: correctly apply configuration precedence in reverse parsing order #12

Merged
merged 3 commits into from
Dec 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions assets/ssh.config
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
# ssh config example

# Command line options, overriding host-specific options
Compression yes
ConnectionAttempts 10
ConnectTimeout 60
ServerAliveInterval 40
TcpKeepAlive yes

Ciphers aes128-ctr,aes192-ctr,aes256-ctr
KexAlgorithms diffie-hellman-group-exchange-sha256
MACs hmac-sha2-512,hmac-sha2-256,hmac-ripemd160

# Host configuration

Host 192.168.*.* 172.26.*.* !192.168.1.30
Expand All @@ -30,3 +27,8 @@ Host tostapane
Host 192.168.1.30
User nutellaro
RemoteForward 123

Host *
Ciphers aes128-ctr,aes192-ctr,aes256-ctr
KexAlgorithms diffie-hellman-group-exchange-sha256
MACs hmac-sha2-512,hmac-sha2-256,hmac-ripemd160
36 changes: 0 additions & 36 deletions src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
//!
//! Ssh host type

use std::cmp::Ordering;

use wildmatch::WildMatch;

use super::HostParams;
Expand Down Expand Up @@ -36,28 +34,6 @@ impl Host {
}
}

impl std::cmp::PartialOrd for Host {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
let self_max_pattern = self.pattern.iter().max_by(|x, y| x.cmp(y));
let other_max_pattern = other.pattern.iter().max_by(|x, y| x.cmp(y));
match (self_max_pattern, other_max_pattern) {
(Some(_self), Some(other)) => Some(_self.cmp(other)),
_ => None,
}
}
}

impl std::cmp::Ord for Host {
fn cmp(&self, other: &Self) -> Ordering {
let self_max_pattern = self.pattern.iter().max_by(|x, y| x.cmp(y));
let other_max_pattern = other.pattern.iter().max_by(|x, y| x.cmp(y));
match (self_max_pattern, other_max_pattern) {
(Some(_self), Some(other)) => _self.cmp(other),
_ => Ordering::Equal,
}
}
}

/// Describes a single clause to match host
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostClause {
Expand All @@ -77,18 +53,6 @@ impl HostClause {
}
}

impl std::cmp::PartialOrd for HostClause {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.pattern.cmp(&other.pattern))
}
}

impl std::cmp::Ord for HostClause {
fn cmp(&self, other: &Self) -> Ordering {
self.pattern.cmp(&other.pattern)
}
}

#[cfg(test)]
mod test {

Expand Down
43 changes: 13 additions & 30 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
//!
//! let config = SshConfig::default().parse(&mut reader, ParseRule::STRICT).expect("Failed to parse configuration");
//!
//! let default_params = config.default_params();
//! // Query parameters for your host
//! // If there's no rule for your host, default params are returned
//! let params = config.query("192.168.1.2");
Expand All @@ -69,30 +68,19 @@ pub use parser::{ParseRule, SshParserError, SshParserResult};

/// Describes the ssh configuration.
/// Configuration is describes in this document: <http://man.openbsd.org/OpenBSD-current/man5/ssh_config.5>
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SshConfig {
/// Rulesets for hosts.
/// Default config will be stored with key `*`
hosts: Vec<Host>,
}

impl Default for SshConfig {
fn default() -> Self {
Self {
hosts: vec![Host::new(
vec![HostClause::new(String::from("*"), false)],
HostParams::default(),
)],
}
}
}

impl SshConfig {
/// Query params for a certain host
pub fn query<S: AsRef<str>>(&self, host: S) -> HostParams {
let mut params = self.default_params();
// iter keys
for cfg_host in self.hosts.iter() {
let mut params = HostParams::default();
// iter keys, merge from lowest to highest precedence
for cfg_host in self.hosts.iter().rev() {
if cfg_host.intersects(host.as_ref()) {
params.merge(&cfg_host.params);
}
Expand All @@ -101,11 +89,6 @@ impl SshConfig {
params
}

/// Get default params
pub fn default_params(&self) -> HostParams {
self.hosts.get(0).map(|x| x.params.clone()).unwrap()
}

/// Parse stream and return parsed configuration or parser error
pub fn parse(mut self, reader: &mut impl BufRead, rules: ParseRule) -> SshParserResult<Self> {
parser::SshConfigParser::parse(&mut self, reader, rules).map(|_| self)
Expand Down Expand Up @@ -144,19 +127,19 @@ mod test {
#[test]
fn should_init_ssh_config() {
let config = SshConfig::default();
assert_eq!(config.hosts.len(), 1);
assert_eq!(config.default_params(), HostParams::default());
assert_eq!(config.hosts.len(), 0);
assert_eq!(config.query("192.168.1.2"), HostParams::default());
}

#[test]
#[cfg(target_family = "unix")]
fn should_parse_default_config() {
assert!(SshConfig::parse_default_file(ParseRule::ALLOW_UNKNOWN_FIELDS).is_ok());
fn should_parse_default_config() -> Result<(), parser::SshParserError> {
let _config = SshConfig::parse_default_file(ParseRule::ALLOW_UNKNOWN_FIELDS)?;
Ok(())
}

#[test]
fn should_parse_config() {
fn should_parse_config() -> Result<(), parser::SshParserError> {
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
Expand All @@ -166,9 +149,9 @@ mod test {
.expect("Could not open configuration file"),
);

assert!(SshConfig::default()
.parse(&mut reader, ParseRule::STRICT)
.is_ok());
SshConfig::default().parse(&mut reader, ParseRule::STRICT)?;

Ok(())
}

#[test]
Expand Down Expand Up @@ -203,6 +186,6 @@ mod test {
assert_eq!(config.query("192.168.10.1"), params1);
// Negated case
assert_eq!(config.query("172.26.254.1"), params3);
assert_eq!(config.query("172.26.104.4"), config.default_params());
assert_eq!(config.query("172.26.104.4"), HostParams::default());
}
}
Loading