From a439e09b69ea7c607911e9f50499cd58ef901d70 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sat, 21 Nov 2026 16:56:47 +0000 Subject: [PATCH 1/2] feat(ad): add modular cached LDAP query API --- powershell/Maester.psd1 | 3 + .../services/ad/Complete-MtADQueryRange.ps1 | 50 +++ .../ad/ConvertFrom-MtADQueryEntry.ps1 | 83 +++++ .../services/ad/Copy-MtADQueryResult.ps1 | 26 ++ .../services/ad/Get-MtADQueryDefinition.ps1 | 18 + .../services/ad/Invoke-MtADQueryCached.ps1 | 86 +++++ .../services/ad/Resolve-MtADQuery.ps1 | 19 + .../ad/protocol/Invoke-MtLdapSearch.ps1 | 33 +- .../ad/ConvertTo-MtLdapFilterValue.ps1 | 46 +++ .../public/services/ad/Invoke-MtADQuery.ps1 | 102 ++++++ .../public/services/ad/New-MtADQuery.ps1 | 92 +++++ .../functions/ADQueryTransport.Tests.ps1 | 327 +++++++++++++++++ .../functions/Invoke-MtADQuery.Tests.ps1 | 340 ++++++++++++++++++ website/astro.config.mjs | 3 +- website/docs/advanced/ad-query-collection.md | 150 ++++++++ 15 files changed, 1375 insertions(+), 3 deletions(-) create mode 100644 powershell/internal/services/ad/Complete-MtADQueryRange.ps1 create mode 100644 powershell/internal/services/ad/ConvertFrom-MtADQueryEntry.ps1 create mode 100644 powershell/internal/services/ad/Copy-MtADQueryResult.ps1 create mode 100644 powershell/internal/services/ad/Get-MtADQueryDefinition.ps1 create mode 100644 powershell/internal/services/ad/Invoke-MtADQueryCached.ps1 create mode 100644 powershell/internal/services/ad/Resolve-MtADQuery.ps1 create mode 100644 powershell/public/services/ad/ConvertTo-MtLdapFilterValue.ps1 create mode 100644 powershell/public/services/ad/Invoke-MtADQuery.ps1 create mode 100644 powershell/public/services/ad/New-MtADQuery.ps1 create mode 100644 powershell/tests/functions/ADQueryTransport.Tests.ps1 create mode 100644 powershell/tests/functions/Invoke-MtADQuery.Tests.ps1 create mode 100644 website/docs/advanced/ad-query-collection.md diff --git a/powershell/Maester.psd1 b/powershell/Maester.psd1 index 4a24c9eed2..b03042a465 100644 --- a/powershell/Maester.psd1 +++ b/powershell/Maester.psd1 @@ -76,6 +76,7 @@ 'ConvertFrom-MailAuthenticationRecordDmarc', 'ConvertFrom-MailAuthenticationRecordMx', 'ConvertFrom-MailAuthenticationRecordSpf', + 'ConvertTo-MtLdapFilterValue', 'Disconnect-Maester', 'Disconnect-MtGitHub', 'Get-MailAuthenticationRecord', @@ -113,12 +114,14 @@ 'Install-MaesterTests', 'Install-MtPack', 'Invoke-Maester', + 'Invoke-MtADQuery', 'Invoke-MtAzureRequest', 'Invoke-MtAzureResourceGraphRequest', 'Invoke-MtGraphRequest', 'Invoke-MtGraphSecurityQuery', 'Invoke-MtTest', 'Merge-MtMaesterResult', + 'New-MtADQuery', 'New-MtMaesterApp', 'New-MtPack', 'New-MtTest', diff --git a/powershell/internal/services/ad/Complete-MtADQueryRange.ps1 b/powershell/internal/services/ad/Complete-MtADQueryRange.ps1 new file mode 100644 index 0000000000..8f30239a97 --- /dev/null +++ b/powershell/internal/services/ad/Complete-MtADQueryRange.ps1 @@ -0,0 +1,50 @@ +function Complete-MtADQueryRange { + [CmdletBinding()] + param( + [Parameter(Mandatory)] [System.DirectoryServices.Protocols.LdapConnection] $Connection, + [Parameter(Mandatory)] [object] $Entry, + [Parameter(Mandatory)] [timespan] $Timeout + ) + + foreach ($key in @($Entry.Attributes.Keys)) { + if ($key -notmatch ';') { continue } + if ($key -notmatch '^([A-Za-z][A-Za-z0-9-]*);range=(\d+)-(\d+|\*)$') { + throw 'LDAP returned an unsupported attribute option.' + } + $attribute = $matches[1] + $values = [System.Collections.Generic.List[object]]::new() + $expectedStart = 0L + $rangeKey = $key + $rangeBag = $Entry.Attributes + if ($Entry.Attributes.Contains($attribute)) { throw 'LDAP returned ambiguous ranged and non-ranged values.' } + + while ($true) { + if ($rangeKey -notmatch ('^' + [regex]::Escape($attribute) + ';range=(\d+)-(\d+|\*)$')) { + throw 'LDAP returned an invalid attribute range.' + } + $start = [long]$matches[1] + $end = $matches[2] + if ($start -ne $expectedStart) { throw 'LDAP attribute range was not contiguous.' } + $chunk = $rangeBag[$rangeKey] + if ($end -ne '*' -and ([long]$end -lt $start -or $chunk.Count -ne ([long]$end - $start + 1))) { + throw 'LDAP attribute range length did not match its bounds.' + } + foreach ($value in $chunk) { $values.Add($value) } + if ($end -eq '*') { break } + $expectedStart = [long]$end + 1 + $continuation = @(Invoke-MtLdapSearch -Connection $Connection -SearchBase $Entry.DistinguishedName -Scope Base ` + -Filter '(objectClass=*)' -Attributes @("$attribute`;range=$expectedStart-*") -PageSize 0 ` + -Timeout $Timeout -AsAttributeBag -RequireComplete) + if ($continuation.Count -ne 1 -or $continuation[0].DistinguishedName -ine $Entry.DistinguishedName) { + throw 'LDAP attribute range continuation did not return the original entry.' + } + $rangeBag = $continuation[0].Attributes + $rangeKeys = @($rangeBag.Keys | Where-Object { $_ -like "$attribute`;range=*" }) + if ($rangeKeys.Count -ne 1) { throw 'LDAP attribute range continuation was missing or ambiguous.' } + $rangeKey = $rangeKeys[0] + } + $Entry.Attributes.Remove($key) + $Entry.Attributes[$attribute] = [object[]]$values.ToArray() + } + return $Entry +} diff --git a/powershell/internal/services/ad/ConvertFrom-MtADQueryEntry.ps1 b/powershell/internal/services/ad/ConvertFrom-MtADQueryEntry.ps1 new file mode 100644 index 0000000000..9515e78bad --- /dev/null +++ b/powershell/internal/services/ad/ConvertFrom-MtADQueryEntry.ps1 @@ -0,0 +1,83 @@ +function ConvertFrom-MtADQueryEntry { + [CmdletBinding()] + param( + [Parameter(Mandatory)] [object] $Entry, + [Parameter(Mandatory)] [string[]] $Attributes + ) + + $bag = [ordered]@{} + $requestedNames = @($Attributes | ForEach-Object { ($_ -split ';')[0].ToLowerInvariant() }) + $utf8 = [System.Text.UTF8Encoding]::new($false, $true) + # DirectoryAttribute enumeration exposes the server's bytes, even for textual values. + # Decode by known attribute semantics, never by whether unknown bytes happen to be valid UTF-8. + $textNames = @( + 'name', 'cn', 'samaccountname', 'displayname', 'dnshostname', 'description', 'member', 'memberof', + 'gplink', 'gpcfilesyspath', 'ldapdisplayname', 'serviceprincipalname', 'objectclass', 'distinguishedname', + 'defaultnamingcontext', 'configurationnamingcontext', 'schemanamingcontext', 'rootdomainnamingcontext', + 'namingcontexts', 'supportedldapversion', 'supportedsaslmechanisms', 'supportedcontrol', + 'operatingsystem', 'operatingsystemversion', 'managedby', 'manager', 'homedirectory', 'profilepath', + 'scriptpath', 'userworkstations', 'location', 'dnsroot', 'ncname', 'netbiosname', 'trustpartner', + 'fsmoroleowner', 'serverreference', 'fromserver', 'transporttype', 'siteobject', 'gpcwqlfilter', + 'msds-allowedtodelegateto', 'msds-psoappliesto' + ) + $fileTimeNames = @('accountexpires', 'badpasswordtime', 'lastlogoff', 'lastlogon', 'lastlogontimestamp', 'pwdlastset') + $convertedNames = @( + 'useraccountcontrol', 'forestfunctionality', 'domainfunctionality', 'ms-ds-machineaccountquota', + 'lockoutthreshold', 'minpwdlength', 'pwdproperties', 'pwdhistorylength', 'objectversion', + 'msds-behavior-version', 'primarygroupid', 'admincount', 'grouptype', 'options', 'trusttype', + 'trustdirection', 'trustattributes', 'gpoptions', 'flags', 'versionnumber', 'msds-passwordsettingsprecedence', + 'msds-lockoutthreshold', 'msds-minimumpasswordlength', 'msds-passwordhistorylength', + 'msds-requiredforestbehaviorversion', 'tombstonelifetime', 'iscriticalsystemobject', 'enabledconnection', + 'msds-passwordcomplexityenabled', 'msds-isrodc', 'maxpwdage', 'minpwdage', 'lockoutduration', + 'msds-lockoutduration', 'msds-maximumpasswordage', 'msds-minimumpasswordage', + 'whencreated', 'whenchanged', 'createtimestamp', 'modifytimestamp' + ) + $fileTimeNames + $names = if ($Entry.Attributes -is [System.Collections.IDictionary]) { @($Entry.Attributes.Keys) } + else { @($Entry.Attributes.AttributeNames) } + foreach ($name in $names) { + $baseName = ([string]$name -split ';')[0].ToLowerInvariant() + if ($requestedNames -notcontains $baseName) { continue } + $values = [System.Collections.Generic.List[object]]::new() + $rawAttribute = $Entry.Attributes[[string]$name] + if ($rawAttribute -is [byte[]]) { $rawValues = ,$rawAttribute } + else { $rawValues = @($rawAttribute) } + foreach ($raw in $rawValues) { + if ($raw -is [byte[]] -and $baseName -in ($textNames + $convertedNames)) { + $raw = $utf8.GetString($raw) + } + if ($raw -is [byte[]]) { + if ($baseName -in 'objectguid', 'invocationid', 'msds-optionalfeatureguid' -and $raw.Length -eq 16) { + $value = [guid]::new($raw) + } elseif ($baseName -in 'objectsid', 'sidhistory', 'securityidentifier', 'ms-ds-creatorsid') { + # All these attributes carry SID bytes. Reuse the base SID converter without + # depending on newer legacy collectors recognizing each attribute alias. + $sid = ConvertFrom-MtLdapValue -Value $raw -AttributeName 'objectSid' + if ($sid -is [byte[]]) { $value = $raw.Clone() } + else { $value = [string]$sid.Value } + } else { + # Unknown binary and security descriptors are never guessed to be UTF-8 strings. + $value = $raw.Clone() + } + } elseif ($raw -is [string]) { + $sentinel = 0L + if ($baseName -in $fileTimeNames -and [long]::TryParse($raw, [ref]$sentinel) -and + $sentinel -in 0L, [long]::MaxValue) { + # Keep AD's unset/never FILETIME sentinels distinguishable from an absent attribute. + $value = $sentinel + } elseif ($baseName -in $convertedNames) { + $value = ConvertFrom-MtLdapValue -Value $raw -AttributeName $baseName + } else { + # No generalized-date guessing for text or unrecognized names. + $value = $raw + } + } else { $value = $raw } + $values.Add($value) + } + $bag[([string]$name).ToLowerInvariant()] = [object[]]$values.ToArray() + } + return [pscustomobject]@{ + PSTypeName = 'Maester.AD.Entry' + DistinguishedName = [string]$Entry.DistinguishedName + Attributes = $bag + } +} diff --git a/powershell/internal/services/ad/Copy-MtADQueryResult.ps1 b/powershell/internal/services/ad/Copy-MtADQueryResult.ps1 new file mode 100644 index 0000000000..7e0a6343ef --- /dev/null +++ b/powershell/internal/services/ad/Copy-MtADQueryResult.ps1 @@ -0,0 +1,26 @@ +function Copy-MtADQueryResult { + [CmdletBinding()] + [OutputType([object], [object[]], [System.Collections.Specialized.OrderedDictionary], [pscustomobject])] + param([AllowNull()] [object] $Value) + + if ($null -eq $Value) { return $null } + if ($Value -is [byte[]]) { return ,([byte[]]$Value.Clone()) } + if ($Value -is [System.Collections.IDictionary]) { + $copy = [ordered]@{} + foreach ($key in $Value.Keys) { $copy[$key] = Copy-MtADQueryResult -Value $Value[$key] } + return $copy + } + if ($Value -is [array]) { + $copy = [object[]]::new($Value.Length) + for ($i = 0; $i -lt $Value.Length; $i++) { $copy[$i] = Copy-MtADQueryResult -Value $Value[$i] } + return ,$copy + } + if ($Value -is [System.Management.Automation.PSCustomObject]) { + $copy = [ordered]@{} + foreach ($property in $Value.PSObject.Properties) { $copy[$property.Name] = Copy-MtADQueryResult -Value $property.Value } + $result = [pscustomobject]$copy + $result.PSObject.TypeNames.Insert(0, $Value.PSObject.TypeNames[0]) + return $result + } + return $Value +} diff --git a/powershell/internal/services/ad/Get-MtADQueryDefinition.ps1 b/powershell/internal/services/ad/Get-MtADQueryDefinition.ps1 new file mode 100644 index 0000000000..f7a5ca2298 --- /dev/null +++ b/powershell/internal/services/ad/Get-MtADQueryDefinition.ps1 @@ -0,0 +1,18 @@ +function Get-MtADQueryDefinition { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [ValidateSet('User', 'Computer', 'Group', 'OrganizationalUnit', 'Gpo')] + [string] $Name + ) + + # Starter queries, not replacements for the legacy collectors' richer projections. + $definitions = @{ + User = @{ Filter = '(&(objectClass=user)(!(objectClass=computer)))'; Attributes = @('objectGUID', 'name', 'sAMAccountName', 'userAccountControl', 'primaryGroupID') } + Computer = @{ Filter = '(objectClass=computer)'; Attributes = @('objectGUID', 'name', 'sAMAccountName', 'dNSHostName', 'userAccountControl') } + Group = @{ Filter = '(objectClass=group)'; Attributes = @('objectGUID', 'name', 'sAMAccountName', 'groupType') } + OrganizationalUnit = @{ Filter = '(objectClass=organizationalUnit)'; Attributes = @('objectGUID', 'name', 'gPLink', 'gPOptions') } + Gpo = @{ Filter = '(objectClass=groupPolicyContainer)'; Attributes = @('objectGUID', 'name', 'displayName', 'gPCFileSysPath', 'versionNumber') } + } + return $definitions[$Name] +} diff --git a/powershell/internal/services/ad/Invoke-MtADQueryCached.ps1 b/powershell/internal/services/ad/Invoke-MtADQueryCached.ps1 new file mode 100644 index 0000000000..32f5571647 --- /dev/null +++ b/powershell/internal/services/ad/Invoke-MtADQueryCached.ps1 @@ -0,0 +1,86 @@ +function Invoke-MtADQueryCached { + [CmdletBinding()] + param( + [Parameter(Mandatory)] [object] $Query, + [Parameter(Mandatory)] [hashtable] $Operation, + [Parameter(Mandatory)] [int] $PageSize, + [Parameter(Mandatory)] [timespan] $Timeout + ) + + $evidence = $__MtSession.ADConnection + if (-not (Test-MtConnection -Service ActiveDirectory) -or -not $evidence.ProtocolValidated -or + [string]::IsNullOrWhiteSpace($evidence.ResolvedServer)) { + throw 'Connect-Maester -Service ActiveDirectory must validate a target before running LDAP queries.' + } + if ($evidence.TlsMode -notin 'Ldaps', 'StartTls') { throw 'The validated AD session has no supported TLS mode.' } + + $base = $Query.SearchBase + if ($null -ne $Query.NamingContext) { + $base = $evidence.("$($Query.NamingContext)NamingContext") + if ([string]::IsNullOrWhiteSpace($base)) { throw 'The selected naming context is unavailable on the connected server.' } + } + $target = [ordered]@{ + Server = $evidence.ResolvedServer.ToLowerInvariant() + Port = if ($evidence.TlsMode -eq 'StartTls') { 389 } else { 636 } + AuthenticationMode = $evidence.AuthenticationMode + TlsMode = $evidence.TlsMode + SkipCertificateCheck = [bool]$evidence.SkipCertificateCheck + } + $targetIdentity = $target | ConvertTo-Json -Compress + $state = $__MtSession.ADCache['ADQueryState'] + if ($null -eq $state -or -not [object]::ReferenceEquals($state.ConnectionState, $evidence) -or + -not [object]::ReferenceEquals($state.Credential, $__MtSession.ADCredential) -or $state.TargetIdentity -cne $targetIdentity) { + $state = @{ + ConnectionState = $evidence + Credential = $__MtSession.ADCredential + TargetIdentity = $targetIdentity + Results = [System.Collections.Generic.Dictionary[string, object]]::new([System.StringComparer]::Ordinal) + } + $__MtSession.ADCache['ADQueryState'] = $state + } + if ($Operation.ContainsKey('State') -and -not [object]::ReferenceEquals($Operation.State, $state)) { + if ($null -ne $Operation.Connection) { $Operation.Connection.Dispose(); $Operation.Connection = $null } + } + $Operation.State = $state + + $request = [ordered]@{ + Target = $target + SearchBase = [string]$base + Scope = $Query.Scope + Filter = $Query.Filter + Attributes = [string[]]$Query.Attributes + SecurityDescriptorFlags = if ($Query.PSObject.Properties['SecurityDescriptorFlags']) { [int]$Query.SecurityDescriptorFlags } else { $null } + ContractVersion = 1 + } + $json = $request | ConvertTo-Json -Depth 5 -Compress + $key = [Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData([System.Text.Encoding]::UTF8.GetBytes($json))) + if (-not $state.Results.ContainsKey($key)) { + if ($null -eq $Operation.Connection) { + # Use validated, resolved evidence directly; never rediscover a DC behind a cache key. + $Operation.Connection = New-MtAdProtocolConnection -ProtocolEvidence $evidence + } + $parameters = @{ + Connection = $Operation.Connection + SearchBase = [string]$base + Scope = $Query.Scope + Filter = $Query.Filter + Attributes = $Query.Attributes + PageSize = $PageSize + Timeout = $Timeout + AsAttributeBag = $true + RequireComplete = $true + } + if ($null -ne $request.SecurityDescriptorFlags) { $parameters.SecurityDescriptorFlags = $Query.SecurityDescriptorFlags } + $entries = @(Invoke-MtLdapSearch @parameters | ForEach-Object { + Complete-MtADQueryRange -Connection $Operation.Connection -Entry $_ -Timeout $Timeout + }) + # Commit only after every page and every ranged attribute succeeds, including successful empty results. + $state.Results[$key] = [pscustomobject]@{ + PSTypeName = 'Maester.AD.QueryResult' + Request = [pscustomobject]$request + CollectedAt = [datetime]::UtcNow + Entries = [object[]]$entries + } + } + return Copy-MtADQueryResult -Value $state.Results[$key] +} diff --git a/powershell/internal/services/ad/Resolve-MtADQuery.ps1 b/powershell/internal/services/ad/Resolve-MtADQuery.ps1 new file mode 100644 index 0000000000..f4c996a40f --- /dev/null +++ b/powershell/internal/services/ad/Resolve-MtADQuery.ps1 @@ -0,0 +1,19 @@ +function Resolve-MtADQuery { + [CmdletBinding()] + param([Parameter(Mandatory)] [object] $Query) + + $parameters = @{} + $names = if ($Query -is [System.Collections.IDictionary]) { @($Query.Keys) } + elseif ($Query -is [System.Management.Automation.PSCustomObject]) { @($Query.PSObject.Properties.Name) } + else { throw 'Query must be a query definition, dictionary or PSCustomObject.' } + foreach ($name in $names) { + if ($name -eq 'PSTypeName') { continue } + if ($name -notin 'Name', 'SearchBase', 'NamingContext', 'Scope', 'Filter', 'Attributes', 'SecurityDescriptorFlags') { + throw 'Query contains an unsupported field.' + } + $value = if ($Query -is [System.Collections.IDictionary]) { $Query[$name] } else { $Query.$name } + if ($name -in 'SearchBase', 'NamingContext' -and $null -eq $value) { continue } + $parameters[$name] = $value + } + return New-MtADQuery @parameters +} diff --git a/powershell/internal/services/ad/protocol/Invoke-MtLdapSearch.ps1 b/powershell/internal/services/ad/protocol/Invoke-MtLdapSearch.ps1 index ea6445091f..46d78f6cb6 100644 --- a/powershell/internal/services/ad/protocol/Invoke-MtLdapSearch.ps1 +++ b/powershell/internal/services/ad/protocol/Invoke-MtLdapSearch.ps1 @@ -35,7 +35,12 @@ [scriptblock] $ProcessPage, - [object] $PageState + [object] $PageState, + + # Opt-in contract for the modular query API. Legacy conversion remains the default. + [switch] $AsAttributeBag, + + [switch] $RequireComplete ) function ConvertTo-LdapFilterLiteral { @@ -66,6 +71,10 @@ function Convert-SearchEntry { param($Entry) + if ($AsAttributeBag) { + return ConvertFrom-MtADQueryEntry -Entry $Entry -Attributes $Attributes + } + $properties = [ordered]@{ DistinguishedName = [string]$Entry.DistinguishedName } @@ -169,6 +178,12 @@ return $null } + if (($AsAttributeBag -or $RequireComplete) -and ($ReturnDirectoryEntry -or $null -ne $ProcessPage)) { + throw 'The modular query contract cannot be combined with DirectoryEntry output or page callbacks.' + } + if ($AsAttributeBag -and (-not $Attributes -or $Attributes.Count -eq 0)) { + throw 'Attribute-bag conversion requires explicit Attributes.' + } $results = [System.Collections.Generic.List[object]]::new() $requestedAttributes = [string[]]$Attributes if ($null -eq $requestedAttributes -or $requestedAttributes.Count -eq 0) { @@ -204,6 +219,11 @@ [void]$request.Controls.Add($securityDescriptorControl) } + if ($RequireComplete) { + # Bound this query to one naming context instead of silently chasing other partitions. + [void]$request.Controls.Add([System.DirectoryServices.Protocols.DomainScopeControl]::new()) + } + try { $overrideProperty = $Connection.PSObject.Properties['MtSendRequestOverride'] if ($null -ne $overrideProperty) { @@ -230,6 +250,14 @@ throw "LDAP search failed. $($_.Exception.Message)" } + if ($RequireComplete -and ($null -eq $response.ResultCode -or + $response.ResultCode -ne [System.DirectoryServices.Protocols.ResultCode]::Success)) { + throw 'LDAP did not return a successful, complete query response.' + } + if ($RequireComplete -and @($response.References).Where({ $null -ne $_ }).Count -gt 0) { + throw 'LDAP returned continuation references despite domain-scoped collection.' + } + if ($null -ne $ProcessPage) { $pageEntries = [System.Collections.Generic.List[object]]::new() foreach ($entry in @($response.Entries)) { @@ -243,6 +271,9 @@ } $pageResponseControl = Get-PageControlFromResponse -Response $response + if ($RequireComplete -and $PageSize -gt 0 -and $null -eq $pageResponseControl) { + throw 'LDAP did not return the required paging response control.' + } $pageCookie = if ($null -ne $pageResponseControl -and $null -ne $pageResponseControl.Cookie) { [byte[]]@($pageResponseControl.Cookie) } diff --git a/powershell/public/services/ad/ConvertTo-MtLdapFilterValue.ps1 b/powershell/public/services/ad/ConvertTo-MtLdapFilterValue.ps1 new file mode 100644 index 0000000000..5e8f991118 --- /dev/null +++ b/powershell/public/services/ad/ConvertTo-MtLdapFilterValue.ps1 @@ -0,0 +1,46 @@ +function ConvertTo-MtLdapFilterValue { + <# + .SYNOPSIS + Escapes an LDAP filter assertion value. + .DESCRIPTION + Encodes strings as UTF-8 bytes and escapes LDAP filter metacharacters and non-ASCII bytes. + Binary values are escaped byte by byte. GUIDs use AD objectGUID byte order. + Pass byte arrays with -Value (or wrap them with a unary comma in a pipeline to prevent enumeration). + This escapes values only, not entire filters, attribute names or distinguished names (DN syntax). + .PARAMETER Value + A string, byte array or GUID to use as an LDAP filter assertion value. Null becomes an empty value. + .EXAMPLE + $value = ConvertTo-MtLdapFilterValue 'Smith (Admin)*' + Invoke-MtADQuery -Filter "(displayName=$value)" -Attributes displayName + + Searches for the literal name, without treating its parentheses or asterisk as filter syntax. + .LINK + https://maester.dev/docs/commands/ConvertTo-MtLdapFilterValue + #> + [CmdletBinding()] + [OutputType([string])] + param( + [Parameter(Mandatory, ValueFromPipeline)] + [AllowNull()] + [AllowEmptyString()] + [object] $Value + ) + process { + Write-Verbose 'Encoding an LDAP filter assertion value without logging its contents.' + $binary = $Value -is [byte[]] -or $Value -is [guid] + $bytes = if ($Value -is [guid]) { $Value.ToByteArray() } + elseif ($Value -is [byte[]]) { $Value } + elseif ($null -eq $Value -or $Value -is [string]) { [System.Text.Encoding]::UTF8.GetBytes([string]$Value) } + else { throw 'Value must be a string, byte array or GUID.' } + + $builder = [System.Text.StringBuilder]::new() + foreach ($b in $bytes) { + if ($binary -or $b -in 0, 40, 41, 42, 92 -or $b -lt 32 -or $b -ge 127) { + [void]$builder.Append(('\{0:x2}' -f $b)) + } else { + [void]$builder.Append([char]$b) + } + } + return $builder.ToString() + } +} diff --git a/powershell/public/services/ad/Invoke-MtADQuery.ps1 b/powershell/public/services/ad/Invoke-MtADQuery.ps1 new file mode 100644 index 0000000000..8d1bb2309f --- /dev/null +++ b/powershell/public/services/ad/Invoke-MtADQuery.ps1 @@ -0,0 +1,102 @@ +function Invoke-MtADQuery { + <# + .SYNOPSIS + Runs an arbitrary, read-only LDAP query with per-session result caching. + .DESCRIPTION + Queries the domain controller validated by Connect-Maester -Service ActiveDirectory. + Accepts reusable New-MtADQuery objects, dictionaries or direct query parameters. Completes + paging and ranged attributes before caching or returning any rows. Failures throw and are not cached. + Returns entries with DistinguishedName and an Attributes dictionary whose values are always arrays. + Absent attributes are omitted; absence cannot distinguish unset values from insufficient permissions. + Known SIDs are strings, known GUIDs are GUID values, and security descriptors/unknown binary stay byte arrays. + Standard text, numeric and date attributes are decoded by name. Unrecognized server attributes stay bytes, + even when their syntax is text; schema-driven decoding is not provided. FILETIME 0/never sentinels stay integers. + Uses one private connection per invocation, reused across pipeline queries and disposed even if stopped early. + Cache hits return independent copies without opening a connection. A full AD cache reset or a new Maester run + clears these results; legacy category-scoped resets do not. No cache bypass is offered. + .PARAMETER Query + Query definition, dictionary or PSCustomObject. May be supplied through the pipeline. + .PARAMETER Name + Optional starter query: User, Computer, Group, OrganizationalUnit or Gpo. + .PARAMETER SearchBase + Explicit distinguished name. An empty string selects RootDSE with Scope Base. + .PARAMETER NamingContext + Default, Configuration or Schema naming context. Defaults to Default; cannot be combined with SearchBase. + .PARAMETER Scope + Base, OneLevel or Subtree. Defaults to Subtree. + .PARAMETER Filter + Raw LDAP filter. Escape interpolated values with ConvertTo-MtLdapFilterValue. + .PARAMETER Attributes + Explicit LDAP display names. Required unless Name supplies a starter selection. + Wildcards, OIDs, options and known password/recovery-secret attributes are rejected. + .PARAMETER SecurityDescriptorFlags + Optional LDAP security descriptor control flags. Returned descriptors remain binary. + .PARAMETER PageSize + LDAP page size, from 1 to 1000. All pages are collected; this does not limit total results. + .PARAMETER Timeout + Positive time limit per LDAP request. Defaults to 30 seconds; not an overall collection deadline. + .PARAMETER AsResult + Returns a result envelope containing Entries, Request and CollectedAt instead of individual entries. + .EXAMPLE + Invoke-MtADQuery -Name User + + Collects starter user attributes once and reuses the complete query result for the session. + .EXAMPLE + New-MtADQuery -Name Group -Attributes name,member | Invoke-MtADQuery -AsResult + + Collects complete group membership, including LDAP range continuations, with request metadata. + .LINK + https://maester.dev/docs/commands/Invoke-MtADQuery + #> + [CmdletBinding(DefaultParameterSetName = 'Parameters')] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'Query')] + [ValidateNotNull()] + [object] $Query, + [Parameter(ParameterSetName = 'Parameters')] + [ValidateSet('User', 'Computer', 'Group', 'OrganizationalUnit', 'Gpo')] + [string] $Name, + [Parameter(ParameterSetName = 'Parameters')] + [AllowEmptyString()] + [string] $SearchBase, + [Parameter(ParameterSetName = 'Parameters')] + [ValidateSet('Default', 'Configuration', 'Schema')] + [string] $NamingContext = 'Default', + [Parameter(ParameterSetName = 'Parameters')] + [ValidateSet('Base', 'OneLevel', 'Subtree')] + [string] $Scope = 'Subtree', + [Parameter(ParameterSetName = 'Parameters')] + [ValidateNotNullOrEmpty()] + [string] $Filter = '(objectClass=*)', + [Parameter(ParameterSetName = 'Parameters')] + [string[]] $Attributes, + [Parameter(ParameterSetName = 'Parameters')] + [System.DirectoryServices.SecurityMasks] $SecurityDescriptorFlags, + [ValidateRange(1, 1000)] + [int] $PageSize = 1000, + [ValidateScript({ $_ -gt [timespan]::Zero })] + [timespan] $Timeout = [timespan]::FromSeconds(30), + [switch] $AsResult + ) + begin { + Write-Verbose 'Running Active Directory queries through the session result cache.' + $operation = @{ Connection = $null } + } + process { + if ($PSCmdlet.ParameterSetName -eq 'Query') { + $definition = Resolve-MtADQuery -Query $Query + } else { + $parameters = @{} + foreach ($field in 'Name', 'SearchBase', 'NamingContext', 'Scope', 'Filter', 'Attributes', 'SecurityDescriptorFlags') { + if ($PSBoundParameters.ContainsKey($field)) { $parameters[$field] = $PSBoundParameters[$field] } + } + $definition = New-MtADQuery @parameters + } + $result = Invoke-MtADQueryCached -Query $definition -Operation $operation -PageSize $PageSize -Timeout $Timeout + if ($AsResult) { $result } else { $result.Entries } + } + clean { + if ($null -ne $operation.Connection) { $operation.Connection.Dispose() } + } +} diff --git a/powershell/public/services/ad/New-MtADQuery.ps1 b/powershell/public/services/ad/New-MtADQuery.ps1 new file mode 100644 index 0000000000..11b38c204c --- /dev/null +++ b/powershell/public/services/ad/New-MtADQuery.ps1 @@ -0,0 +1,92 @@ +function New-MtADQuery { + <# + .SYNOPSIS + Creates a reusable, validated LDAP query definition. + .DESCRIPTION + Builds a query object for Invoke-MtADQuery without connecting to Active Directory. + Named definitions are small starter queries, not replacements for legacy collector output. + Only explicit LDAP display names are accepted. Wildcards, OIDs, attribute options and known + password/recovery-secret attributes are rejected. This prevents accidental secret collection; + it is not an authorization boundary. Raw filters must not contain untrusted, unescaped values. + .PARAMETER Name + Optional starter definition: User, Computer, Group, OrganizationalUnit or Gpo. + .PARAMETER SearchBase + An explicit distinguished name. An empty string selects RootDSE; use Scope Base for RootDSE. + Cannot be combined with an explicit NamingContext. + .PARAMETER NamingContext + The connected server's Default, Configuration or Schema naming context. Defaults to Default. + .PARAMETER Scope + LDAP search scope: Base, OneLevel or Subtree. Defaults to Subtree. + .PARAMETER Filter + Raw LDAP filter. Defaults to the named definition's filter, or (objectClass=*). + Use ConvertTo-MtLdapFilterValue for interpolated assertion values. + .PARAMETER Attributes + Explicit attributes to collect. Overrides a named definition's selection. Required for custom queries. + .PARAMETER SecurityDescriptorFlags + Optional Owner, Group, Dacl or Sacl flags for the LDAP security descriptor control. + Security descriptors are returned as binary values, not parsed objects. + .EXAMPLE + New-MtADQuery -Name User + + Creates the starter User query without contacting a domain controller. + .EXAMPLE + New-MtADQuery -NamingContext Schema -Filter '(objectClass=attributeSchema)' -Attributes name,lDAPDisplayName + + Defines a query against the connected server's schema partition. + .LINK + https://maester.dev/docs/commands/New-MtADQuery + #> + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an in-memory query definition without changing the directory or session.')] + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [ValidateSet('User', 'Computer', 'Group', 'OrganizationalUnit', 'Gpo')] + [string] $Name, + [AllowEmptyString()] + [string] $SearchBase, + [ValidateSet('Default', 'Configuration', 'Schema')] + [string] $NamingContext = 'Default', + [ValidateSet('Base', 'OneLevel', 'Subtree')] + [string] $Scope = 'Subtree', + [ValidateNotNullOrEmpty()] + [string] $Filter = '(objectClass=*)', + [string[]] $Attributes, + [System.DirectoryServices.SecurityMasks] $SecurityDescriptorFlags + ) + + Write-Verbose 'Creating a validated Active Directory query definition.' + if ($PSBoundParameters.ContainsKey('SearchBase') -and $PSBoundParameters.ContainsKey('NamingContext')) { + throw 'Specify SearchBase or NamingContext, not both.' + } + if ($Name) { + $definition = Get-MtADQueryDefinition -Name $Name + if (-not $PSBoundParameters.ContainsKey('Filter')) { $Filter = $definition.Filter } + if (-not $PSBoundParameters.ContainsKey('Attributes')) { $Attributes = $definition.Attributes } + } + if (-not $Attributes -or $Attributes.Count -eq 0) { + throw 'Select explicit Attributes or use a named query definition.' + } + foreach ($attribute in $Attributes) { + if ($attribute -notmatch '^[A-Za-z][A-Za-z0-9-]*$') { + throw 'Attributes must be explicit LDAP display names without wildcards, OIDs or options.' + } + if ($attribute -imatch '^(ms-Mcs-AdmPwd|msLAPS-Password|msLAPS-EncryptedPassword.*|msLAPS-EncryptedDSRMPassword.*|msDS-ManagedPassword|unicodePwd|dBCSPwd|ntPwdHistory|lmPwdHistory|supplementalCredentials|userPassword|unixUserPassword|msSFU30Password|msFVE-RecoveryPassword|msFVE-KeyPackage|msTPM-OwnerInformation|msPKIAccountCredentials|msPKIDPAPIMasterKeys|currentValue|priorValue|trustAuthIncoming|trustAuthOutgoing|initialAuthIncoming|initialAuthOutgoing)$') { + throw 'Password and recovery-secret attributes are not supported by the cached query API.' + } + } + if ($PSBoundParameters.ContainsKey('SearchBase') -and $SearchBase.Length -eq 0 -and $Scope -ne 'Base') { + throw 'An empty SearchBase (RootDSE) requires Scope Base.' + } + $query = [ordered]@{ + PSTypeName = 'Maester.AD.Query' + NamingContext = if ($PSBoundParameters.ContainsKey('SearchBase')) { $null } else { $NamingContext } + SearchBase = if ($PSBoundParameters.ContainsKey('SearchBase')) { $SearchBase } else { $null } + Scope = $Scope + Filter = $Filter + Attributes = [string[]]@($Attributes | ForEach-Object { $_.ToLowerInvariant() } | Sort-Object -Unique) + } + if ($PSBoundParameters.ContainsKey('SecurityDescriptorFlags')) { + $query['SecurityDescriptorFlags'] = $SecurityDescriptorFlags + } + return [pscustomobject]$query +} diff --git a/powershell/tests/functions/ADQueryTransport.Tests.ps1 b/powershell/tests/functions/ADQueryTransport.Tests.ps1 new file mode 100644 index 0000000000..1c883bd5f4 --- /dev/null +++ b/powershell/tests/functions/ADQueryTransport.Tests.ps1 @@ -0,0 +1,327 @@ +#Requires -Modules @{ ModuleName='Pester'; ModuleVersion='5.0.0' } + +Describe 'AD query LDAP transport and range completion' { + BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force -ErrorAction Stop + $script:MaesterModule = Get-Module Maester + $script:ADBase = 'DC=contoso,DC=com' + $script:ADDn = 'CN=User,DC=contoso,DC=com' + + function New-ADEntry { + param([System.Collections.IDictionary] $Attributes = ([ordered]@{}), [string] $Dn = $script:ADDn) + [pscustomobject]@{ DistinguishedName = $Dn; Attributes = $Attributes } + } + + function New-ADResponse { + param([object[]] $Entries = @(), [object[]] $Controls = @(), + [object[]] $References = @(), + [object] $ResultCode = [System.DirectoryServices.Protocols.ResultCode]::Success) + [pscustomobject]@{ + Entries = $Entries + Controls = $Controls + References = $References + ResultCode = $ResultCode + } + } + + function New-ADFixture { + param([object[]] $Responses) + $state = @{ Responses = $Responses; Index = 0; Requests = [System.Collections.Generic.List[object]]::new() } + $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('ldap.mock') + $script:FixtureConnections.Add($connection) + $hook = { + param($request, $timeout) + $state.Requests.Add($request) + $index = $state.Index + $state.Index++ + if ($index -ge $state.Responses.Count) { throw 'Unexpected LDAP request.' } + return $state.Responses[$index] + }.GetNewClosure() + $connection | Add-Member -MemberType NoteProperty -Name MtSendRequestOverride -Value $hook + [pscustomobject]@{ Connection = $connection; State = $state } + } + $script:FixtureConnections = [System.Collections.Generic.List[object]]::new() + } + + AfterEach { + foreach ($connection in $script:FixtureConnections) { $connection.Dispose() } + $script:FixtureConnections.Clear() + } + + Context 'legacy and attribute-bag conversion' { + It 'keeps the legacy scalar and null-for-missing contract for the same raw entry' { + $entry = New-ADEntry ([ordered]@{ displayName = @('Ada'); member = @('One', 'Two') }) + $fixture = New-ADFixture @((New-ADResponse -Entries @($entry))) + $rows = @($script:MaesterModule.Invoke({ param($c, $b) Invoke-MtLdapSearch -Connection $c -SearchBase $b -Attributes @('displayName', 'member', 'missing') -PageSize 0 }, $fixture.Connection, $script:ADBase)) + $rows | Should -HaveCount 1 + $rows[0].displayName | Should -BeOfType [string] + $rows[0].displayName | Should -Be 'Ada' + $rows[0].missing | Should -BeNullOrEmpty + $rows[0].PSObject.Properties.Name | Should -Contain 'missing' + $rows[0].member | Should -HaveCount 2 + $rows[0].PSObject.Properties.Name | Should -Not -Contain 'Attributes' + } + + It 'returns object arrays for single and empty values, omits absent names, and filters unrequested names' { + $entry = New-ADEntry ([ordered]@{ displayName = @('Ada'); member = @(); ignored = @('secret') }) + $fixture = New-ADFixture @((New-ADResponse -Entries @($entry))) + $rows = @($script:MaesterModule.Invoke({ param($c, $b) Invoke-MtLdapSearch -Connection $c -SearchBase $b -Attributes @('displayName', 'member', 'missing') -PageSize 0 -AsAttributeBag }, $fixture.Connection, $script:ADBase)) + $rows | Should -HaveCount 1 + $rows[0].PSObject.TypeNames | Should -Contain 'Maester.AD.Entry' + ($rows[0].Attributes['displayname'] -is [object[]]) | Should -BeTrue + $rows[0].Attributes['displayname'].Count | Should -Be 1 + ($rows[0].Attributes['member'] -is [object[]]) | Should -BeTrue + $rows[0].Attributes['member'].Count | Should -Be 0 + $rows[0].Attributes.Contains('missing') | Should -BeFalse + $rows[0].Attributes.Contains('ignored') | Should -BeFalse + } + + It 'normalizes known GUID, SID, integer and date values without guessing arbitrary dates or binary data' { + $guid = [guid]::NewGuid() + $sid = [byte[]]@(1, 1, 0, 0, 0, 0, 0, 5, 21, 0, 0, 0) + $binary = [byte[]]@(0, 255, 128, 42) + $descriptor = [byte[]]@(1, 2, 0, 255) + $entry = New-ADEntry ([ordered]@{ + objectGUID = $guid.ToByteArray() + objectSid = $sid + 'mS-DS-CreatorSID' = $sid + nTSecurityDescriptor = $descriptor + customBlob = $binary + userAccountControl = @('512') + whenCreated = @('20260102030405.0Z') + customDate = @('20260102030405.0Z') + }) + $fixture = New-ADFixture @((New-ADResponse -Entries @($entry))) + $names = @('objectGUID', 'objectSid', 'mS-DS-CreatorSID', 'nTSecurityDescriptor', 'customBlob', 'userAccountControl', 'whenCreated', 'customDate') + $rows = @($script:MaesterModule.Invoke({ param($c, $b, $a) Invoke-MtLdapSearch -Connection $c -SearchBase $b -Attributes $a -PageSize 0 -AsAttributeBag }, $fixture.Connection, $script:ADBase, $names)) + $bag = $rows[0].Attributes + $bag['objectguid'][0] | Should -BeOfType [guid] + $bag['objectguid'][0] | Should -Be $guid + $bag['objectsid'][0] | Should -BeOfType [string] + $bag['objectsid'][0] | Should -Be 'S-1-5-21' + $bag['ms-ds-creatorsid'][0] | Should -Be 'S-1-5-21' + $bag['useraccountcontrol'][0] | Should -BeOfType [int] + $bag['useraccountcontrol'][0] | Should -Be 512 + $bag['whencreated'][0] | Should -BeOfType [datetime] + $bag['customdate'][0] | Should -BeOfType [string] + $bag['customdate'][0] | Should -Be '20260102030405.0Z' + foreach ($name in @('ntsecuritydescriptor', 'customblob')) { + ($bag[$name][0] -is [byte[]]) | Should -BeTrue + } + [Convert]::ToHexString($bag['ntsecuritydescriptor'][0]) | Should -Be ([Convert]::ToHexString($descriptor)) + [Convert]::ToHexString($bag['customblob'][0]) | Should -Be ([Convert]::ToHexString($binary)) + [object]::ReferenceEquals($bag['customblob'][0], $binary) | Should -BeFalse + } + + It 'deep-copies nested attribute arrays and bytes when copying a query result' { + $entry = [pscustomobject]@{ DistinguishedName = $script:ADDn; Attributes = [ordered]@{ photo = ,([byte[]]@(0, 255)) } } + $copy = $script:MaesterModule.Invoke({ param($value) Copy-MtADQueryResult -Value $value }, $entry) + ($copy.Attributes['photo'] -is [object[]]) | Should -BeTrue + ($copy.Attributes['photo'][0] -is [byte[]]) | Should -BeTrue + $copy.Attributes['photo'][0][0] = 9 + $entry.Attributes['photo'][0][0] | Should -Be 0 + } + + It 'normalizes standard attributes from DirectoryAttribute byte collections without guessing unknown binary' { + $attributes = [ordered]@{} + foreach ($pair in @{ + name = 'Alice' + sAMAccountName = 'alice' + userAccountControl = '512' + whenCreated = '20260102030405.0Z' + customBlob = 'looks like text' + objectGUID = 'abcdefghijklmnop' + }.GetEnumerator()) { + $attribute = [System.DirectoryServices.Protocols.DirectoryAttribute]::new() + $attribute.Name = $pair.Key + [void]$attribute.Add([System.Text.Encoding]::UTF8.GetBytes($pair.Value)) + $attributes[$pair.Key] = $attribute + } + $fixture = New-ADFixture @((New-ADResponse -Entries @((New-ADEntry $attributes)))) + $rows = @($script:MaesterModule.Invoke({ param($c, $b) + Invoke-MtLdapSearch -Connection $c -SearchBase $b -Attributes name,sAMAccountName,userAccountControl,whenCreated,customBlob,objectGUID -PageSize 0 -AsAttributeBag + }, $fixture.Connection, $script:ADBase)) + $bag = $rows[0].Attributes + $bag['name'][0] | Should -Be 'Alice' + $bag['samaccountname'][0] | Should -Be 'alice' + $bag['useraccountcontrol'][0] | Should -BeOfType [int] + $bag['whencreated'][0] | Should -BeOfType [datetime] + ($bag['customblob'][0] -is [byte[]]) | Should -BeTrue + $bag['objectguid'][0] | Should -Be ([guid]::new([System.Text.Encoding]::UTF8.GetBytes('abcdefghijklmnop'))) + } + + It 'retains unset and never FILETIME sentinels as integers rather than absent values' { + $entry = New-ADEntry ([ordered]@{ + lastLogon = [System.Text.Encoding]::UTF8.GetBytes('0') + accountExpires = [System.Text.Encoding]::UTF8.GetBytes([long]::MaxValue.ToString()) + }) + $fixture = New-ADFixture @((New-ADResponse -Entries @($entry))) + $rows = @($script:MaesterModule.Invoke({ param($c, $b) + Invoke-MtLdapSearch -Connection $c -SearchBase $b -Attributes lastLogon,accountExpires -PageSize 0 -AsAttributeBag + }, $fixture.Connection, $script:ADBase)) + $rows[0].Attributes['lastlogon'][0] | Should -BeOfType [long] + $rows[0].Attributes['lastlogon'][0] | Should -Be 0 + $rows[0].Attributes['accountexpires'][0] | Should -Be ([long]::MaxValue) + } + + It 'throws on invalid UTF-8 under a known text attribute' { + $fixture = New-ADFixture @((New-ADResponse -Entries @((New-ADEntry ([ordered]@{ name = [byte[]]@(255) }))))) + { $script:MaesterModule.Invoke({ param($c, $b) + Invoke-MtLdapSearch -Connection $c -SearchBase $b -Attributes name -PageSize 0 -AsAttributeBag + }, $fixture.Connection, $script:ADBase) } | Should -Throw + } + } + + Context 'complete-response safeguards' { + It 'rejects failed result codes only in strict mode' { + $response = New-ADResponse -Entries @((New-ADEntry)) -ResultCode ([System.DirectoryServices.Protocols.ResultCode]::SizeLimitExceeded) + $legacy = New-ADFixture @($response) + @($script:MaesterModule.Invoke({ param($c, $b) Invoke-MtLdapSearch -Connection $c -SearchBase $b -PageSize 0 }, $legacy.Connection, $script:ADBase)) | Should -HaveCount 1 + $strict = New-ADFixture @($response) + { $script:MaesterModule.Invoke({ param($c, $b) Invoke-MtLdapSearch -Connection $c -SearchBase $b -PageSize 0 -RequireComplete }, $strict.Connection, $script:ADBase) } | Should -Throw '*complete query response*' + } + + It 'rejects a response with no result code when completeness is required' { + $fixture = New-ADFixture @([pscustomobject]@{ Entries = @((New-ADEntry)); Controls = @(); References = @(); ResultCode = $null }) + { $script:MaesterModule.Invoke({ param($c, $b) Invoke-MtLdapSearch -Connection $c -SearchBase $b -PageSize 0 -RequireComplete }, $fixture.Connection, $script:ADBase) } | Should -Throw '*complete query response*' + } + + It 'requires a paging response control only in strict mode' { + $response = New-ADResponse -Entries @((New-ADEntry)) + $legacy = New-ADFixture @($response) + @($script:MaesterModule.Invoke({ param($c, $b) Invoke-MtLdapSearch -Connection $c -SearchBase $b -PageSize 1 }, $legacy.Connection, $script:ADBase)) | Should -HaveCount 1 + $strict = New-ADFixture @($response) + { $script:MaesterModule.Invoke({ param($c, $b) Invoke-MtLdapSearch -Connection $c -SearchBase $b -PageSize 1 -RequireComplete }, $strict.Connection, $script:ADBase) } | Should -Throw '*paging response control*' + } + + It 'adds a domain-scope control and consumes a successful paged response' { + $response = New-ADResponse -Entries @((New-ADEntry)) -Controls @([pscustomobject]@{ Cookie = [byte[]]@() }) + $fixture = New-ADFixture @($response) + $rows = @($script:MaesterModule.Invoke({ param($c, $b) Invoke-MtLdapSearch -Connection $c -SearchBase $b -PageSize 1 -RequireComplete }, $fixture.Connection, $script:ADBase)) + $rows | Should -HaveCount 1 + @($fixture.State.Requests[0].Controls | Where-Object { $_ -is [System.DirectoryServices.Protocols.DomainScopeControl] }) | Should -HaveCount 1 + @($fixture.State.Requests[0].Controls | Where-Object { $_ -is [System.DirectoryServices.Protocols.PageResultRequestControl] }) | Should -HaveCount 1 + } + + It 'carries paging cookies through strict mode and checks every response' { + $first = New-ADResponse -Entries @((New-ADEntry)) -Controls @([pscustomobject]@{ Cookie = [byte[]]@(3, 4) }) + $last = New-ADResponse -Entries @((New-ADEntry -Dn 'CN=Other,DC=contoso,DC=com')) -Controls @([pscustomobject]@{ Cookie = [byte[]]@() }) + $fixture = New-ADFixture @($first, $last) + $rows = @($script:MaesterModule.Invoke({ param($c, $b) Invoke-MtLdapSearch -Connection $c -SearchBase $b -PageSize 1 -RequireComplete }, $fixture.Connection, $script:ADBase)) + $rows | Should -HaveCount 2 + $fixture.State.Requests | Should -HaveCount 2 + [Convert]::ToHexString($fixture.State.Requests[1].Controls[0].Cookie) | Should -Be '0304' + @($fixture.State.Requests[1].Controls | Where-Object { $_ -is [System.DirectoryServices.Protocols.DomainScopeControl] }) | Should -HaveCount 1 + } + + It 'rejects referral references in strict mode but tolerates them by default' { + $response = New-ADResponse -Entries @((New-ADEntry)) -References @('ldap://other.example') + $legacy = New-ADFixture @($response) + @($script:MaesterModule.Invoke({ param($c, $b) Invoke-MtLdapSearch -Connection $c -SearchBase $b -PageSize 0 }, $legacy.Connection, $script:ADBase)) | Should -HaveCount 1 + $strict = New-ADFixture @($response) + { $script:MaesterModule.Invoke({ param($c, $b) Invoke-MtLdapSearch -Connection $c -SearchBase $b -PageSize 0 -RequireComplete }, $strict.Connection, $script:ADBase) } | Should -Throw '*continuation references*' + } + + It 'disallows callbacks and directory entries with either modular option before sending' { + foreach ($option in @('AsAttributeBag', 'RequireComplete')) { + foreach ($incompatible in @('ReturnDirectoryEntry', 'ProcessPage')) { + $fixture = New-ADFixture @() + $arguments = @{ Connection = $fixture.Connection; SearchBase = $script:ADBase; Attributes = @('cn'); PageSize = 0 } + $arguments[$option] = $true + $arguments[$incompatible] = if ($incompatible -eq 'ProcessPage') { { param($page, $state) } } else { $true } + { $script:MaesterModule.Invoke({ param($p) Invoke-MtLdapSearch @p }, $arguments) } | Should -Throw '*modular query contract*' + $fixture.State.Index | Should -Be 0 + } + } + } + } + + Context 'ranged attribute completion' { + It 'decodes ranged membership from server byte values on initial and continuation responses' { + $first = [System.DirectoryServices.Protocols.DirectoryAttribute]::new() + [void]$first.Add([Text.Encoding]::UTF8.GetBytes('CN=Alice')) + $last = [System.DirectoryServices.Protocols.DirectoryAttribute]::new() + [void]$last.Add([Text.Encoding]::UTF8.GetBytes('CN=Bob')) + $fixture = New-ADFixture @( + (New-ADResponse -Entries @((New-ADEntry ([ordered]@{ 'member;range=0-0' = $first })))), + (New-ADResponse -Entries @((New-ADEntry ([ordered]@{ 'member;range=1-*' = $last })))) + ) + $result = $script:MaesterModule.Invoke({ param($c, $b) + $entry = Invoke-MtLdapSearch -Connection $c -SearchBase $b -Attributes member -PageSize 0 -AsAttributeBag + Complete-MtADQueryRange -Connection $c -Entry $entry -Timeout ([timespan]::FromSeconds(30)) + }, $fixture.Connection, $script:ADBase) + $result.Attributes['member'] | Should -Be @('CN=Alice', 'CN=Bob') + } + It 'follows unsolicited contiguous member ranges via base-scope requests until the final chunk' { + $first = New-ADEntry ([ordered]@{ 'member;range=0-1' = [object[]]@('A', 'B') }) + $middle = New-ADEntry ([ordered]@{ 'member;range=2-3' = [object[]]@('C', 'D') }) + $last = New-ADEntry ([ordered]@{ 'member;range=4-*' = [object[]]@('E') }) + $fixture = New-ADFixture @((New-ADResponse -Entries @($middle)), (New-ADResponse -Entries @($last))) + $result = $script:MaesterModule.Invoke({ param($c, $e) Complete-MtADQueryRange -Connection $c -Entry $e -Timeout ([timespan]::FromSeconds(5)) }, $fixture.Connection, $first) + $result.Attributes['member'] | Should -HaveCount 5 + ($result.Attributes['member'] -join ',') | Should -Be 'A,B,C,D,E' + $result.Attributes.Contains('member;range=0-1') | Should -BeFalse + $fixture.State.Requests | Should -HaveCount 2 + foreach ($index in 0..1) { + $request = $fixture.State.Requests[$index] + $request.DistinguishedName | Should -Be $script:ADDn + $request.Scope | Should -Be ([System.DirectoryServices.Protocols.SearchScope]::Base) + @($request.Controls | Where-Object { $_ -is [System.DirectoryServices.Protocols.DomainScopeControl] }) | Should -HaveCount 1 + @($request.Controls | Where-Object { $_ -is [System.DirectoryServices.Protocols.PageResultRequestControl] }) | Should -HaveCount 0 + } + @($fixture.State.Requests[0].Attributes) | Should -HaveCount 1 + @($fixture.State.Requests[1].Attributes) | Should -HaveCount 1 + $fixture.State.Requests[0].Attributes[0] | Should -Be 'member;range=2-*' + $fixture.State.Requests[1].Attributes[0] | Should -Be 'member;range=4-*' + } + + It 'normalizes an initially final range without requesting another page' { + $entry = New-ADEntry ([ordered]@{ 'member;range=0-*' = [object[]]@('A') }) + $fixture = New-ADFixture @() + $result = $script:MaesterModule.Invoke({ param($c, $e) Complete-MtADQueryRange -Connection $c -Entry $e -Timeout ([timespan]::FromSeconds(5)) }, $fixture.Connection, $entry) + $result.Attributes['member'] | Should -HaveCount 1 + $result.Attributes['member'][0] | Should -Be 'A' + $fixture.State.Index | Should -Be 0 + } + + It 'leaves a nonranged attribute intact without additional requests' { + $entry = New-ADEntry ([ordered]@{ member = [object[]]@('A') }) + $fixture = New-ADFixture @() + $result = $script:MaesterModule.Invoke({ param($c, $e) Complete-MtADQueryRange -Connection $c -Entry $e -Timeout ([timespan]::FromSeconds(5)) }, $fixture.Connection, $entry) + $result.Attributes['member'] | Should -HaveCount 1 + $result.Attributes['member'][0] | Should -Be 'A' + $fixture.State.Index | Should -Be 0 + } + + It 'rejects missing entries, wrong DNs, discontinuities, mismatched lengths and ambiguous continuations' { + $cases = @( + @{ Name = 'missing'; Entries = @(); Message = '*original entry*' } + @{ Name = 'multiple entries'; Entries = @((New-ADEntry ([ordered]@{ 'member;range=1-*' = [object[]]@('B') })), (New-ADEntry ([ordered]@{ 'member;range=1-*' = [object[]]@('C') }))); Message = '*original entry*' } + @{ Name = 'wrong DN'; Entries = @((New-ADEntry -Attributes ([ordered]@{ 'member;range=1-*' = [object[]]@('B') }) -Dn 'CN=Other,DC=contoso,DC=com')); Message = '*original entry*' } + @{ Name = 'missing range'; Entries = @((New-ADEntry ([ordered]@{ member = [object[]]@('B') }))); Message = '*missing or ambiguous*' } + @{ Name = 'out of sequence'; Entries = @((New-ADEntry ([ordered]@{ 'member;range=2-*' = [object[]]@('B') }))); Message = '*not contiguous*' } + @{ Name = 'size mismatch'; Entries = @((New-ADEntry ([ordered]@{ 'member;range=1-3' = [object[]]@('B') }))); Message = '*length did not match*' } + @{ Name = 'ambiguous'; Entries = @((New-ADEntry ([ordered]@{ 'member;range=1-*' = [object[]]@('B'); 'member;range=2-*' = [object[]]@('C') }))); Message = '*missing or ambiguous*' } + ) + foreach ($case in $cases) { + $entry = New-ADEntry ([ordered]@{ 'member;range=0-0' = [object[]]@('A') }) + $fixture = New-ADFixture @((New-ADResponse -Entries $case.Entries)) + { $script:MaesterModule.Invoke({ param($c, $e) Complete-MtADQueryRange -Connection $c -Entry $e -Timeout ([timespan]::FromSeconds(5)) }, $fixture.Connection, $entry) } | Should -Throw $case.Message -Because $case.Name + $entry.Attributes.Contains('member;range=0-0') | Should -BeTrue + $entry.Attributes.Contains('member') | Should -BeFalse + } + } + + It 'rejects an ambiguous nonranged attribute and an invalid initial range length' { + foreach ($attributes in @( + ([ordered]@{ member = [object[]]@('A'); 'member;range=0-*' = [object[]]@('B') }), + ([ordered]@{ 'member;range=0-2' = [object[]]@('A') }) + )) { + $fixture = New-ADFixture @() + $entry = New-ADEntry $attributes + { $script:MaesterModule.Invoke({ param($c, $e) Complete-MtADQueryRange -Connection $c -Entry $e -Timeout ([timespan]::FromSeconds(5)) }, $fixture.Connection, $entry) } | Should -Throw + $fixture.State.Index | Should -Be 0 + } + } + } +} diff --git a/powershell/tests/functions/Invoke-MtADQuery.Tests.ps1 b/powershell/tests/functions/Invoke-MtADQuery.Tests.ps1 new file mode 100644 index 0000000000..1173e8d221 --- /dev/null +++ b/powershell/tests/functions/Invoke-MtADQuery.Tests.ps1 @@ -0,0 +1,340 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force -ErrorAction Stop +} + +Describe 'Modular AD query definitions and filter values' { + It 'creates independent named definitions and canonical attribute selections' { + $first = New-MtADQuery -Name User + $first.Attributes[0] = 'changed' + $second = New-MtADQuery -Name User + $second.Attributes | Should -Contain 'primarygroupid' + $second.Attributes | Should -Not -Contain 'changed' + $second.Filter | Should -Be '(&(objectClass=user)(!(objectClass=computer)))' + (New-MtADQuery -Attributes NAME,name,objectGUID).Attributes | Should -Be @('name', 'objectguid') + } + + It 'allows explicit overrides of a named definition' { + $query = New-MtADQuery -Name Group -SearchBase 'OU=Groups,DC=example,DC=com' -Filter '(name=A)' -Attributes name,member + $query.Filter | Should -Be '(name=A)' + $query.NamingContext | Should -BeNullOrEmpty + $query.Attributes | Should -Be @('member', 'name') + } + + It 'requires attributes and disallows ambiguous naming contexts or unscoped RootDSE' { + { New-MtADQuery } | Should -Throw '*explicit Attributes*' + { New-MtADQuery -Name User -NamingContext Default -SearchBase 'DC=example,DC=com' } | Should -Throw '*not both*' + { New-MtADQuery -SearchBase '' -Attributes name } | Should -Throw '*Scope Base*' + (New-MtADQuery -SearchBase '' -Scope Base -Attributes defaultNamingContext).SearchBase | Should -Be '' + } + + It 'rejects wildcard, OID, option and known secret selections: ' -ForEach @( + @{ Attribute = '*' }, @{ Attribute = '+' }, @{ Attribute = '1.1' }, @{ Attribute = '1.2.840.113556.1.4.90' }, + @{ Attribute = 'member;range=0-*' }, @{ Attribute = 'msLAPS-Password' }, @{ Attribute = 'MS-MCS-ADMPWD' }, + @{ Attribute = 'msLAPS-EncryptedPasswordHistory' }, @{ Attribute = 'msDS-ManagedPassword' }, + @{ Attribute = 'msLAPS-EncryptedDSRMPassword' }, @{ Attribute = 'msLAPS-EncryptedDSRMPasswordHistory' }, + @{ Attribute = 'supplementalCredentials' }, @{ Attribute = 'msFVE-RecoveryPassword' }, @{ Attribute = 'msPKIDPAPIMasterKeys' } + ) { + { New-MtADQuery -Attributes $Attribute } | Should -Throw + } + + It 'permits password policy and expiration metadata' { + (New-MtADQuery -Attributes msLAPS-PasswordExpirationTime,ms-Mcs-AdmPwdExpirationTime,pwdLastSet).Attributes | Should -HaveCount 3 + } + + It 'escapes metacharacters, nulls, Unicode and binary filter values' { + ConvertTo-MtLdapFilterValue 'a*(b)\' | Should -Be 'a\2a\28b\29\5c' + ConvertTo-MtLdapFilterValue "a$([char]0)b" | Should -Be 'a\00b' + ConvertTo-MtLdapFilterValue ([string][char]0xE9) | Should -Be '\c3\a9' + ConvertTo-MtLdapFilterValue ([byte[]]@(0, 65, 255)) | Should -Be '\00\41\ff' + ConvertTo-MtLdapFilterValue $null | Should -Be '' + ConvertTo-MtLdapFilterValue ([guid]'00112233-4455-6677-8899-aabbccddeeff') | Should -Be '\33\22\11\00\55\44\77\66\88\99\aa\bb\cc\dd\ee\ff' + { ConvertTo-MtLdapFilterValue 10 } | Should -Throw '*string, byte array or GUID*' + } + + It 'does not include assertion values or query filters in verbose messages' { + $records = @(ConvertTo-MtLdapFilterValue 'sensitive-assertion' -Verbose 4>&1) + $records += @(New-MtADQuery -Attributes name -Filter '(name=sensitive-assertion)' -Verbose 4>&1) + $messages = @($records | Where-Object { $_ -is [System.Management.Automation.VerboseRecord] }) + $messages | Should -HaveCount 2 + foreach ($message in $messages) { $message.Message | Should -Not -Match 'sensitive-assertion' } + } +} + +Describe 'Invoke-MtADQuery additive cached collection' { + BeforeEach { + $script:ADQueryTestConnection = InModuleScope Maester { + $__MtSession.ADCache = @{} + $__MtSession.ADCredential = $null + $__MtSession.ADConnection = [ordered]@{ + Connected = $true + ProtocolValidated = $true + ResolvedServer = 'dc1.example.com' + ResolvedDomain = 'example.com' + DefaultNamingContext = 'DC=example,DC=com' + ConfigurationNamingContext = 'CN=Configuration,DC=example,DC=com' + SchemaNamingContext = 'CN=Schema,CN=Configuration,DC=example,DC=com' + AuthenticationMode = 'Negotiate' + TlsMode = 'Ldaps' + SkipCertificateCheck = $false + } + $script:ADQueryTestState = @{ + Reads = 0 + Disposed = 0 + Fail = $false + Requests = [System.Collections.Generic.List[object]]::new() + Entries = @([pscustomobject]@{ + DistinguishedName = 'CN=Alice,DC=example,DC=com' + Attributes = [ordered]@{ name = @('Alice'); objectGUID = [guid]'00112233-4455-6677-8899-aabbccddeeff' } + }) + } + $script:ADQueryTestConnection = [System.DirectoryServices.Protocols.LdapConnection]::new('dc1.example.com') + $script:ADQueryTestConnection | Add-Member NoteProperty MtState $script:ADQueryTestState + $script:ADQueryTestConnection | Add-Member ScriptMethod Dispose { + $this.MtState.Disposed++ + $this.psbase.Dispose() + } -Force + $script:ADQueryTestConnection | Add-Member NoteProperty MtSendRequestOverride { + param($request, $timeout) + $script:ADQueryTestState.Reads++ + $script:ADQueryTestState.Requests.Add($request) + if ($script:ADQueryTestState.Fail) { throw 'query test failure' } + [pscustomobject]@{ + ResultCode = [System.DirectoryServices.Protocols.ResultCode]::Success + Entries = $script:ADQueryTestState.Entries + Controls = @([pscustomobject]@{ Cookie = [byte[]]@() }) + References = @() + } + } + $script:ADQueryTestConnection + } + Mock -ModuleName Maester Test-MtConnection { $true } + Mock -ModuleName Maester New-MtAdProtocolConnection { $script:ADQueryTestConnection } + } + + AfterEach { + InModuleScope Maester { $script:ADQueryTestConnection.psbase.Dispose() } + } + + It 'returns rows or envelopes with a consistent independent object contract' { + $first = Invoke-MtADQuery -Attributes name,objectGUID -AsResult + ($first.Entries[0].Attributes['name'] -is [object[]]) | Should -BeTrue + $first.Entries[0].Attributes['name'][0] | Should -Be 'Alice' + $first.Entries[0].Attributes['objectguid'][0] | Should -BeOfType ([guid]) + $first.Request.SearchBase | Should -Be 'DC=example,DC=com' + $first.Request.Target.Server | Should -Be 'dc1.example.com' + $first.CollectedAt | Should -BeOfType ([datetime]) + $first.Entries[0].Attributes['name'][0] = 'mutated' + $first.Request.Attributes[0] = 'mutated' + $rows = @(Invoke-MtADQuery -Attributes OBJECTGUID,NAME -PageSize 1) + $rows | Should -HaveCount 1 + $rows[0].Attributes['name'][0] | Should -Be 'Alice' + $rows[0].Attributes['objectguid'][0] | Should -BeOfType ([guid]) + Should -Invoke New-MtAdProtocolConnection -ModuleName Maester -Times 1 -Exactly + InModuleScope Maester { $script:ADQueryTestState.Reads | Should -Be 1; $script:ADQueryTestState.Disposed | Should -Be 1 } + } + + It 'caches successful empty collections without mistaking them for a miss' { + InModuleScope Maester { $script:ADQueryTestState.Entries = @() } + $first = Invoke-MtADQuery -Attributes name -AsResult + $first.Entries | Should -HaveCount 0 + @(Invoke-MtADQuery -Attributes name) | Should -HaveCount 0 + InModuleScope Maester { $script:ADQueryTestState.Reads | Should -Be 1 } + Should -Invoke New-MtAdProtocolConnection -ModuleName Maester -Times 1 -Exactly + } + + It 'accepts query objects, dictionaries, and direct parameters with the same cache identity' { + $query = New-MtADQuery -Name User -Attributes name + $null = $query | Invoke-MtADQuery + $null = Invoke-MtADQuery -Query @{ Name = 'User'; Attributes = @('name') } + $null = Invoke-MtADQuery -Name User -Attributes name + InModuleScope Maester { $script:ADQueryTestState.Reads | Should -Be 1 } + } + + It 'rejects unexpected fields and revalidates modified query objects' { + { Invoke-MtADQuery -Query @{ Attributes = @('name'); Unexpected = 'x' } } | Should -Throw '*unsupported field*' + $query = New-MtADQuery -Name User + $query.Attributes = @('msLAPS-Password') + { Invoke-MtADQuery -Query $query } | Should -Throw '*secret attributes*' + { Invoke-MtADQuery -Query 'not a definition' } | Should -Throw '*dictionary or PSCustomObject*' + Should -Invoke New-MtAdProtocolConnection -ModuleName Maester -Times 0 -Exactly + } + + It 'separates filters by exact values, bases, scopes, selections and descriptor controls' { + InModuleScope Maester { + $operation = @{ Connection = $null } + $queries = @( + (New-MtADQuery -Attributes name -Filter '(name=Alice)'), + (New-MtADQuery -Attributes name -Filter '(name=alice)'), + (New-MtADQuery -Attributes name -SearchBase 'OU=A,DC=example,DC=com'), + (New-MtADQuery -Attributes name -Scope OneLevel), + (New-MtADQuery -Attributes name,objectGUID), + (New-MtADQuery -Attributes name -SecurityDescriptorFlags Dacl), + (New-MtADQuery -Attributes name -SecurityDescriptorFlags Owner) + ) + foreach ($query in $queries) { + $null = Invoke-MtADQueryCached -Query $query -Operation $operation -PageSize 1000 -Timeout ([timespan]::FromSeconds(30)) + } + $script:ADQueryTestState.Reads | Should -Be 7 + $__MtSession.ADCache.ADQueryState.Results.Count | Should -Be 7 + $operation.Connection.Dispose() + } + } + + It 'resolves each naming context and explicit RootDSE without rediscovering the target' { + $queries = @( + (New-MtADQuery -Attributes name), + (New-MtADQuery -Attributes name -NamingContext Configuration), + (New-MtADQuery -Attributes name -NamingContext Schema), + (New-MtADQuery -Attributes defaultNamingContext -SearchBase '' -Scope Base) + ) + $results = @($queries | Invoke-MtADQuery -AsResult) + $results.Request.SearchBase | Should -Be @('DC=example,DC=com', 'CN=Configuration,DC=example,DC=com', 'CN=Schema,CN=Configuration,DC=example,DC=com', '') + Should -Invoke New-MtAdProtocolConnection -ModuleName Maester -Times 1 -Exactly -ParameterFilter { $ProtocolEvidence.ResolvedServer -eq 'dc1.example.com' } + InModuleScope Maester { $script:ADQueryTestState.Disposed | Should -Be 1 } + } + + It 'throws before cache access if the session is no longer connected or validated' { + $null = Invoke-MtADQuery -Attributes name + Mock -ModuleName Maester Test-MtConnection { $false } + { Invoke-MtADQuery -Attributes name } | Should -Throw '*must validate a target*' + Mock -ModuleName Maester Test-MtConnection { $true } + InModuleScope Maester { $__MtSession.ADConnection.ProtocolValidated = $false } + { Invoke-MtADQuery -Attributes name } | Should -Throw '*must validate a target*' + } + + It 'throws when a naming context is missing instead of querying an empty base' { + InModuleScope Maester { $__MtSession.ADConnection.SchemaNamingContext = $null } + { Invoke-MtADQuery -NamingContext Schema -Attributes name } | Should -Throw '*naming context is unavailable*' + Should -Invoke New-MtAdProtocolConnection -ModuleName Maester -Times 0 -Exactly + } + + It 'does not cache failed collections and disposes the connection' { + InModuleScope Maester { $script:ADQueryTestState.Fail = $true } + { Invoke-MtADQuery -Attributes name } | Should -Throw '*query test failure*' + InModuleScope Maester { + $__MtSession.ADCache.ADQueryState.Results.Count | Should -Be 0 + $script:ADQueryTestState.Disposed | Should -Be 1 + $script:ADQueryTestState.Fail = $false + } + @(Invoke-MtADQuery -Attributes name) | Should -HaveCount 1 + InModuleScope Maester { $script:ADQueryTestState.Reads | Should -Be 2 } + } + + It 'does not return or cache partial entries when a later page fails' { + InModuleScope Maester { + $script:ADQueryTestConnection.MtSendRequestOverride = { + param($request, $timeout) + $script:ADQueryTestState.Reads++ + if ($script:ADQueryTestState.Reads -gt 1) { throw 'second page failed' } + [pscustomobject]@{ + ResultCode = [System.DirectoryServices.Protocols.ResultCode]::Success + Entries = $script:ADQueryTestState.Entries + Controls = @([pscustomobject]@{ Cookie = [byte[]]@(1) }) + References = @() + } + } + $received = [System.Collections.Generic.List[object]]::new() + { Invoke-MtADQuery -Attributes name | ForEach-Object { $received.Add($_) } } | Should -Throw '*second page failed*' + $received.Count | Should -Be 0 + $__MtSession.ADCache.ADQueryState.Results.Count | Should -Be 0 + } + } + + It 'disposes the pipeline connection even when the consumer stops early' { + @((New-MtADQuery -Name User), (New-MtADQuery -Name Group)) | Invoke-MtADQuery | Select-Object -First 1 | Out-Null + InModuleScope Maester { $script:ADQueryTestState.Reads | Should -Be 1; $script:ADQueryTestState.Disposed | Should -Be 1 } + } + + It 'never caches or emits an entry with a missing range continuation' { + InModuleScope Maester { + $script:ADQueryTestConnection.MtSendRequestOverride = { + param($request, $timeout) + $script:ADQueryTestState.Reads++ + $entries = if ($request.Scope -eq [System.DirectoryServices.Protocols.SearchScope]::Base) { @() } + else { @([pscustomobject]@{ + DistinguishedName = 'CN=Group,DC=example,DC=com' + Attributes = [ordered]@{ 'member;range=0-0' = @('CN=Alice,DC=example,DC=com') } + }) } + [pscustomobject]@{ + ResultCode = [System.DirectoryServices.Protocols.ResultCode]::Success + Entries = $entries + Controls = @([pscustomobject]@{ Cookie = [byte[]]@() }) + References = @() + } + } + $received = [System.Collections.Generic.List[object]]::new() + { Invoke-MtADQuery -Name Group -Attributes member | ForEach-Object { $received.Add($_) } } | Should -Throw '*original entry*' + $received.Count | Should -Be 0 + $__MtSession.ADCache.ADQueryState.Results.Count | Should -Be 0 + $script:ADQueryTestState.Disposed | Should -Be 1 + } + } + + It 'preserves and isolates binary values on the first return and cache hits' { + InModuleScope Maester { + $script:ADQueryTestState.Entries[0].Attributes = [ordered]@{ customBlob = [byte[]]@(0, 255, 65) } + } + $first = Invoke-MtADQuery -Attributes customBlob -AsResult + $first.Entries[0].Attributes['customblob'][0][0] = 42 + $second = Invoke-MtADQuery -Attributes customBlob -AsResult + ($second.Entries[0].Attributes['customblob'][0] -is [byte[]]) | Should -BeTrue + $second.Entries[0].Attributes['customblob'][0][0] | Should -Be 0 + InModuleScope Maester { $script:ADQueryTestState.Reads | Should -Be 1 } + } + + It 'does not cache known text values with invalid UTF-8' { + InModuleScope Maester { $script:ADQueryTestState.Entries[0].Attributes = [ordered]@{ name = [byte[]]@(255) } } + { Invoke-MtADQuery -Attributes name } | Should -Throw + InModuleScope Maester { + $__MtSession.ADCache.ADQueryState.Results.Count | Should -Be 0 + $script:ADQueryTestState.Disposed | Should -Be 1 + } + } + + It 'invalidates only new results when connection evidence or credentials change' { + InModuleScope Maester { + $__MtSession.ADCache['DomainState:Users'] = @{ Users = @('legacy') } + $operation = @{ Connection = $null } + $query = New-MtADQuery -Attributes name + $null = Invoke-MtADQueryCached -Query $query -Operation $operation -PageSize 1 -Timeout ([timespan]::FromSeconds(30)) + $__MtSession.ADConnection = [ordered]@{} + $__MtSession.ADConnection + $null = Invoke-MtADQueryCached -Query $query -Operation $operation -PageSize 1 -Timeout ([timespan]::FromSeconds(30)) + $__MtSession.ADCredential = [pscredential]::new('reader', [securestring]::new()) + $null = Invoke-MtADQueryCached -Query $query -Operation $operation -PageSize 1 -Timeout ([timespan]::FromSeconds(30)) + $script:ADQueryTestState.Reads | Should -Be 3 + $__MtSession.ADCache['DomainState:Users'].Users | Should -Be @('legacy') + $operation.Connection.Dispose() + } + } + + It 'invalidates on changed resolved target or TLS identity' { + InModuleScope Maester { + $operation = @{ Connection = $null } + $query = New-MtADQuery -Attributes name + $null = Invoke-MtADQueryCached -Query $query -Operation $operation -PageSize 1 -Timeout ([timespan]::FromSeconds(30)) + $__MtSession.ADConnection.ResolvedServer = 'dc2.example.com' + $result = Invoke-MtADQueryCached -Query $query -Operation $operation -PageSize 1 -Timeout ([timespan]::FromSeconds(30)) + $result.Request.Target.Server | Should -Be 'dc2.example.com' + $__MtSession.ADConnection.TlsMode = 'StartTls' + $result = Invoke-MtADQueryCached -Query $query -Operation $operation -PageSize 1 -Timeout ([timespan]::FromSeconds(30)) + $result.Request.Target.Port | Should -Be 389 + $script:ADQueryTestState.Reads | Should -Be 3 + $operation.Connection.Dispose() + } + } + + It 'resets with a full AD cache clear but remains separate from scoped legacy clears' { + InModuleScope Maester { + $operation = @{ Connection = $null } + $query = New-MtADQuery -Attributes name + $null = Invoke-MtADQueryCached -Query $query -Operation $operation -PageSize 1 -Timeout ([timespan]::FromSeconds(30)) + Clear-MtADCache -Categories Users + $null = Invoke-MtADQueryCached -Query $query -Operation $operation -PageSize 1 -Timeout ([timespan]::FromSeconds(30)) + $script:ADQueryTestState.Reads | Should -Be 1 + Clear-MtADCache + $null = Invoke-MtADQueryCached -Query $query -Operation $operation -PageSize 1 -Timeout ([timespan]::FromSeconds(30)) + $script:ADQueryTestState.Reads | Should -Be 2 + $operation.Connection.Dispose() + } + } +} diff --git a/website/astro.config.mjs b/website/astro.config.mjs index 37090a182d..43fd6e5211 100644 --- a/website/astro.config.mjs +++ b/website/astro.config.mjs @@ -115,7 +115,7 @@ export default defineConfig({ { label: 'Automate', items: [{ autogenerate: { directory: 'docs/monitoring' } }] }, { label: 'Alerts', items: [{ autogenerate: { directory: 'docs/alerts' } }] }, { label: 'Many tenants', items: [{ autogenerate: { directory: 'docs/multi-tenant' } }] }, - { label: 'Active Directory', items: ['docs/advanced/active-directory'] }, + { label: 'Active Directory', items: ['docs/advanced/active-directory', 'docs/advanced/ad-query-collection'] }, { label: 'Maester Packs', items: [ @@ -204,4 +204,3 @@ export default defineConfig({ redirects(), ], }); - diff --git a/website/docs/advanced/ad-query-collection.md b/website/docs/advanced/ad-query-collection.md new file mode 100644 index 0000000000..f92f4aa362 --- /dev/null +++ b/website/docs/advanced/ad-query-collection.md @@ -0,0 +1,150 @@ +--- +title: Modular Active Directory queries +--- + +# Modular Active Directory queries + +Maester provides an opt-in LDAP query API for custom tests and collectors. It adds +`New-MtADQuery`, `Invoke-MtADQuery` and `ConvertTo-MtLdapFilterValue`; it does not +replace or change the existing Active Directory collectors. Connect first with +`Connect-Maester -Service ActiveDirectory` so Maester can validate the target. + +## Define and run a query + +`New-MtADQuery` creates a reusable query definition without contacting a domain +controller. Its small starter selections are `User`, `Computer`, `Group`, +`OrganizationalUnit` and `Gpo`. They are intentionally not the richer projections +or legacy output shapes used by existing collectors. You can replace a starter's +attribute selection, or describe a custom query with explicit attributes: + +```powershell +$query = New-MtADQuery -Name User -Attributes name,sAMAccountName,userAccountControl +$users = Invoke-MtADQuery -Query $query + +$custom = @{ + SearchBase = 'OU=Service Accounts,DC=example,DC=com' + Scope = 'OneLevel' + Filter = '(objectClass=user)' + Attributes = @('name', 'sAMAccountName') +} +$accounts = Invoke-MtADQuery -Query $custom +``` + +Queries can also be passed through the pipeline or specified directly: + +```powershell +@($query, (New-MtADQuery -Name Group -Attributes name,member)) | + Invoke-MtADQuery -AsResult + +$computers = Invoke-MtADQuery -Name Computer +$schema = Invoke-MtADQuery -NamingContext Schema ` + -Filter '(objectClass=attributeSchema)' -Attributes name,lDAPDisplayName +``` + +`Invoke-MtADQuery` accepts a query object, dictionary or `PSCustomObject`. A query +uses the connected server's `Default` naming context unless another context is +selected; `Configuration` and `Schema` are also available. Alternatively, supply +an explicit distinguished name with `SearchBase`. These options cannot be combined. +Use `SearchBase '' -Scope Base` to query RootDSE. The default scope is `Subtree`. +The default filter is `(objectClass=*)`; a named starter supplies its own filter. + +By default the command emits entries. With `-AsResult`, it emits an envelope with +`Entries`, the normalized `Request`, and UTC `CollectedAt` metadata. Each entry has +a scalar `DistinguishedName` and an `Attributes` dictionary. Attribute names are +lowercase and values are always arrays, including single-valued attributes: + +```powershell +$users[0].DistinguishedName +$users[0].Attributes['samaccountname'][0] +``` + +The distinguished name is always available on the entry, even when it was not +requested as an attribute. Absent attributes are omitted; +their absence cannot tell you whether an attribute is unset or unreadable. Known +GUID attributes are returned as `[guid]` values and known SID attributes as strings. +Standard text attributes (including the starter selections, `member`, `memberOf`, +`description`, `servicePrincipalName` and `lDAPDisplayName`), and known date, integer, +boolean and interval attributes are decoded by name. Invalid UTF-8 for a known text +attribute throws. FILETIME values of `0` and `Int64.MaxValue` remain integers so their +unset/never meanings are not lost. Other attributes received as bytes remain byte +arrays, **even if they contain text**. This API does not read the schema to infer their +types. To decode a custom text attribute whose syntax you know, use: + +```powershell +[Text.UTF8Encoding]::new($false, $true).GetString($entry.Attributes['customattribute'][0]) +``` + +Security descriptors remain byte arrays on all operating systems and are not parsed. +No live credentials or LDAP +connection objects are included in results. + +## Filters, completeness and caching + +Filters are raw LDAP filter syntax. Escape interpolated assertion values with +`ConvertTo-MtLdapFilterValue`, which supports strings, byte arrays and GUIDs (using +AD GUID byte order). It escapes filter assertion values only: it does not escape DNs, +attribute names or an entire filter. Do not build filters from untrusted raw input. +Pass binary values with `-Value $bytes`, not `$bytes | ConvertTo-MtLdapFilterValue`, +because PowerShell enumerates byte arrays in the pipeline. +The query validator accepts explicit LDAP display names +only; wildcards, OIDs, attribute options and known password or recovery-secret +attributes are rejected. This denylist helps prevent accidental secret collection, +but is not an authorization boundary. + +Results are collected completely, including LDAP pages and ranged attributes, +before they are returned or cached. A successful empty result is cached. If a query, +page or range continuation fails, the command throws and returns no partial result. +The query's domain-scope control confines the search to its naming context; this +does not make a query across one context a complete forest inventory. The validated +target is pinned for the query rather than rediscovered through DNS. + +Successful results are cached on first read for the Maester session. This is a +per-query cache, not an atomic directory snapshot: different queries can observe +directory changes made at different times. `Clear-MtADCache` with no parameters +clears this cache; per-run session reset and AD disconnect also clear it. Legacy +category-scoped cache resets do not clear these query results. Reconnection or a +change in connection state, credential reference or target identity invalidates the +new query cache. There is no cache-bypass switch. + +The API holds complete results in memory and returns independent copies on cache +hits. Copying large results consumes CPU as well as memory, even without another +LDAP request. Request only the +attributes and scope needed. + +## Opt-in migration for custom collectors + +The new commands are exported and available to custom tests. For example, an +external collector can opt in and adapt the new result contract to its own shape: + +```powershell +function Get-MyUserInventory { + $entries = Invoke-MtADQuery -Query ( + New-MtADQuery -Name User -Attributes name,sAMAccountName,userAccountControl) + + foreach ($entry in $entries) { + $uac = $entry.Attributes['useraccountcontrol'] + [pscustomobject]@{ + DistinguishedName = $entry.DistinguishedName + SamAccountName = if ($entry.Attributes.Contains('samaccountname')) { + $entry.Attributes['samaccountname'][0] + } else { $null } + Enabled = if ($null -ne $uac -and $uac.Count -gt 0 -and $null -ne $uac[0]) { + -not ([int]$uac[0] -band 2) + } else { $null } + } + } +} +``` + +Existing `Get-MtLdap` helpers, `ADDomainState`, `ADGpoState`, `ADDacls` and the +legacy query catalog are not rewired to this API. Their richer projections, gates, +and contracts (including distinctions between null and empty results) remain in +place. This API does not add automatic affected-object reporting or persistent +cache storage. + +Any future internal migration should preserve the original attributes, filters and +security-descriptor controls, as well as range and relationship semantics, category +dependencies, and failure/skip behavior. Compare old and new results against fixtures +on Windows and Linux. The new query cache currently supports full reset only, so a +coordinated aggregate invalidation strategy is needed before legacy collectors can +share it. Do not bypass the session cache as a migration workaround. From 4339c9fb6bd6b03d37b42903e166bf209581dfc3 Mon Sep 17 00:00:00 2001 From: Snozz-Al Date: Sat, 21 Nov 2026 18:07:04 +0000 Subject: [PATCH 2/2] fix(ad): handle range placeholders and abort failed conversions --- .../services/ad/Complete-MtADQueryRange.ps1 | 6 +- .../services/ad/Invoke-MtADQueryCached.ps1 | 16 ++- .../functions/ADQueryTransport.Tests.ps1 | 39 +++++- .../functions/Invoke-MtADQuery.Tests.ps1 | 120 +++++++++++++++++- website/docs/advanced/ad-query-collection.md | 4 + 5 files changed, 178 insertions(+), 7 deletions(-) diff --git a/powershell/internal/services/ad/Complete-MtADQueryRange.ps1 b/powershell/internal/services/ad/Complete-MtADQueryRange.ps1 index 8f30239a97..c22c365e94 100644 --- a/powershell/internal/services/ad/Complete-MtADQueryRange.ps1 +++ b/powershell/internal/services/ad/Complete-MtADQueryRange.ps1 @@ -16,7 +16,11 @@ function Complete-MtADQueryRange { $expectedStart = 0L $rangeKey = $key $rangeBag = $Entry.Attributes - if ($Entry.Attributes.Contains($attribute)) { throw 'LDAP returned ambiguous ranged and non-ranged values.' } + # AD can return an empty base attribute alongside the populated range. + # Only a populated base attribute conflicts with the ranged values. + if ($Entry.Attributes.Contains($attribute) -and $Entry.Attributes[$attribute].Count -gt 0) { + throw 'LDAP returned ambiguous ranged and non-ranged values.' + } while ($true) { if ($rangeKey -notmatch ('^' + [regex]::Escape($attribute) + ';range=(\d+)-(\d+|\*)$')) { diff --git a/powershell/internal/services/ad/Invoke-MtADQueryCached.ps1 b/powershell/internal/services/ad/Invoke-MtADQueryCached.ps1 index 32f5571647..1024e0b0b0 100644 --- a/powershell/internal/services/ad/Invoke-MtADQueryCached.ps1 +++ b/powershell/internal/services/ad/Invoke-MtADQueryCached.ps1 @@ -71,9 +71,19 @@ function Invoke-MtADQueryCached { RequireComplete = $true } if ($null -ne $request.SecurityDescriptorFlags) { $parameters.SecurityDescriptorFlags = $Query.SecurityDescriptorFlags } - $entries = @(Invoke-MtLdapSearch @parameters | ForEach-Object { - Complete-MtADQueryRange -Connection $Operation.Connection -Entry $_ -Timeout $Timeout - }) + $previousErrorPreference = $ErrorActionPreference + try { + # Method/conversion errors must abort collection even when the caller uses Continue. + $ErrorActionPreference = 'Stop' + $entries = @(Invoke-MtLdapSearch @parameters | ForEach-Object { + Complete-MtADQueryRange -Connection $Operation.Connection -Entry $_ -Timeout $Timeout + }) + } catch { + # Rethrow so the caller's script stops, rather than merely skipping the failed statement. + throw + } finally { + $ErrorActionPreference = $previousErrorPreference + } # Commit only after every page and every ranged attribute succeeds, including successful empty results. $state.Results[$key] = [pscustomobject]@{ PSTypeName = 'Maester.AD.QueryResult' diff --git a/powershell/tests/functions/ADQueryTransport.Tests.ps1 b/powershell/tests/functions/ADQueryTransport.Tests.ps1 index 1c883bd5f4..684420ab44 100644 --- a/powershell/tests/functions/ADQueryTransport.Tests.ps1 +++ b/powershell/tests/functions/ADQueryTransport.Tests.ps1 @@ -8,11 +8,13 @@ Describe 'AD query LDAP transport and range completion' { $script:ADDn = 'CN=User,DC=contoso,DC=com' function New-ADEntry { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an in-memory LDAP entry fixture; no directory or system state is changed.')] param([System.Collections.IDictionary] $Attributes = ([ordered]@{}), [string] $Dn = $script:ADDn) [pscustomobject]@{ DistinguishedName = $Dn; Attributes = $Attributes } } function New-ADResponse { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an in-memory LDAP response fixture; no directory or system state is changed.')] param([object[]] $Entries = @(), [object[]] $Controls = @(), [object[]] $References = @(), [object] $ResultCode = [System.DirectoryServices.Protocols.ResultCode]::Success) @@ -25,13 +27,15 @@ Describe 'AD query LDAP transport and range completion' { } function New-ADFixture { + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Creates an unbound in-memory LDAP client with a fixture response hook; no connection is established.')] param([object[]] $Responses) - $state = @{ Responses = $Responses; Index = 0; Requests = [System.Collections.Generic.List[object]]::new() } + $state = @{ Responses = $Responses; Index = 0; Requests = [System.Collections.Generic.List[object]]::new(); Timeouts = [System.Collections.Generic.List[object]]::new() } $connection = [System.DirectoryServices.Protocols.LdapConnection]::new('ldap.mock') $script:FixtureConnections.Add($connection) $hook = { param($request, $timeout) $state.Requests.Add($request) + $state.Timeouts.Add($timeout) $index = $state.Index $state.Index++ if ($index -ge $state.Responses.Count) { throw 'Unexpected LDAP request.' } @@ -228,7 +232,7 @@ Describe 'AD query LDAP transport and range completion' { $fixture = New-ADFixture @() $arguments = @{ Connection = $fixture.Connection; SearchBase = $script:ADBase; Attributes = @('cn'); PageSize = 0 } $arguments[$option] = $true - $arguments[$incompatible] = if ($incompatible -eq 'ProcessPage') { { param($page, $state) } } else { $true } + $arguments[$incompatible] = if ($incompatible -eq 'ProcessPage') { {} } else { $true } { $script:MaesterModule.Invoke({ param($p) Invoke-MtLdapSearch @p }, $arguments) } | Should -Throw '*modular query contract*' $fixture.State.Index | Should -Be 0 } @@ -237,6 +241,36 @@ Describe 'AD query LDAP transport and range completion' { } Context 'ranged attribute completion' { + It 'accepts an empty base placeholder with a populated response' -ForEach @( + @{ Range = 'member;range=0-1'; Continuation = $true } + @{ Range = 'member;range=0-*'; Continuation = $false } + ) { + $base = [System.DirectoryServices.Protocols.DirectoryAttribute]::new() + $base.Name = 'member' + $ranged = [System.DirectoryServices.Protocols.DirectoryAttribute]::new() + $ranged.Name = $Range + [void]$ranged.Add([Text.Encoding]::UTF8.GetBytes('CN=Alice')) + [void]$ranged.Add([Text.Encoding]::UTF8.GetBytes('CN=Bob')) + $attributes = [ordered]@{ member = $base } + $attributes[$Range] = $ranged + $responses = @((New-ADResponse -Entries @((New-ADEntry $attributes)))) + if ($Continuation) { + $responses += New-ADResponse -Entries @((New-ADEntry ([ordered]@{ 'member;range=2-*' = @('CN=Carol') }))) + } + $fixture = New-ADFixture $responses + $result = $script:MaesterModule.Invoke({ param($c, $b) + $entry = Invoke-MtLdapSearch -Connection $c -SearchBase $b -Attributes member -PageSize 0 -AsAttributeBag -RequireComplete + Complete-MtADQueryRange -Connection $c -Entry $entry -Timeout ([timespan]::FromSeconds(5)) + }, $fixture.Connection, $script:ADBase) + $expected = @('CN=Alice', 'CN=Bob') + if ($Continuation) { $expected += 'CN=Carol' } + $result.Attributes['member'] | Should -Be $expected + ($result.Attributes['member'] -is [object[]]) | Should -BeTrue + @($result.Attributes.Keys | Where-Object { $_ -match ';range=' }) | Should -HaveCount 0 + $fixture.State.Index | Should -Be $(if ($Continuation) { 2 } else { 1 }) + if ($Continuation) { $fixture.State.Timeouts[1] | Should -Be ([timespan]::FromSeconds(5)) } + } + It 'decodes ranged membership from server byte values on initial and continuation responses' { $first = [System.DirectoryServices.Protocols.DirectoryAttribute]::new() [void]$first.Add([Text.Encoding]::UTF8.GetBytes('CN=Alice')) @@ -273,6 +307,7 @@ Describe 'AD query LDAP transport and range completion' { @($fixture.State.Requests[1].Attributes) | Should -HaveCount 1 $fixture.State.Requests[0].Attributes[0] | Should -Be 'member;range=2-*' $fixture.State.Requests[1].Attributes[0] | Should -Be 'member;range=4-*' + $fixture.State.Timeouts | Should -Be @([timespan]::FromSeconds(5), [timespan]::FromSeconds(5)) } It 'normalizes an initially final range without requesting another page' { diff --git a/powershell/tests/functions/Invoke-MtADQuery.Tests.ps1 b/powershell/tests/functions/Invoke-MtADQuery.Tests.ps1 index 1173e8d221..166430e308 100644 --- a/powershell/tests/functions/Invoke-MtADQuery.Tests.ps1 +++ b/powershell/tests/functions/Invoke-MtADQuery.Tests.ps1 @@ -82,6 +82,7 @@ Describe 'Invoke-MtADQuery additive cached collection' { Disposed = 0 Fail = $false Requests = [System.Collections.Generic.List[object]]::new() + Timeouts = [System.Collections.Generic.List[object]]::new() Entries = @([pscustomobject]@{ DistinguishedName = 'CN=Alice,DC=example,DC=com' Attributes = [ordered]@{ name = @('Alice'); objectGUID = [guid]'00112233-4455-6677-8899-aabbccddeeff' } @@ -97,6 +98,7 @@ Describe 'Invoke-MtADQuery additive cached collection' { param($request, $timeout) $script:ADQueryTestState.Reads++ $script:ADQueryTestState.Requests.Add($request) + $script:ADQueryTestState.Timeouts.Add($timeout) if ($script:ADQueryTestState.Fail) { throw 'query test failure' } [pscustomobject]@{ ResultCode = [System.DirectoryServices.Protocols.ResultCode]::Success @@ -130,7 +132,11 @@ Describe 'Invoke-MtADQuery additive cached collection' { $rows[0].Attributes['name'][0] | Should -Be 'Alice' $rows[0].Attributes['objectguid'][0] | Should -BeOfType ([guid]) Should -Invoke New-MtAdProtocolConnection -ModuleName Maester -Times 1 -Exactly - InModuleScope Maester { $script:ADQueryTestState.Reads | Should -Be 1; $script:ADQueryTestState.Disposed | Should -Be 1 } + InModuleScope Maester { + $script:ADQueryTestState.Reads | Should -Be 1 + $script:ADQueryTestState.Disposed | Should -Be 1 + $script:ADQueryTestState.Timeouts[0] | Should -Be ([timespan]::FromSeconds(30)) + } } It 'caches successful empty collections without mistaking them for a miss' { @@ -225,6 +231,8 @@ Describe 'Invoke-MtADQuery additive cached collection' { $script:ADQueryTestConnection.MtSendRequestOverride = { param($request, $timeout) $script:ADQueryTestState.Reads++ + $script:ADQueryTestState.Requests.Add($request) + $script:ADQueryTestState.Timeouts.Add($timeout) if ($script:ADQueryTestState.Reads -gt 1) { throw 'second page failed' } [pscustomobject]@{ ResultCode = [System.DirectoryServices.Protocols.ResultCode]::Success @@ -250,6 +258,7 @@ Describe 'Invoke-MtADQuery additive cached collection' { $script:ADQueryTestConnection.MtSendRequestOverride = { param($request, $timeout) $script:ADQueryTestState.Reads++ + $script:ADQueryTestState.Timeouts.Add($timeout) $entries = if ($request.Scope -eq [System.DirectoryServices.Protocols.SearchScope]::Base) { @() } else { @([pscustomobject]@{ DistinguishedName = 'CN=Group,DC=example,DC=com' @@ -270,6 +279,38 @@ Describe 'Invoke-MtADQuery additive cached collection' { } } + It 'completes and caches ranged membership when AD returns an empty base placeholder' { + InModuleScope Maester { + $script:ADQueryTestConnection.MtSendRequestOverride = { + param($request, $timeout) + $script:ADQueryTestState.Reads++ + $script:ADQueryTestState.Requests.Add($request) + $script:ADQueryTestState.Timeouts.Add($timeout) + $attributes = if ($request.Scope -eq [System.DirectoryServices.Protocols.SearchScope]::Base) { + [ordered]@{ 'member;range=1-*' = @('CN=Bob') } + } else { + [ordered]@{ member = @(); 'member;range=0-0' = @('CN=Alice') } + } + [pscustomobject]@{ + ResultCode = [System.DirectoryServices.Protocols.ResultCode]::Success + Entries = @([pscustomobject]@{ DistinguishedName = 'CN=Group,DC=example,DC=com'; Attributes = $attributes }) + Controls = @([pscustomobject]@{ Cookie = [byte[]]@() }) + References = @() + } + } + } + $first = Invoke-MtADQuery -Name Group -Attributes member -AsResult + $first.Entries[0].Attributes['member'] | Should -Be @('CN=Alice', 'CN=Bob') + @($first.Entries[0].Attributes.Keys | Where-Object { $_ -match ';range=' }) | Should -HaveCount 0 + $cached = Invoke-MtADQuery -Name Group -Attributes member -AsResult + $cached.CollectedAt | Should -Be $first.CollectedAt + $cached.Entries[0].Attributes['member'] | Should -Be @('CN=Alice', 'CN=Bob') + InModuleScope Maester { + $script:ADQueryTestState.Reads | Should -Be 2 + $script:ADQueryTestState.Disposed | Should -Be 1 + } + } + It 'preserves and isolates binary values on the first return and cache hits' { InModuleScope Maester { $script:ADQueryTestState.Entries[0].Attributes = [ordered]@{ customBlob = [byte[]]@(0, 255, 65) } @@ -291,6 +332,83 @@ Describe 'Invoke-MtADQuery additive cached collection' { } } + It 'terminates conversion failures under Continue without an enclosing error handler' { + # A fresh runspace isolates the call from Pester's own exception handlers and preferences. + $runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace() + $powershell = [powershell]::Create() + try { + $runspace.Open() + $powershell.Runspace = $runspace + $script = @' +param($Manifest) +Import-Module $Manifest -Force -ErrorAction Stop +$ErrorActionPreference = 'Continue' +$script:ReachedAfterQuery = $false +& (Get-Module Maester) { + $__MtSession.ADCache = @{} + $__MtSession.ADCredential = $null + $__MtSession.ADConnection = [ordered]@{ + ProtocolValidated = $true; ResolvedServer = 'ldap.mock'; DefaultNamingContext = 'DC=example,DC=com' + AuthenticationMode = 'Negotiate'; TlsMode = 'Ldaps'; SkipCertificateCheck = $false + } + $script:ContinueFixture = @{ Disposed = 0 } + $script:ContinueConnection = [System.DirectoryServices.Protocols.LdapConnection]::new('ldap.mock') + $script:ContinueConnection | Add-Member NoteProperty Fixture $script:ContinueFixture + $script:ContinueConnection | Add-Member ScriptMethod Dispose { + $this.Fixture.Disposed++ + $this.psbase.Dispose() + } -Force + $script:ContinueConnection | Add-Member NoteProperty MtSendRequestOverride { + [pscustomobject]@{ + ResultCode = [System.DirectoryServices.Protocols.ResultCode]::Success + Entries = @( + [pscustomobject]@{ DistinguishedName = 'CN=Valid'; Attributes = [ordered]@{ name = @('Valid') } } + [pscustomobject]@{ DistinguishedName = 'CN=Invalid'; Attributes = [ordered]@{ name = [byte[]]@(255) } } + ) + Controls = @([pscustomobject]@{ Cookie = [byte[]]@() }) + References = @() + } + } + function script:Test-MtConnection { param([string]$Service) $Service -eq 'ActiveDirectory' } + function script:New-MtAdProtocolConnection { + param([object]$ProtocolEvidence) + if ($ProtocolEvidence.ResolvedServer -ne 'ldap.mock') { throw 'Unexpected fixture target.' } + $script:ContinueConnection + } +} +Invoke-MtADQuery -Attributes name -AsResult +$script:ReachedAfterQuery = $true +'@ + $null = $powershell.AddScript($script).AddArgument((Join-Path $PSScriptRoot '../../Maester.psd1')) + $output = @() + $failure = $null + # Catch only the host-side Invoke exception. The isolated script has no error handler. + try { $output = @($powershell.Invoke()) } catch { $failure = $_ } + $failure | Should -Not -BeNullOrEmpty + $output | Should -HaveCount 0 + $powershell.InvocationStateInfo.State | Should -Be ([System.Management.Automation.PSInvocationState]::Failed) + $powershell.Commands.Clear() + $powershell.Streams.Error.Clear() + $null = $powershell.AddScript(@' +$module = Get-Module Maester +[pscustomobject]@{ + CacheEntries = $module.Invoke({ $__MtSession.ADCache.ADQueryState.Results.Count })[0] + Disposed = $module.Invoke({ $script:ContinueFixture.Disposed })[0] + ReachedAfterQuery = $script:ReachedAfterQuery + ErrorPreference = $ErrorActionPreference +} +'@) + $state = @($powershell.Invoke())[0] + $state.CacheEntries | Should -Be 0 + $state.Disposed | Should -Be 1 + $state.ReachedAfterQuery | Should -BeFalse + $state.ErrorPreference | Should -Be 'Continue' + } finally { + $powershell.Dispose() + $runspace.Dispose() + } + } + It 'invalidates only new results when connection evidence or credentials change' { InModuleScope Maester { $__MtSession.ADCache['DomainState:Users'] = @{ Users = @('legacy') } diff --git a/website/docs/advanced/ad-query-collection.md b/website/docs/advanced/ad-query-collection.md index f92f4aa362..b4adbf4a12 100644 --- a/website/docs/advanced/ad-query-collection.md +++ b/website/docs/advanced/ad-query-collection.md @@ -9,6 +9,10 @@ Maester provides an opt-in LDAP query API for custom tests and collectors. It ad replace or change the existing Active Directory collectors. Connect first with `Connect-Maester -Service ActiveDirectory` so Maester can validate the target. +These three exported commands are public API for custom tests and collectors. Their +documented query parameters and result shapes form the compatibility contract; +existing internal collector helpers are not promoted to public commands. + ## Define and run a query `New-MtADQuery` creates a reusable query definition without contacting a domain