{
    "definition": {
        "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
        "contentVersion": "1.0.0.0",
        "triggers": {
            "HTTP_Request": {
                "type": "Request",
                "kind": "Http",
                "inputs": {
                    "schema": {
                        "type": "object",
                        "properties": {
                            "incidentId": {
                                "type": "string"
                            },
                            "incidentTitle": {
                                "type": "string"
                            },
                            "incidentTime": {
                                "type": "string"
                            },
                            "accounts": {
                                "type": "array",
                                "items": {
                                    "type": "object",
                                    "properties": {
                                        "Name": {
                                            "type": "string"
                                        },
                                        "UPNSuffix": {
                                            "type": "string"
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        },
        "actions": {
            "Initialize_AccountEnrichment": {
                "runAfter": {},
                "type": "InitializeVariable",
                "inputs": {
                    "variables": [
                        {
                            "name": "AccountEnrichment",
                            "type": "array",
                            "value": []
                        }
                    ]
                }
            },
            "Initialize_AccountTableHTML": {
                "runAfter": {},
                "type": "InitializeVariable",
                "inputs": {
                    "variables": [
                        {
                            "name": "AccountTableHTML",
                            "type": "String",
                            "value": ""
                        }
                    ]
                }
            },
            "Initialize_KQLSectionHTML": {
                "runAfter": {},
                "type": "InitializeVariable",
                "inputs": {
                    "variables": [
                        {
                            "name": "KQLSectionHTML",
                            "type": "String",
                            "value": ""
                        }
                    ]
                }
            },
            "Condition_ValidateKey": {
                "actions": {
                    "For_each_Account_Enrich": {
                        "foreach": "@triggerBody()?['accounts']",
                        "actions": {
                            "Compose_Account_SAM": {
                                "type": "Compose",
                                "inputs": "@item()?['Name']"
                            },
                            "Get_User_From_Graph": {
                                "runAfter": {
                                    "Compose_Account_SAM": [
                                        "Succeeded"
                                    ]
                                },
                                "type": "Http",
                                "inputs": {
                                    "uri": "@concat('https://graph.microsoft.com/v1.0/users?$filter=onPremisesSamAccountName eq ', '''', outputs('Compose_Account_SAM'), '''', '&$select=displayName,jobTitle,department,userPrincipalName,accountEnabled,createdDateTime,lastPasswordChangeDateTime,onPremisesSamAccountName,onPremisesDomainName&$count=true')",
                                    "method": "GET",
                                    "headers": {
                                        "ConsistencyLevel": "eventual"
                                    },
                                    "authentication": {
                                        "type": "ManagedServiceIdentity",
                                        "audience": "https://graph.microsoft.com"
                                    }
                                }
                            },
                            "Parse_Graph_User": {
                                "runAfter": {
                                    "Get_User_From_Graph": [
                                        "Succeeded",
                                        "Failed"
                                    ]
                                },
                                "type": "ParseJson",
                                "inputs": {
                                    "content": "@body('Get_User_From_Graph')",
                                    "schema": {
                                        "type": "object",
                                        "properties": {
                                            "value": {
                                                "type": "array",
                                                "items": {
                                                    "type": "object",
                                                    "properties": {
                                                        "displayName": {
                                                            "type": [
                                                                "string",
                                                                "null"
                                                            ]
                                                        },
                                                        "jobTitle": {
                                                            "type": [
                                                                "string",
                                                                "null"
                                                            ]
                                                        },
                                                        "department": {
                                                            "type": [
                                                                "string",
                                                                "null"
                                                            ]
                                                        },
                                                        "userPrincipalName": {
                                                            "type": [
                                                                "string",
                                                                "null"
                                                            ]
                                                        },
                                                        "accountEnabled": {
                                                            "type": [
                                                                "boolean",
                                                                "null"
                                                            ]
                                                        },
                                                        "createdDateTime": {
                                                            "type": [
                                                                "string",
                                                                "null"
                                                            ]
                                                        },
                                                        "lastPasswordChangeDateTime": {
                                                            "type": [
                                                                "string",
                                                                "null"
                                                            ]
                                                        },
                                                        "onPremisesSamAccountName": {
                                                            "type": [
                                                                "string",
                                                                "null"
                                                            ]
                                                        },
                                                        "onPremisesDomainName": {
                                                            "type": [
                                                                "string",
                                                                "null"
                                                            ]
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            },
                            "Compose_Resolved_UPN": {
                                "runAfter": {
                                    "Parse_Graph_User": [
                                        "Succeeded",
                                        "Failed"
                                    ]
                                },
                                "type": "Compose",
                                "inputs": "@coalesce(body('Parse_Graph_User')?['value']?[0]?['userPrincipalName'], concat(item()?['Name'], '@', item()?['UPNSuffix']))"
                            },
                            "Compose_User_Found": {
                                "runAfter": {
                                    "Compose_Resolved_UPN": [
                                        "Succeeded"
                                    ]
                                },
                                "type": "Compose",
                                "inputs": "@greater(length(coalesce(body('Parse_Graph_User')?['value'], json('[]'))), 0)"
                            },
                            "Condition_User_Found": {
                                "actions": {
                                    "Run_SignIn_KQL": {
                                        "type": "ApiConnection",
                                        "inputs": {
                                            "host": {
                                                "connection": {
                                                    "name": "@parameters('$connections')['azuremonitorlogs']['connectionId']"
                                                }
                                            },
                                            "method": "post",
                                            "body": "@concat('SigninLogs | where TimeGenerated > ago(7d) | where UserPrincipalName =~ \"', outputs('Compose_Resolved_UPN'), '\" | project TimeGenerated, UserPrincipalName, AppDisplayName, IPAddress, Location, ResultType, ResultDescription, ConditionalAccessStatus, DeviceDetail, RiskLevelDuringSignIn, RiskLevelAggregated, AuthenticationDetails, MfaDetail, ClientAppUsed, UserAgent | order by TimeGenerated desc | take 20')",
                                            "path": "/queryData",
                                            "queries": {
                                                "subscriptions": "<AZURE-SUBSCRIPTION-ID>",
                                                "resourcegroups": "<RESOURCE-GROUP>",
                                                "resourcetype": "Log Analytics Workspace",
                                                "resourcename": "<LOG-ANALYTICS-WORKSPACE>",
                                                "timerange": "7d"
                                            }
                                        }
                                    },
                                    "Run_NonInteractive_SignIn_KQL": {
                                        "type": "ApiConnection",
                                        "inputs": {
                                            "host": {
                                                "connection": {
                                                    "name": "@parameters('$connections')['azuremonitorlogs']['connectionId']"
                                                }
                                            },
                                            "method": "post",
                                            "body": "@concat('AADNonInteractiveUserSignInLogs | where TimeGenerated > ago(7d) | where UserPrincipalName =~ \"', outputs('Compose_Resolved_UPN'), '\" | project TimeGenerated, UserPrincipalName, AppDisplayName, AppId, IPAddress, Location, ResultType, ResultDescription, ConditionalAccessStatus, RiskLevelDuringSignIn, RiskLevelAggregated, ClientAppUsed, ResourceDisplayName, CorrelationId | order by TimeGenerated desc | take 20')",
                                            "path": "/queryData",
                                            "queries": {
                                                "subscriptions": "<AZURE-SUBSCRIPTION-ID>",
                                                "resourcegroups": "<RESOURCE-GROUP>",
                                                "resourcetype": "Log Analytics Workspace",
                                                "resourcename": "<LOG-ANALYTICS-WORKSPACE>",
                                                "timerange": "7d"
                                            }
                                        }
                                    },
                                    "Run_IdentityRisk_KQL": {
                                        "type": "ApiConnection",
                                        "inputs": {
                                            "host": {
                                                "connection": {
                                                    "name": "@parameters('$connections')['azuremonitorlogs']['connectionId']"
                                                }
                                            },
                                            "method": "post",
                                            "body": "@concat('AADUserRiskEvents | where TimeGenerated > ago(30d) | where UserPrincipalName =~ \"', outputs('Compose_Resolved_UPN'), '\" | project TimeGenerated, UserPrincipalName, RiskEventType, RiskDetail, RiskLevel, RiskState, IpAddress, Location, DetectionTimingType, AdditionalInfo, CorrelationId | order by TimeGenerated desc | take 10')",
                                            "path": "/queryData",
                                            "queries": {
                                                "subscriptions": "<AZURE-SUBSCRIPTION-ID>",
                                                "resourcegroups": "<RESOURCE-GROUP>",
                                                "resourcetype": "Log Analytics Workspace",
                                                "resourcename": "<LOG-ANALYTICS-WORKSPACE>",
                                                "timerange": "30d"
                                            }
                                        }
                                    },
                                    "Run_CloudApp_KQL": {
                                        "type": "ApiConnection",
                                        "inputs": {
                                            "host": {
                                                "connection": {
                                                    "name": "@parameters('$connections')['azuremonitorlogs']['connectionId']"
                                                }
                                            },
                                            "method": "post",
                                            "body": "@concat('CloudAppEvents | where TimeGenerated > ago(7d) | where AccountId =~ \"', outputs('Compose_Resolved_UPN'), '\" or AccountDisplayName =~ \"', coalesce(body('Parse_Graph_User')?['value']?[0]?['displayName'], outputs('Compose_Account_SAM')), '\" | project TimeGenerated, AccountId, AccountDisplayName, Application, ActionType, ObjectName, ObjectType, IPAddress, CountryCode, ISP, ActivityType, ActivityObjects, RawEventData | order by TimeGenerated desc | take 25')",
                                            "path": "/queryData",
                                            "queries": {
                                                "subscriptions": "<AZURE-SUBSCRIPTION-ID>",
                                                "resourcegroups": "<RESOURCE-GROUP>",
                                                "resourcetype": "Log Analytics Workspace",
                                                "resourcename": "<LOG-ANALYTICS-WORKSPACE>",
                                                "timerange": "7d"
                                            }
                                        }
                                    },
                                    "Run_IdentityLogon_KQL": {
                                        "type": "ApiConnection",
                                        "inputs": {
                                            "host": {
                                                "connection": {
                                                    "name": "@parameters('$connections')['azuremonitorlogs']['connectionId']"
                                                }
                                            },
                                            "method": "post",
                                            "body": "@concat('IdentityLogonEvents | where TimeGenerated > ago(7d) | where AccountUpn =~ \"', outputs('Compose_Resolved_UPN'), '\" or AccountName =~ \"', outputs('Compose_Account_SAM'), '\" | project TimeGenerated, AccountUpn, AccountName, AccountDomain, Protocol, ActionType, LogonType, DeviceName, IPAddress, DestinationDeviceName, DestinationPort, FailureReason | order by TimeGenerated desc | take 25')",
                                            "path": "/queryData",
                                            "queries": {
                                                "subscriptions": "<AZURE-SUBSCRIPTION-ID>",
                                                "resourcegroups": "<RESOURCE-GROUP>",
                                                "resourcetype": "Log Analytics Workspace",
                                                "resourcename": "<LOG-ANALYTICS-WORKSPACE>",
                                                "timerange": "7d"
                                            }
                                        }
                                    },
                                    "Count_SignIn_KQL": {
                                        "type": "ApiConnection",
                                        "inputs": {
                                            "host": {
                                                "connection": {
                                                    "name": "@parameters('$connections')['azuremonitorlogs']['connectionId']"
                                                }
                                            },
                                            "method": "post",
                                            "body": "@concat('SigninLogs | where TimeGenerated > ago(7d) | where UserPrincipalName =~ \"', outputs('Compose_Resolved_UPN'), '\" | summarize TotalCount=count()')",
                                            "path": "/queryData",
                                            "queries": {
                                                "subscriptions": "<AZURE-SUBSCRIPTION-ID>",
                                                "resourcegroups": "<RESOURCE-GROUP>",
                                                "resourcetype": "Log Analytics Workspace",
                                                "resourcename": "<LOG-ANALYTICS-WORKSPACE>",
                                                "timerange": "7d"
                                            }
                                        }
                                    },
                                    "Count_NonInteractive_SignIn_KQL": {
                                        "type": "ApiConnection",
                                        "inputs": {
                                            "host": {
                                                "connection": {
                                                    "name": "@parameters('$connections')['azuremonitorlogs']['connectionId']"
                                                }
                                            },
                                            "method": "post",
                                            "body": "@concat('AADNonInteractiveUserSignInLogs | where TimeGenerated > ago(7d) | where UserPrincipalName =~ \"', outputs('Compose_Resolved_UPN'), '\" | summarize TotalCount=count()')",
                                            "path": "/queryData",
                                            "queries": {
                                                "subscriptions": "<AZURE-SUBSCRIPTION-ID>",
                                                "resourcegroups": "<RESOURCE-GROUP>",
                                                "resourcetype": "Log Analytics Workspace",
                                                "resourcename": "<LOG-ANALYTICS-WORKSPACE>",
                                                "timerange": "7d"
                                            }
                                        }
                                    },
                                    "Count_IdentityRisk_KQL": {
                                        "type": "ApiConnection",
                                        "inputs": {
                                            "host": {
                                                "connection": {
                                                    "name": "@parameters('$connections')['azuremonitorlogs']['connectionId']"
                                                }
                                            },
                                            "method": "post",
                                            "body": "@concat('AADUserRiskEvents | where TimeGenerated > ago(30d) | where UserPrincipalName =~ \"', outputs('Compose_Resolved_UPN'), '\" | summarize TotalCount=count()')",
                                            "path": "/queryData",
                                            "queries": {
                                                "subscriptions": "<AZURE-SUBSCRIPTION-ID>",
                                                "resourcegroups": "<RESOURCE-GROUP>",
                                                "resourcetype": "Log Analytics Workspace",
                                                "resourcename": "<LOG-ANALYTICS-WORKSPACE>",
                                                "timerange": "30d"
                                            }
                                        }
                                    },
                                    "Count_CloudApp_KQL": {
                                        "type": "ApiConnection",
                                        "inputs": {
                                            "host": {
                                                "connection": {
                                                    "name": "@parameters('$connections')['azuremonitorlogs']['connectionId']"
                                                }
                                            },
                                            "method": "post",
                                            "body": "@concat('CloudAppEvents | where TimeGenerated > ago(7d) | where AccountId =~ \"', outputs('Compose_Resolved_UPN'), '\" or AccountDisplayName =~ \"', coalesce(body('Parse_Graph_User')?['value']?[0]?['displayName'], outputs('Compose_Account_SAM')), '\" | summarize TotalCount=count()')",
                                            "path": "/queryData",
                                            "queries": {
                                                "subscriptions": "<AZURE-SUBSCRIPTION-ID>",
                                                "resourcegroups": "<RESOURCE-GROUP>",
                                                "resourcetype": "Log Analytics Workspace",
                                                "resourcename": "<LOG-ANALYTICS-WORKSPACE>",
                                                "timerange": "7d"
                                            }
                                        }
                                    },
                                    "Count_IdentityLogon_KQL": {
                                        "type": "ApiConnection",
                                        "inputs": {
                                            "host": {
                                                "connection": {
                                                    "name": "@parameters('$connections')['azuremonitorlogs']['connectionId']"
                                                }
                                            },
                                            "method": "post",
                                            "body": "@concat('IdentityLogonEvents | where TimeGenerated > ago(7d) | where AccountUpn =~ \"', outputs('Compose_Resolved_UPN'), '\" or AccountName =~ \"', outputs('Compose_Account_SAM'), '\" | summarize TotalCount=count()')",
                                            "path": "/queryData",
                                            "queries": {
                                                "subscriptions": "<AZURE-SUBSCRIPTION-ID>",
                                                "resourcegroups": "<RESOURCE-GROUP>",
                                                "resourcetype": "Log Analytics Workspace",
                                                "resourcename": "<LOG-ANALYTICS-WORKSPACE>",
                                                "timerange": "7d"
                                            }
                                        }
                                    },
                                    "Append_Account_Enrichment_Found": {
                                        "runAfter": {
                                            "Run_SignIn_KQL": [
                                                "Succeeded",
                                                "Failed",
                                                "TimedOut"
                                            ],
                                            "Run_NonInteractive_SignIn_KQL": [
                                                "Succeeded",
                                                "Failed",
                                                "TimedOut"
                                            ],
                                            "Run_IdentityRisk_KQL": [
                                                "Succeeded",
                                                "Failed",
                                                "TimedOut"
                                            ],
                                            "Run_CloudApp_KQL": [
                                                "Succeeded",
                                                "Failed",
                                                "TimedOut"
                                            ],
                                            "Run_IdentityLogon_KQL": [
                                                "Succeeded",
                                                "Failed",
                                                "TimedOut"
                                            ],
                                            "Count_SignIn_KQL": [
                                                "Succeeded",
                                                "Failed",
                                                "TimedOut"
                                            ],
                                            "Count_NonInteractive_SignIn_KQL": [
                                                "Succeeded",
                                                "Failed",
                                                "TimedOut"
                                            ],
                                            "Count_IdentityRisk_KQL": [
                                                "Succeeded",
                                                "Failed",
                                                "TimedOut"
                                            ],
                                            "Count_CloudApp_KQL": [
                                                "Succeeded",
                                                "Failed",
                                                "TimedOut"
                                            ],
                                            "Count_IdentityLogon_KQL": [
                                                "Succeeded",
                                                "Failed",
                                                "TimedOut"
                                            ]
                                        },
                                        "type": "AppendToArrayVariable",
                                        "inputs": {
                                            "name": "AccountEnrichment",
                                            "value": {
                                                "samAccountName": "@outputs('Compose_Account_SAM')",
                                                "upn": "@outputs('Compose_Resolved_UPN')",
                                                "onPremisesDomain": "@coalesce(body('Parse_Graph_User')?['value']?[0]?['onPremisesDomainName'], 'Unknown')",
                                                "displayName": "@coalesce(body('Parse_Graph_User')?['value']?[0]?['displayName'], 'Unknown')",
                                                "jobTitle": "@coalesce(body('Parse_Graph_User')?['value']?[0]?['jobTitle'], 'Unknown')",
                                                "department": "@coalesce(body('Parse_Graph_User')?['value']?[0]?['department'], 'Unknown')",
                                                "accountEnabled": "@string(coalesce(body('Parse_Graph_User')?['value']?[0]?['accountEnabled'], false))",
                                                "lastPasswordChange": "@coalesce(body('Parse_Graph_User')?['value']?[0]?['lastPasswordChangeDateTime'], 'Unknown')",
                                                "entraResolved": true,
                                                "recentSignIns": "@coalesce(body('Run_SignIn_KQL')?['value'], json('[]'))",
                                                "recentSignInCount": "@length(coalesce(body('Run_SignIn_KQL')?['value'], json('[]')))",
                                                "recentSignInTotal": "@coalesce(body('Count_SignIn_KQL')?['value']?[0]?['TotalCount'], 0)",
                                                "nonInteractiveSignIns": "@coalesce(body('Run_NonInteractive_SignIn_KQL')?['value'], json('[]'))",
                                                "nonInteractiveSignInCount": "@length(coalesce(body('Run_NonInteractive_SignIn_KQL')?['value'], json('[]')))",
                                                "nonInteractiveSignInTotal": "@coalesce(body('Count_NonInteractive_SignIn_KQL')?['value']?[0]?['TotalCount'], 0)",
                                                "identityRiskEvents": "@coalesce(body('Run_IdentityRisk_KQL')?['value'], json('[]'))",
                                                "identityRiskEventCount": "@length(coalesce(body('Run_IdentityRisk_KQL')?['value'], json('[]')))",
                                                "identityRiskEventTotal": "@coalesce(body('Count_IdentityRisk_KQL')?['value']?[0]?['TotalCount'], 0)",
                                                "cloudAppEvents": "@coalesce(body('Run_CloudApp_KQL')?['value'], json('[]'))",
                                                "cloudAppEventCount": "@length(coalesce(body('Run_CloudApp_KQL')?['value'], json('[]')))",
                                                "cloudAppEventTotal": "@coalesce(body('Count_CloudApp_KQL')?['value']?[0]?['TotalCount'], 0)",
                                                "identityLogonEvents": "@coalesce(body('Run_IdentityLogon_KQL')?['value'], json('[]'))",
                                                "identityLogonEventCount": "@length(coalesce(body('Run_IdentityLogon_KQL')?['value'], json('[]')))",
                                                "identityLogonEventTotal": "@coalesce(body('Count_IdentityLogon_KQL')?['value']?[0]?['TotalCount'], 0)"
                                            }
                                        }
                                    },
                                    "Append_Account_HTML_Row_Found": {
                                        "runAfter": {
                                            "Append_Account_Enrichment_Found": [
                                                "Succeeded"
                                            ]
                                        },
                                        "type": "AppendToStringVariable",
                                        "inputs": {
                                            "name": "AccountTableHTML",
                                            "value": "@concat('<tr style=\"background:#f9f9f9\"><td style=\"padding:6px 10px;border:1px solid #ddd\">', coalesce(body('Parse_Graph_User')?['value']?[0]?['displayName'], 'Unknown'), '</td><td style=\"padding:6px 10px;border:1px solid #ddd;font-family:monospace;font-size:12px\">', outputs('Compose_Resolved_UPN'), '</td><td style=\"padding:6px 10px;border:1px solid #ddd;font-size:11px;color:#666\">', outputs('Compose_Account_SAM'), ' @ ', coalesce(body('Parse_Graph_User')?['value']?[0]?['onPremisesDomainName'], item()?['UPNSuffix']), '</td><td style=\"padding:6px 10px;border:1px solid #ddd\">', coalesce(body('Parse_Graph_User')?['value']?[0]?['jobTitle'], 'Unknown'), '</td><td style=\"padding:6px 10px;border:1px solid #ddd\">', coalesce(body('Parse_Graph_User')?['value']?[0]?['department'], 'Unknown'), '</td><td style=\"padding:6px 10px;border:1px solid #ddd;text-align:center;font-weight:bold;color:', if(equals(body('Parse_Graph_User')?['value']?[0]?['accountEnabled'], true), 'green', 'red'), '\">', if(equals(body('Parse_Graph_User')?['value']?[0]?['accountEnabled'], true), 'Enabled', 'Disabled'), '</td><td style=\"padding:6px 10px;border:1px solid #ddd;text-align:center;font-size:11px\">', coalesce(body('Parse_Graph_User')?['value']?[0]?['lastPasswordChangeDateTime'], 'Unknown'), '</td><td style=\"padding:6px 10px;border:1px solid #ddd;text-align:center;', if(greater(coalesce(body('Count_SignIn_KQL')?['value']?[0]?['TotalCount'], 0), length(coalesce(body('Run_SignIn_KQL')?['value'], json('[]')))), 'background:#fff3cd;', ''), '\">', string(length(coalesce(body('Run_SignIn_KQL')?['value'], json('[]')))), '/', string(coalesce(body('Count_SignIn_KQL')?['value']?[0]?['TotalCount'], 0)), if(greater(coalesce(body('Count_SignIn_KQL')?['value']?[0]?['TotalCount'], 0), length(coalesce(body('Run_SignIn_KQL')?['value'], json('[]')))), ' ⚠', ''), '</td><td style=\"padding:6px 10px;border:1px solid #ddd;text-align:center;font-size:11px;', if(greater(coalesce(body('Count_NonInteractive_SignIn_KQL')?['value']?[0]?['TotalCount'], 0), length(coalesce(body('Run_NonInteractive_SignIn_KQL')?['value'], json('[]')))), 'background:#fff3cd;', ''), '\">', string(length(coalesce(body('Run_NonInteractive_SignIn_KQL')?['value'], json('[]')))), '/', string(coalesce(body('Count_NonInteractive_SignIn_KQL')?['value']?[0]?['TotalCount'], 0)), if(greater(coalesce(body('Count_NonInteractive_SignIn_KQL')?['value']?[0]?['TotalCount'], 0), length(coalesce(body('Run_NonInteractive_SignIn_KQL')?['value'], json('[]')))), ' ⚠', ''), ' SVC</td><td style=\"padding:6px 10px;border:1px solid #ddd;text-align:center;font-size:11px;font-weight:bold;color:', if(greater(length(coalesce(body('Run_IdentityRisk_KQL')?['value'], json('[]'))), 0), '#c0392b', '#27ae60'), ';', if(greater(coalesce(body('Count_IdentityRisk_KQL')?['value']?[0]?['TotalCount'], 0), length(coalesce(body('Run_IdentityRisk_KQL')?['value'], json('[]')))), 'background:#fff3cd;', ''), '\">', string(length(coalesce(body('Run_IdentityRisk_KQL')?['value'], json('[]')))), '/', string(coalesce(body('Count_IdentityRisk_KQL')?['value']?[0]?['TotalCount'], 0)), if(greater(coalesce(body('Count_IdentityRisk_KQL')?['value']?[0]?['TotalCount'], 0), length(coalesce(body('Run_IdentityRisk_KQL')?['value'], json('[]')))), ' ⚠', ''), ' risk</td><td style=\"padding:6px 10px;border:1px solid #ddd;text-align:center;font-size:11px;', if(greater(coalesce(body('Count_CloudApp_KQL')?['value']?[0]?['TotalCount'], 0), length(coalesce(body('Run_CloudApp_KQL')?['value'], json('[]')))), 'background:#fff3cd;', ''), '\">', string(length(coalesce(body('Run_CloudApp_KQL')?['value'], json('[]')))), '/', string(coalesce(body('Count_CloudApp_KQL')?['value']?[0]?['TotalCount'], 0)), if(greater(coalesce(body('Count_CloudApp_KQL')?['value']?[0]?['TotalCount'], 0), length(coalesce(body('Run_CloudApp_KQL')?['value'], json('[]')))), ' ⚠', ''), ' cloud</td><td style=\"padding:6px 10px;border:1px solid #ddd;text-align:center;font-size:11px;', if(greater(coalesce(body('Count_IdentityLogon_KQL')?['value']?[0]?['TotalCount'], 0), length(coalesce(body('Run_IdentityLogon_KQL')?['value'], json('[]')))), 'background:#fff3cd;', ''), '\">', string(length(coalesce(body('Run_IdentityLogon_KQL')?['value'], json('[]')))), '/', string(coalesce(body('Count_IdentityLogon_KQL')?['value']?[0]?['TotalCount'], 0)), if(greater(coalesce(body('Count_IdentityLogon_KQL')?['value']?[0]?['TotalCount'], 0), length(coalesce(body('Run_IdentityLogon_KQL')?['value'], json('[]')))), ' ⚠', ''), ' onprem</td><td style=\"padding:6px 10px;border:1px solid #ddd;text-align:center\"><span style=\"color:green\">✔ Resolved</span></td></tr>')"
                                        }
                                    },
                                    "Compose_Account_KQL_Block": {
                                        "runAfter": {
                                            "Append_Account_HTML_Row_Found": [
                                                "Succeeded",
                                                "Failed",
                                                "Skipped",
                                                "TimedOut"
                                            ]
                                        },
                                        "type": "Compose",
                                        "inputs": "@concat('<div style=\"border-left:4px solid #27ae60;padding:10px 14px;margin-bottom:20px;background:#f0fff4\"><strong style=\"color:#1a6b37;font-size:13px\">&#128100; ', coalesce(body('Parse_Graph_User')?['value']?[0]?['displayName'], outputs('Compose_Account_SAM')), '</strong><span style=\"color:#7f8c8d;font-size:11px;margin-left:10px\">UPN: ', outputs('Compose_Resolved_UPN'), ' &nbsp;|&nbsp; SAM: ', outputs('Compose_Account_SAM'), '</span><br><br><strong style=\"font-size:12px;color:#1e8449\">&#128274; SigninLogs (7d lookback)</strong><br><span style=\"font-family:Consolas,Courier New,monospace;font-size:11px;color:#1c2833;white-space:pre\">SigninLogs<br>| where TimeGenerated &gt; ago(7d)<br>| where UserPrincipalName =~ \"', outputs('Compose_Resolved_UPN'), '\"<br>| project TimeGenerated, UserPrincipalName, AppDisplayName, IPAddress, Location,<br>         ResultType, ResultDescription, ConditionalAccessStatus, DeviceDetail,<br>         RiskLevelDuringSignIn, RiskLevelAggregated, AuthenticationDetails,<br>         MfaDetail, ClientAppUsed, UserAgent<br>| order by TimeGenerated desc<br>| take 20</span><br><br><strong style=\"font-size:12px;color:#1e8449\">&#128274; AADNonInteractiveUserSignInLogs (7d lookback)</strong><br><span style=\"font-family:Consolas,Courier New,monospace;font-size:11px;color:#1c2833;white-space:pre\">AADNonInteractiveUserSignInLogs<br>| where TimeGenerated &gt; ago(7d)<br>| where UserPrincipalName =~ \"', outputs('Compose_Resolved_UPN'), '\"<br>| project TimeGenerated, UserPrincipalName, AppDisplayName, AppId, IPAddress,<br>         Location, ResultType, ResultDescription, ConditionalAccessStatus,<br>         RiskLevelDuringSignIn, RiskLevelAggregated, ClientAppUsed,<br>         ResourceDisplayName, CorrelationId<br>| order by TimeGenerated desc<br>| take 20</span><br><br><strong style=\"font-size:12px;color:#1e8449\">&#9888; AADUserRiskEvents (30d lookback)</strong><br><span style=\"font-family:Consolas,Courier New,monospace;font-size:11px;color:#1c2833;white-space:pre\">AADUserRiskEvents<br>| where TimeGenerated &gt; ago(30d)<br>| where UserPrincipalName =~ \"', outputs('Compose_Resolved_UPN'), '\"<br>| project TimeGenerated, UserPrincipalName, RiskEventType, RiskDetail, RiskLevel,<br>         RiskState, IpAddress, Location, DetectionTimingType, AdditionalInfo, CorrelationId<br>| order by TimeGenerated desc<br>| take 10</span><br><br><strong style=\"font-size:12px;color:#1e8449\">&#9729; CloudAppEvents (7d lookback)</strong><br><span style=\"font-family:Consolas,Courier New,monospace;font-size:11px;color:#1c2833;white-space:pre\">CloudAppEvents<br>| where TimeGenerated &gt; ago(7d)<br>| where AccountId =~ \"', outputs('Compose_Resolved_UPN'), '\"<br>    or AccountDisplayName =~ \"', coalesce(body('Parse_Graph_User')?['value']?[0]?['displayName'], outputs('Compose_Account_SAM')), '\"<br>| project TimeGenerated, AccountId, AccountDisplayName, Application, ActionType,<br>         ObjectName, ObjectType, IPAddress, CountryCode, ISP,<br>         ActivityType, ActivityObjects, RawEventData<br>| order by TimeGenerated desc<br>| take 25</span><br><br><strong style=\"font-size:12px;color:#1e8449\">&#128421; IdentityLogonEvents (7d lookback)</strong><br><span style=\"font-family:Consolas,Courier New,monospace;font-size:11px;color:#1c2833;white-space:pre\">IdentityLogonEvents<br>| where TimeGenerated &gt; ago(7d)<br>| where AccountUpn =~ \"', outputs('Compose_Resolved_UPN'), '\"<br>    or AccountName =~ \"', outputs('Compose_Account_SAM'), '\"<br>| project TimeGenerated, AccountUpn, AccountName, AccountDomain, Protocol,<br>         ActionType, LogonType, DeviceName, IPAddress, DestinationDeviceName,<br>         DestinationPort, FailureReason<br>| order by TimeGenerated desc<br>| take 25</span></div>')"
                                    },
                                    "Append_Account_KQL_Section": {
                                        "runAfter": {
                                            "Compose_Account_KQL_Block": [
                                                "Succeeded"
                                            ]
                                        },
                                        "type": "AppendToStringVariable",
                                        "inputs": {
                                            "name": "KQLSectionHTML",
                                            "value": "@outputs('Compose_Account_KQL_Block')"
                                        }
                                    }
                                },
                                "runAfter": {
                                    "Compose_User_Found": [
                                        "Succeeded"
                                    ]
                                },
                                "else": {
                                    "actions": {
                                        "Append_Account_Enrichment_NotFound": {
                                            "type": "AppendToArrayVariable",
                                            "inputs": {
                                                "name": "AccountEnrichment",
                                                "value": {
                                                    "samAccountName": "@outputs('Compose_Account_SAM')",
                                                    "upn": "@outputs('Compose_Resolved_UPN')",
                                                    "onPremisesDomain": "@item()?['UPNSuffix']",
                                                    "displayName": "Not found in Entra ID",
                                                    "jobTitle": "Unknown",
                                                    "department": "Unknown",
                                                    "accountEnabled": "Unknown",
                                                    "lastPasswordChange": "Unknown",
                                                    "entraResolved": false,
                                                    "recentSignIns": [],
                                                    "recentSignInCount": 0,
                                                    "recentSignInTotal": 0,
                                                    "nonInteractiveSignIns": [],
                                                    "nonInteractiveSignInCount": 0,
                                                    "nonInteractiveSignInTotal": 0,
                                                    "identityRiskEvents": [],
                                                    "identityRiskEventCount": 0,
                                                    "identityRiskEventTotal": 0,
                                                    "cloudAppEvents": [],
                                                    "cloudAppEventCount": 0,
                                                    "cloudAppEventTotal": 0,
                                                    "identityLogonEvents": [],
                                                    "identityLogonEventCount": 0,
                                                    "identityLogonEventTotal": 0
                                                }
                                            }
                                        },
                                        "Append_Account_HTML_Row_NotFound": {
                                            "runAfter": {
                                                "Append_Account_Enrichment_NotFound": [
                                                    "Succeeded"
                                                ]
                                            },
                                            "type": "AppendToStringVariable",
                                            "inputs": {
                                                "name": "AccountTableHTML",
                                                "value": "@concat('<tr style=\"background:#fff3cd\"><td style=\"padding:6px 10px;border:1px solid #ddd;color:#856404\">Not found in Entra</td><td style=\"padding:6px 10px;border:1px solid #ddd;font-family:monospace;font-size:12px\">', outputs('Compose_Resolved_UPN'), '</td><td style=\"padding:6px 10px;border:1px solid #ddd;font-size:11px;color:#666\">', outputs('Compose_Account_SAM'), ' @ ', item()?['UPNSuffix'], '</td><td colspan=\"10\" style=\"padding:6px 10px;border:1px solid #ddd;text-align:center\"><span style=\"color:orange\">⚠ Not Found in Entra ID</span></td></tr>')"
                                            }
                                        },
                                        "Append_Account_KQL_Section_NotFound": {
                                            "runAfter": {
                                                "Append_Account_HTML_Row_NotFound": [
                                                    "Succeeded"
                                                ]
                                            },
                                            "type": "AppendToStringVariable",
                                            "inputs": {
                                                "name": "KQLSectionHTML",
                                                "value": "@concat('<div style=\"border-left:4px solid #f39c12;padding:8px 14px;margin-bottom:12px;background:#fffdf0\"><span style=\"color:#7d6608;font-size:12px\">&#9888; <strong>', outputs('Compose_Account_SAM'), '</strong> (', outputs('Compose_Resolved_UPN'), ') — not found in Entra ID — KQL queries not executed</span></div>')"
                                            }
                                        }
                                    }
                                },
                                "expression": {
                                    "and": [
                                        {
                                            "equals": [
                                                "@outputs('Compose_User_Found')",
                                                true
                                            ]
                                        }
                                    ]
                                },
                                "type": "If"
                            }
                        },
                        "type": "Foreach",
                        "operationOptions": "Sequential"
                    },
                    "Response_Success": {
                        "runAfter": {
                            "For_each_Account_Enrich": [
                                "Succeeded",
                                "Failed",
                                "Skipped",
                                "TimedOut"
                            ]
                        },
                        "type": "Response",
                        "kind": "Http",
                        "inputs": {
                            "statusCode": 200,
                            "headers": {
                                "Content-Type": "application/json"
                            },
                            "body": {
                                "accountTableHTML": "@variables('AccountTableHTML')",
                                "kqlSectionHTML": "@variables('KQLSectionHTML')",
                                "results": "@variables('AccountEnrichment')"
                            }
                        }
                    }
                },
                "runAfter": {
                    "Initialize_AccountEnrichment": [
                        "Succeeded"
                    ],
                    "Initialize_AccountTableHTML": [
                        "Succeeded"
                    ],
                    "Initialize_KQLSectionHTML": [
                        "Succeeded"
                    ]
                },
                "else": {
                    "actions": {
                        "Response_Unauthorized": {
                            "type": "Response",
                            "kind": "Http",
                            "inputs": {
                                "statusCode": 401,
                                "body": {
                                    "error": "Unauthorized - invalid worker key"
                                }
                            }
                        }
                    }
                },
                "expression": {
                    "and": [
                        {
                            "equals": [
                                "@triggerOutputs()?['headers']?['x-worker-key']",
                                "@parameters('WorkerSharedKey')"
                            ]
                        }
                    ]
                },
                "type": "If"
            }
        },
        "outputs": {},
        "parameters": {
            "WorkerSharedKey": {
                "defaultValue": "<WORKER-SHARED-KEY>",
                "type": "String"
            },
            "$connections": {
                "type": "Object",
                "defaultValue": {}
            }
        }
    },
    "parameters": {
        "$connections": {
            "type": "Object",
            "value": {
                "azuremonitorlogs": {
                    "id": "/subscriptions/<AZURE-SUBSCRIPTION-ID>/providers/Microsoft.Web/locations/westus2/managedApis/azuremonitorlogs",
                    "connectionId": "/subscriptions/<AZURE-SUBSCRIPTION-ID>/resourceGroups/<RESOURCE-GROUP>/providers/Microsoft.Web/connections/azuremonitorlogs-1",
                    "connectionName": "azuremonitorlogs-1",
                    "connectionProperties": {}
                }
            }
        }
    }
}