Skip to content
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
38 changes: 34 additions & 4 deletions IcingaForWindows.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ function New-ModuleBaseEnvironment()
'WorkerQueue' = $null;
};
'WebSocket' = [PSCustomObject]@{
'Config' = New-Object PSCustomObject; # Global config, containing all endpoints being loaded
'Config' = New-Object PSCustomObject; # Global config, containing all endpoints being loaded
<#
WebSocket example structure:
$WebSocketName = [PSCustomObject]@{
Expand Down Expand Up @@ -193,7 +193,8 @@ function New-ModuleBaseEnvironment()
'CurrentLoggingId' = (New-Guid);
};
'Icinga' = [PSCustomObject]@{
'CheckResult' = $null;
'CheckResult' = $null;
'ActiveCheckCommand' = $null;
};
};
'Protected' = [PSCustomObject]@{
Expand Down Expand Up @@ -233,6 +234,35 @@ function Get-ModuleCertificateDirectory()
return (Join-Path -Path $env:ProgramData -ChildPath (Join-Path -Path (Get-ModuleProjectName) -ChildPath 'Certificates'));
}

<#
.SYNOPSIS
Return the approved directory path for external check binaries and scripts

.DESCRIPTION
Get-ModuleBinaryDirectory resolves the dedicated Binaries subdirectory inside
the Icinga for Windows ProgramData root ($env:ProgramData\IcingaForWindows\Binaries
on Windows, or $env:HOME\ProgramData\IcingaForWindows\Binaries on Linux and
macOS). Resolve-IcingaProtocolCommand and Invoke-IcingaProtocolCheckCommand
restrict external binary and .ps1 script execution exclusively to this folder.

.OUTPUTS
System.String -- Full path to the Icinga for Windows Binaries directory.

.EXAMPLE
PS> Get-ModuleBinaryDirectory
C:\ProgramData\IcingaForWindows\Binaries

Returns the approved Icinga for Windows binaries directory path.

.NOTES
Created automatically during startup by New-ModuleConfigEnvironment and
whitelisted in Get-SecureChildItem.
#>
function Get-ModuleBinaryDirectory()
{
return (Join-Path -Path $env:ProgramData -ChildPath (Join-Path -Path (Get-ModuleProjectName) -ChildPath 'Binaries'));
}

<#
.SYNOPSIS
Build and compile the Icinga for Windows module project
Expand Down Expand Up @@ -277,7 +307,7 @@ function Build-ModuleProject()
[switch]$TestDaemonMemoryLeaks = $false
);

& (Join-Path -Path $PSScriptRoot -ChildPath 'build\Build-ModuleProject.ps1') -SkipTests:$SkipTests -GenerateDocs:$GenerateDocs -TestDaemonMemoryLeaks:$TestDaemonMemoryLeaks;
& (Join-Path -Path $PSScriptRoot -ChildPath (Join-Path -Path 'build' -ChildPath 'Build-ModuleProject.ps1')) -SkipTests:$SkipTests -GenerateDocs:$GenerateDocs -TestDaemonMemoryLeaks:$TestDaemonMemoryLeaks;
}

<#
Expand Down Expand Up @@ -316,7 +346,7 @@ function Invoke-IcingaModuleTests()
[string]$Path = $null
);

& (Join-Path -Path $PSScriptRoot -ChildPath 'build\Invoke-ModuleTests.ps1') -Path $Path;
& (Join-Path -Path $PSScriptRoot -ChildPath (Join-Path -Path 'build' -ChildPath 'Invoke-ModuleTests.ps1')) -Path $Path;
}

function Get-GlobalRuntimeVariable()
Expand Down
406 changes: 406 additions & 0 deletions Tests/ConvertFrom-IcingaProtocolMacros.Tests.ps1

Large diffs are not rendered by default.

73 changes: 73 additions & 0 deletions Tests/ConvertFrom-ModuleBoolean.Tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
$ModulePath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') -ChildPath 'IcingaForWindows.psd1';
if (-not (Get-Module -Name 'IcingaForWindows')) {
Import-Module -Name $ModulePath -Force -Global;
}

