Skip to content

Commit

Permalink
Merge pull request #1037 from JohnDuprey/dev
Browse files Browse the repository at this point in the history
PermissionUpdate Changes
  • Loading branch information
JohnDuprey authored Jul 30, 2024
2 parents a665e00 + 3361764 commit 819076a
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,47 @@ function Push-UpdatePermissionsQueue {
Entrypoint
#>
param($Item)
Write-Host "Applying permissions for $($Item.defaulomainName)"
$Table = Get-CIPPTable -TableName cpvtenants
$CPVRows = Get-CIPPAzDataTableEntity @Table | Where-Object -Property Tenant -EQ $Item.customerId
$PermissionUpdateRequired = $false
if (!$CPVRows -or $ENV:ApplicationID -notin $CPVRows.applicationId) {
Write-LogMessage -tenant $Item.defaultDomainName -tenantId $Item.customerId -message 'A New tenant has been added, or a new CIPP-SAM Application is in use' -Sev 'Warn' -API 'NewTenant'
Write-Host 'Adding CPV permissions'
Set-CIPPCPVConsent -Tenantfilter $Item.customerId
$PermissionUpdateRequired = $true
}

$CippCorePath = (Get-Item $PSScriptRoot).Parent.Parent.FullName
try {
$DomainRefreshRequired = $false

if (!$Item.defaultDomainName) {
$DomainRefreshRequired = $true
}

Write-Information "Applying permissions for $($Item.displayName)"
$Table = Get-CIPPTable -TableName cpvtenants
$CPVRows = Get-CIPPAzDataTableEntity @Table | Where-Object -Property Tenant -EQ $Item.customerId

Add-CIPPApplicationPermission -RequiredResourceAccess 'CippDefaults' -ApplicationId $ENV:ApplicationID -tenantfilter $Item.customerId
Add-CIPPDelegatedPermission -RequiredResourceAccess 'CippDefaults' -ApplicationId $ENV:ApplicationID -tenantfilter $Item.customerId
if (!$CPVRows -or $ENV:ApplicationID -notin $CPVRows.applicationId) {
Write-LogMessage -tenant $Item.defaultDomainName -tenantId $Item.customerId -message 'A New tenant has been added, or a new CIPP-SAM Application is in use' -Sev 'Warn' -API 'NewTenant'
Write-Information 'Adding CPV permissions'
Set-CIPPCPVConsent -Tenantfilter $Item.customerId
$DomainRefreshRequired = $true
}
Write-Information 'Updating permissions'
Add-CIPPApplicationPermission -RequiredResourceAccess 'CippDefaults' -ApplicationId $ENV:ApplicationID -tenantfilter $Item.customerId
Add-CIPPDelegatedPermission -RequiredResourceAccess 'CippDefaults' -ApplicationId $ENV:ApplicationID -tenantfilter $Item.customerId
Write-LogMessage -tenant $Item.defaultDomainName -tenantId $Item.customerId -message "Updated permissions for $($Item.displayName)" -Sev 'Info' -API 'UpdatePermissionsQueue'

Write-LogMessage -tenant $Item.defaultDomainName -tenantId $Item.customerId -message "Updated permissions for $($Item.displayName)" -Sev 'Info' -API 'UpdatePermissionsQueue'
$Table = Get-CIPPTable -TableName cpvtenants
$unixtime = [int64](([datetime]::UtcNow) - (Get-Date '1/1/1970')).TotalSeconds
$GraphRequest = @{
LastApply = "$unixtime"
applicationId = "$($ENV:applicationId)"
Tenant = "$($Item.customerId)"
PartitionKey = 'Tenant'
RowKey = "$($Item.customerId)"
}
Add-CIPPAzDataTableEntity @Table -Entity $GraphRequest -Force

if ($DomainRefreshRequired) {
$UpdatedTenant = Get-Tenants -TenantFilter $Item.customerId -TriggerRefresh
if ($UpdatedTenant.defaultDomainName) {
Write-Information "Updated tenant domains $($UpdatedTenant.defaultDomainName)"
}
}
} catch {
Write-Information "Error updating permissions for $($Item.displayName)"
}
}
27 changes: 23 additions & 4 deletions Modules/CIPPCore/Public/GraphHelper/Get-Tenants.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ function Get-Tenants {
[switch]$IncludeErrors,
[switch]$SkipDomains,
[switch]$TriggerRefresh,
[switch]$CleanOld
[switch]$CleanOld,
[string]$TenantFilter
)

$TenantsTable = Get-CippTable -tablename 'Tenants'
Expand All @@ -29,6 +30,24 @@ function Get-Tenants {
} else {
$Filter = "PartitionKey eq 'Tenants' and Excluded eq false and GraphErrorCount lt 50"
}

if ($TenantFilter) {
Write-Information "Getting tenant $TenantFilter"
if ($TenantFilter -match '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') {
$Filter = "{0} and customerId eq '{1}'" -f $Filter, $TenantFilter
# create where-object scriptblock
$IncludedTenantFilter = [scriptblock]::Create("`$_.customerId -eq '$TenantFilter'")
$RelationshipFilter = " and customer/tenantId eq '$TenantFilter'"
} else {
$Filter = "{0} and defaultDomainName eq '{1}'" -f $Filter, $TenantFilter
$IncludedTenantFilter = [scriptblock]::Create("`$_.defaultDomainName -eq '$TenantFilter'")
$RelationshipFilter = ''
}
} else {
$IncludedTenantFilter = [scriptblock]::Create('$true')
$RelationshipFilter = ''
}

