Skip to content

Commit 0e7a48d

Browse files
authored
Merge pull request #269 from KelvinTegelaar/dev
[pull] dev from KelvinTegelaar:dev
2 parents 27e432e + d57feaa commit 0e7a48d

File tree

5 files changed

+121
-16
lines changed

5 files changed

+121
-16
lines changed

Modules/CIPPCore/Public/Entrypoints/HTTP Functions/CIPP/Setup/Invoke-ExecUpdateRefreshToken.ps1

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,14 @@ Function Invoke-ExecUpdateRefreshToken {
3232
if ($env:TenantID -eq $Request.body.tenantId) {
3333
Set-AzKeyVaultSecret -VaultName $kv -Name 'RefreshToken' -SecretValue (ConvertTo-SecureString -String $Request.body.refreshtoken -AsPlainText -Force)
3434
} else {
35-
$name = $Request.body.tenantId -replace '-', '_'
36-
Set-AzKeyVaultSecret -VaultName $kv -Name $name -SecretValue (ConvertTo-SecureString -String $Request.body.refreshtoken -AsPlainText -Force)
35+
Write-Host "$($env:TenantID) does not match $($Request.body.tenantId) - we're adding a new secret for the tenant."
36+
$name = $Request.body.tenantId
37+
try {
38+
Set-AzKeyVaultSecret -VaultName $kv -Name $name -SecretValue (ConvertTo-SecureString -String $Request.body.refreshtoken -AsPlainText -Force)
39+
} catch {
40+
Write-Host "Failed to set secret $name in KeyVault. $($_.Exception.Message)"
41+
throw $_
42+
}
3743
}
3844
}
3945
$InstanceId = Start-UpdatePermissionsOrchestrator #start the CPV refresh immediately while wizard still runs.

Modules/CIPPCore/Public/Entrypoints/Invoke-ListLogs.ps1

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
using namespace System.Net
22

