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
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:
sshd_config_filepath: $filepath
"@
}

Expand Down Expand Up @@ -64,15 +63,14 @@ metadata:
resources:
- name: sshdconfig
type: Microsoft.OpenSSH.SSHD/sshd_config
metadata:
filepath: $filepath
properties:
sshd_config_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:
sshd_config_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:
sshd_config_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:
sshd_config_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:
sshd_config_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:
sshd_config_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:
sshd_config_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:
sshd_config_filepath: $script:TestConfigPath
_purge: true
subsystem:
- name: sftp
Expand Down
5 changes: 0 additions & 5 deletions resources/sshdconfig/src/canonical_properties.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ pub enum CanonicalProperty {
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 @@ -30,7 +28,6 @@ impl CanonicalProperty {
Self::Exist => "_exist",
Self::IncludeDefaults => "_includeDefaults",
Self::InheritedDefaults => "_inheritedDefaults",
Self::Metadata => "_metadata",
Self::Purge => "_purge",
}
}
Expand All @@ -41,7 +38,6 @@ impl CanonicalProperty {
"_exist" => Some(Self::Exist),
"_includeDefaults" => Some(Self::IncludeDefaults),
"_inheritedDefaults" => Some(Self::InheritedDefaults),
"_metadata" => Some(Self::Metadata),
"_purge" => Some(Self::Purge),
_ => None,
}
Expand All @@ -53,7 +49,6 @@ impl CanonicalProperty {
Self::Exist,
Self::IncludeDefaults,
Self::InheritedDefaults,
Self::Metadata,
Self::Purge,
]
}
Expand Down
10 changes: 5 additions & 5 deletions resources/sshdconfig/src/get.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use tracing::{debug, trace, warn};
use crate::args::Setting;
use crate::canonical_properties::CanonicalProperty;
use crate::error::SshdConfigError;
use crate::inputs::CommandInfo;
use crate::inputs::{CommandInfo, SSHD_CONFIG_FILEPATH};
use crate::parser::parse_text_to_map;
use crate::util::{
build_command_info,
Expand Down 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(SSHD_CONFIG_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
31 changes: 10 additions & 21 deletions resources/sshdconfig/src/inputs.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
// 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;

/// Property key for the `sshd_config` file path.
///
/// This is a regular resource property (not a leading-underscore canonical
/// property) used to specify the path to the `sshd_config` file to process.
pub const SSHD_CONFIG_FILEPATH: &str = "sshd_config_filepath";

#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CommandInfo {
/// Switch to include defaults in the output
#[serde(rename = "_includeDefaults")]
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 +31,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 +43,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 = "sshd_config_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 = "sshd_config_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
13 changes: 7 additions & 6 deletions resources/sshdconfig/src/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use crate::canonical_properties::CanonicalProperties;
use crate::error::SshdConfigError;
use crate::formatter::write_config_map_to_text;
use crate::get::get_sshd_settings;
use crate::inputs::{CommandInfo, SshdCommandArgs};
use crate::inputs::{CommandInfo, SshdCommandArgs, SSHD_CONFIG_FILEPATH};
use crate::metadata::{SSHD_CONFIG_HEADER, SSHD_CONFIG_HEADER_VERSION, SSHD_CONFIG_HEADER_WARNING};
use crate::repeat_keyword::{
RepeatInput, RepeatListInput, NameValueEntry,
Expand Down 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,13 +202,14 @@ 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.
fn write_and_validate_config(config: &mut Map<String, Value>, filepath: Option<&PathBuf>) -> Result<(), SshdConfigError> {
debug!("{}", t!("set.writingTempConfig"));
CanonicalProperties::remove_all(config);
config.remove(SSHD_CONFIG_FILEPATH);
let mut config_text = SSHD_CONFIG_HEADER.to_string() + "\n" + SSHD_CONFIG_HEADER_VERSION + "\n" + SSHD_CONFIG_HEADER_WARNING + "\n";
config_text.push_str(&write_config_map_to_text(config)?);

Expand Down Expand Up @@ -274,6 +275,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)
}
Loading
Loading