$IncludedTenantsCache = Get-CIPPAzDataTableEntity @TenantsTable -Filter $Filter

if (($IncludedTenantsCache | Measure-Object).Count -eq 0) {
Expand All @@ -55,7 +74,7 @@ function Get-Tenants {

if (($BuildRequired -or $TriggerRefresh.IsPresent) -and $PartnerTenantState.state -ne 'owntenant') {
#get the full list of tenants
$GDAPRelationships = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/tenantRelationships/delegatedAdminRelationships?`$filter=status eq 'active' and not startsWith(displayName,'MLT_')&`$select=customer,autoExtendDuration,endDateTime&`$top=300" -NoAuthCheck:$true
$GDAPRelationships = New-GraphGetRequest -uri "https://graph.microsoft.com/beta/tenantRelationships/delegatedAdminRelationships?`$filter=status eq 'active' and not startsWith(displayName,'MLT_')$RelationshipFilter&`$select=customer,autoExtendDuration,endDateTime&`$top=300" -NoAuthCheck:$true
$GDAPList = foreach ($Relationship in $GDAPRelationships) {
[PSCustomObject]@{
customerId = $Relationship.customer.tenantId
Expand All @@ -65,7 +84,7 @@ function Get-Tenants {
}
}

$ActiveRelationships = $GDAPList | Where-Object { $_.customerId -notin $SkipListCache.customerId }
$ActiveRelationships = $GDAPList | Where-Object $IncludedTenantFilter | Where-Object { $_.customerId -notin $SkipListCache.customerId }
$TenantList = $ActiveRelationships | Group-Object -Property customerId | ForEach-Object {
#Write-Host "Processing $($_.Name) to add to tenant list."
$ExistingTenantInfo = Get-CIPPAzDataTableEntity @TenantsTable -Filter "PartitionKey eq 'Tenants' and RowKey eq '$($_.Name)'"
Expand Down Expand Up @@ -152,7 +171,7 @@ function Get-Tenants {
}) | Out-Null

}
foreach ($Tenant in $TenantList) {
foreach ($Tenant in $TenantList | Where-Object $IncludedTenantFilter) {
if ($Tenant.defaultDomainName -eq 'Invalid' -or !$Tenant.defaultDomainName) {
Write-LogMessage -API 'Get-Tenants' -message "We're skipping $($Tenant.displayName) as it has an invalid default domain name. Something is up with this instance." -level 'Critical'
continue
Expand Down
25 changes: 19 additions & 6 deletions UpdatePermissions/run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,29 @@
param($Timer)

try {
$Tenants = Get-Tenants -IncludeAll -TriggerRefresh | Where-Object { $_.customerId -ne $env:TenantId -and $_.Excluded -eq $false }
$Queue = New-CippQueueEntry -Name 'Update Permissions' -TotalTasks ($Tenants | Measure-Object).Count
$TenantBatch = $Tenants | Select-Object defaultDomainName, customerId, displayName, @{n = 'FunctionName'; exp = { 'UpdatePermissionsQueue' } }, @{n = 'QueueId'; exp = { $Queue.RowKey } }

if (($Tenants | Measure-Object).Count -gt 0) {
$Tenants = Get-Tenants -IncludeAll | Where-Object { $_.customerId -ne $env:TenantId -and $_.Excluded -eq $false }
$CPVTable = Get-CIPPTable -TableName cpvtenants
$CPVRows = Get-CIPPAzDataTableEntity @CPVTable
$ModuleRoot = (Get-Module CIPPCore).ModuleBase
$SAMManifest = Get-Item -Path "$ModuleRoot\Public\SAMManifest.json"
$AdditionalPermissions = Get-Item -Path "$ModuleRoot\Public\AdditionalPermissions.json"
$Tenants = $Tenants | ForEach-Object {
$CPVRow = $CPVRows | Where-Object -Property Tenant -EQ $_.customerId
if (!$CPVRow -or $env:ApplicationID -notin $CPVRow.applicationId -or $SAMManifest.LastWriteTime.ToUniversalTime() -gt $CPVRow.Timestamp.DateTime -or $AdditionalPermissions.LastWriteTime.ToUniversalTime() -ge $CPVRow.Timestamp.DateTime -or $CPVRow.Timestamp.DateTime -le (Get-Date).AddDays(-7).ToUniversalTime() -or !$_.defaultDomainName) {
$_
}
}
$TenantCount = ($Tenants | Measure-Object).Count
if ($TenantCount -gt 0) {
$Queue = New-CippQueueEntry -Name 'Update Permissions' -TotalTasks $TenantCount
$TenantBatch = $Tenants | Select-Object defaultDomainName, customerId, displayName, @{n = 'FunctionName'; exp = { 'UpdatePermissionsQueue' } }, @{n = 'QueueId'; exp = { $Queue.RowKey } }
$InputObject = [PSCustomObject]@{
OrchestratorName = 'UpdatePermissionsOrchestrator'
Batch = @($TenantBatch)
}
$InstanceId = Start-NewOrchestration -FunctionName 'CIPPOrchestrator' -InputObject ($InputObject | ConvertTo-Json -Depth 5 -Compress)
Write-Host "Started permissions orchestration with ID = '$InstanceId'"
} else {
Write-Host 'No tenants require permissions update'
}
} catch {}
} catch {}

0 comments on commit 819076a

Please sign in to comment.