src/Get-AZSCIdSegment.ps1
|
#Requires -Version 7.0 Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' <# .Synopsis Reads one '/'-delimited segment out of an Azure resource id, safely under StrictMode. .DESCRIPTION Several declarative collectors pull a name out of a related resource's id with a FIXED index -- `$data.networkSecurityGroup.id.split('/')[8]` for the NSG name, `$1.MANAGEDBY.split('/')[8]` for the VM a disk is attached to, `($_.id -split '/')[10]` for a subnet -- because the canonical resource id /subscriptions/{s}/resourceGroups/{rg}/providers/{Namespace}/{type}/{name} 0 1 2 3 4 5 6 7 8 puts the name at index 8. Plenty of real ids are shorter than that. A subscription-scoped id (a Defender or Security assessment with no resource target, a subscription-level policy assignment) has five or six segments; a `managedBy` can be a bare resource group id. Under Set-StrictMode -Version Latest an out-of-range array index THROWS Index was outside the bounds of the array. where without StrictMode it quietly returns $null (AB#5671) -- so the collectors were written against the quiet behaviour and crash under the strict one. That is the third of the three StrictMode defect classes in the collectors, alongside the absent-property read (Get-AZSCSafeProperty) and the empty-collection member enumeration (Get-AZSCCollectedValue). This function returns $null for an out-of-range index, a $null/empty id, or a non-string id, which is exactly what the unguarded expression produced with StrictMode off. Nothing about a collector's output changes for an id that IS long enough. .PARAMETER Id The resource id to split. $null, empty and non-string values are accepted and return $null. .PARAMETER Index The zero-based segment index. 8 is the resource name in a canonical resource id. .OUTPUTS The segment at that index, or $null if the id has too few segments. .EXAMPLE Get-AZSCIdSegment -Id $data.networkSecurityGroup.id -Index 8 .EXAMPLE # The guarded form of ($_.id -split '/')[10] -- a subnet name. Get-AZSCIdSegment -Id $_.id -Index 10 .COMPONENT This PowerShell Module is part of Azure Scout (AZSC). #> function Get-AZSCIdSegment { [CmdletBinding()] Param( [Parameter(Position = 0, ValueFromPipeline)] [AllowNull()] [AllowEmptyString()] $Id, [Parameter(Mandatory, Position = 1)] [int]$Index ) process { if ($null -eq $Id) { return $null } # A member-enumeration result can arrive here as an array of ids; [string] on it matches # what the unguarded `$array.split('/')` chain degenerated to rather than inventing a new # answer, and the single-id case (every real caller) is unaffected. $Text = [string]$Id if ([string]::IsNullOrEmpty($Text)) { return $null } $Segments = @($Text -split '/') if ($Index -lt 0 -or $Index -ge $Segments.Count) { return $null } return $Segments[$Index] } } # --- Resource lookups for collectors, indexed once per resource list (#110) ------------------------ # # Twenty-one collectors looked up a related row inside their per-row loop with # $Resources | Where-Object { $_.id -eq $1.PARENTID } # $Resources | Where-Object { $_.TYPE -eq 'AZSC/Operational/VirtualMachine' -and $_.id -eq $1.id } # which tests every resource in the run once per row. On a 90-subscription tenant (281,529 rows) # Compute/VirtualMachine took 45 minutes for 135 VMs. These helpers index the list once (by id, by # type, and by type + id) and answer each lookup from the index, returning the same rows in the same # order the Where-Object scan returned. The comparison is the one -eq made: case-insensitive. A null # or empty id is answered by the original scan, so even that edge behaves exactly as before. $script:AZSCResourceLookup = $null $script:AZSCResourceIndexerState = $null function Initialize-AZSCResourceIndexer { <# .SYNOPSIS Compiles the index build (one pass over the list, three dictionaries) once per session; $false when compilation is unavailable, in which case Get-AZSCResourceLookup builds it in PowerShell. Same keys, same lists, same order either way. 280,000 rows took minutes as a PowerShell loop. #> [CmdletBinding()] [OutputType([bool])] param() if ($null -ne $script:AZSCResourceIndexerState) { return [bool]$script:AZSCResourceIndexerState } if ('AzureScout.ResourceIndexer' -as [type]) { $script:AZSCResourceIndexerState = $true; return $true } $source = @' using System; using System.Collections; using System.Collections.Generic; using System.Management.Automation; namespace AzureScout { public static class ResourceIndexer { private static string ReadString(PSObject item, string name) { PSPropertyInfo property = item.Properties[name]; if (property == null) { return null; } object value = property.Value; PSObject wrapped = value as PSObject; if (wrapped != null) { value = wrapped.BaseObject; } return value as string; } private static void Add(Dictionary<string, List<object>> map, string key, object item) { List<object> list; if (!map.TryGetValue(key, out list)) { list = new List<object>(); map[key] = list; } list.Add(item); } // Returns the number of entries visited (nulls included), as the PowerShell builder counts them. public static int Build(IEnumerable source, Dictionary<string, List<object>> byId, Dictionary<string, List<object>> byType, Dictionary<string, List<object>> byTypeId) { int count = 0; if (source == null) { return 0; } foreach (object entry in source) { count++; if (entry == null) { continue; } PSObject item = PSObject.AsPSObject(entry); string id = ReadString(item, "id"); string type = ReadString(item, "TYPE"); object row = entry; if (!string.IsNullOrEmpty(id)) { Add(byId, id, row); } if (!string.IsNullOrEmpty(type)) { Add(byType, type, row); if (!string.IsNullOrEmpty(id)) { Add(byTypeId, type + "|" + id, row); } } } return count; } } } '@ try { Add-Type -TypeDefinition $source -Language CSharp -ErrorAction Stop $script:AZSCResourceIndexerState = $true } catch { Write-Verbose "Initialize-AZSCResourceIndexer: compiled index build unavailable, using PowerShell: $($_.Exception.Message)" $script:AZSCResourceIndexerState = $false } return [bool]$script:AZSCResourceIndexerState } function New-AZSCResourceLookupRecord { <# .SYNOPSIS The cached index plus the rows Get-AZSCResourceLookup samples to recognise the same list again. #> [CmdletBinding(SupportsShouldProcess = $false)] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Builds an in-memory object; changes no state.')] param($Source, [int] $Count, $ById, $ByType, $ByTypeId) $first = $null; $middle = $null; $last = $null if ($Source -is [System.Collections.IList] -and $Count -gt 0 -and $Source.Count -eq $Count) { $first = $Source[0]; $middle = $Source[[int][Math]::Floor($Count / 2)]; $last = $Source[$Count - 1] } [pscustomobject]@{ Count = $Count; First = $first; Middle = $middle; Last = $last; ById = $ById; ByType = $ByType; ByTypeId = $ByTypeId } } function Get-AZSCResourceLookup { <# .SYNOPSIS The id / type index of a resource list, built once and reused while the list is the same object. #> [CmdletBinding()] param([AllowNull()] $Resources) # Assigned inside each branch on purpose: `$source = if (...) { $Resources }` would enumerate a # multi-row list into a NEW array, so the reference check below would never match and the index # would be rebuilt on every lookup. if ($Resources -is [psobject]) { $source = $Resources.psobject.BaseObject } else { $source = $Resources } $cached = $script:AZSCResourceLookup # A list's own Count, not @($source).Count: that copies the whole list on every lookup. $sourceCount = if ($source -is [System.Collections.ICollection]) { $source.Count } elseif ($null -eq $source) { 0 } else { -1 } # Is this the list the cached index was built from? Handing the list itself to a .NET method # ([object]::ReferenceEquals($cached.Source, $source)) costs ~14 ms per call on a 280,000-row list, # because PowerShell converts the argument. So the check is the count plus the identity of the # first, middle and last rows: single objects, cheap to compare. A different list that matched all # four would have to be a copy with only other rows changed; collectors never modify $Resources. if ($null -ne $cached -and $sourceCount -gt 0 -and $cached.Count -eq $sourceCount -and $source -is [System.Collections.IList]) { $middle = [int][Math]::Floor($sourceCount / 2) if ([object]::ReferenceEquals($cached.First, $source[0]) -and [object]::ReferenceEquals($cached.Middle, $source[$middle]) -and [object]::ReferenceEquals($cached.Last, $source[$sourceCount - 1])) { return $cached } } $byId = [System.Collections.Generic.Dictionary[string, System.Collections.Generic.List[object]]]::new([System.StringComparer]::OrdinalIgnoreCase) $byType = [System.Collections.Generic.Dictionary[string, System.Collections.Generic.List[object]]]::new([System.StringComparer]::OrdinalIgnoreCase) $byTypeId = [System.Collections.Generic.Dictionary[string, System.Collections.Generic.List[object]]]::new([System.StringComparer]::OrdinalIgnoreCase) $count = 0 $enumerable = $source -as [System.Collections.IEnumerable] if ($null -ne $enumerable -and $source -isnot [string] -and (Initialize-AZSCResourceIndexer)) { $count = [AzureScout.ResourceIndexer]::Build($enumerable, $byId, $byType, $byTypeId) $script:AZSCResourceLookup = New-AZSCResourceLookupRecord -Source $source -Count $count -ById $byId -ByType $byType -ByTypeId $byTypeId return $script:AZSCResourceLookup } foreach ($resource in @($source)) { $count++ if ($null -eq $resource) { continue } $properties = $resource.psobject.Properties $idProperty = $properties['id'] $typeProperty = $properties['TYPE'] $id = if ($null -ne $idProperty -and $idProperty.Value -is [string]) { [string]$idProperty.Value } else { $null } $type = if ($null -ne $typeProperty -and $typeProperty.Value -is [string]) { [string]$typeProperty.Value } else { $null } $list = $null if (-not [string]::IsNullOrEmpty($id)) { if (-not $byId.TryGetValue($id, [ref]$list)) { $list = [System.Collections.Generic.List[object]]::new(); $byId[$id] = $list } $list.Add($resource) } if (-not [string]::IsNullOrEmpty($type)) { if (-not $byType.TryGetValue($type, [ref]$list)) { $list = [System.Collections.Generic.List[object]]::new(); $byType[$type] = $list } $list.Add($resource) if (-not [string]::IsNullOrEmpty($id)) { $typeIdKey = "$type|$id" if (-not $byTypeId.TryGetValue($typeIdKey, [ref]$list)) { $list = [System.Collections.Generic.List[object]]::new(); $byTypeId[$typeIdKey] = $list } $list.Add($resource) } } } $script:AZSCResourceLookup = New-AZSCResourceLookupRecord -Source $source -Count $count -ById $byId -ByType $byType -ByTypeId $byTypeId return $script:AZSCResourceLookup } function Read-AZSCRowValue { <# .SYNOPSIS A row's property as StrictMode-off code reads it: $null for a $null row or a missing property. #> [CmdletBinding()] param([AllowNull()] $Row, [Parameter(Mandatory)][string] $Name) if ($null -eq $Row) { return $null } $property = $Row.psobject.Properties[$Name] if ($null -eq $property) { return $null } return $property.Value } function Find-AZSCResource { <# .SYNOPSIS The rows of $Resources whose id equals Id (and, with -Type, whose TYPE equals Type), in list order. .DESCRIPTION Same rows, same order as `$Resources | Where-Object { $_.id -eq $Id }` (or `{ $_.TYPE -eq $Type -and $_.id -eq $Id }`), answered from an index built once per list. #> [CmdletBinding()] param( [AllowNull()] $Resources, [AllowNull()] $Id, [AllowNull()][string] $Type ) if ($Id -isnot [string] -or [string]::IsNullOrEmpty($Id)) { # The rare edge (a row with no parent id): the original scan, so it behaves exactly as before. # The collectors run that scan with StrictMode off, where a missing property (or a $null row) # reads as $null; Read-AZSCRowValue gives the same answer under StrictMode Latest. if ($Type) { return @($Resources | Where-Object { (Read-AZSCRowValue $_ 'TYPE') -eq $Type -and (Read-AZSCRowValue $_ 'id') -eq $Id }) } return @($Resources | Where-Object { (Read-AZSCRowValue $_ 'id') -eq $Id }) } $lookup = Get-AZSCResourceLookup -Resources $Resources $list = $null $found = if ($Type) { $lookup.ByTypeId.TryGetValue("$Type|$Id", [ref]$list) } else { $lookup.ById.TryGetValue($Id, [ref]$list) } if (-not $found) { return @() } return $list.ToArray() } function Get-AZSCResourcesOfType { <# .SYNOPSIS The rows of $Resources whose TYPE equals Type, in list order -- the same rows as `$Resources | Where-Object { $_.TYPE -eq $Type }`, from an index built once per list. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Returns the set of resources of one type.')] [CmdletBinding()] param( [AllowNull()] $Resources, [Parameter(Mandatory)][string] $Type ) $lookup = Get-AZSCResourceLookup -Resources $Resources $list = $null if (-not $lookup.ByType.TryGetValue($Type, [ref]$list)) { return @() } return $list.ToArray() } |