@aaa-sentinel/iac-cost 0.7.0 → 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 +36 -2
  2. package/dist/cli.js +180 -20
  3. package/package.json +43 -43
package/README.md CHANGED
@@ -7,7 +7,9 @@ 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
- > **New in 0.7.0:** the plan check flags RDS and Aurora instances with `auto_minor_version_upgrade = false`
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`
11
13
  > (CIS AWS 2.3.2; RDS Custom is skipped), and `iac-cost fix` turns it back on. Security findings have a
12
14
  > seventh category, `security_patching`.
13
15
 
@@ -83,6 +85,7 @@ npx @aaa-sentinel/iac-cost plan.json # or: … | npx @aaa-sentinel/iac-
83
85
  | `IAC_SECURITY_FAIL_ON` | no | Same as `--fail-on` |
84
86
  | `IAC_SECURITY_ACCOUNT_ID` | no | Same as `--drift-account` |
85
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 |
86
89
 
87
90
  The Markdown comment goes to **stdout**; warnings go to **stderr**. If there is nothing to
88
91
  say, stdout is empty.
@@ -91,11 +94,13 @@ say, stdout is empty.
91
94
  | --- | --- |
92
95
  | `--format markdown` | The pull request comment (default) |
93
96
  | `--format text` | Plain lines for a terminal or a CI log |
94
- | `--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 |
95
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` |
96
99
  | `--no-security` | Cost only, exactly as in 0.1 |
97
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 |
98
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` |
99
104
 
100
105
  ### It never fails your build — unless you ask for a gate
101
106
 
@@ -116,6 +121,35 @@ Any other unknown or malformed argument only prints a warning, with or without a
116
121
  Only the plan decides the code. The cost estimate and the drift check go over the network, and
117
122
  neither can change it. A check that **could not be decided** (see below) never blocks.
118
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
+
119
153
  ## What actually leaves your machine
120
154
 
121
155
  Not the plan. `terraform show -json` output carries CIDRs, account identifiers and, often,
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";
@@ -9822,18 +9863,103 @@ function parseTerraformPlan(plan) {
9822
9863
  };
9823
9864
  }
9824
9865
 
9825
- // src/security/drift.ts
9826
- var SCOPE2 = "security:read";
9866
+ // src/budget.ts
9867
+ var SCOPE2 = "budgets:read";
9827
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;
9828
9954
  var CAUSE_OUTSIDE_PLAN = /* @__PURE__ */ new Set(["SEC_AWS_LOGGING_VPC_SIN_FLOW_LOGS", "SEC_AWS_LOGGING_FLOW_LOGS_INCOMPLETOS"]);
9829
9955
  var REGIONAL_NAMES = /* @__PURE__ */ new Set(["lambda_function", "rds_instance"]);
9830
9956
  async function fetchLiveFindings(config2) {
9831
9957
  const fetchImpl = config2.fetchImpl ?? fetch;
9832
- const token = await fetchToken(config2, SCOPE2);
9958
+ const token = await fetchToken(config2, SCOPE3);
9833
9959
  const url = `${config2.baseUrl}/v1/security/findings?accountId=${encodeURIComponent(config2.accountId)}`;
9834
9960
  const response = await fetchImpl(url, {
9835
9961
  headers: { authorization: `Bearer ${token}` },
9836
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
9962
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS3)
9837
9963
  });
9838
9964
  if (!response.ok) throw new Error(`security_findings_http_${response.status}`);
9839
9965
  const body2 = await response.json();
@@ -13356,7 +13482,7 @@ function displayAddress(address) {
13356
13482
  return address.replace(/\["((?:[^"\\]|\\.)*)"\]/g, (_, key) => `[#${createHash2("sha256").update(key).digest("hex").slice(0, 8)}]`);
13357
13483
  }
13358
13484
  var code = (text) => "`" + displayAddress(text).replace(/[\r\n]+/g, " ").replace(/`/g, "'").replace(/\|/g, "\\|") + "`";
13359
- 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, " ");
13360
13486
  function groupedGaps(items) {
13361
13487
  const seen = /* @__PURE__ */ new Set();
13362
13488
  return items.filter((item) => {
@@ -13391,7 +13517,7 @@ function renderSecurityMarkdown(report) {
13391
13517
  for (const { finding, count } of rows.values()) {
13392
13518
  const detail = [evidenceSummary(finding), count > 1 ? `\xD7${count}` : ""].filter(Boolean).join(" ");
13393
13519
  lines2.push(
13394
- `| ${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"} |`
13395
13521
  );
13396
13522
  }
13397
13523
  }
@@ -13399,7 +13525,7 @@ function renderSecurityMarkdown(report) {
13399
13525
  lines2.push("", "**Toxic combinations** \u2014 findings that are worse together, fix these first:", "");
13400
13526
  lines2.push("| Severity | Combination | Resource |", "|---|---|---|");
13401
13527
  for (const combo of report.combos) {
13402
- 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)} |`);
13403
13529
  }
13404
13530
  }
13405
13531
  if (drift.length > 0) {
@@ -13407,7 +13533,7 @@ function renderSecurityMarkdown(report) {
13407
13533
  lines2.push("", `**Last scan vs. this plan** (AAA Sentinel scan${when}):`, "");
13408
13534
  lines2.push("| Severity | Rule | Resource | What it means |", "|---|---|---|---|");
13409
13535
  for (const item of drift) {
13410
- 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]} |`);
13411
13537
  }
13412
13538
  }
