@pagopa/dx-savemoney 0.4.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +48 -0
  2. package/dist/azure/__tests__/azqr.test.d.ts +13 -0
  3. package/dist/azure/__tests__/azqr.test.d.ts.map +1 -0
  4. package/dist/azure/__tests__/azqr.test.js +177 -0
  5. package/dist/azure/__tests__/azqr.test.js.map +1 -0
  6. package/dist/azure/__tests__/config.test.js +23 -1
  7. package/dist/azure/__tests__/config.test.js.map +1 -1
  8. package/dist/azure/analyzer.d.ts.map +1 -1
  9. package/dist/azure/analyzer.js +32 -4
  10. package/dist/azure/analyzer.js.map +1 -1
  11. package/dist/azure/analyzers/advisor.d.ts.map +1 -1
  12. package/dist/azure/analyzers/advisor.js.map +1 -1
  13. package/dist/azure/azqr.d.ts +136 -0
  14. package/dist/azure/azqr.d.ts.map +1 -0
  15. package/dist/azure/azqr.js +235 -0
  16. package/dist/azure/azqr.js.map +1 -0
  17. package/dist/azure/config.d.ts.map +1 -1
  18. package/dist/azure/config.js +2 -5
  19. package/dist/azure/config.js.map +1 -1
  20. package/dist/azure/resources/public-ip.d.ts.map +1 -1
  21. package/dist/azure/resources/public-ip.js.map +1 -1
  22. package/dist/azure/types.d.ts +13 -3
  23. package/dist/azure/types.d.ts.map +1 -1
  24. package/dist/finding.d.ts +2 -1
  25. package/dist/finding.d.ts.map +1 -1
  26. package/dist/finding.js.map +1 -1
  27. package/dist/index.d.ts +1 -0
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +1 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/schema.d.ts +6 -1
  32. package/dist/schema.d.ts.map +1 -1
  33. package/dist/schema.js +11 -3
  34. package/dist/schema.js.map +1 -1
  35. package/package.json +8 -8
  36. package/src/azure/__tests__/azqr.test.ts +238 -0
  37. package/src/azure/__tests__/config.test.ts +33 -1
  38. package/src/azure/__tests__/fixtures/full-override.yaml +3 -0
  39. package/src/azure/analyzer.ts +50 -9
  40. package/src/azure/analyzers/advisor.ts +1 -2
  41. package/src/azure/azqr.ts +270 -0
  42. package/src/azure/config.ts +2 -5
  43. package/src/azure/resources/public-ip.ts +1 -2
  44. package/src/azure/types.ts +13 -3
  45. package/src/finding.ts +3 -6
  46. package/src/index.ts +1 -0
  47. package/src/schema.ts +13 -3