Describe 'ConvertFrom-ModuleBoolean' {
BeforeAll {
$script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All |
Where-Object { $_.ModuleType -eq 'Script' } |
Select-Object -First 1;

function Invoke-TestBoolConversion()
{
param (
[object]$InputValue = $null
);

return (& $script:IcingaModule {
param ($Val);
return (ConvertFrom-ModuleBoolean -Value $Val);
} $InputValue);
}
}

Context 'Native booleans, switches and null' {
It 'preserves native booleans and evaluates $null to $false' {
(Invoke-TestBoolConversion -InputValue $true) | Should -BeTrue;
(Invoke-TestBoolConversion -InputValue $false) | Should -BeFalse;
(Invoke-TestBoolConversion -InputValue $null) | Should -BeFalse;
}

It 'converts SwitchParameter values accurately' {
[switch]$PresentSwitch = $true;
[switch]$AbsentSwitch = $false;

(Invoke-TestBoolConversion -InputValue $PresentSwitch) | Should -BeTrue;
(Invoke-TestBoolConversion -InputValue $AbsentSwitch) | Should -BeFalse;
}
}

Context 'Numeric and string representations' {
It 'maps numeric 1 and truthy strings case-insensitively to $true' {
(Invoke-TestBoolConversion -InputValue 1) | Should -BeTrue;
(Invoke-TestBoolConversion -InputValue 1.0) | Should -BeTrue;
(Invoke-TestBoolConversion -InputValue 'true') | Should -BeTrue;
(Invoke-TestBoolConversion -InputValue 'TRUE') | Should -BeTrue;
(Invoke-TestBoolConversion -InputValue '1') | Should -BeTrue;
(Invoke-TestBoolConversion -InputValue 'yes') | Should -BeTrue;
(Invoke-TestBoolConversion -InputValue 'YES') | Should -BeTrue;
(Invoke-TestBoolConversion -InputValue '$true') | Should -BeTrue;
}

It 'maps numeric 0, empty strings and falsy strings to $false without PowerShell string-truthiness bugs' {
(Invoke-TestBoolConversion -InputValue 0) | Should -BeFalse;
(Invoke-TestBoolConversion -InputValue 0.0) | Should -BeFalse;
(Invoke-TestBoolConversion -InputValue 'false') | Should -BeFalse;
(Invoke-TestBoolConversion -InputValue 'False') | Should -BeFalse;
(Invoke-TestBoolConversion -InputValue '0') | Should -BeFalse;
(Invoke-TestBoolConversion -InputValue 'no') | Should -BeFalse;
(Invoke-TestBoolConversion -InputValue '$false') | Should -BeFalse;
(Invoke-TestBoolConversion -InputValue '') | Should -BeFalse;
(Invoke-TestBoolConversion -InputValue ' ') | Should -BeFalse;
}

It 'returns $false and logs StringToBoolConversionInvalidValue on unrecognized values' {
(Invoke-TestBoolConversion -InputValue 'not-a-bool') | Should -BeFalse;
(Invoke-TestBoolConversion -InputValue 42) | Should -BeFalse;
(Invoke-TestBoolConversion -InputValue -1) | Should -BeFalse;
(Invoke-TestBoolConversion -InputValue ([byte]1)) | Should -BeTrue;
(Invoke-TestBoolConversion -InputValue ([int64]0)) | Should -BeFalse;
}
}
}
78 changes: 78 additions & 0 deletions Tests/ConvertTo-IcingaSortedArray.Tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1';
if (-not (Get-Module -Name 'IcingaForWindows')) {
Import-Module -Name $ModulePath -Force -Global;
}

