@aaa-sentinel/iac-cost 0.6.1 → 0.8.0

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 (3) hide show
  1. package/README.md +42 -4
  2. package/dist/cli.js +374 -39
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -7,7 +7,13 @@ internet is caught in review instead of after the deploy. With `iac-cost fix`, t
7
7
  your last scan on resources this Terraform manages come back to you as **pull requests**, not as
8
8
  console changes (see [Fixes as pull requests](#fixes-as-pull-requests)).
9
9
 
10
- > **Changed in 0.6.1:** `fix` says when the security add-on is not active on the account, names the
10
+ > **New in 0.8.0:** `--fail-on-budget` fails the pull request when the change takes an AAA Sentinel budget over (see [Budget gate](#budget-gate)).
11
+ >
12
+ > **In 0.7.0:** the plan check flags RDS and Aurora instances with `auto_minor_version_upgrade = false`
13
+ > (CIS AWS 2.3.2; RDS Custom is skipped), and `iac-cost fix` turns it back on. Security findings have a
14
+ > seventh category, `security_patching`.
15
+
16
+ > **Changed in 0.6.1:** `fix` says when the risk and compliance add-on is not active on the account, names the
11
17
  > fixes whose pull or merge request was closed without merging (they are not reopened), and says
12
18
  > "merge request" on GitLab. The fix jobs below no longer end in `|| true` or `continue-on-error`, so a
13
19
  > setup error (exit code 2) fails the job instead of passing unseen. Rejected OAuth app credentials
@@ -56,7 +62,7 @@ console changes (see [Fixes as pull requests](#fixes-as-pull-requests)).
56
62
  estimate needs a **Pro** or **Business** plan.
57
63
  - For the optional **drift check**, a second application with `security:read` and the security
58
64
  add-on on the account (see [Drift](#drift-plan-vs-cloud)).
59
- - For **`iac-cost fix`**, an application with the `security:fix` scope, the security add-on on the
65
+ - For **`iac-cost fix`**, an application with the `security:fix` scope, the risk and compliance add-on on the
60
66
  account, and a CI token that can push a branch and open a pull request (see
61
67
  [Fixes as pull requests](#fixes-as-pull-requests)).
62
68
  - On **GitLab**, a project access token of your own for the note or the merge request: the job
@@ -79,6 +85,7 @@ npx @aaa-sentinel/iac-cost plan.json # or: … | npx @aaa-sentinel/iac-
79
85
  | `IAC_SECURITY_FAIL_ON` | no | Same as `--fail-on` |
80
86
  | `IAC_SECURITY_ACCOUNT_ID` | no | Same as `--drift-account` |
81
87
  | `IAC_SECURITY_CLIENT_ID` / `IAC_SECURITY_CLIENT_SECRET` | for drift | An OAuth2 application with the `security:read` scope |
88
+ | `IAC_FAIL_ON_BUDGET` | no | Same as `--fail-on-budget`: `true` or `strict` turns the gate on, empty or `none` leaves it off |
82
89
 
83
90
  The Markdown comment goes to **stdout**; warnings go to **stderr**. If there is nothing to
84
91
  say, stdout is empty.
@@ -87,11 +94,13 @@ say, stdout is empty.
87
94
  | --- | --- |
88
95
  | `--format markdown` | The pull request comment (default) |
89
96
  | `--format text` | Plain lines for a terminal or a CI log |
90
- | `--format json` | `{ formatVersion, cost, security, warnings }`, with the full evidence of each finding. It is evidence for you, not for a pull request: it keeps the Terraform addresses as written (for_each keys included) and the evidence as the rules see it — ARNs, subscription ids, emails or internal CIDRs of resources that already exist. Do not post it as a comment |
97
+ | `--format json` | `{ formatVersion, cost, security, warnings }` (plus `budgets` with `--fail-on-budget`), with the full evidence of each finding. It is evidence for you, not for a pull request: it keeps the Terraform addresses as written (for_each keys included) and the evidence as the rules see it — ARNs, subscription ids, emails or internal CIDRs of resources that already exist. Do not post it as a comment |
91
98
  | `--fail-on <critical\|high\|medium\|low>` | Exit 1 when a security finding or toxic combination is at that severity or worse. Also `IAC_SECURITY_FAIL_ON` |
92
99
  | `--no-security` | Cost only, exactly as in 0.1 |
93
100
  | `--no-cost` | Security only and no credentials needed. Nothing leaves your machine unless you also pass `--drift-account` explicitly: with `--no-cost`, `IAC_SECURITY_ACCOUNT_ID` in the environment is ignored |
94
101
  | `--drift-account <accountId>` | Compare with the last scan of that account (see [Drift](#drift-plan-vs-cloud)). Also `IAC_SECURITY_ACCOUNT_ID`, except with `--no-cost`. It puts what the scan found in your cloud into the PR comment: **never on a public repository** |
102
+ | `--fail-on-budget[=strict]` | Exit 1 when the change takes an AAA Sentinel budget over (see [Budget gate](#budget-gate)). Also `IAC_FAIL_ON_BUDGET` |
103
+ | `--budget-account <accountId>` | Account whose budgets also apply to the gate. Defaults to `--drift-account` |
95
104
 
96
105
  ### It never fails your build — unless you ask for a gate
97
106
 
@@ -112,6 +121,35 @@ Any other unknown or malformed argument only prints a warning, with or without a
112
121
  Only the plan decides the code. The cost estimate and the drift check go over the network, and
113
122
  neither can change it. A check that **could not be decided** (see below) never blocks.
114
123
 
124
+ ## Budget gate
125
+
126
+ With `--fail-on-budget` the CLI sends the estimated monthly change (`totalMonthlyDeltaUsd`, one
127
+ number) to AAA Sentinel, which compares it with your budgets: for each budget that applies, this
128
+ month's spend so far scaled to the whole month, plus the change. The budgets that apply are the
129
+ organization ones, and those of the account in `--budget-account` (or `--drift-account`).
130
+
131
+ **Limitation of this version: budgets scoped to one billing service are not checked.** A
132
+ Terraform plan names resource types, not the billing services they are charged under, so the CLI
133
+ cannot tell which service a change belongs to and does not guess. Those budgets still alert from
134
+ AAA Sentinel; only the pull request gate skips them.
135
+ Budgets are part of every plan; the API used by the gate is part of the Pro and Business plans.
136
+
137
+ The OAuth2 application in `IAC_COST_CLIENT_ID` needs the `budgets:read` scope as well as
138
+ `iac:estimate`.
139
+
140
+ | Code | When |
141
+ | --- | --- |
142
+ | `0` | Every budget that applies stays within its amount |
143
+ | `1` | The change takes at least one budget over. With `=strict`, also a budget without a forecast yet (no data this month, only an estimate, or the first days of the month), no budget that applies, or an estimate without a total |
144
+ | `2` | The gate could not decide: no cost credentials, the estimate failed, the check did not answer, or the plan is not readable |
145
+
146
+ The comment gets a **Budgets** section with each budget, the month at the current pace, the
147
+ change and the projected total, in the budget's currency (`≈` when converted from USD).
148
+
149
+ ```bash
150
+ npx --yes @aaa-sentinel/iac-cost plan.json --fail-on-budget --budget-account acc_9f2c1e
151
+ ```
152
+
115
153
  ## What actually leaves your machine
116
154
 
117
155
  Not the plan. `terraform show -json` output carries CIDRs, account identifiers and, often,
@@ -299,7 +337,7 @@ or an RDS instance is only matched when the region of the plan resource is known
299
337
  their names are unique only within a region.
300
338
 
301
339
  It needs a **separate** OAuth2 application with the `security:read` scope, in
302
- `IAC_SECURITY_CLIENT_ID` / `IAC_SECURITY_CLIENT_SECRET`, and the security add-on on that account.
340
+ `IAC_SECURITY_CLIENT_ID` / `IAC_SECURITY_CLIENT_SECRET`, and the risk and compliance add-on on that account.
303
341
  Keep `iac:estimate` and `security:read` in two applications: the first one is safe in a CI that
304
342
  third parties can trigger, the second one reads your findings.
305
343
 
package/dist/cli.js CHANGED
@@ -28,6 +28,13 @@ Options:
28
28
  --no-cost Skip the cost estimate
29
29
  --drift-account <accountId> Compare with the last scan of this AAA Sentinel
30
30
  account (needs IAC_SECURITY_CLIENT_ID/SECRET)
31
+ --fail-on-budget[=strict] Exit 1 when the change takes an AAA Sentinel budget over
32
+ (organization budgets, and the account ones with
33
+ --budget-account). With =strict a budget without a
34
+ forecast, or no budget at all, also fails. Needs the
35
+ budgets:read scope on IAC_COST_CLIENT_ID. Service
36
+ budgets are not checked in this version
37
+ --budget-account <accountId> Account whose budgets also apply (default: --drift-account)
31
38
  -h, --help Show this help`;
32
39
  function parseCliArgs(argv, env) {
33
40
  const warnings = [];
@@ -42,13 +49,17 @@ function parseCliArgs(argv, env) {
42
49
  "no-security": { type: "boolean" },
43
50
  "no-cost": { type: "boolean" },
44
51
  "drift-account": { type: "string" },
52
+ // Booleana para que no se trague el siguiente argumento; sin `strict`, `--fail-on-budget=strict` llega como texto.
53
+ "fail-on-budget": { type: "boolean" },
54
+ "budget-account": { type: "string" },
45
55
  help: { type: "boolean", short: "h" }
46
56
  }
47
57
  });
48
- const known = /* @__PURE__ */ new Set(["format", "fail-on", "no-security", "no-cost", "drift-account", "help", "h"]);
58
+ const known = /* @__PURE__ */ new Set(["format", "fail-on", "no-security", "no-cost", "drift-account", "fail-on-budget", "budget-account", "help", "h"]);
49
59
  for (const name of Object.keys(values)) {
50
60
  if (known.has(name)) continue;
51
61
  if (/^fail[-_]?on$/i.test(name)) return { error: `unknown option --${name}: the gate is spelled --fail-on` };
62
+ if (/^fail[-_]?on[-_]?budgets?$/i.test(name)) return { error: `unknown option --${name}: the gate is spelled --fail-on-budget` };
52
63
  warnings.push(`unknown option --${name} ignored`);
53
64
  }
54
65
  if (positionals.length > 1) warnings.push(`only one plan file is read, ignoring ${positionals.slice(1).join(" ")}`);
@@ -76,6 +87,16 @@ function parseCliArgs(argv, env) {
76
87
  const driftAccount = typeof driftRaw === "string" && driftRaw.trim() !== "" ? driftRaw.trim() : null;
77
88
  if (values["drift-account"] === true) warnings.push("--drift-account needs an account id, skipping the comparison with the last scan");
78
89
  if (!security && failOn) warnings.push("--fail-on has no effect with --no-security: no security gate is applied");
90
+ const budgetGate = parseBudgetGate(values["fail-on-budget"], env["IAC_FAIL_ON_BUDGET"]);
91
+ if ("error" in budgetGate) return budgetGate;
92
+ const failOnBudget = budgetGate.mode;
93
+ if (failOnBudget && !cost) return { error: "--fail-on-budget needs the cost estimate: remove --no-cost" };
94
+ if (values["budget-account"] === true || typeof values["budget-account"] === "string" && values["budget-account"].startsWith("-")) {
95
+ return { error: "--budget-account needs an account id" };
96
+ }
97
+ const budgetRaw = typeof values["budget-account"] === "string" ? values["budget-account"].trim() : "";
98
+ const budgetAccount = budgetRaw !== "" ? budgetRaw : failOnBudget ? driftAccount : null;
99
+ if (budgetRaw !== "" && !failOnBudget) warnings.push("--budget-account has no effect without --fail-on-budget");
79
100
  return {
80
101
  planPath: positionals[0] ?? null,
81
102
  format,
@@ -83,10 +104,30 @@ function parseCliArgs(argv, env) {
83
104
  cost,
84
105
  security,
85
106
  driftAccount,
107
+ failOnBudget,
108
+ budgetAccount,
86
109
  help: values.help === true || values.h === true,
87
110
  warnings
88
111
  };
89
112
  }
113
+ var BUDGET_ON = /* @__PURE__ */ new Set(["1", "true", "on", "yes", "normal"]);
114
+ var BUDGET_OFF = /* @__PURE__ */ new Set(["none", "off", "false", "0"]);
115
+ function parseBudgetGate(flag, envValue) {
116
+ if (flag !== void 0) {
117
+ if (flag === true) return { mode: "normal" };
118
+ const text2 = String(flag).trim().toLowerCase();
119
+ if (text2 === "") return { error: "--fail-on-budget= needs a value: strict, or no value for the normal gate" };
120
+ if (text2 === "strict") return { mode: "strict" };
121
+ if (BUDGET_ON.has(text2)) return { mode: "normal" };
122
+ if (BUDGET_OFF.has(text2)) return { mode: null };
123
+ return { error: `--fail-on-budget takes no value or =strict (got "${String(flag)}"); put the plan file before the option` };
124
+ }
125
+ const text = (envValue ?? "").trim().toLowerCase();
126
+ if (text === "" || BUDGET_OFF.has(text)) return { mode: null };
127
+ if (text === "strict") return { mode: "strict" };
128
+ if (BUDGET_ON.has(text)) return { mode: "normal" };
129
+ return { error: `IAC_FAIL_ON_BUDGET must be strict, true or none (got "${envValue}")` };
130
+ }
90
131
 
91
132
  // src/comment.ts
92
133
  import { parseArgs as parseArgs2 } from "node:util";
@@ -8170,6 +8211,7 @@ function rdsInstances(index) {
8170
8211
  const builder = new ObservationBuilder(index, db, "rds_instance", "aws").cloudId("identifier");
8171
8212
  builder.from("engine", index.get(db, "engine"), String, null);
8172
8213
  builder.from("publiclyAccessible", index.get(db, "publicly_accessible"), Boolean, false);
8214
+ builder.from("autoMinorVersionUpgrade", index.get(db, "auto_minor_version_upgrade"), Boolean, true);
8173
8215
  if (db.type === "aws_rds_cluster_instance") {
8174
8216
  const cluster = index.parentOf(db, "cluster_identifier", ["aws_rds_cluster"], "cluster_identifier");
8175
8217
  const clusterId = index.get(db, "cluster_identifier");
@@ -8657,6 +8699,7 @@ var RULE_TITLES = {
8657
8699
  SEC_AWS_IAM_POLITICA_CONTRASENAS: "Weak or missing IAM password policy",
8658
8700
  SEC_AWS_ENCRYPTION_KMS_SIN_ROTACION: "KMS key without rotation",
8659
8701
  SEC_AWS_ENCRYPTION_RDS_SIN_CIFRAR: "Unencrypted RDS",
8702
+ SEC_AWS_PATCHING_RDS_SIN_ACTUALIZACION_MENOR: "RDS without automatic minor version upgrade",
8660
8703
  SEC_AWS_LOGGING_TRAIL_PARADO: "CloudTrail stopped",
8661
8704
  SEC_AWS_LOGGING_TRAIL_GESTION_INCOMPLETA: "CloudTrail skips some management events",
8662
8705
  SEC_AWS_LOGGING_VPC_SIN_FLOW_LOGS: "VPC without flow logs",
@@ -9004,6 +9047,14 @@ function kmsRotation(ctx, builder) {
9004
9047
  throw new FixedInCode(where.file, "enable_key_rotation");
9005
9048
  }
9006
9049
  }
9050
+ function rdsAutoMinor(ctx, builder) {
9051
+ const where = located(ctx, ctx.anchor);
9052
+ const items = body(where.text, where.block);
9053
+ if (setLiteral(builder, where, items, "auto_minor_version_upgrade", "true", (l) => l?.kind === "bool" && l.value) === "already") {
9054
+ throw new FixedInCode(where.file, "auto_minor_version_upgrade");
9055
+ }
9056
+ builder.changes.push("note: RDS may apply a pending minor version upgrade in the next maintenance window, which restarts the instance");
9057
+ }
9007
9058
  function lambdaUrl(ctx, builder) {
9008
9059
  const { index, anchor: anchor2 } = ctx;
9009
9060
  const urls = index.ofType("aws_lambda_function_url").filter((url) => index.parentOf(url, "function_name", ["aws_lambda_function"], "function_name", lambdaName) === anchor2).filter((url) => {
@@ -9058,6 +9109,7 @@ var FIXERS = {
9058
9109
  SEC_AWS_NETWORK_ADMIN_ABIERTO: { types: ["aws_security_group", "aws_default_security_group"], fix: awsAdminOpen },
9059
9110
  SEC_AWS_EXPOSURE_S3_PUBLICO: { types: ["aws_s3_bucket"], fix: s3PublicAccess },
9060
9111
  SEC_AWS_ENCRYPTION_KMS_SIN_ROTACION: { types: ["aws_kms_key"], fix: kmsRotation },
9112
+ SEC_AWS_PATCHING_RDS_SIN_ACTUALIZACION_MENOR: { types: ["aws_db_instance", "aws_rds_cluster_instance"], fix: rdsAutoMinor },
9061
9113
  SEC_AWS_EXPOSURE_LAMBDA_PUBLICA: { types: ["aws_lambda_function"], fix: lambdaUrl },
9062
9114
  SEC_AZURE_EXPOSURE_BLOB_PUBLICO: { types: ["azurerm_storage_account"], fix: azureBlobPublic },
9063
9115
  SEC_AZURE_ENCRYPTION_STORAGE_TLS: { types: ["azurerm_storage_account"], fix: azureStorageTls },
@@ -9177,10 +9229,10 @@ function loadFailure(error2, accountId) {
9177
9229
  return { message: `${detail} (${tag})`, setup: true };
9178
9230
  }
9179
9231
  if (code2 === "SECURITY_ADDON_INACTIVE") {
9180
- return { message: `the security add-on is not active on account ${accountId} (402 SECURITY_ADDON_INACTIVE): activate it in AAA Sentinel to get fixes; nothing to fix`, setup: false };
9232
+ return { message: `the risk and compliance add-on is not active on account ${accountId} (402 SECURITY_ADDON_INACTIVE): activate it in AAA Sentinel to get fixes; nothing to fix`, setup: false };
9181
9233
  }
9182
9234
  if (code2 === "PLAN_SECURITY_ADDON") {
9183
- return { message: `the plan of this organization does not include the security add-on (402 PLAN_SECURITY_ADDON): fixes need the Pro or Business plan with the add-on; nothing to fix`, setup: false };
9235
+ return { message: `the plan of this organization does not include the risk and compliance add-on (402 PLAN_SECURITY_ADDON): fixes need the Pro or Business plan with the add-on; nothing to fix`, setup: false };
9184
9236
  }
9185
9237
  return { message: `could not read the open findings, nothing to fix: ${error2.message}`, setup: false };
9186
9238
  }
@@ -9669,7 +9721,7 @@ ${POSTURE_USAGE}`);
9669
9721
  return { stdout: null, warnings: [...warnings, `could not read the posture history, skipping: ${mensaje}`], exitCode: 0 };
9670
9722
  }
9671
9723
  if (history.access !== "full") {
9672
- return { stdout: null, warnings: [...warnings, "the account does not have the security add-on: no posture history to show"], exitCode: 0 };
9724
+ return { stdout: null, warnings: [...warnings, "the account does not have the risk and compliance add-on: no posture history to show"], exitCode: 0 };
9673
9725
  }
9674
9726
  const nuevos = gate ? newAtOrAbove(history.summary, gate) : 0;
9675
9727
  const stdout = format === "json" ? JSON.stringify(history, null, 2) : renderPosture(history, format);
@@ -9811,18 +9863,103 @@ function parseTerraformPlan(plan) {
9811
9863
  };
9812
9864
  }
9813
9865
 
9814
- // src/security/drift.ts
9815
- var SCOPE2 = "security:read";
9866
+ // src/budget.ts
9867
+ var SCOPE2 = "budgets:read";
9816
9868
  var REQUEST_TIMEOUT_MS2 = 35e3;
9869
+ var RETRYABLE_STATUS2 = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
9870
+ async function checkBudgets(config2, input) {
9871
+ const fetchImpl = config2.fetchImpl ?? fetch;
9872
+ const sleepImpl = config2.sleepImpl ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
9873
+ const token = await fetchToken(config2, SCOPE2);
9874
+ for (let attempt = 0; attempt < 2; attempt++) {
9875
+ const response = await fetchImpl(`${config2.baseUrl}/v1/budgets/check`, {
9876
+ method: "POST",
9877
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
9878
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2),
9879
+ body: JSON.stringify({ monthlyDeltaUsd: input.monthlyDeltaUsd, ...input.accountId ? { accountId: input.accountId } : {} })
9880
+ });
9881
+ if (response.ok) {
9882
+ const body2 = await response.json();
9883
+ if (!Array.isArray(body2.results)) throw new Error("iac_cost_budget_check_malformed");
9884
+ return { results: body2.results, approximate: body2.approximate === true };
9885
+ }
9886
+ if (RETRYABLE_STATUS2.has(response.status) && attempt === 0) {
9887
+ await sleepImpl(1e3);
9888
+ continue;
9889
+ }
9890
+ const code2 = await apiErrorCode(response);
9891
+ throw new Error(`iac_cost_budget_check_http_${response.status}${code2 ? ` ${code2}` : ""}`);
9892
+ }
9893
+ throw new Error("iac_cost_budget_check_exhausted_retries");
9894
+ }
9895
+ function evaluateBudgetGate(response, mode) {
9896
+ const over = response.results.filter((r) => r.status === "over").length;
9897
+ const unresolved = response.results.filter((r) => r.status === "unresolved").length + (response.results.length === 0 ? 1 : 0);
9898
+ return { over, unresolved, blocks: over > 0 || mode === "strict" && unresolved > 0 };
9899
+ }
9900
+ function money(n, currency) {
9901
+ try {
9902
+ return new Intl.NumberFormat("en-US", { style: "currency", currency }).format(n);
9903
+ } catch {
9904
+ return `${n.toFixed(2)} ${currency}`;
9905
+ }
9906
+ }
9907
+ var signed = (n, currency) => `${n < 0 ? "-" : "+"}${money(Math.abs(n), currency)}`;
9908
+ function scopeText(scope) {
9909
+ if (scope.kind === "org") return "organization";
9910
+ if (scope.kind === "account") return `account ${scope.accountId}`;
9911
+ return scope.accountId ? `${scope.service} in ${scope.accountId}` : scope.service;
9912
+ }
9913
+ var STATUS_TEXT = {
9914
+ ok: "\u2705 within budget",
9915
+ over: "\u274C over budget",
9916
+ unresolved: "\u26A0\uFE0F no forecast yet"
9917
+ };
9918
+ var cell = (s) => s.replace(/[|\r\n]+/g, " ").replace(/\s+/g, " ").trim();
9919
+ function renderBudgetMarkdown(response, mode) {
9920
+ const lines2 = ["### \u{1F3AF} Budgets", ""];
9921
+ if (response.results.length === 0) {
9922
+ lines2.push(
9923
+ mode === "strict" ? "No budget applies to this change (organization budgets, or account budgets with `--budget-account`). Strict mode fails the check." : "No budget applies to this change (organization budgets, or account budgets with `--budget-account`)."
9924
+ );
9925
+ return lines2.join("\n");
9926
+ }
9927
+ const approx = response.approximate ? "\u2248 " : "";
9928
+ lines2.push("| Budget | Scope | Monthly budget | This month at current pace | This change | Projected | Status |", "|---|---|---:|---:|---:|---:|---|");
9929
+ for (const r of response.results) {
9930
+ lines2.push(
9931
+ `| ${cell(r.name)} | ${cell(scopeText(r.scope))} | ${money(r.amount, r.currency)} | ${r.forecast === null ? "\u2014" : approx + money(r.forecast, r.currency)} | ${approx}${signed(r.delta, r.currency)} | ${r.projected === null ? "\u2014" : approx + money(r.projected, r.currency)} | ${STATUS_TEXT[r.status]} |`
9932
+ );
9933
+ }
9934
+ lines2.push("");
9935
+ lines2.push("_The pace is this month\u2019s spend so far, scaled to the whole month. The change is the list-price estimate above._");
9936
+ if (response.approximate) lines2.push("_\u2248 converted from USD at today\u2019s rate._");
9937
+ if (mode === "normal" && response.results.some((r) => r.status === "unresolved")) {
9938
+ lines2.push("_A budget without a forecast does not fail the check; `--fail-on-budget=strict` makes it fail._");
9939
+ }
9940
+ return lines2.join("\n");
9941
+ }
9942
+ function renderBudgetText(response) {
9943
+ if (response.results.length === 0) return "Budgets\n No budget applies to this change.";
9944
+ const approx = response.approximate ? "~" : "";
9945
+ const rows = response.results.map(
9946
+ (r) => ` ${r.name} (${scopeText(r.scope)}): ${r.status}, budget ${money(r.amount, r.currency)}, projected ${r.projected === null ? "unknown" : approx + money(r.projected, r.currency)} (change ${approx}${signed(r.delta, r.currency)})`
9947
+ );
9948
+ return ["Budgets", ...rows].join("\n");
9949
+ }
9950
+
9951
+ // src/security/drift.ts
9952
+ var SCOPE3 = "security:read";
9953
+ var REQUEST_TIMEOUT_MS3 = 35e3;
9817
9954
  var CAUSE_OUTSIDE_PLAN = /* @__PURE__ */ new Set(["SEC_AWS_LOGGING_VPC_SIN_FLOW_LOGS", "SEC_AWS_LOGGING_FLOW_LOGS_INCOMPLETOS"]);
9818
9955
  var REGIONAL_NAMES = /* @__PURE__ */ new Set(["lambda_function", "rds_instance"]);
9819
9956
  async function fetchLiveFindings(config2) {
9820
9957
  const fetchImpl = config2.fetchImpl ?? fetch;
9821
- const token = await fetchToken(config2, SCOPE2);
9958
+ const token = await fetchToken(config2, SCOPE3);
9822
9959
  const url = `${config2.baseUrl}/v1/security/findings?accountId=${encodeURIComponent(config2.accountId)}`;
9823
9960
  const response = await fetchImpl(url, {
9824
9961
  headers: { authorization: `Bearer ${token}` },
9825
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
9962
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS3)
9826
9963
  });
9827
9964
  if (!response.ok) throw new Error(`security_findings_http_${response.status}`);
9828
9965
  const body2 = await response.json();
@@ -9932,6 +10069,23 @@ function costEvidence(input, signal, options) {
9932
10069
  ...options.amount ? { monthlySavingsUsd: signal.monthlySavingsUsd } : {}
9933
10070
  };
9934
10071
  }
10072
+ function withCostSignal(input, options) {
10073
+ const senales = new Map(costSignalsOf(input, options.costRule).map((s) => [options.signalKey(s), s]));
10074
+ if (senales.size === 0) return [];
10075
+ return input.findings.filter((f) => f.ruleId === options.rule).flatMap((f) => {
10076
+ const coste = senales.get(options.findingKey(f));
10077
+ if (!coste) return [];
10078
+ return [
10079
+ {
10080
+ region: f.region,
10081
+ resourceId: f.resourceId,
10082
+ resourceName: f.resourceName,
10083
+ findingIds: [f.id],
10084
+ evidence: costEvidence(input, coste, { amount: options.amount })
10085
+ }
10086
+ ];
10087
+ });
10088
+ }
9935
10089
  var indices = /* @__PURE__ */ new WeakMap();
9936
10090
  function observationOf(input, kind, region, id) {
9937
10091
  let indice = indices.get(input.observations);
@@ -9978,11 +10132,18 @@ function lambdaRef(resourceId, region) {
9978
10132
  }
9979
10133
  return `${region}::${resourceId}`;
9980
10134
  }
10135
+ var LAMBDA_SIN_USO = {
10136
+ costRule: "SERVERLESS_UNUSED_LAMBDA",
10137
+ findingKey: (f) => lambdaRef(f.resourceId, f.region),
10138
+ signalKey: (s) => lambdaRef(s.resourceId, s.region),
10139
+ amount: false
10140
+ };
9981
10141
  var AWS_SECURITY_COMBOS = [
9982
10142
  {
9983
10143
  // Cualquiera puede invocarla y lleva credenciales en su configuración: un fallo de la función las expone.
9984
10144
  id: "COMBO_AWS_PUBLIC_FUNCTION_SECRETS",
9985
10145
  provider: "aws",
10146
+ resourceKind: "lambda_function",
9986
10147
  severity: "critical",
9987
10148
  rules: ["SEC_AWS_EXPOSURE_LAMBDA_PUBLICA", "SEC_AWS_SECRETS_LAMBDA_ENV"],
9988
10149
  detect: (input) => sameResource(input, "SEC_AWS_EXPOSURE_LAMBDA_PUBLICA", "SEC_AWS_SECRETS_LAMBDA_ENV")
@@ -9991,23 +10152,83 @@ var AWS_SECURITY_COMBOS = [
9991
10152
  // Cualquiera puede invocarla y nadie la ha invocado en 30 días: superficie de ataque que no da servicio a nadie.
9992
10153
  id: "COMBO_AWS_PUBLIC_FUNCTION_UNUSED",
9993
10154
  provider: "aws",
10155
+ resourceKind: "lambda_function",
9994
10156
  severity: "high",
9995
10157
  rules: ["SEC_AWS_EXPOSURE_LAMBDA_PUBLICA"],
9996
10158
  costRules: ["SERVERLESS_UNUSED_LAMBDA"],
10159
+ detect: (input) => withCostSignal(input, { rule: "SEC_AWS_EXPOSURE_LAMBDA_PUBLICA", ...LAMBDA_SIN_USO })
10160
+ },
10161
+ {
10162
+ // Guarda credenciales en su configuración y nadie la invoca: se borra y se rotan las credenciales.
10163
+ id: "COMBO_AWS_UNUSED_FUNCTION_SECRETS",
10164
+ provider: "aws",
10165
+ resourceKind: "lambda_function",
10166
+ severity: "high",
10167
+ rules: ["SEC_AWS_SECRETS_LAMBDA_ENV"],
10168
+ costRules: ["SERVERLESS_UNUSED_LAMBDA"],
9997
10169
  detect: (input) => {
9998
- const sinUso = new Map(costSignalsOf(input, "SERVERLESS_UNUSED_LAMBDA").map((s) => [lambdaRef(s.resourceId, s.region), s]));
9999
- if (sinUso.size === 0) return [];
10000
- return input.findings.filter((f) => f.ruleId === "SEC_AWS_EXPOSURE_LAMBDA_PUBLICA").flatMap((f) => {
10001
- const coste = sinUso.get(lambdaRef(f.resourceId, f.region));
10002
- if (!coste) return [];
10003
- return [{ region: f.region, resourceId: f.resourceId, resourceName: f.resourceName, findingIds: [f.id], evidence: costEvidence(input, coste, { amount: false }) }];
10004
- });
10170
+ const publicas = findingsByResource(input.findings, "SEC_AWS_EXPOSURE_LAMBDA_PUBLICA");
10171
+ return withCostSignal(input, { rule: "SEC_AWS_SECRETS_LAMBDA_ENV", ...LAMBDA_SIN_USO }).filter(
10172
+ (m) => !publicas.has(`${m.region}::${m.resourceId}`)
10173
+ );
10005
10174
  }
10006
10175
  },
10176
+ {
10177
+ // Cualquiera puede copiarlo y su volumen de origen ya no existe; se sigue pagando cada mes.
10178
+ id: "COMBO_AWS_PUBLIC_SNAPSHOT_ORPHAN",
10179
+ provider: "aws",
10180
+ resourceKind: "ebs_snapshot",
10181
+ severity: "critical",
10182
+ rules: ["SEC_AWS_EXPOSURE_EBS_SNAPSHOT_PUBLICO"],
10183
+ costRules: ["STORAGE_ORPHAN_SNAPSHOT"],
10184
+ detect: (input) => withCostSignal(input, {
10185
+ rule: "SEC_AWS_EXPOSURE_EBS_SNAPSHOT_PUBLICO",
10186
+ costRule: "STORAGE_ORPHAN_SNAPSHOT",
10187
+ // Los dos módulos usan el id del snapshot (snap-…) y la región.
10188
+ findingKey: (f) => `${f.region}::${f.resourceId}`,
10189
+ signalKey: (s) => `${s.region}::${s.resourceId}`,
10190
+ amount: true
10191
+ })
10192
+ },
10193
+ {
10194
+ // Endpoint público y una semana sin conexiones: se paga por una puerta abierta que nadie usa.
10195
+ id: "COMBO_AWS_PUBLIC_DB_IDLE",
10196
+ provider: "aws",
10197
+ resourceKind: "rds_instance",
10198
+ severity: "high",
10199
+ rules: ["SEC_AWS_EXPOSURE_RDS_PUBLICA"],
10200
+ costRules: ["DATABASE_ZERO_CONN_RDS"],
10201
+ detect: (input) => withCostSignal(input, {
10202
+ rule: "SEC_AWS_EXPOSURE_RDS_PUBLICA",
10203
+ costRule: "DATABASE_ZERO_CONN_RDS",
10204
+ // Los dos módulos usan el DBInstanceIdentifier, único por región.
10205
+ findingKey: (f) => `${f.region}::${f.resourceId}`,
10206
+ signalKey: (s) => `${s.region}::${s.resourceId}`,
10207
+ amount: true
10208
+ })
10209
+ },
10210
+ {
10211
+ // Se paga el soporte extendido para recibir parches y no se aplican solos. Medium: no afirma ninguna vulnerabilidad.
10212
+ id: "COMBO_AWS_RDS_EXTENDED_NO_AUTO_MINOR",
10213
+ provider: "aws",
10214
+ resourceKind: "rds_instance",
10215
+ severity: "medium",
10216
+ rules: ["SEC_AWS_PATCHING_RDS_SIN_ACTUALIZACION_MENOR"],
10217
+ costRules: ["DATABASE_RDS_EXTENDED_SUPPORT"],
10218
+ detect: (input) => withCostSignal(input, {
10219
+ rule: "SEC_AWS_PATCHING_RDS_SIN_ACTUALIZACION_MENOR",
10220
+ costRule: "DATABASE_RDS_EXTENDED_SUPPORT",
10221
+ findingKey: (f) => `${f.region}::${f.resourceId}`,
10222
+ signalKey: (s) => `${s.region}::${s.resourceId}`,
10223
+ amount: true
10224
+ // El aviso de «entra en soporte extendido en ≤60 días» lleva importe 0: aún no se paga nada.
10225
+ }).filter((m) => typeof m.evidence["monthlySavingsUsd"] === "number" && m.evidence["monthlySavingsUsd"] > 0)
10226
+ },
10007
10227
  {
10008
10228
  // Dos defensas que faltan a la vez: endpoint público (PubliclyAccessible) y datos sin cifrar en disco. No prueba la ruta de red completa.
10009
10229
  id: "COMBO_AWS_PUBLIC_DB_UNENCRYPTED",
10010
10230
  provider: "aws",
10231
+ resourceKind: "rds_instance",
10011
10232
  severity: "critical",
10012
10233
  rules: ["SEC_AWS_ENCRYPTION_RDS_SIN_CIFRAR", "SEC_AWS_EXPOSURE_RDS_PUBLICA"],
10013
10234
  detect: (input) => sameResource(input, "SEC_AWS_ENCRYPTION_RDS_SIN_CIFRAR", "SEC_AWS_EXPOSURE_RDS_PUBLICA").map((m) => ({ ...m, evidence: { publiclyAccessible: true } }))
@@ -10016,6 +10237,7 @@ var AWS_SECURITY_COMBOS = [
10016
10237
  // Entra a la consola solo con contraseña y además tiene una clave de acceso vieja y activa: dos puertas sin segundo factor.
10017
10238
  id: "COMBO_AWS_USER_NO_MFA_OLD_KEY",
10018
10239
  provider: "aws",
10240
+ resourceKind: "iam_user",
10019
10241
  severity: "critical",
10020
10242
  rules: ["SEC_AWS_IAM_USUARIO_SIN_MFA", "SEC_AWS_IAM_CLAVE_ANTIGUA"],
10021
10243
  detect: (input) => {
@@ -10040,6 +10262,7 @@ var AWS_SECURITY_COMBOS = [
10040
10262
  // Administrador efectivo, consola sin MFA y una clave activa que nadie usa: tres puertas a toda la cuenta y nadie mirando una de ellas.
10041
10263
  id: "COMBO_AWS_ADMIN_NO_MFA_UNUSED_KEY",
10042
10264
  provider: "aws",
10265
+ resourceKind: "iam_user",
10043
10266
  severity: "critical",
10044
10267
  rules: ["SEC_AWS_IAM_ADMIN_EFECTIVO", "SEC_AWS_IAM_USUARIO_SIN_MFA", "SEC_AWS_IAM_CLAVE_SIN_USO"],
10045
10268
  detect: (input) => {
@@ -11738,6 +11961,34 @@ var ALARM_RULES = ALARM_CONTROLS.map((control) => ({
11738
11961
  evaluate: (observations) => evaluateAlarmControl(control, observations)
11739
11962
  }));
11740
11963
 
11964
+ // ../../services/security/src/rules/aws/patching.ts
11965
+ var SIN_ACTUALIZACION_MENOR_GESTIONADA = /^(custom-|docdb$|neptune$)/;
11966
+ function rdsSinActualizacionMenorEvaluate(observation) {
11967
+ const engine = observation.attributes.engine;
11968
+ if (typeof engine === "string" && SIN_ACTUALIZACION_MENOR_GESTIONADA.test(engine)) return { status: "ok" };
11969
+ const auto = observation.attributes.autoMinorVersionUpgrade;
11970
+ if (typeof auto !== "boolean") return { status: "unknown", check: RDS_CHECKS.instances, attribute: "autoMinorVersionUpgrade" };
11971
+ if (auto) return { status: "ok" };
11972
+ return {
11973
+ status: "finding",
11974
+ evidence: {
11975
+ autoMinorVersionUpgrade: false,
11976
+ engine: engine ?? null,
11977
+ engineVersion: observation.attributes.engineVersion ?? null
11978
+ }
11979
+ };
11980
+ }
11981
+ var rdsSinActualizacionMenor = {
11982
+ id: "SEC_AWS_PATCHING_RDS_SIN_ACTUALIZACION_MENOR",
11983
+ scope: "resource",
11984
+ category: "security_patching",
11985
+ severity: "medium",
11986
+ provider: "aws",
11987
+ kinds: ["rds_instance"],
11988
+ requires: [REGION_CHECKS.listRegions, RDS_CHECKS.instances],
11989
+ evaluate: rdsSinActualizacionMenorEvaluate
11990
+ };
11991
+
11741
11992
  // ../../services/security/src/rules/aws/secrets.ts
11742
11993
  var SOSPECHOSAS = [
11743
11994
  "PASSWORD",
@@ -11798,6 +12049,7 @@ var AWS_SECURITY_RULES = [
11798
12049
  lambdaPublica,
11799
12050
  kmsSinRotacion,
11800
12051
  rdsSinCifrar,
12052
+ rdsSinActualizacionMenor,
11801
12053
  rootSinMfa,
11802
12054
  usuarioSinMfa,
11803
12055
  claveAntigua,
@@ -11822,6 +12074,7 @@ var AZURE_SECURITY_COMBOS = [
11822
12074
  // Abierto a internet y con un TLS que admite versiones viejas: lo que viaja se puede leer por el camino.
11823
12075
  id: "COMBO_AZURE_PUBLIC_SQL_WEAK_TLS",
11824
12076
  provider: "azure",
12077
+ resourceKind: "sql_server",
11825
12078
  severity: "high",
11826
12079
  rules: ["SEC_AZURE_EXPOSURE_SQL_PUBLICO", "SEC_AZURE_ENCRYPTION_SQL_TLS"],
11827
12080
  detect: (input) => sameResource(input, "SEC_AZURE_EXPOSURE_SQL_PUBLICO", "SEC_AZURE_ENCRYPTION_SQL_TLS")
@@ -11830,10 +12083,40 @@ var AZURE_SECURITY_COMBOS = [
11830
12083
  // Permite contenedores públicos y además TLS débil o HTTP: la exposición de la cuenta se suma a la del tránsito.
11831
12084
  id: "COMBO_AZURE_PUBLIC_STORAGE_WEAK_TLS",
11832
12085
  provider: "azure",
12086
+ resourceKind: "storage_account",
11833
12087
  severity: "critical",
11834
12088
  rules: ["SEC_AZURE_EXPOSURE_BLOB_PUBLICO", "SEC_AZURE_ENCRYPTION_STORAGE_TLS"],
11835
12089
  detect: (input) => sameResource(input, "SEC_AZURE_EXPOSURE_BLOB_PUBLICO", "SEC_AZURE_ENCRYPTION_STORAGE_TLS")
11836
12090
  },
12091
+ {
12092
+ // Servidor abierto a internet con bases que llevan una semana sin conexiones: se paga por datos expuestos que nadie usa.
12093
+ id: "COMBO_AZURE_PUBLIC_SQL_IDLE",
12094
+ provider: "azure",
12095
+ resourceKind: "sql_server",
12096
+ severity: "high",
12097
+ rules: ["SEC_AZURE_EXPOSURE_SQL_PUBLICO"],
12098
+ costRules: ["AZURE_SQL_ZERO_CONN"],
12099
+ detect: (input) => {
12100
+ const sinUso = costSignalsOf(input, "AZURE_SQL_ZERO_CONN").filter((s) => s.armId);
12101
+ if (sinUso.length === 0) return [];
12102
+ return input.findings.filter((f) => f.ruleId === "SEC_AZURE_EXPOSURE_SQL_PUBLICO").flatMap((f) => {
12103
+ const prefijo2 = `${f.resourceId.toLowerCase()}/databases/`;
12104
+ const bases = sinUso.filter((s) => s.armId.toLowerCase().startsWith(prefijo2));
12105
+ const primera = bases[0];
12106
+ if (!primera) return [];
12107
+ const ahorro = Math.round(bases.reduce((total2, s) => total2 + s.monthlySavingsUsd, 0) * 100) / 100;
12108
+ return [
12109
+ {
12110
+ region: f.region,
12111
+ resourceId: f.resourceId,
12112
+ resourceName: f.resourceName,
12113
+ findingIds: [f.id],
12114
+ evidence: { ...costEvidence(input, { ...primera, monthlySavingsUsd: ahorro }, { amount: true }), idleDatabases: bases.length }
12115
+ }
12116
+ ];
12117
+ });
12118
+ }
12119
+ },
11837
12120
  {
11838
12121
  // VM expuesta a internet según Defender y con un CVE crítico o alto con exploit conocido.
11839
12122
  id: "COMBO_AZURE_PUBLIC_VULNERABLE",
@@ -12301,18 +12584,36 @@ var GCP_SECURITY_COMBOS = [
12301
12584
  // Abierta a internet, sin uso en 7 días y facturando: se paga por una puerta que nadie usa.
12302
12585
  id: "COMBO_GCP_PUBLIC_SQL_IDLE",
12303
12586
  provider: "gcp",
12587
+ resourceKind: "cloud_sql_instance",
12304
12588
  severity: "high",
12305
12589
  rules: ["SEC_GCP_EXPOSURE_SQL_PUBLICO"],
12306
12590
  costRules: ["GCP_SQL_ZERO_CONNECTIONS"],
12307
- detect: (input) => {
12308
- const sinUso = new Map(costSignalsOf(input, "GCP_SQL_ZERO_CONNECTIONS").map((s) => [s.resourceId, s]));
12309
- if (sinUso.size === 0) return [];
12310
- return input.findings.filter((f) => f.ruleId === "SEC_GCP_EXPOSURE_SQL_PUBLICO").flatMap((f) => {
12311
- const coste = sinUso.get(f.resourceId);
12312
- if (!coste) return [];
12313
- return [{ region: f.region, resourceId: f.resourceId, resourceName: f.resourceName, findingIds: [f.id], evidence: costEvidence(input, coste, { amount: true }) }];
12314
- });
12315
- }
12591
+ detect: (input) => withCostSignal(input, {
12592
+ rule: "SEC_GCP_EXPOSURE_SQL_PUBLICO",
12593
+ costRule: "GCP_SQL_ZERO_CONNECTIONS",
12594
+ // Por nombre: coste y seguridad usan el nombre de la instancia, único dentro del proyecto.
12595
+ findingKey: (f) => f.resourceId,
12596
+ signalKey: (s) => s.resourceId,
12597
+ amount: true
12598
+ })
12599
+ },
12600
+ {
12601
+ // Guarda credenciales en su configuración y nadie la invoca: borrarla quita las credenciales del proyecto sin romper nada.
12602
+ id: "COMBO_GCP_UNUSED_FUNCTION_SECRETS",
12603
+ provider: "gcp",
12604
+ resourceKind: "cloud_function",
12605
+ severity: "high",
12606
+ rules: ["SEC_GCP_SECRETS_FUNCTION_ENV"],
12607
+ costRules: ["GCP_FUNCTION_UNUSED"],
12608
+ detect: (input) => withCostSignal(input, {
12609
+ rule: "SEC_GCP_SECRETS_FUNCTION_ENV",
12610
+ costRule: "GCP_FUNCTION_UNUSED",
12611
+ // Los dos módulos usan el nombre completo (projects/…/locations/…/functions/…), que ya lleva la región.
12612
+ findingKey: (f) => f.resourceId,
12613
+ signalKey: (s) => s.resourceId,
12614
+ // El módulo de coste no pone precio a una función: depende del uso.
12615
+ amount: false
12616
+ })
12316
12617
  },
12317
12618
  {
12318
12619
  // Una cuenta de servicio Owner o Editor con una clave descargable: quien tenga el fichero tiene el proyecto.
@@ -13181,7 +13482,7 @@ function displayAddress(address) {
13181
13482
  return address.replace(/\["((?:[^"\\]|\\.)*)"\]/g, (_, key) => `[#${createHash2("sha256").update(key).digest("hex").slice(0, 8)}]`);
13182
13483
  }
13183
13484
  var code = (text) => "`" + displayAddress(text).replace(/[\r\n]+/g, " ").replace(/`/g, "'").replace(/\|/g, "\\|") + "`";
13184
- var cell = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\|/g, "\\|").replace(/[\r\n]+/g, " ");
13485
+ var cell2 = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\|/g, "\\|").replace(/[\r\n]+/g, " ");
13185
13486
  function groupedGaps(items) {
13186
13487
  const seen = /* @__PURE__ */ new Set();
13187
13488
  return items.filter((item) => {
@@ -13216,7 +13517,7 @@ function renderSecurityMarkdown(report) {
13216
13517
  for (const { finding, count } of rows.values()) {
13217
13518
  const detail = [evidenceSummary(finding), count > 1 ? `\xD7${count}` : ""].filter(Boolean).join(" ");
13218
13519
  lines2.push(
13219
- `| ${BADGE[finding.severity]} | ${cell(ruleTitle(finding.ruleId))} | ${code(finding.address)} | ${ACTION[finding.action] ?? finding.action} | ${cell(detail) || "\u2014"} |`
13520
+ `| ${BADGE[finding.severity]} | ${cell2(ruleTitle(finding.ruleId))} | ${code(finding.address)} | ${ACTION[finding.action] ?? finding.action} | ${cell2(detail) || "\u2014"} |`
13220
13521
  );
13221
13522
  }
13222
13523
  }
@@ -13224,7 +13525,7 @@ function renderSecurityMarkdown(report) {
13224
13525
  lines2.push("", "**Toxic combinations** \u2014 findings that are worse together, fix these first:", "");
13225
13526
  lines2.push("| Severity | Combination | Resource |", "|---|---|---|");
13226
13527
  for (const combo of report.combos) {
13227
- lines2.push(`| ${BADGE[combo.severity]} | ${cell(comboTitle(combo.comboId))} | ${code(combo.address)} |`);
13528
+ lines2.push(`| ${BADGE[combo.severity]} | ${cell2(comboTitle(combo.comboId))} | ${code(combo.address)} |`);
13228
13529
  }
13229
13530
  }
13230
13531
  if (drift.length > 0) {
@@ -13232,7 +13533,7 @@ function renderSecurityMarkdown(report) {
13232
13533
  lines2.push("", `**Last scan vs. this plan** (AAA Sentinel scan${when}):`, "");
13233
13534
  lines2.push("| Severity | Rule | Resource | What it means |", "|---|---|---|---|");
13234
13535
  for (const item of drift) {
13235
- lines2.push(`| ${BADGE[item.severity]} | ${cell(ruleTitle(item.ruleId))} | ${code(item.address)} | ${DRIFT_TEXT[item.status]} |`);
13536
+ lines2.push(`| ${BADGE[item.severity]} | ${cell2(ruleTitle(item.ruleId))} | ${code(item.address)} | ${DRIFT_TEXT[item.status]} |`);
13236
13537
  }
13237
13538
  }
13238
13539
  if (report.drift?.truncated) {
@@ -13242,7 +13543,7 @@ function renderSecurityMarkdown(report) {
13242
13543
  if (gaps.length > 0) {
13243
13544
  lines2.push("", `<details><summary>Not evaluable before apply (${gaps.length})</summary>`, "");
13244
13545
  lines2.push("| Rule | Resource | Why |", "|---|---|---|");
13245
- for (const gap of gaps) lines2.push(`| ${cell(ruleTitle(gap.ruleId))} | ${code(gap.address)} | ${GAP_TEXT[gap.reason]} |`);
13546
+ for (const gap of gaps) lines2.push(`| ${cell2(ruleTitle(gap.ruleId))} | ${code(gap.address)} | ${GAP_TEXT[gap.reason]} |`);
13246
13547
  lines2.push("", "</details>");
13247
13548
  }
13248
13549
  const notes = [];
@@ -13341,10 +13642,11 @@ async function runCli(options, readPlan, credentials) {
13341
13642
  }
13342
13643
  } catch (error2) {
13343
13644
  warnings.push(`could not read the plan: ${error2.message}`);
13344
- return { stdout: null, warnings, exitCode: options.failOn && options.security ? 2 : 0 };
13645
+ return { stdout: null, warnings, exitCode: options.failOn && options.security || options.failOnBudget ? 2 : 0 };
13345
13646
  }
13346
13647
  let estimate = null;
13347
13648
  let costMarkdown = null;
13649
+ let costFailed = false;
13348
13650
  if (options.cost) {
13349
13651
  if (credentials.baseUrl === null) warnings.push("IAC_COST_BASE_URL must be an https URL, skipping every call to the API (cost estimate and last-scan comparison).");
13350
13652
  else if (!credentials.cost) warnings.push("IAC_COST_CLIENT_ID/IAC_COST_CLIENT_SECRET not set, skipping cost estimate.");
@@ -13355,12 +13657,14 @@ async function runCli(options, readPlan, credentials) {
13355
13657
  ...credentials.fetchImpl ? { fetchImpl: credentials.fetchImpl } : {}
13356
13658
  });
13357
13659
  if (result.warning) warnings.push(result.warning);
13660
+ costFailed = result.failed;
13358
13661
  estimate = result.estimate;
13359
13662
  costMarkdown = result.markdown;
13360
13663
  }
13361
13664
  }
13362
13665
  let report = null;
13363
13666
  let exitCode = 0;
13667
+ let gateUnavailable = false;
13364
13668
  if (options.security) {
13365
13669
  try {
13366
13670
  const evaluation = evaluatePlan(plan);
@@ -13387,23 +13691,54 @@ async function runCli(options, readPlan, credentials) {
13387
13691
  if (options.failOn && blockingCount(report, options.failOn) > 0) exitCode = 1;
13388
13692
  } catch (error2) {
13389
13693
  warnings.push(`Security check failed: ${error2.message}`);
13390
- if (options.failOn) exitCode = 2;
13694
+ if (options.failOn) gateUnavailable = true;
13391
13695
  }
13392
13696
  }
13697
+ let budgets = null;
13698
+ if (options.failOnBudget) {
13699
+ const mode = options.failOnBudget;
13700
+ if (!estimate) {
13701
+ if (costFailed || credentials.baseUrl === null || !credentials.cost) {
13702
+ warnings.push("Budget check unavailable: it needs the cost estimate.");
13703
+ gateUnavailable = true;
13704
+ }
13705
+ } else if (estimate.totalMonthlyDeltaUsd === null) {
13706
+ warnings.push("Budget check skipped: the estimate has no total (coverage too low).");
13707
+ if (mode === "strict") exitCode = 1;
13708
+ } else if (credentials.baseUrl !== null && credentials.cost) {
13709
+ try {
13710
+ budgets = await checkBudgets(
13711
+ { baseUrl: credentials.baseUrl, ...credentials.cost, ...credentials.fetchImpl ? { fetchImpl: credentials.fetchImpl } : {} },
13712
+ { monthlyDeltaUsd: estimate.totalMonthlyDeltaUsd, ...options.budgetAccount ? { accountId: options.budgetAccount } : {} }
13713
+ );
13714
+ if (evaluateBudgetGate(budgets, mode).blocks) exitCode = 1;
13715
+ } catch (error2) {
13716
+ warnings.push(`Budget check unavailable: ${error2.message}`);
13717
+ gateUnavailable = true;
13718
+ }
13719
+ }
13720
+ }
13721
+ if (exitCode === 0 && gateUnavailable) exitCode = 2;
13393
13722
  if (options.format === "json") {
13394
- return { stdout: JSON.stringify({ formatVersion: "1", cost: estimate, security: report, warnings }, null, 2), warnings, exitCode };
13723
+ return {
13724
+ stdout: JSON.stringify({ formatVersion: "1", cost: estimate, security: report, ...options.failOnBudget ? { budgets } : {}, warnings }, null, 2),
13725
+ warnings,
13726
+ exitCode
13727
+ };
13395
13728
  }
13396
13729
  if (options.format === "text") {
13397
- const parts = [estimate ? costText(estimate) : null, report ? renderSecurityText(report) : null].filter((p) => p !== null);
13730
+ const parts = [estimate ? costText(estimate) : null, report ? renderSecurityText(report) : null, budgets ? renderBudgetText(budgets) : null].filter(
13731
+ (p) => p !== null
13732
+ );
13398
13733
  return { stdout: parts.length > 0 ? parts.join("\n\n") : null, warnings, exitCode };
13399
13734
  }
13400
13735
  const securityMarkdown = report ? renderSecurityMarkdown(report) : null;
13401
- if (costMarkdown && securityMarkdown) return { stdout: `${costMarkdown}
13402
-
13403
- ${securityMarkdown}`, warnings, exitCode };
13404
- if (securityMarkdown) return { stdout: `${COMMENT_MARKER}
13405
- ${securityMarkdown}`, warnings, exitCode };
13406
- return { stdout: costMarkdown, warnings, exitCode };
13736
+ const budgetMarkdown = budgets && options.failOnBudget ? renderBudgetMarkdown(budgets, options.failOnBudget) : null;
13737
+ const sections = [costMarkdown, securityMarkdown, budgetMarkdown].filter((p) => p !== null);
13738
+ if (sections.length === 0) return { stdout: null, warnings, exitCode };
13739
+ const body2 = sections.join("\n\n");
13740
+ return { stdout: costMarkdown ? body2 : `${COMMENT_MARKER}
13741
+ ${body2}`, warnings, exitCode };
13407
13742
  }
13408
13743
 
13409
13744
  // src/cli.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aaa-sentinel/iac-cost",
3
- "version": "0.6.1",
3
+ "version": "0.8.0",
4
4
  "description": "Estimate the monthly cost delta of a Terraform plan, check it against the AAA Sentinel security rules, open security fixes as pull requests and report how the security posture changed, from your CI",
5
5
  "license": "MIT",
6
6
  "type": "module",