3-
Function Invoke-ListLogs {
3+
function Invoke-ListLogs {
44
<#
55
.FUNCTIONALITY
66
Entrypoint
@@ -25,17 +25,35 @@ Function Invoke-ListLogs {
2525
}
2626
} else {
2727
if ($request.Query.Filter -eq 'True') {
28-
$LogLevel = if ($Request.query.Severity) { ($Request.query.Severity).split(',') } else { 'Info', 'Warn', 'Error', 'Critical', 'Alert' }
29-
$PartitionKey = $Request.query.DateFilter
28+
$LogLevel = if ($Request.Query.Severity) { ($Request.query.Severity).split(',') } else { 'Info', 'Warn', 'Error', 'Critical', 'Alert' }
29+
$PartitionKey = $Request.Query.DateFilter
3030
$username = $Request.Query.User
31+
32+
$StartDate = $Request.Query.StartDate ?? $Request.Query.DateFilter
33+
$EndDate = $Request.Query.EndDate ?? $Request.Query.DateFilter
34+
35+
if ($StartDate -and $EndDate) {
36+
# Collect logs for each partition key date in range
37+
$PartitionKeys = for ($Date = [datetime]::ParseExact($StartDate, 'yyyyMMdd', $null); $Date -le [datetime]::ParseExact($EndDate, 'yyyyMMdd', $null); $Date = $Date.AddDays(1)) {
38+
$PartitionKey = $Date.ToString('yyyyMMdd')
39+
"PartitionKey eq '$PartitionKey'"
40+
}
41+
$Filter = $PartitionKeys -join ' or '
42+
} elseif ($StartDate) {
43+
$Filter = "PartitionKey eq '{0}'" -f $StartDate
44+
} else {
45+
$Filter = "PartitionKey eq '{0}'" -f (Get-Date -UFormat '%Y%m%d')
46+
}
3147
} else {
3248
$LogLevel = 'Info', 'Warn', 'Error', 'Critical', 'Alert'
3349
$PartitionKey = Get-Date -UFormat '%Y%m%d'
3450
$username = '*'
51+
$Filter = "PartitionKey eq '{0}'" -f $PartitionKey
3552
}
3653
$AllowedTenants = Test-CIPPAccess -Request $Request -TenantList
37-
$Filter = "PartitionKey eq '{0}'" -f $PartitionKey
38-
$Rows = Get-AzDataTableEntity @Table -Filter $Filter | Where-Object { $_.Severity -In $LogLevel -and $_.user -like $username }
54+
Write-Host "Getting logs for filter: $Filter, LogLevel: $LogLevel, Username: $username"
55+
56+
$Rows = Get-AzDataTableEntity @Table -Filter $Filter | Where-Object { $_.Severity -in $LogLevel -and $_.user -like $username }
3957
foreach ($Row in $Rows) {
4058
if ($AllowedTenants -notcontains 'AllTenants') {
4159
$TenantList = Get-Tenants -IncludeErrors

Modules/CIPPCore/Public/Entrypoints/Timer Functions/Start-UpdateTokensTimer.ps1

Lines changed: 89 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@ function Start-UpdateTokensTimer {
77
[CmdletBinding(SupportsShouldProcess = $true)]
88
param()
99
if ($PSCmdlet.ShouldProcess('Start-UpdateTokensTimer', 'Starting Update Tokens Timer')) {
10-
10+
Write-Information 'Starting Update Tokens Timer'
11+
Write-Information "Getting new refresh token for $($env:TenantId)"
1112
# Get the current universal time in the default string format.
1213
$currentUTCtime = (Get-Date).ToUniversalTime()
1314
try {
1415
$Refreshtoken = (Get-GraphToken -ReturnRefresh $true).Refresh_token
15-
1616
if ($env:AzureWebJobsStorage -eq 'UseDevelopmentStorage=true') {
1717
$Table = Get-CIPPTable -tablename 'DevSecrets'
1818
$Secret = Get-CIPPAzDataTableEntity @Table -Filter "PartitionKey eq 'Secret' and RowKey eq 'Secret'"
@@ -37,10 +37,95 @@ function Start-UpdateTokensTimer {
3737
}
3838
}
3939
} catch {
40+
Write-Warning "Error updating refresh token $($_.Exception.Message)."
41+
Write-Information ($_.InvocationInfo.PositionMessage)
4042
Write-LogMessage -API 'Update Tokens' -message 'Error updating refresh token, see Log Data for details. Will try again in 7 days.' -sev 'CRITICAL' -LogData (Get-CippException -Exception $_)
4143
}
42-
# Write an information log with the current time.
43-
Write-Information "PowerShell timer trigger function ran! TIME: $currentUTCtime"
4444

45+
# Check application secret expiration for $env:ApplicationId and generate a new application secret if expiration is within 30 days.
46+
try {
47+
$AppId = $env:ApplicationID
48+
$PasswordCredentials = New-GraphGetRequest -uri "https://graph.microsoft.com/v1.0/applications(appId='$AppId')?`$select=id,passwordCredentials" -NoAuthCheck $true -AsApp $true -ErrorAction Stop
49+
# sort by latest expiration date and get the first one
50+
$LastPasswordCredential = $PasswordCredentials.passwordCredentials | Sort-Object -Property endDateTime -Descending | Select-Object -First 1
51+
if ($LastPasswordCredential.endDateTime -lt (Get-Date).AddDays(30).ToUniversalTime()) {
52+
Write-Information "Application secret for $AppId is expiring soon. Generating a new application secret."
53+
$AppSecret = New-GraphPostRequest -uri "https://graph.microsoft.com/v1.0/applications/$($PasswordCredentials.id)/addPassword" -Body '{"passwordCredential":{"displayName":"UpdateTokens"}}' -NoAuthCheck $true -AsApp $true -ErrorAction Stop
54+
Write-Information "New application secret generated for $AppId. Expiration date: $($AppSecret.endDateTime)."
55+
} else {
56+
Write-Information "Application secret for $AppId is valid until $($LastPasswordCredential.endDateTime). No need to generate a new application secret."
57+
}
58+
59+
if ($AppSecret) {
60+
if ($env:AzureWebJobsStorage -eq 'UseDevelopmentStorage=true') {
61+
$Table = Get-CIPPTable -tablename 'DevSecrets'
62+
$Secret = Get-CIPPAzDataTableEntity @Table -Filter "PartitionKey eq 'Secret' and RowKey eq 'Secret'"
63+
$Secret.ApplicationSecret = $AppSecret.secretText
64+
Add-AzDataTableEntity @Table -Entity $Secret -Force
65+
} else {
66+
Set-AzKeyVaultSecret -VaultName $KV -Name 'ApplicationSecret' -SecretValue (ConvertTo-SecureString -String $AppSecret.secretText -AsPlainText -Force)
67+
}
68+
Write-LogMessage -API 'Update Tokens' -message "New application secret generated for $AppId. Expiration date: $($AppSecret.endDateTime)." -sev 'INFO'
69+
}
70+
71+
# Clean up expired application secrets
72+
$ExpiredSecrets = $PasswordCredentials.passwordCredentials | Where-Object { $_.endDateTime -lt (Get-Date).ToUniversalTime() }
73+
if ($ExpiredSecrets.Count -gt 0) {
74+
Write-Information "Found $($ExpiredSecrets.Count) expired application secrets for $AppId. Removing them."
75+
foreach ($Secret in $ExpiredSecrets) {
76+
try {
77+
New-GraphPostRequest -type DELETE -uri "https://graph.microsoft.com/v1.0/applications/$($PasswordCredentials.id)/removePassword" -Body "{`"keyId`":`"$($Secret.keyId)`"}" -NoAuthCheck $true -AsApp $true -ErrorAction Stop
78+
Write-Information "Removed expired application secret with keyId $($Secret.keyId)."
79+
} catch {
80+
Write-LogMessage -API 'Update Tokens' -message "Error removing expired application secret with keyId $($Secret.keyId), see Log Data for details." -sev 'CRITICAL' -LogData (Get-CippException -Exception $_)
81+
}
82+
}
83+
} else {
84+
Write-Information "No expired application secrets found for $AppId."
85+
}
86+
} catch {
87+
Write-Warning "Error updating application secret $($_.Exception.Message)."
88+
Write-Information ($_.InvocationInfo.PositionMessage)
89+
Write-LogMessage -API 'Update Tokens' -message 'Error updating application secret, will try again in 7 days' -sev 'CRITICAL' -LogData (Get-CippException -Exception $_)
90+
}
91+
92+
# Get new refresh token for each direct added tenant
93+
$TenantList = Get-Tenants -IncludeAll | Where-Object { $_.Excluded -eq $false -and $_.delegatedPrivilegeStatus -eq 'directTenant' }
94+
if ($TenantList.Count -eq 0) {
95+
Write-Information 'No direct tenants found for refresh token update.'
96+
} else {
97+
Write-Information "Found $($TenantList.Count) direct tenant(s) for refresh token update."
98+
foreach ($Tenant in $TenantList) {
99+
try {
100+
Write-Information "Updating refresh token for tenant $($Tenant.displayName) - $($Tenant.customerId)"
101+
$Refreshtoken = (Get-GraphToken -ReturnRefresh $true -TenantId $Tenant.customerId).Refresh_token
102+
if ($env:AzureWebJobsStorage -eq 'UseDevelopmentStorage=true') {
103+
$Table = Get-CIPPTable -tablename 'DevSecrets'
104+
$Secret = Get-CIPPAzDataTableEntity @Table -Filter "PartitionKey eq 'Secret' and RowKey eq 'Secret'"
105+
if ($Secret) {
106+
$name = $Tenant.customerId -replace '-', '_'
107+
$Secret | Add-Member -MemberType NoteProperty -Name $name -Value $Refreshtoken -Force
108+
Add-AzDataTableEntity @Table -Entity $Secret -Force
109+
} else {
110+
Write-Warning "Could not update refresh token for tenant $($Tenant.displayName) ($($Tenant.customerId))."
111+
Write-LogMessage -API 'Update Tokens' -tenant $Tenant.defaultDomainName -tenantid $Tenant.customerId -message "Could not update refresh token for tenant $($Tenant.displayName). Will try again in 7 days." -sev 'CRITICAL'
112+
}
113+
} else {
114+
if ($Refreshtoken) {
115+
$name = $Tenant.customerId
116+
Set-AzKeyVaultSecret -VaultName $KV -Name $name -SecretValue (ConvertTo-SecureString -String $Refreshtoken -AsPlainText -Force)
117+
} else {
118+
Write-Warning "Could not update refresh token for tenant $($Tenant.displayName) ($($Tenant.customerId))."
119+
Write-LogMessage -API 'Update Tokens' -tenant $Tenant.defaultDomainName -tenantid $Tenant.customerId -message "Could not update refresh token for tenant $($Tenant.displayName). Will try again in 7 days." -sev 'CRITICAL'
120+
}
121+
}
122+
} catch {
123+
Write-LogMessage -API 'Update Tokens' -tenant $Tenant.defaultDomainName -tenantid $Tenant.customerId -message "Error updating refresh token for tenant $($Tenant.displayName), see Log Data for details. Will try again in 7 days." -sev 'CRITICAL' -LogData (Get-CippException -Exception $_)
124+
}
125+
}
126+
}
127+
128+
# Write an information log with the current time.
129+
Write-Information "UpdateTokens completed: $currentUTCtime"
45130
}
46131
}

Modules/CIPPCore/Public/Get-CIPPAuthentication.ps1

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,11 +57,9 @@ function Get-CIPPAuthentication {
5757
$tenants = Get-CIPPAzDataTableEntity @TenantsTable -Filter $Filter
5858
if ($tenants) {
5959
$tenants | ForEach-Object {
60-
$name = $_.tenantId -replace '-', '_'
60+
$name = $_.customerId
6161
$secret = Get-AzKeyVaultSecret -VaultName $keyvaultname -Name $name -AsPlainText -ErrorAction Stop
6262
if ($secret) {
63-
#set the name back to the original tenantId
64-
$name = $_.customerId
6563
Set-Item -Path env:$name -Value $secret -Force
6664
}
6765
}

Modules/CIPPCore/Public/GraphHelper/Get-GraphToken.ps1

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,10 @@ function Get-GraphToken($tenantid, $scope, $AsApp, $AppID, $AppSecret, $refreshT
1010
$Filter = "PartitionKey eq 'AppCache' and RowKey eq 'AppCache'"
1111
$AppCache = Get-CIPPAzDataTableEntity @ConfigTable -Filter $Filter
1212
#force auth update is appId is not the same as the one in the environment variable.
13-
Write-Host "My appId pre-launch is $($env:ApplicationID) and the one in the cache is $($AppCache.ApplicationId)"
1413
if ($AppCache.ApplicationId -and $env:ApplicationID -ne $AppCache.ApplicationId) {
1514
Write-Host "Setting environment variable ApplicationID to $($AppCache.ApplicationId)"
1615
$CIPPAuth = Get-CIPPAuthentication
1716
}
18-
Write-Host "My appId post-launch is $($env:ApplicationID) and the one in the cache is $($AppCache.ApplicationId)"
1917
$refreshToken = $env:RefreshToken
2018
if (!$tenantid) { $tenantid = $env:TenantID }
2119
#Get list of tenants that have 'directTenant' set to true

0 commit comments

Comments
 (0)