@@ -0,0 +1,270 @@
1
+ /**
2
+ * AZQR report ingestion.
3
+ *
4
+ * Parses an AZQR (`azqr scan --json`) report and turns its `impacted`
5
+ * resources into the unified `Finding` model (`source: "azqr"`), keeping only
6
+ * the rows that carry FinOps signal so the SaveMoney output is not flooded with
7
+ * security / reliability / high-availability best-practice noise. Promoted rows
8
+ * fall into two classes (see {@link classifyAzqrRow}):
9
+ *
10
+ * - **cost** (`category: "cost"`): billable waste — rows AZQR categorises as
11
+ * `Cost`, or orphaned resources whose type actually incurs cost (public IPs,
12
+ * NAT gateways, application gateways, …).
13
+ * - **cleanup** (`category: "operationalExcellence"`): orphaned *free* resources
14
+ * (empty subnets, unattached NSGs, orphan API connections, …). They carry no
15
+ * direct cost but are cleanup candidates worth investigating.
16
+ *
17
+ * Orphans are detected via AZQR's `AOR` (Azure Orphan Resources) check source
18
+ * rather than fragile recommendation-text matching.
19
+ *
20
+ * The AZQR CLI masks subscription IDs by default (e.g.
21
+ * `/subscriptions/xxxxxxxx-…/`). Masked IDs do not match the real resource IDs
22
+ * produced by a live scan, so masked findings cannot be merged onto their
23
+ * resources — {@link isAzqrReportMasked} lets the orchestrator warn and advise
24
+ * re-running with `azqr scan --mask=false`.
25
+ *
26
+ * Scope note (CES-2192 / Fase 1): only `impacted` rows are ingested, enriched
27
+ * with `inventory` metadata when available. AZQR `advisor` rows are ignored to
28
+ * avoid duplicating SaveMoney's own Azure Advisor cost query.
29
+ */
30
+
31
+ import { readFile } from "node:fs/promises";
32
+ import { z } from "zod";
33
+
34
+ import type { CostRisk } from "../types.js";
35
+
36
+ import { type Finding } from "../finding.js";
37
+
38
+ /** A single `impacted` row from an AZQR JSON report (fields we consume). */
39
+ const azqrImpactedRowSchema = z.object({
40
+ category: z.string().optional(),
41
+ impact: z.string().optional(),
42
+ learn: z.string().optional(),
43
+ recommendation: z.string(),
44
+ recommendationId: z.string().optional(),
45
+ resourceGroup: z.string().optional(),
46
+ resourceId: z.string(),
47
+ resourceName: z.string().optional(),
48
+ resourceType: z.string().optional(),
49
+ source: z.string().optional(),
50
+ subscriptionId: z.string().optional(),
51
+ subscriptionName: z.string().optional(),
52
+ });
53
+
54
+ /** A single `inventory` row from an AZQR JSON report (used for enrichment). */
55
+ const azqrInventoryRowSchema = z.object({
56
+ location: z.string().optional(),
57
+ resourceId: z.string(),
58
+ resourceName: z.string().optional(),
59
+ resourceType: z.string().optional(),
60
+ skuName: z.string().optional(),
61
+ skuTier: z.string().optional(),
62
+ subscriptionId: z.string().optional(),
63
+ });
64
+
65
+ /**
66
+ * Lenient top-level schema. AZQR reports carry many sections we do not use
67
+ * (`advisor`, `defender`, `recommendations`, …); unknown keys are stripped and
68
+ * missing arrays default to empty so a partial/older report still parses.
69
+ */
70
+ const azqrReportSchema = z.object({
71
+ impacted: z.array(azqrImpactedRowSchema).default([]),
72
+ inventory: z.array(azqrInventoryRowSchema).default([]),
73
+ });
74
+
75
+ export type AzqrImpactedRow = z.infer<typeof azqrImpactedRowSchema>;
76
+ export type AzqrInventoryRow = z.infer<typeof azqrInventoryRowSchema>;
77
+ export type AzqrReport = z.infer<typeof azqrReportSchema>;
78
+
79
+ /**
80
+ * Azure resource types whose orphaned/unassociated instances actually incur
81
+ * cost. AZQR's `AOR` (Azure Orphan Resources) check mixes these billable
82
+ * resources with free config-hygiene ones (NSGs, subnets, orphan API
83
+ * connections, private endpoints, …): the former are classified as `cost`
84
+ * opportunities, the latter as `cleanup` candidates.
85
+ */
86
+ const BILLABLE_ORPHAN_RESOURCE_TYPES: ReadonlySet<string> = new Set([
87
+ "microsoft.compute/disks",
88
+ "microsoft.compute/snapshots",
89
+ "microsoft.network/applicationgateways",
90
+ "microsoft.network/ddosprotectionplans",
91
+ "microsoft.network/frontdoorwebapplicationfirewallpolicies",
92
+ "microsoft.network/loadbalancers",
93
+ "microsoft.network/natgateways",
94
+ "microsoft.network/publicipaddresses",
95
+ "microsoft.network/virtualnetworkgateways",
96
+ "microsoft.sql/servers/elasticpools",
97
+ "microsoft.web/serverfarms",
98
+ ]);
99
+
100
+ /**
101
+ * AZQR's check source for orphaned resources (the Azure Orphan Resources
102
+ * project). Every `impacted` row tagged with it is a provisioned-but-unused
103
+ * resource, so it is a reliable, text-independent orphan marker.
104
+ */
105
+ const ORPHAN_CHECK_SOURCE = "aor";
106
+
107
+ /** AZQR masks subscription GUID segments with runs of `x`. */
108
+ const MASK_MARKER = "xxxxxxxx";
109
+
110
+ /** How a promoted AZQR row is classified for reporting. */
111
+ export type AzqrOpportunityKind = "cleanup" | "cost";
112
+
113
+ const COST_REMEDIATION =
114
+ "Review the resource and remove or right-size it if it is no longer needed to stop incurring cost.";
115
+
116
+ const CLEANUP_REMEDIATION =
117
+ "Orphaned resource with no direct cost. Verify it is unused, then remove it to reduce clutter and management overhead.";
118
+
119
+ /**
120
+ * Converts the promoted `impacted` rows of an AZQR report into findings.
121
+ * AZQR carries no monetary estimate, so `estimatedMonthlySavings` is left
122
+ * unset. Billable rows render as `cost` opportunities (keeping AZQR's impact as
123
+ * severity); orphaned free resources render as low-severity
124
+ * `operationalExcellence` cleanup candidates. All carry an `[azqr]` badge.
125
+ */
126
+ export function azqrImpactedToFindings(report: AzqrReport): Finding[] {
127
+ const inventoryById = new Map(
128
+ report.inventory.map((row) => [row.resourceId.toLowerCase(), row]),
129
+ );
130
+ const findings: Finding[] = [];
131
+ for (const row of report.impacted) {
132
+ const kind = classifyAzqrRow(row);
133
+ if (kind === null) continue;
134
+ const inventory = inventoryById.get(row.resourceId.toLowerCase());
135
+ const cleanup = kind === "cleanup";
136
+ const remediation = cleanup ? CLEANUP_REMEDIATION : COST_REMEDIATION;
137
+ findings.push({
138
+ category: cleanup ? "operationalExcellence" : "cost",
139
+ code: row.recommendationId
140
+ ? `azqr.${row.recommendationId}`
141
+ : "azqr.impacted",
142
+ reason: buildReason(row, inventory),
143
+ recommendedAction: row.learn
144
+ ? `${remediation} Learn more: ${row.learn}`
145
+ : remediation,
146
+ resourceId: row.resourceId,
147
+ severity: cleanup ? "low" : mapAzqrImpact(row.impact),
148
+ source: "azqr",
149
+ });
150
+ }
151
+ return findings;
152
+ }
153
+
154
+ /**
155
+ * Classifies an `impacted` row for FinOps reporting, or returns `null` to drop
156
+ * it as noise.
157
+ *
158
+ * - `"cost"` — AZQR categorises the row as a cost item, or it is an orphaned
159
+ * resource of a billable type (real savings potential).
160
+ * - `"cleanup"` — an orphaned resource of a *free* type (empty subnets,
161
+ * unattached NSGs, orphan API connections, …): no direct cost, but a cleanup
162
+ * candidate worth investigating.
163
+ * - `null` — everything else (security, reliability, high-availability and
164
+ * other best-practice rows) is treated as noise and dropped.
165
+ *
166
+ * Orphans are identified by AZQR's `AOR` check source, not by matching the
167
+ * recommendation text.
168
+ */
169
+ export function classifyAzqrRow(
170
+ row: AzqrImpactedRow,
171
+ ): AzqrOpportunityKind | null {
172
+ if ((row.category ?? "").toLowerCase().includes("cost")) {
173
+ return "cost";
174
+ }
175
+ if ((row.source ?? "").toLowerCase() !== ORPHAN_CHECK_SOURCE) {
176
+ return null;
177
+ }
178
+ const resourceType = (row.resourceType ?? "").toLowerCase();
179
+ return BILLABLE_ORPHAN_RESOURCE_TYPES.has(resourceType) ? "cost" : "cleanup";
180
+ }
181
+
182
+ /**
183
+ * Detects whether the report still carries AZQR's default subscription-ID
184
+ * masking. Masked resource IDs cannot be matched against a live scan, so the
185
+ * caller should advise re-running with `azqr scan --mask=false`.
186
+ */
187
+ export function isAzqrReportMasked(report: AzqrReport): boolean {
188
+ return report.impacted.some(
189
+ (row) =>
190
+ row.resourceId.includes(MASK_MARKER) ||
191
+ (row.subscriptionId?.includes(MASK_MARKER) ?? false),
192
+ );
193
+ }
194
+
195
+ /**
196
+ * Reads and parses an AZQR JSON report from disk.
197
+ *
198
+ * @throws Error when the file cannot be read or is not valid AZQR JSON; the
199
+ * underlying failure is preserved as `cause`.
200
+ */
201
+ export async function loadAzqrReport(filePath: string): Promise<AzqrReport> {
202
+ let content: string;
203
+ try {
204
+ content = await readFile(filePath, "utf8");
205
+ } catch (error) {
206
+ throw new Error(`Cannot read AZQR report at "${filePath}"`, {
207
+ cause: error,
208
+ });
209
+ }
210
+
211
+ let json: unknown;
212
+ try {
213
+ json = JSON.parse(content);
214
+ } catch (error) {
215
+ throw new Error(`AZQR report at "${filePath}" is not valid JSON`, {
216
+ cause: error,
217
+ });
218
+ }
219
+
220
+ return parseAzqrReport(json);
221
+ }
222
+
223
+ /**
224
+ * Validates and parses an unknown value as an AZQR report.
225
+ *
226
+ * @throws Error (with the zod issue as `cause`) when the shape is invalid.
227
+ */
228
+ export function parseAzqrReport(raw: unknown): AzqrReport {
229
+ const result = azqrReportSchema.safeParse(raw);
230
+ if (!result.success) {
231
+ throw new Error(`Invalid AZQR report: ${result.error.message}`, {
232
+ cause: result.error,
233
+ });
234
+ }
235
+ return result.data;
236
+ }
237
+
238
+ /**
239
+ * Builds the finding reason from the AZQR recommendation, appending SKU / tier
240
+ * / location context from the matching `inventory` row when available.
241
+ */
242
+ function buildReason(
243
+ row: AzqrImpactedRow,
244
+ inventory: AzqrInventoryRow | undefined,
245
+ ): string {
246
+ const base = row.recommendation.trim();
247
+ const sentence = base.endsWith(".") ? base : `${base}.`;
248
+ const context: string[] = [];
249
+ if (inventory?.skuName) context.push(inventory.skuName);
250
+ if (inventory?.skuTier && inventory.skuTier !== inventory.skuName) {
251
+ context.push(inventory.skuTier);
252
+ }
253
+ if (inventory?.location) context.push(inventory.location);
254
+ return context.length > 0 ? `${sentence} (${context.join(", ")})` : sentence;
255
+ }
256
+
257
+ /**
258
+ * Maps AZQR/APRL `impact` (`High` | `Medium` | `Low`) onto the SaveMoney
259
+ * `CostRisk` scale, defaulting to `low` for unknown values.
260
+ */
261
+ function mapAzqrImpact(impact: string | undefined): CostRisk {
262
+ switch (impact?.toLowerCase()) {
263
+ case "high":
264
+ return "high";
265
+ case "medium":
266
+ return "medium";
267
+ default:
268
+ return "low";
269
+ }
270
+ }
@@ -42,6 +42,7 @@ export async function loadAzureConfig(
42
42
  const rawYaml = yaml.load(raw);
43
43
  const parsed = ConfigSchema.parse(rawYaml);
44
44
  return {
45
+ azqrReportPath: parsed.azure.azqrReportPath,
45
46
  concurrency: parsed.azure.concurrency,
46
47
  preferredLocation: parsed.azure.preferredLocation,
47
48
  sources: parsed.azure.sources,
@@ -71,11 +72,7 @@ export async function loadAzureConfig(
71
72
  ? process.env.ARM_SUBSCRIPTION_ID.split(",")
72
73
  : (await prompt("Enter Subscription IDs (comma-separated): ")).split(",");
73
74
 
74
- return {
75
- preferredLocation: "italynorth",
76
- subscriptionIds,
77
- timespanDays: 30,
78
- };
75
+ return ConfigSchema.parse({ azure: { subscriptionIds } }).azure;
79
76
  }
80
77
 
81
78
  /**
@@ -66,8 +66,7 @@ export async function analyzePublicIp(
66
66
  // Capture details outside the try so the pricing enrichment below can
67
67
  // reuse them without an extra API round-trip.
68
68
  let publicIpDetails:
69
- | Awaited<ReturnType<typeof networkClient.publicIPAddresses.get>>
70
- | undefined;
69
+ Awaited<ReturnType<typeof networkClient.publicIPAddresses.get>> | undefined;
71
70
 
72
71
  try {
73
72
  // Get detailed Public IP information
@@ -5,6 +5,7 @@
5
5
  import type * as armResources from "@azure/arm-resources";
6
6
 
7
7
  import type { Finding } from "../finding.js";
8
+ import type { Config } from "../schema.js";
8
9
  import type {
9
10
  AnalysisResult,
10
11
  BaseConfig,
@@ -16,6 +17,14 @@ import type {
16
17
  * Azure configuration extending base config
17
18
  */
18
19
  export type AzureConfig = BaseConfig & {
20
+ /**
21
+ * Optional path to an AZQR (`azqr scan --json`) report. When set, the
22
+ * orchestrator ingests its `impacted` resources, filters them down to
23
+ * FinOps-relevant opportunities and merges them into the run output as
24
+ * findings with `source: "azqr"`. Can be set via YAML (`azure.azqrReportPath`)
25
+ * or the CLI `--azqr-report` flag, which takes precedence.
26
+ */
27
+ azqrReportPath?: string;
19
28
  /**
20
29
  * Maximum number of resources analyzed in parallel within a single
21
30
  * subscription. Defaults to 8 when not provided. Set to 1 for a fully
@@ -38,9 +47,10 @@ export type AzureConfig = BaseConfig & {
38
47
  * - `"custom"` → enables the per-resource analyzer plugins
39
48
  * - `"advisor"` → enables the Azure Advisor subscription-level analyzer
40
49
  *
41
- * Defaults to `["advisor", "custom"]` when omitted (i.e. all sources).
50
+ * Config loading applies the `["advisor", "custom"]` default, so this list
51
+ * is always defined and contains at least one source.
42
52
  */
43
- sources?: AzureSource[];
53
+ sources: Config["azure"]["sources"];
44
54
  subscriptionIds: string[];
45
55
  /**
46
56
  * Analysis thresholds. Defaults from DEFAULT_THRESHOLDS are used when not provided.
@@ -88,7 +98,7 @@ export type AzureResourceReport = {
88
98
  * Narrowed from `FindingSource` to exclude "aws", which is not a valid
89
99
  * filter for Azure runs and would silently produce an empty report.
90
100
  */
91
- export type AzureSource = "advisor" | "custom";
101
+ export type AzureSource = Config["azure"]["sources"][number];
92
102
 
93
103
  export type PricingConfig = {
94
104
  /**
package/src/finding.ts CHANGED
@@ -67,20 +67,17 @@ export type Finding = {
67
67
  * model is open to future Advisor categories.
68
68
  */
69
69
  export type FindingCategory =
70
- | "cost"
71
- | "operationalExcellence"
72
- | "performance"
73
- | "reliability"
74
- | "security";
70
+ "cost" | "operationalExcellence" | "performance" | "reliability" | "security";
75
71
 
76
72
  /**
77
73
  * Where the finding originated from.
78
74
  *
79
75
  * - `custom` → emitted by a savemoney analyzer plugin
80
76
  * - `advisor` → fetched from Azure Advisor recommendations
77
+ * - `azqr` → ingested from an AZQR (`azqr scan --json`) report
81
78
  * - `aws` → reserved for future AWS Trusted Advisor / Compute Optimizer
82
79
  */
83
- export type FindingSource = "advisor" | "aws" | "custom";
80
+ export type FindingSource = "advisor" | "aws" | "azqr" | "custom";
84
81
 
85
82
  /**
86
83
  * Monetary value associated with a finding, when known.
package/src/index.ts CHANGED
@@ -37,6 +37,7 @@ export {
37
37
  type Money,
38
38
  type ResourceReport,
39
39
  } from "./finding.js";
40
+ export { AZURE_SOURCE_VALUES } from "./schema.js";
40
41
 
41
42
  export * from "./types.js";
42
43
 
package/src/schema.ts CHANGED
@@ -103,8 +103,18 @@ export const ThresholdsSchema = z
103
103
 
104
104
  // ── top-level config schema ──────────────────────────────────────────────────
105
105
 
106
+ export const AZURE_SOURCE_VALUES = ["advisor", "custom"] as const;
107
+
108
+ const AzureSourceSchema = z.enum(AZURE_SOURCE_VALUES);
109
+
106
110
  const AzureSectionSchema = z
107
111
  .object({
112
+ /**
113
+ * Optional path to an AZQR (`azqr scan --json`) report. When set, its
114
+ * FinOps-relevant impacted resources are merged into the analysis. The
115
+ * `--azqr-report` CLI flag, when provided, overrides this value.
116
+ */
117
+ azqrReportPath: z.string().optional(),
108
118
  /**
109
119
  * Maximum number of resources analyzed in parallel within a single
110
120
  * subscription. Defaults to 8 when not provided.
@@ -117,9 +127,9 @@ const AzureSectionSchema = z
117
127
  * Azure Advisor recommendations, or `["custom"]` to skip Advisor.
118
128
  */
119
129
  sources: z
120
- .array(z.enum(["advisor", "custom"]))
121
- .nonempty()
122
- .default(["advisor", "custom"]),
130
+ .tuple([AzureSourceSchema])
131
+ .rest(AzureSourceSchema)
132
+ .default([...AZURE_SOURCE_VALUES]),
123
133
  subscriptionIds: z
124
134
  .array(z.string())
125
135
  .min(