13413
13539
  if (report.drift?.truncated) {
@@ -13417,7 +13543,7 @@ function renderSecurityMarkdown(report) {
13417
13543
  if (gaps.length > 0) {
13418
13544
  lines2.push("", `<details><summary>Not evaluable before apply (${gaps.length})</summary>`, "");
13419
13545
  lines2.push("| Rule | Resource | Why |", "|---|---|---|");
13420
- 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]} |`);
13421
13547
  lines2.push("", "</details>");
13422
13548
  }
13423
13549
  const notes = [];
@@ -13516,10 +13642,11 @@ async function runCli(options, readPlan, credentials) {
13516
13642
  }
13517
13643
  } catch (error2) {
13518
13644
  warnings.push(`could not read the plan: ${error2.message}`);
13519
- 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 };
13520
13646
  }
13521
13647
  let estimate = null;
13522
13648
  let costMarkdown = null;
13649
+ let costFailed = false;
13523
13650
  if (options.cost) {
13524
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).");
13525
13652
  else if (!credentials.cost) warnings.push("IAC_COST_CLIENT_ID/IAC_COST_CLIENT_SECRET not set, skipping cost estimate.");
@@ -13530,12 +13657,14 @@ async function runCli(options, readPlan, credentials) {
13530
13657
  ...credentials.fetchImpl ? { fetchImpl: credentials.fetchImpl } : {}
13531
13658
  });
13532
13659
  if (result.warning) warnings.push(result.warning);
13660
+ costFailed = result.failed;
13533
13661
  estimate = result.estimate;
13534
13662
  costMarkdown = result.markdown;
13535
13663
  }
13536
13664
  }
13537
13665
  let report = null;
13538
13666
  let exitCode = 0;
13667
+ let gateUnavailable = false;
13539
13668
  if (options.security) {
13540
13669
  try {
13541
13670
  const evaluation = evaluatePlan(plan);
@@ -13562,23 +13691,54 @@ async function runCli(options, readPlan, credentials) {
13562
13691
  if (options.failOn && blockingCount(report, options.failOn) > 0) exitCode = 1;
13563
13692
  } catch (error2) {
13564
13693
  warnings.push(`Security check failed: ${error2.message}`);
13565
- if (options.failOn) exitCode = 2;
13694
+ if (options.failOn) gateUnavailable = true;
13566
13695
  }
13567
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;
13568
13722
  if (options.format === "json") {
13569
- 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
+ };
13570
13728
  }
13571
13729
  if (options.format === "text") {
13572
- 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
+ );
13573
13733
  return { stdout: parts.length > 0 ? parts.join("\n\n") : null, warnings, exitCode };
13574
13734
  }
13575
13735
  const securityMarkdown = report ? renderSecurityMarkdown(report) : null;
13576
- if (costMarkdown && securityMarkdown) return { stdout: `${costMarkdown}
13577
-
13578
- ${securityMarkdown}`, warnings, exitCode };
13579
- if (securityMarkdown) return { stdout: `${COMMENT_MARKER}
13580
- ${securityMarkdown}`, warnings, exitCode };
13581
- 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 };
13582
13742
  }
13583
13743
 
13584
13744
  // src/cli.ts
package/package.json CHANGED
@@ -1,43 +1,43 @@
1
- {
2
- "name": "@aaa-sentinel/iac-cost",
3
- "version": "0.7.0",
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
- "license": "MIT",
6
- "type": "module",
7
- "bin": {
8
- "iac-cost": "dist/cli.js"
9
- },
10
- "files": [
11
- "dist"
12
- ],
13
- "keywords": [
14
- "terraform",
15
- "finops",
16
- "cost",
17
- "iac",
18
- "security",
19
- "shift-left"
20
- ],
21
- "publishConfig": {
22
- "access": "public"
23
- },
24
- "homepage": "https://app.aaa-sentinel.com/developer/docs#terraform-ci",
25
- "bugs": {
26
- "url": "https://app.aaa-sentinel.com/contact"
27
- },
28
- "engines": {
29
- "node": ">=20"
30
- },
31
- "scripts": {
32
- "build": "esbuild src/cli.ts --bundle --platform=node --format=esm --target=node20 --outfile=dist/cli.js",
33
- "prepublishOnly": "npm --prefix ../.. run build:iac-cost",
34
- "test": "vitest run"
35
- },
36
- "devDependencies": {
37
- "@finops-sentinel/shared": "*",
38
- "@types/node": "^22.0.0",
39
- "esbuild": "^0.24.0",
40
- "typescript": "^5.7.0",
41
- "vitest": "^3.2.0"
42
- }
43
- }
1
+ {
2
+ "name": "@aaa-sentinel/iac-cost",
3
+ "version": "0.8.0",
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
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "iac-cost": "dist/cli.js"
9
+ },
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "keywords": [
14
+ "terraform",
15
+ "finops",
16
+ "cost",
17
+ "iac",
18
+ "security",
19
+ "shift-left"
20
+ ],
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "homepage": "https://app.aaa-sentinel.com/developer/docs#terraform-ci",
25
+ "bugs": {
26
+ "url": "https://app.aaa-sentinel.com/contact"
27
+ },
28
+ "engines": {
29
+ "node": ">=20"
30
+ },
31
+ "scripts": {
32
+ "build": "esbuild src/cli.ts --bundle --platform=node --format=esm --target=node20 --outfile=dist/cli.js",
33
+ "prepublishOnly": "npm --prefix ../.. run build:iac-cost",
34
+ "test": "vitest run"
35
+ },
36
+ "devDependencies": {
37
+ "@finops-sentinel/shared": "*",
38
+ "@types/node": "^22.0.0",
39
+ "esbuild": "^0.24.0",
40
+ "typescript": "^5.7.0",
41
+ "vitest": "^3.2.0"
42
+ }
43
+ }