Azure Log Analytics purge requests failing with Internal Server Error - azure

I am trying to purge few records from an Azure Log Analytics workspace table.
I am following the documentation from https://learn.microsoft.com/en-us/rest/api/loganalytics/workspace-purge/purge
My account has Data Purger RBAC role added. Also, I am an Owner on the subscription.
I have tried the Try it button on the documentation page, but get Internal Server error after triggering the HTTP post request.
Request Body/Payload
{
filters: [
{
"column": "TimeGenerated",
"operator": ">",
"value": "2022-05-26T06:09:00"
}],
table: "AppRequests"
}
error response
{
"error": {
"code": "InternalServerError",
"message": "Operation Id: 1df0f52bd248b548b713baf53288eec6"
}
}
I have also coded a PowerShell script and tried but getting the same error my script:
param(
[Parameter(Mandatory = $true)][string]$SubscriptionName,
[Parameter(Mandatory = $true)][string]$ResourceGroupName,
[Parameter(Mandatory = $true)][string]$WorkspaceName
)
Set-AzContext -Subscription $SubscriptionName | Out-Null
$AzContext = Get-AzContext
$AzAccessToken = Get-AzAccessToken -TenantId $AzContext.Tenant.Id
$Token = $AzAccessToken.Token
$SubscriptionId = $AzContext.Subscription.Id
$LogAnalyticsPurgeUriBase = "https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroupName/providers/Microsoft.OperationalInsights/workspaces/$WorkspaceName/purge?api-version=2020-08-01";
Write-Host $LogAnalyticsPurgeUriBase
$AuthHeader = #{
'Content-Type' = 'application/json'
'Authorization' = "Bearer $Token"
}
Write-Host $AuthHeader
$Body = #"
{
"table": "AppRequests",
"filters": [
{
"column": "TimeGenerated",
"operator": ">",
"value": "2022-05-26T06:09:00"
}]
}
"#
Write-Host $Body
$PurgeResult = Invoke-RestMethod -Method Post -Uri $LogAnalyticsPurgeUriBase -Body $Body -Headers $AuthHeader
Return $PurgeResult;
error response after executing the PowerShell script ( and passing the parameters )
{"error":{"code":"InternalServerError","message":"Operation Id: 4159055a9a69bb44afd3509c3a2d42ca"}}
I have gone to the Log Analytics activity log - events pane and tried getting more details on the error there, but unfortunately the events details there also just mention 'Internal Server' error without expanding any details.
Any guidance on what I am doing wrong would be much appreciated. Thank you!

Issue is unrelated to anything you performed (No client-side error is visible in the response). it originates from the RP (Azure Resource provider), 500 is a server-side error, hence - they will need to address it. if you have the option to open a ticket with their support that will be recommended as next move.

Related

ExpiredAuthenticationToken in FunctionApp

I have a powershell script that connects to the ADO API and shows me a pool of agents. When I run it locally it works for me, but unfortunately there is already a bug in Function App
401 Unauthorized
{
"error": {
"code": "ExpiredAuthenticationToken",
"message": "The access token expiry UTC time '12/22/2022 2:49:41 PM' is earlier than current UTC time '12/22/2022 2:53:08 PM'."
}
}
This is a new generated PAT and it is active.
Script:
$personalToken = "t0k3n"
$patToken = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($personalToken)"))
$repoHeader = #{"Authorization"="Basic $patToken"}
Write-Output $repoHeader
$repoUrl = [string]::Format("https://dev.azure.com/org/_apis/distributedtask/pools?api-version=5.1")
Write-Output $repoUrl
$output = Invoke-RestMethod -Uri $repoUrl -Method Get -ContentType "application/json; charset=utf-8; api-version=6.0" -Headers $repoHeader -MaximumRedirection 10
Write-Output $output
foreach ($outputValue in $output.value)
{
Write-Output $outputValue.name
}
I have no idea why this works locally and not in Function App
This may seem strange.. But it was enough to refresh the page, because Cloud Shell has a certain time of operation, after which it throws you out of the session..

Why I cannot authenticate an app in Azure

I am trying to authenticate app in azure, but getting the following error,
Response status code does not indicate success: 401 (Unauthorized).
Authentication is done using a powershell cmdlet,
function Get-AzureToken {
Param(
[Parameter(Mandatory)][String]$TenantId,
[Parameter(Mandatory)][String]$ApplicationId,
[Parameter(Mandatory)][String]$Secret,
[Parameter()][string]$apiEndpointUri = "https://management.azure.com/.default"
)
$encodedSecret = [System.Web.HttpUtility]::UrlEncode($secret)
$RequestAccessTokenUri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$body = "grant_type=client_credentials&client_id=$applicationId&client_secret=$encodedSecret&scope=$apiEndpointUri"
$contentType = 'application/x-www-form-urlencoded'
Write-Information "Fetching token for service principal"
try {
$Token = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $body -ContentType $contentType
if (!$token) {
throw "Something went wrong getting token"
}
}
catch {
write-error $_.Exception.Message
write-error "Failed to get token" -ErrorAction Stop
}
return "$($Token.access_token)"
}
Error in GitHub actions:
Try URLEncode on the scope URI.
Also use double slashes for the URL:
https://github.com/MicrosoftDocs/azure-docs/issues/68642?msclkid=908717bbb41f11eca828738506359fcb

What causes "invalid query definition, dataset is invalid or not supplied" querying the Azure REST API with powershell?