Describe 'ConvertTo-IcingaSortedArray' {
Context 'Natural order' {
It 'sorts processor instances numerically with the totals last' {
$Sorted = ConvertTo-IcingaSortedArray -InputObject @('0,10', '_Total', '1,0', '0,2', '0,_Total', '0,0');
$Sorted | Should -Be @('0,0', '0,2', '0,10', '0,_Total', '1,0', '_Total');
}

It 'compares digit runs by value and text case-insensitively' {
$Sorted = ConvertTo-IcingaSortedArray -InputObject @('core 10', 'Core 9', 'CORE 1', 'Core 01a');
$Sorted | Should -Be @('CORE 1', 'Core 01a', 'Core 9', 'core 10');
}

It 'compares numbers numerically and puts $null first' {
$Sorted = ConvertTo-IcingaSortedArray -InputObject @(10, 9, $null, 100);
$Sorted | Should -Be @($null, 9, 10, 100);
}

It 'sorts in descending order' {
$Sorted = ConvertTo-IcingaSortedArray -InputObject @('b', 'c', 'a') -Descending;
$Sorted | Should -Be @('c', 'b', 'a');
}
}

Context 'Properties' {
It 'sorts objects and hashtables by a property' {
$Objects = @([PSCustomObject]@{ 'Name' = 'Spooler'; }, [PSCustomObject]@{ 'Name' = 'AppInfo'; });
(ConvertTo-IcingaSortedArray -InputObject $Objects -Property 'Name').Name | Should -Be @('AppInfo', 'Spooler');

$Tables = @(@{ 'Name' = 'D:\'; }, @{ 'Name' = 'C:\'; });
(ConvertTo-IcingaSortedArray -InputObject $Tables -Property 'Name') | ForEach-Object { $_['Name'] } | Should -Be @('C:\', 'D:\');
}

It 'breaks ties with the next property' {
$Partitions = @(
@{ 'Disk' = 1; 'Partition' = 1; },
@{ 'Disk' = 0; 'Partition' = 2; },
@{ 'Disk' = 0; 'Partition' = 1; }
);
$Sorted = ConvertTo-IcingaSortedArray -InputObject $Partitions -Property 'Disk', 'Partition';
($Sorted | ForEach-Object { '{0}:{1}' -f $_['Disk'], $_['Partition'] }) | Should -Be @('0:1', '0:2', '1:1');
}

It 'keeps equal elements in input order' {
$Objects = @(
[PSCustomObject]@{ 'Key' = 'a'; 'Order' = 1; },
[PSCustomObject]@{ 'Key' = 'b'; 'Order' = 2; },
[PSCustomObject]@{ 'Key' = 'a'; 'Order' = 3; },
[PSCustomObject]@{ 'Key' = 'a'; 'Order' = 4; }
);
(ConvertTo-IcingaSortedArray -InputObject $Objects -Property 'Key').Order | Should -Be @(1, 3, 4, 2);
(ConvertTo-IcingaSortedArray -InputObject $Objects -Property 'Key' -Descending).Order | Should -Be @(2, 1, 3, 4);
}
}

Context 'Result shape' {
It 'returns a new array and leaves the input unchanged' {
$Input1 = @('b', 'a');
$Sorted = ConvertTo-IcingaSortedArray -InputObject $Input1;
$Sorted | Should -Be @('a', 'b');
$Input1 | Should -Be @('b', 'a');
}

It 'returns an array for a single element and an empty array for no element' {
$Single = ConvertTo-IcingaSortedArray -InputObject @('a');
($Single -is [array]) | Should -BeTrue;
$Single.Count | Should -Be 1;

$Empty = ConvertTo-IcingaSortedArray -InputObject @();
($Empty -is [array]) | Should -BeTrue;
$Empty.Count | Should -Be 0;
}
}
}
154 changes: 154 additions & 0 deletions Tests/ConvertTo-ModuleSecureString.Tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
$ModulePath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') -ChildPath 'IcingaForWindows.psd1';
if (-not (Get-Module -Name 'IcingaForWindows')) {
Import-Module -Name $ModulePath -Force -Global;
}

Describe 'ConvertTo-ModuleSecureString and Get-IcingaUnixTime' {
BeforeAll {
$script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All |
Where-Object { $_.ModuleType -eq 'Script' } |
Select-Object -First 1;

function ConvertFrom-TestSecureString()
{
param (
[System.Security.SecureString]$Secure = $null
);

if ($null -eq $Secure) {
return $null;
}

[System.IntPtr]$Ptr = [System.IntPtr]::Zero;
try {
$Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($Secure);
return [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr);
} finally {
if ($Ptr -ne [System.IntPtr]::Zero) {
[System.Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($Ptr);
}
}
}
}

Context 'ConvertTo-ModuleSecureString' {
It 'returns $null when InputObject is $null' {
$Result = & $script:IcingaModule { ConvertTo-ModuleSecureString -InputObject $null };
$Result | Should -BeNullOrEmpty;
}

It 'returns an empty read-only SecureString without throwing on empty string input' {
$Result = & $script:IcingaModule { ConvertTo-ModuleSecureString -InputObject '' };
($Result -is [System.Security.SecureString]) | Should -BeTrue;
$Result.IsReadOnly() | Should -BeTrue;
$Result.Length | Should -Be 0;
(ConvertFrom-TestSecureString -Secure $Result) | Should -Be '';
$Result.Dispose();
}

It 'converts plain-text strings and scalar inputs into a read-only SecureString' {
$Result = & $script:IcingaModule { ConvertTo-ModuleSecureString -InputObject 'S3cr3t!Pass#2026' };
$NumResult = & $script:IcingaModule { ConvertTo-ModuleSecureString -InputObject 98765 };
try {
($Result -is [System.Security.SecureString]) | Should -BeTrue;
$Result.IsReadOnly() | Should -BeTrue;
(ConvertFrom-TestSecureString -Secure $Result) | Should -Be 'S3cr3t!Pass#2026';
(ConvertFrom-TestSecureString -Secure $NumResult) | Should -Be '98765';
} finally {
$Result.Dispose();
$NumResult.Dispose();
}
}

It 'returns an existing SecureString instance unchanged' {
$Existing = & $script:IcingaModule { ConvertTo-ModuleSecureString -InputObject 'AlreadySecure' };
try {
$Returned = & $script:IcingaModule {
param ($Sec);
return (ConvertTo-ModuleSecureString -InputObject $Sec);
} $Existing;

[object]::ReferenceEquals($Existing, $Returned) | Should -BeTrue;
} finally {
$Existing.Dispose();
}
}

It 'emits SecureStringConversionFailed via Write-FunctionReturnValue and returns $null without throwing on oversized input' {
[string]$OversizedSecret = ('S' * 65537);
[hashtable]$FailureData = & $script:IcingaModule {
param ($BigInput);

$script:CapturedCodeKeys = @();
$RealReturnCmd = Get-Command -Name 'Write-FunctionReturnValue' -CommandType Function;

function Write-FunctionReturnValue()
{
param (
[string]$ReturnValue = $null,
[hashtable]$Data = @{ },
$OverrideReturn = 'Core::IgnoreOverride',
[switch]$AutomationRun = $false
);

$script:CapturedCodeKeys += $ReturnValue;
return (& $RealReturnCmd -ReturnValue $ReturnValue -Data $Data -OverrideReturn $OverrideReturn -AutomationRun:$AutomationRun);
}

$Converted = ConvertTo-ModuleSecureString -InputObject $BigInput;

function Invoke-IcingaCheckMockOversizedSecret()
{
param (
[securestring]$Password = $null
);

return 0;
}

$CheckRes = Invoke-IcingaProtocolCheckCommand -Params @{
'command' = 'Invoke-IcingaCheckMockOversizedSecret';
'macros' = @{
'ifw_api_command' = 'Invoke-IcingaCheckMockOversizedSecret';
'ifw_api_arguments' = @{
'Password' = @{ 'value' = $BigInput; };
};
};
};

return @{
'Converted' = $Converted;
'CapturedKeys' = $script:CapturedCodeKeys;
'CheckExitCode' = $CheckRes['ExitCode'];
'CheckOutput' = $CheckRes['Output'];
'CommandLine' = $CheckRes['CommandLine'];
};
} $OversizedSecret;

$FailureData['Converted'] | Should -BeNullOrEmpty;
$FailureData['CapturedKeys'] | Should -Contain 'SecureStringConversionFailed';
$FailureData['CapturedKeys'] | Should -Contain 'IcingaProtocolMacroMappingFailed';
$FailureData['CheckExitCode'] | Should -Be 3;
$FailureData['CheckOutput'] | Should -Match '\[UNKNOWN\]';
$FailureData['CommandLine'] | Should -Not -Match 'SSSSSS';
}
}

Context 'Get-IcingaUnixTime' {
It 'returns UTC Unix seconds without local timezone drift' {
[int]$Expected = [int][System.DateTimeOffset]::UtcNow.ToUnixTimeSeconds();
$Actual = Get-IcingaUnixTime;

($Actual -is [int]) | Should -BeTrue;
[System.Math]::Abs($Actual - $Expected) | Should -BeLessOrEqual 2;
}

It 'returns fractional UTC Unix seconds as Double when -Milliseconds is set' {
[double]$Expected = [double]([System.DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() / 1000.0);
$Actual = Get-IcingaUnixTime -Milliseconds;

($Actual -is [double]) | Should -BeTrue;
[System.Math]::Abs($Actual - $Expected) | Should -BeLessOrEqual 2.0;
}
}
}
Loading
Loading