|
| 1 | +import { createAction, Property, Validators } from '@openops/blocks-framework'; |
| 2 | +import { |
| 3 | + azureAuth, |
| 4 | + getUseHostSessionProperty, |
| 5 | + makeHttpRequest, |
| 6 | +} from '@openops/common'; |
| 7 | +import { AxiosHeaders } from 'axios'; |
| 8 | +import { getAzureAccessToken } from '../auth/get-azure-access-token'; |
| 9 | +import { createSubscriptionDynamicProperty } from '../common-properties'; |
| 10 | + |
| 11 | +const RESOURCE_GRAPH_API_VERSION = '2024-04-01'; |
| 12 | +const BATCH_SIZE = 1000; |
| 13 | + |
| 14 | +interface ResourceGraphResponse { |
| 15 | + data: Record<string, unknown>[]; |
| 16 | + $skipToken?: string; |
| 17 | +} |
| 18 | + |
| 19 | +interface ResourceGraphRequestBody { |
| 20 | + query: string; |
| 21 | + options: { |
| 22 | + $top: number; |
| 23 | + $skipToken?: string; |
| 24 | + }; |
| 25 | + subscriptions?: string[]; |
| 26 | +} |
| 27 | + |
| 28 | +const buildResourceGraphUrl = (apiVersion?: string): string => |
| 29 | + `https://management.azure.com/providers/Microsoft.ResourceGraph/resources?api-version=${ |
| 30 | + apiVersion || RESOURCE_GRAPH_API_VERSION |
| 31 | + }`; |
| 32 | + |
| 33 | +const buildRequestBody = ( |
| 34 | + query: string, |
| 35 | + batch?: string[], |
| 36 | + skipToken?: string, |
| 37 | +): ResourceGraphRequestBody => ({ |
| 38 | + query, |
| 39 | + options: { |
| 40 | + $top: BATCH_SIZE, |
| 41 | + ...(skipToken && { $skipToken: skipToken }), |
| 42 | + }, |
| 43 | + ...(batch?.length && { subscriptions: batch }), |
| 44 | +}); |
| 45 | + |
| 46 | +const queryBatch = async ( |
| 47 | + url: string, |
| 48 | + headers: AxiosHeaders, |
| 49 | + query: string, |
| 50 | + batch?: string[], |
| 51 | + hardLimit?: number, |
| 52 | +): Promise<Record<string, unknown>[]> => { |
| 53 | + const results: Record<string, unknown>[] = []; |
| 54 | + let skipToken: string | undefined; |
| 55 | + |
| 56 | + do { |
| 57 | + const requestBody = buildRequestBody(query, batch, skipToken); |
| 58 | + const response = await makeHttpRequest<ResourceGraphResponse>( |
| 59 | + 'POST', |
| 60 | + url, |
| 61 | + headers, |
| 62 | + requestBody, |
| 63 | + ); |
| 64 | + |
| 65 | + if (response.data?.length) { |
| 66 | + if (hardLimit) { |
| 67 | + const remaining = hardLimit - results.length; |
| 68 | + results.push(...response.data.slice(0, remaining)); |
| 69 | + if (results.length >= hardLimit) { |
| 70 | + break; |
| 71 | + } |
| 72 | + } else { |
| 73 | + results.push(...response.data); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + skipToken = response.$skipToken; |
| 78 | + } while (skipToken); |
| 79 | + |
| 80 | + return results; |
| 81 | +}; |
| 82 | + |
| 83 | +export const azureResourceGraphAction = createAction({ |
| 84 | + auth: azureAuth, |
| 85 | + name: 'resource_graph_query', |
| 86 | + description: |
| 87 | + 'Query Azure Resource Graph using KQL to retrieve resources across multiple subscriptions', |
| 88 | + displayName: 'Azure Resource Graph Query', |
| 89 | + isWriteAction: false, |
| 90 | + props: { |
| 91 | + query: Property.LongText({ |
| 92 | + displayName: 'KQL Query', |
| 93 | + description: 'The Kusto Query Language (KQL) query to execute.', |
| 94 | + required: true, |
| 95 | + }), |
| 96 | + useHostSession: getUseHostSessionProperty('Azure', 'az login'), |
| 97 | + querySubscriptions: createSubscriptionDynamicProperty( |
| 98 | + { |
| 99 | + displayName: 'Query Subscriptions', |
| 100 | + description: |
| 101 | + 'Select Azure subscriptions to query for Azure Resource Graph.', |
| 102 | + required: true, |
| 103 | + multiSelect: true, |
| 104 | + preselectAll: true, |
| 105 | + }, |
| 106 | + 'querySubscriptions', |
| 107 | + ), |
| 108 | + maxResults: Property.Number({ |
| 109 | + displayName: 'Maximum Results', |
| 110 | + description: |
| 111 | + 'Maximum number of results to return. Leave empty for no limit.', |
| 112 | + required: false, |
| 113 | + validators: [Validators.minValue(1), Validators.integer], |
| 114 | + }), |
| 115 | + apiVersion: Property.ShortText({ |
| 116 | + displayName: 'API Version', |
| 117 | + description: |
| 118 | + 'Azure Resource Graph API version. Leave empty to use the latest stable version (2022-10-01).', |
| 119 | + required: false, |
| 120 | + defaultValue: RESOURCE_GRAPH_API_VERSION, |
| 121 | + }), |
| 122 | + }, |
| 123 | + async run(context) { |
| 124 | + const { |
| 125 | + useHostSession, |
| 126 | + querySubscriptions, |
| 127 | + query, |
| 128 | + maxResults, |
| 129 | + apiVersion, |
| 130 | + } = context.propsValue; |
| 131 | + |
| 132 | + const kql = query?.trim(); |
| 133 | + if (!kql) { |
| 134 | + throw new Error('KQL query is required.'); |
| 135 | + } |
| 136 | + |
| 137 | + const normalizedMax = |
| 138 | + typeof maxResults === 'number' ? maxResults : undefined; |
| 139 | + |
| 140 | + const subscriptionList = querySubscriptions as string[] | undefined; |
| 141 | + |
| 142 | + const token = await getAzureAccessToken( |
| 143 | + context.auth, |
| 144 | + !!useHostSession?.['useHostSessionCheckbox'], |
| 145 | + ); |
| 146 | + |
| 147 | + const headers = new AxiosHeaders({ |
| 148 | + Authorization: `Bearer ${token}`, |
| 149 | + 'Content-Type': 'application/json', |
| 150 | + }); |
| 151 | + |
| 152 | + const allResults = await getQueryResults( |
| 153 | + splitSubscriptionListIntoBatches(subscriptionList), |
| 154 | + buildResourceGraphUrl(apiVersion), |
| 155 | + headers, |
| 156 | + kql, |
| 157 | + normalizedMax, |
| 158 | + ); |
| 159 | + |
| 160 | + return { |
| 161 | + totalRecords: allResults.length, |
| 162 | + data: allResults, |
| 163 | + query: kql, |
| 164 | + querySubscriptions: subscriptionList, |
| 165 | + }; |
| 166 | + }, |
| 167 | +}); |
| 168 | + |
| 169 | +function splitSubscriptionListIntoBatches( |
| 170 | + subscriptionList?: string[], |
| 171 | +): (string[] | undefined)[] { |
| 172 | + if (!subscriptionList?.length) { |
| 173 | + return [undefined]; |
| 174 | + } |
| 175 | + |
| 176 | + const batches: string[][] = []; |
| 177 | + for (let i = 0; i < subscriptionList.length; i += BATCH_SIZE) { |
| 178 | + const batch = subscriptionList.slice(i, i + BATCH_SIZE); |
| 179 | + batches.push(batch); |
| 180 | + } |
| 181 | + |
| 182 | + return batches; |
| 183 | +} |
| 184 | + |
| 185 | +async function getQueryResults( |
| 186 | + batches: (string[] | undefined)[], |
| 187 | + url: string, |
| 188 | + headers: AxiosHeaders, |
| 189 | + query: string, |
| 190 | + maxResults?: number, |
| 191 | +): Promise<Record<string, unknown>[]> { |
| 192 | + const allResults: Record<string, unknown>[] = []; |
| 193 | + let remaining = maxResults ?? Number.POSITIVE_INFINITY; |
| 194 | + |
| 195 | + for (const batch of batches) { |
| 196 | + if (remaining <= 0) { |
| 197 | + break; |
| 198 | + } |
| 199 | + |
| 200 | + const batchResults = await queryBatch( |
| 201 | + url, |
| 202 | + headers, |
| 203 | + query, |
| 204 | + batch, |
| 205 | + Number.isFinite(remaining) ? remaining : undefined, |
| 206 | + ); |
| 207 | + |
| 208 | + allResults.push(...batchResults); |
| 209 | + remaining = Math.max(0, remaining - batchResults.length); |
| 210 | + } |
| 211 | + |
| 212 | + return allResults; |
| 213 | +} |
0 commit comments