Skip to content
Open
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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 11 additions & 20 deletions dsc/tests/dsc_sshdconfig.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,8 @@ metadata:
resources:
- name: sshdconfig
type: Microsoft.OpenSSH.SSHD/sshd_config
metadata:
filepath: $filepath
properties:
_filepath: $filepath
"@
}

Expand Down Expand Up @@ -64,15 +63,14 @@ metadata:
resources:
- name: sshdconfig
type: Microsoft.OpenSSH.SSHD/sshd_config
metadata:
filepath: $filepath
properties:
_filepath: $filepath
passwordauthentication: 'yes'
"@
$out = dsc config export -i "$export_yaml" | ConvertFrom-Json -Depth 10
$LASTEXITCODE | Should -Be 0
$out.resources.count | Should -Be 1
($out.resources[0].properties.psobject.properties | Measure-Object).count | Should -Be 1
($out.resources[0].properties.psobject.properties | Measure-Object).count | Should -Be 2
$out.resources[0].properties.passwordAuthentication | Should -Be $false
}

Expand All @@ -90,9 +88,8 @@ metadata:
resources:
- name: sshdconfig
type: Microsoft.OpenSSH.SSHD/sshd_config
metadata:
filepath: $filepath
properties:
_filepath: $filepath
_includeDefaults: $includeDefaults
"@
$out = dsc config $command -i "$input" | ConvertFrom-Json -Depth 10
Expand All @@ -104,7 +101,7 @@ resources:
$out.resources[0].properties._inheritedDefaults | Should -BeNullOrEmpty
} else {
$out.results.count | Should -Be 1
($out.results.result.actualState.psobject.properties | Measure-Object).count | Should -Be 2
($out.results.result.actualState.psobject.properties | Measure-Object).count | Should -Be 3
$out.results.result.actualState.loglevel | Should -Be 'debug3'
$out.results.result.actualState._inheritedDefaults | Should -BeNullOrEmpty
}
Expand Down Expand Up @@ -148,9 +145,8 @@ metadata:
resources:
- name: sshdconfig
type: Microsoft.OpenSSH.SSHD/sshd_config
metadata:
filepath: $filepath
properties:
_filepath: $filepath
_purge: true
port: 1234
allowUsers:
Expand Down Expand Up @@ -228,9 +224,8 @@ metadata:
resources:
- name: newsub
type: Microsoft.OpenSSH.SSHD/Subsystem
metadata:
filepath: $script:TestConfigPath
properties:
_filepath: $script:TestConfigPath
_exist: true
subsystem:
name: newsubsystem
Expand Down Expand Up @@ -260,9 +255,8 @@ metadata:
resources:
- name: removesub
type: Microsoft.OpenSSH.SSHD/Subsystem
metadata:
filepath: $script:TestConfigPath
properties:
_filepath: $script:TestConfigPath
_exist: false
subsystem:
name: sftp
Expand All @@ -286,9 +280,8 @@ metadata:
resources:
- name: multisubsystem
type: Microsoft.OpenSSH.SSHD/SubsystemList
metadata:
filepath: $script:TestConfigPath
properties:
_filepath: $script:TestConfigPath
_purge: false
subsystem:
- name: newsub1
Expand Down Expand Up @@ -331,9 +324,8 @@ metadata:
resources:
- name: preservesubsystem
type: Microsoft.OpenSSH.SSHD/SubsystemList
metadata:
filepath: $script:TestConfigPath
properties:
_filepath: $script:TestConfigPath
_purge: false
subsystem:
- name: addedSubsystem
Expand Down Expand Up @@ -367,9 +359,8 @@ metadata:
resources:
- name: purgesubsystem
type: Microsoft.OpenSSH.SSHD/SubsystemList
metadata:
filepath: $script:TestConfigPath
properties:
_filepath: $script:TestConfigPath
_purge: true
subsystem:
- name: sftp
Expand Down
10 changes: 5 additions & 5 deletions resources/sshdconfig/src/canonical_properties.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ use crate::error::SshdConfigError;
pub enum CanonicalProperty {
/// Boolean flag indicating if an entry should exist or be removed
Exist,
/// Path to the sshd_config file to be processed
Filepath,
/// Boolean flag to include default values in output
IncludeDefaults,
/// Contains SSH default values inherited from system
InheritedDefaults,
/// Metadata object containing filepath and other configuration info
Metadata,
/// Boolean flag indicating if non-specified entries should be removed
Purge,
}
Expand All @@ -28,9 +28,9 @@ impl CanonicalProperty {
pub const fn as_str(self) -> &'static str {
match self {
Self::Exist => "_exist",
Self::Filepath => "_filepath",
Self::IncludeDefaults => "_includeDefaults",
Self::InheritedDefaults => "_inheritedDefaults",
Self::Metadata => "_metadata",
Self::Purge => "_purge",
}
}
Expand All @@ -39,9 +39,9 @@ impl CanonicalProperty {
pub fn from_str(s: &str) -> Option<Self> {
match s {
"_exist" => Some(Self::Exist),
"_filepath" => Some(Self::Filepath),
"_includeDefaults" => Some(Self::IncludeDefaults),
"_inheritedDefaults" => Some(Self::InheritedDefaults),
"_metadata" => Some(Self::Metadata),
"_purge" => Some(Self::Purge),
_ => None,
}
Expand All @@ -51,9 +51,9 @@ impl CanonicalProperty {
pub const fn all() -> &'static [CanonicalProperty] {
&[
Self::Exist,
Self::Filepath,
Self::IncludeDefaults,
Self::InheritedDefaults,
Self::Metadata,
Self::Purge,
]
}
Expand Down
8 changes: 4 additions & 4 deletions resources/sshdconfig/src/get.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ fn get_default_shell() -> Result<(), SshdConfigError> {
///
/// # Arguments
///
/// * `cmd_info` - `CommandInfo` struct containing optional filters, metadata, and includeDefaults flag.
/// * `cmd_info` - `CommandInfo` struct containing optional filters, filepath, and includeDefaults flag.
///
/// # Errors
///
Expand All @@ -118,7 +118,7 @@ pub fn get_sshd_settings(cmd_info: &CommandInfo, is_get: bool) -> Result<Map<Str
let mut inherited_defaults: Vec<String> = Vec::new();

// parse settings from sshd_config file
let sshd_config_file = read_sshd_config(cmd_info.metadata.filepath.clone())?;
let sshd_config_file = read_sshd_config(cmd_info.filepath.clone())?;
Comment thread
tgauth marked this conversation as resolved.
let explicit_settings = parse_text_to_map(&sshd_config_file)?;

// handle special cases for keywords
Expand Down Expand Up @@ -163,8 +163,8 @@ pub fn get_sshd_settings(cmd_info: &CommandInfo, is_get: bool) -> Result<Map<Str
}
}

if cmd_info.metadata.filepath.is_some() {
result.insert(CanonicalProperty::Metadata.to_string(), serde_json::to_value(cmd_info.metadata.clone())?);
if cmd_info.filepath.is_some() {
result.insert(CanonicalProperty::Filepath.to_string(), serde_json::to_value(cmd_info.filepath.clone())?);
}
if cmd_info.include_defaults && is_get {
result.insert(CanonicalProperty::InheritedDefaults.to_string(), serde_json::to_value(inherited_defaults)?);
Expand Down
25 changes: 4 additions & 21 deletions resources/sshdconfig/src/inputs.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::path::PathBuf;
Expand All @@ -13,8 +12,8 @@ pub struct CommandInfo {
pub include_defaults: bool,
/// input provided with the command
pub input: Map<String, Value>,
/// metadata provided with the command
pub metadata: Metadata,
/// Filepath for the `sshd_config` file to be processed
pub filepath: Option<PathBuf>,
#[serde(rename = "_purge")]
pub purge: bool,
/// additional arguments for the call to sshd -T
Expand All @@ -26,7 +25,7 @@ impl CommandInfo {
pub fn new(
include_defaults: bool,
input: Map<String, Value>,
metadata: Metadata,
filepath: Option<PathBuf>,
purge: bool,
sshd_args: Option<SshdCommandArgs>
) -> Self {
Expand All @@ -38,29 +37,13 @@ impl CommandInfo {
Self {
include_defaults,
input,
metadata,
filepath,
purge,
sshd_args
}
}
}

#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub struct Metadata {
/// Filepath for the `sshd_config` file to be processed
#[serde(skip_serializing_if = "Option::is_none")]
pub filepath: Option<PathBuf>
}

impl Metadata {
/// Create a new `Metadata` instance.
pub fn new() -> Self {
Self {
filepath: None
}
}
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SshdCommandArgs {
/// the path to the `sshd_config` file to be processed
Expand Down
14 changes: 7 additions & 7 deletions resources/sshdconfig/src/repeat_keyword.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ use rust_i18n::t;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::path::PathBuf;

use crate::error::SshdConfigError;
use crate::inputs::Metadata;
// the multi-arg comma-separated and space-separated lists are mutually exclusive, but the repeatable list can overlap with either of them.
// the multi-arg lists are maintained for formatting arrays into the correct format when writing back to the config file.

Expand Down Expand Up @@ -86,9 +86,9 @@ pub struct RepeatInput {
/// Whether the entry should exist (true) or be removed (false)
#[serde(rename = "_exist", default = "default_true")]
pub exist: bool,
/// Metadata for the operation
#[serde(rename = "_metadata", skip_serializing_if = "Option::is_none")]
pub metadata: Option<Metadata>,
/// Path to the sshd_config file to be processed
#[serde(rename = "_filepath", skip_serializing_if = "Option::is_none")]
pub filepath: Option<PathBuf>,
/// The keyword and its entry (e.g., "subsystem": {"name": "sftp", "value": "/usr/bin/sftp"})
#[serde(flatten)]
pub additional_properties: Map<String, Value>,
Expand All @@ -100,9 +100,9 @@ pub struct RepeatListInput {
/// Whether to remove entries not in the input list
#[serde(rename = "_purge", default)]
pub purge: bool,
/// Metadata for the operation
#[serde(rename = "_metadata", skip_serializing_if = "Option::is_none")]
pub metadata: Option<Metadata>,
/// Path to the sshd_config file to be processed
#[serde(rename = "_filepath", skip_serializing_if = "Option::is_none")]
pub filepath: Option<PathBuf>,
/// The keyword and its array of entries (e.g., "subsystem": [{"name": "sftp", "value": "..."}])
#[serde(flatten)]
pub additional_properties: Map<String, Value>,
Expand Down
10 changes: 5 additions & 5 deletions resources/sshdconfig/src/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ fn set_sshd_config_repeat(input: &str, cmd_info: &CommandInfo) -> Result<Map<Str
remove_entry(&mut existing_config, &keyword, &entry.name);
}

write_and_validate_config(&mut existing_config, cmd_info.metadata.filepath.as_ref())?;
write_and_validate_config(&mut existing_config, cmd_info.filepath.as_ref())?;
Ok(Map::new())
}

Expand Down Expand Up @@ -120,7 +120,7 @@ fn set_sshd_config_repeat_list(input: &str, cmd_info: &CommandInfo) -> Result<Ma
add_or_update_entry(&mut existing_config, &keyword, &entry)?;
}
}
write_and_validate_config(&mut existing_config, cmd_info.metadata.filepath.as_ref())?;
write_and_validate_config(&mut existing_config, cmd_info.filepath.as_ref())?;
Ok(Map::new())
}

Expand Down Expand Up @@ -189,7 +189,7 @@ fn set_sshd_config(cmd_info: &mut CommandInfo) -> Result<(), SshdConfigError> {
let mut get_cmd_info = cmd_info.clone();
get_cmd_info.include_defaults = false;
get_cmd_info.input = Map::new();
ensure_sshd_config_exists(get_cmd_info.metadata.filepath.clone())?;
ensure_sshd_config_exists(get_cmd_info.filepath.clone())?;

let mut existing_config = get_sshd_settings(&get_cmd_info, true)?;
for (key, value) in &cmd_info.input {
Expand All @@ -202,7 +202,7 @@ fn set_sshd_config(cmd_info: &mut CommandInfo) -> Result<(), SshdConfigError> {
existing_config
};

write_and_validate_config(&mut config_to_write, cmd_info.metadata.filepath.as_ref())
write_and_validate_config(&mut config_to_write, cmd_info.filepath.as_ref())
}

/// Write configuration to file after validation.
Expand Down Expand Up @@ -274,6 +274,6 @@ fn get_existing_config(cmd_info: &CommandInfo) -> Result<Map<String, Value>, Ssh
let mut get_cmd_info = cmd_info.clone();
get_cmd_info.include_defaults = false;
get_cmd_info.input = Map::new();
ensure_sshd_config_exists(get_cmd_info.metadata.filepath.clone())?;
ensure_sshd_config_exists(get_cmd_info.filepath.clone())?;
get_sshd_settings(&get_cmd_info, false)
}
18 changes: 9 additions & 9 deletions resources/sshdconfig/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use tracing_subscriber::{EnvFilter, Layer, prelude::__tracing_subscriber_Subscri
use crate::args::{TraceFormat, TraceLevel};
use crate::canonical_properties::{CanonicalProperty, CanonicalProperties};
use crate::error::SshdConfigError;
use crate::inputs::{CommandInfo, Metadata, SshdCommandArgs};
use crate::inputs::{CommandInfo, SshdCommandArgs};
use crate::metadata::{SSHD_CONFIG_DEFAULT_PATH_UNIX, SSHD_CONFIG_DEFAULT_PATH_WINDOWS};
use crate::parser::parse_text_to_map;

Expand Down Expand Up @@ -246,14 +246,14 @@ pub fn extract_sshd_defaults() -> Result<Map<String, Value>, SshdConfigError> {
Ok(sshd_config)
}

/// Extract _metadata field from the input string, if it can be parsed as JSON.
/// Extract _filepath field from the input string, if it can be parsed as JSON.
///
/// # Errors
///
/// This function will return an error if it fails to parse the input string and if the _metadata field exists, extract it.
/// This function will return an error if it fails to parse the input string and if the _filepath field exists, extract it.
pub fn build_command_info(input: Option<&String>, is_get: bool) -> Result<CommandInfo, SshdConfigError> {
let mut include_defaults = is_get;
let mut metadata: Metadata = Metadata::new();
let mut filepath: Option<std::path::PathBuf> = None;
let mut purge = false;
let mut sshd_args: Option<SshdCommandArgs> = None;
let mut sshd_config: Map<String, Value> = Map::new();
Expand All @@ -262,14 +262,14 @@ pub fn build_command_info(input: Option<&String>, is_get: bool) -> Result<Comman
sshd_config = serde_json::from_str(inputs.as_str())?;
purge = CanonicalProperties::extract_bool(&mut sshd_config, CanonicalProperty::Purge, false)?;
include_defaults = CanonicalProperties::extract_bool(&mut sshd_config, CanonicalProperty::IncludeDefaults, is_get)?;
metadata = if let Some(value) = sshd_config.remove(CanonicalProperty::Metadata.as_str()) {
filepath = if let Some(value) = sshd_config.remove(CanonicalProperty::Filepath.as_str()) {
serde_json::from_value(value)?
} else {
Metadata::new()
None
};
sshd_args = metadata.filepath.clone().map(|filepath| {
sshd_args = filepath.clone().map(|fp| {
SshdCommandArgs {
filepath: Some(filepath),
filepath: Some(fp),
additional_args: None,
}
});
Expand All @@ -279,7 +279,7 @@ pub fn build_command_info(input: Option<&String>, is_get: bool) -> Result<Comman
}
}

Ok(CommandInfo::new(include_defaults, sshd_config, metadata, purge, sshd_args))
Ok(CommandInfo::new(include_defaults, sshd_config, filepath, purge, sshd_args))
}

/// Reads `sshd_config` file.
Expand Down
Loading
Loading