I've tried multiple ways to get cost management information from the Azure REST API using Powershell. I'm copy/pasting the data for my $body variable directly from their documentation. I get this error with every example they've posted.
Below is my original attempt.
I've tried to pipe $body to convertto-json.
I've tried saving it as a .json file and then using get-content -raw to get it.
I've tried defining everything in a $params hash table and then using invoke-restmethod #params
No matter what I get the same error.
invalid query definition, dataset is invalid or not supplied
$method = "post"
$URI = "https://management.azure.com//subscriptions/12345678-1234-1234-1234-1234556789123/resourceGroups/HubRG/providers/Microsoft.CostManagement/query?api-version=2019-11-01"
$headers = #{
"authorization" = "Bearer verylongstringofcharacters"
}
$body = #"
{
"type": "ActualCost",
"dataset": {
"granularity": "Daily",
"aggregation": {
"totalcost" : {
"name": "cost",
"function": "Sum"
}
},
"grouping": [
{
"type": "Dimension",
"name": "ResourceGroup"
}
]
}
}
"#
Invoke-RestMethod -Method $method -URI $URI -Headers $headers -Body $body
I had this same issue - drove me crazy for at least an hour. It turned out that even though I was using Invoke-RestMethod, I had to explicitly set 'Content-Type' = 'application/json' in the headers of the request. Without it: 'Dataset is invalid...', with it: success.
$headers = #{
"authorization" = "Bearer verylongstringofcharacters"
"Content-Type" = "application/json"
}

Defender 365 REST API (you don't have any of the required app permissions (Incident.ReadWrite.All, Incident.Read.All) to access resource)

I am trying to download list of incidents from Defender 365 (MDATP).
I have a script to get a Bearer Token:
. 'Functions\Credentials.ps1'
Function GET_BEARER_TOKEN_FOR_MDATP_AUTHENTICATION {
$Body = [Ordered] #{
resource = "$ResourceApplicationIdUri"
client_id = "$ApplicationId"
client_secret = "$ApplicationSecret"
grant_type = 'client_credentials'
}
try {
$Response = Invoke-RestMethod -Method Post -Uri $OAuthenticationURI -Body $body -ErrorAction Stop
}
catch {
Write-Output("unable to get the bearer token")
Exit
}
$BearerToken = $Response.access_token
return $BearerToken
}
$xx = GET_BEARER_TOKEN_FOR_MDATP_AUTHENTICATION
$xx | Out-File '.\Bearer_Token.txt'
That script worked fine. Today, I have been granted permission to display incidents.
When I try to do that, I get the error message:
{
"error": {
"code": "Forbidden",
"message": "The application does not have any of the required application permissions (Incident.ReadWrite.All, Incident.Read.All) to access the resource.",
}
}
When I check in the token tester website: https://jwt.ms/
I cannot see those incident.Read.All Roles but only:
"roles": [
"Alert.ReadWrite.All",
"AdvancedQuery.Read.All"
]
Roles have been given by this instruction manual:
https://learn.microsoft.com/en-us/microsoft-365/security/defender/api-create-app-web?view=o365-worldwide
Many Thanks,
Aster
so I have found the issue:
$ResourceApplicationIdUri = 'https://api.securitycenter.microsoft.com' (Alerts are allowed)
$ResourceApplicationIdUri = 'https://api.security.microsoft.com' (Incidents are allowed)
Regards,
Aster

Azure DevOps REST API returns a 403 when using the system OAuth token during a build

I'm running a script:
# Variables
$organization = "****"
$project = "****"
$repositoryId = "****"
$pullRequestId = $env:BUILD_PULLREQUEST_ID
$pat = "Bearer $env:System_AccessToken"
$featureReleaseUrl = "http://" + $env:prSourceBranchName + ".azurewebsites.net"
$body = #"
{
"comments": [
{
"content": "Link naar feature release $featureReleaseUrl"
}
]
}
"#
$createThreadInPRUrl = "https://dev.azure.com/$organization/$project/_apis/git/repositories/$repositoryId/pullRequests/$pullRequestId/threads?api-version=5.0"
if ($pullRequestId) {
Invoke-RestMethod -Uri $createThreadInPRUrl -Headers #{Authorization = $pat} -Body $body -Method Post -ContentType 'application/json'
}
When it runs it returns a:
##[error]The remote server returned an error: (403) Forbidden.
I've created a Personal Access Tokens in my personal settings.
I've also created this script:
# Variables
$organization = "****"
$project = "****"
$buildId = $****
$pat = "Bearer $env:System_AccessToken"
if (!$env:Build_PullRequest_SourceBranchName) {
$retrieveSourceBranchFromBuildURL = "https://dev.azure.com/$organization/$project/_apis/build/builds/$buildId" + "?api-version=5.0"
$buildInformation = Invoke-RestMethod -Uri $retrieveSourceBranchFromBuildURL -Headers #{Authorization = $pat } -Method Get -ContentType 'application/json'
$SourceBranchFromBuild = $buildInformation.sourceBranch.split('/')[-1]
Write-Host "### no Build PullRequest SourceBranchName available ###"
Write-Host "##vso[task.setvariable variable=prSourceBranchName;]"$SourceBranchFromBuild
}
And this runs fine. The difference between the first and second script is that the first is a POST and the second a GET. But they both use the $pat token.
Even though the token you used is System.AccessToken, if you don't have access permission of Pull Request, you will also could not operate it.
Go Project Setting--> Repositories--> Repository you want to access, locate your account or the group you are in. Check the permission state of Contribute to pull requests.
You must have this Contribute to pull requests permission allowed, so that you can add the comment to PR.

Resources