@aaa-sentinel/iac-cost 0.7.0 → 0.9.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 +66 -2
  2. package/dist/cli.js +446 -58
  3. package/package.json +43 -43
package/README.md CHANGED
@@ -7,7 +7,11 @@ 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.9.0:** `iac-cost env-cost --env <name>` prints what an ephemeral environment has cost so far, resource by resource, with when its lease expires, and `--comment` posts it on the merge request (see [Environment cost](#environment-cost)).
11
+ >
12
+ > **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)).
13
+ >
14
+ > **In 0.7.0:** the plan check flags RDS and Aurora instances with `auto_minor_version_upgrade = false`
11
15
  > (CIS AWS 2.3.2; RDS Custom is skipped), and `iac-cost fix` turns it back on. Security findings have a
12
16
  > seventh category, `security_patching`.
13
17
 
@@ -83,6 +87,7 @@ npx @aaa-sentinel/iac-cost plan.json # or: … | npx @aaa-sentinel/iac-
83
87
  | `IAC_SECURITY_FAIL_ON` | no | Same as `--fail-on` |
84
88
  | `IAC_SECURITY_ACCOUNT_ID` | no | Same as `--drift-account` |
85
89
  | `IAC_SECURITY_CLIENT_ID` / `IAC_SECURITY_CLIENT_SECRET` | for drift | An OAuth2 application with the `security:read` scope |
90
+ | `IAC_FAIL_ON_BUDGET` | no | Same as `--fail-on-budget`: `true` or `strict` turns the gate on, empty or `none` leaves it off |
86
91
 
87
92
  The Markdown comment goes to **stdout**; warnings go to **stderr**. If there is nothing to
88
93
  say, stdout is empty.
@@ -91,11 +96,13 @@ say, stdout is empty.
91
96
  | --- | --- |
92
97
  | `--format markdown` | The pull request comment (default) |
93
98
  | `--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 |
99
+ | `--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
100
  | `--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
101
  | `--no-security` | Cost only, exactly as in 0.1 |
97
102
  | `--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
103
  | `--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** |
104
+ | `--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` |
105
+ | `--budget-account <accountId>` | Account whose budgets also apply to the gate. Defaults to `--drift-account` |
99
106
 
100
107
  ### It never fails your build — unless you ask for a gate
101
108
 
@@ -116,6 +123,63 @@ Any other unknown or malformed argument only prints a warning, with or without a
116
123
  Only the plan decides the code. The cost estimate and the drift check go over the network, and
117
124
  neither can change it. A check that **could not be decided** (see below) never blocks.
118
125
 
126
+ ## Budget gate
127
+
128
+ With `--fail-on-budget` the CLI sends the estimated monthly change (`totalMonthlyDeltaUsd`, one
129
+ number) to AAA Sentinel, which compares it with your budgets: for each budget that applies, this
130
+ month's spend so far scaled to the whole month, plus the change. The budgets that apply are the
131
+ organization ones, and those of the account in `--budget-account` (or `--drift-account`).
132
+
133
+ **Limitation of this version: budgets scoped to one billing service are not checked.** A
134
+ Terraform plan names resource types, not the billing services they are charged under, so the CLI
135
+ cannot tell which service a change belongs to and does not guess. Those budgets still alert from
136
+ AAA Sentinel; only the pull request gate skips them.
137
+ Budgets are part of every plan; the API used by the gate is part of the Pro and Business plans.
138
+
139
+ The OAuth2 application in `IAC_COST_CLIENT_ID` needs the `budgets:read` scope as well as
140
+ `iac:estimate`.
141
+
142
+ | Code | When |
143
+ | --- | --- |
144
+ | `0` | Every budget that applies stays within its amount |
145
+ | `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 |
146
+ | `2` | The gate could not decide: no cost credentials, the estimate failed, the check did not answer, or the plan is not readable |
147
+
148
+ The comment gets a **Budgets** section with each budget, the month at the current pace, the
149
+ change and the projected total, in the budget's currency (`≈` when converted from USD).
150
+
151
+ ```bash
152
+ npx --yes @aaa-sentinel/iac-cost plan.json --fail-on-budget --budget-account acc_9f2c1e
153
+ ```
154
+
155
+ ## Environment cost
156
+
157
+ `iac-cost env-cost --env <name>` reads `GET /v1/environments/{env}/cost` and prints what an
158
+ ephemeral environment (the preview of a pull request, a load test) has cost so far. An environment
159
+ is every resource tagged `aaa-sentinel:env=<name>` (`aaa-sentinel_env` on GCP) or covered by an
160
+ AAA Sentinel lease with that `env`. For each resource it shows the type, account and region, its
161
+ monthly list cost, what it has cost over the days it has been alive, and when its lease expires.
162
+
163
+ ```bash
164
+ npx --yes @aaa-sentinel/iac-cost env-cost --env pr-412 # text table
165
+ npx --yes @aaa-sentinel/iac-cost env-cost --env pr-412 --format markdown > env.md
166
+ npx --yes @aaa-sentinel/iac-cost env-cost --env pr-412 --comment # GitLab merge request note
167
+ ```
168
+
169
+ | Option | Effect |
170
+ | --- | --- |
171
+ | `--env <name>` | Environment name: lowercase letters, digits, `.`, `_` or `-`, up to 63. Also `IAC_COST_ENV` |
172
+ | `--format <text\|markdown\|json>` | `text` by default, `markdown` with `--comment` |
173
+ | `--comment` | Posts the Markdown as a note on the GitLab merge request of the pipeline and updates it on later runs, like [`iac-cost comment`](#gitlab-ci) (needs `GITLAB_TOKEN`). It has its own marker, so it never replaces the plan cost note. On GitHub Actions and Bitbucket Pipelines, post stdout with the snippets below, changing the marker they look for to `<!-- aaa-sentinel:iac-cost-env -->` |
174
+
175
+ - **The amounts are an estimate**, not the bill: the list price of each resource in the last daily
176
+ scan, prorated over its days alive, in your organization currency and marked `≈`. A resource
177
+ created after the last scan, or tagged since, shows up after the next one; a resource without a
178
+ known list price shows `—` and does not add to the total.
179
+ - The OAuth2 application in `IAC_COST_CLIENT_ID` needs the `leases:read` scope (Pro plan or above).
180
+ - It always exits `0`, so a report can never fail the environment pipeline. Only a missing or
181
+ invalid `--env` or `--format` exits `2`.
182
+
119
183
  ## What actually leaves your machine
120
184
 
121
185
  Not the plan. `terraform show -json` output carries CIDRs, account identifiers and, often,
package/dist/cli.js CHANGED
@@ -16,6 +16,7 @@ var USAGE = `Usage: iac-cost [plan.json] [options]
16
16
  iac-cost fix [plan.json] --account <accountId> [options] (see iac-cost fix --help)
17
17
  iac-cost posture --account <accountId> [options] (see iac-cost posture --help)
18
18
  iac-cost comment [comment.md] (note on the GitLab merge request, see iac-cost comment --help)
19
+ iac-cost env-cost --env <name> [--comment] (estimated cost of an environment, see iac-cost env-cost --help)
19
20
 
20
21
  Reads \`terraform show -json\` output from the file or from stdin.
21
22
 
@@ -28,6 +29,13 @@ Options:
28
29
  --no-cost Skip the cost estimate
29
30
  --drift-account <accountId> Compare with the last scan of this AAA Sentinel
30
31
  account (needs IAC_SECURITY_CLIENT_ID/SECRET)
32
+ --fail-on-budget[=strict] Exit 1 when the change takes an AAA Sentinel budget over
33
+ (organization budgets, and the account ones with
34
+ --budget-account). With =strict a budget without a
35
+ forecast, or no budget at all, also fails. Needs the
36
+ budgets:read scope on IAC_COST_CLIENT_ID. Service
37
+ budgets are not checked in this version
38
+ --budget-account <accountId> Account whose budgets also apply (default: --drift-account)
31
39
  -h, --help Show this help`;
32
40
  function parseCliArgs(argv, env) {
33
41
  const warnings = [];
@@ -42,13 +50,17 @@ function parseCliArgs(argv, env) {
42
50
  "no-security": { type: "boolean" },
43
51
  "no-cost": { type: "boolean" },
44
52
  "drift-account": { type: "string" },
53
+ // Booleana para que no se trague el siguiente argumento; sin `strict`, `--fail-on-budget=strict` llega como texto.
54
+ "fail-on-budget": { type: "boolean" },
55
+ "budget-account": { type: "string" },
45
56
  help: { type: "boolean", short: "h" }
46
57
  }
47
58
  });
48
- const known = /* @__PURE__ */ new Set(["format", "fail-on", "no-security", "no-cost", "drift-account", "help", "h"]);
59
+ const known = /* @__PURE__ */ new Set(["format", "fail-on", "no-security", "no-cost", "drift-account", "fail-on-budget", "budget-account", "help", "h"]);
49
60
  for (const name of Object.keys(values)) {
50
61
  if (known.has(name)) continue;
51
62
  if (/^fail[-_]?on$/i.test(name)) return { error: `unknown option --${name}: the gate is spelled --fail-on` };
63
+ if (/^fail[-_]?on[-_]?budgets?$/i.test(name)) return { error: `unknown option --${name}: the gate is spelled --fail-on-budget` };
52
64
  warnings.push(`unknown option --${name} ignored`);
53
65
  }
54
66
  if (positionals.length > 1) warnings.push(`only one plan file is read, ignoring ${positionals.slice(1).join(" ")}`);
@@ -76,6 +88,16 @@ function parseCliArgs(argv, env) {
76
88
  const driftAccount = typeof driftRaw === "string" && driftRaw.trim() !== "" ? driftRaw.trim() : null;
77
89
  if (values["drift-account"] === true) warnings.push("--drift-account needs an account id, skipping the comparison with the last scan");
78
90
  if (!security && failOn) warnings.push("--fail-on has no effect with --no-security: no security gate is applied");
91
+ const budgetGate = parseBudgetGate(values["fail-on-budget"], env["IAC_FAIL_ON_BUDGET"]);
92
+ if ("error" in budgetGate) return budgetGate;
93
+ const failOnBudget = budgetGate.mode;
94
+ if (failOnBudget && !cost) return { error: "--fail-on-budget needs the cost estimate: remove --no-cost" };
95
+ if (values["budget-account"] === true || typeof values["budget-account"] === "string" && values["budget-account"].startsWith("-")) {
96
+ return { error: "--budget-account needs an account id" };
97
+ }
98
+ const budgetRaw = typeof values["budget-account"] === "string" ? values["budget-account"].trim() : "";
99
+ const budgetAccount = budgetRaw !== "" ? budgetRaw : failOnBudget ? driftAccount : null;
100
+ if (budgetRaw !== "" && !failOnBudget) warnings.push("--budget-account has no effect without --fail-on-budget");
79
101
  return {
80
102
  planPath: positionals[0] ?? null,
81
103
  format,
@@ -83,10 +105,30 @@ function parseCliArgs(argv, env) {
83
105
  cost,
84
106
  security,
85
107
  driftAccount,
108
+ failOnBudget,
109
+ budgetAccount,
86
110
  help: values.help === true || values.h === true,
87
111
  warnings
88
112
  };
89
113
  }
114
+ var BUDGET_ON = /* @__PURE__ */ new Set(["1", "true", "on", "yes", "normal"]);
115
+ var BUDGET_OFF = /* @__PURE__ */ new Set(["none", "off", "false", "0"]);
116
+ function parseBudgetGate(flag, envValue) {
117
+ if (flag !== void 0) {
118
+ if (flag === true) return { mode: "normal" };
119
+ const text2 = String(flag).trim().toLowerCase();
120
+ if (text2 === "") return { error: "--fail-on-budget= needs a value: strict, or no value for the normal gate" };
121
+ if (text2 === "strict") return { mode: "strict" };
122
+ if (BUDGET_ON.has(text2)) return { mode: "normal" };
123
+ if (BUDGET_OFF.has(text2)) return { mode: null };
124
+ return { error: `--fail-on-budget takes no value or =strict (got "${String(flag)}"); put the plan file before the option` };
125
+ }
126
+ const text = (envValue ?? "").trim().toLowerCase();
127
+ if (text === "" || BUDGET_OFF.has(text)) return { mode: null };
128
+ if (text === "strict") return { mode: "strict" };
129
+ if (BUDGET_ON.has(text)) return { mode: "normal" };
130
+ return { error: `IAC_FAIL_ON_BUDGET must be strict, true or none (got "${envValue}")` };
131
+ }
90
132
 
91
133
  // src/comment.ts
92
134
  import { parseArgs as parseArgs2 } from "node:util";
@@ -146,7 +188,7 @@ var GitLabError = class extends Error {
146
188
  this.status = status;
147
189
  }
148
190
  };
149
- async function gitLabCall(fetchImpl, url, token, init, label) {
191
+ async function gitLabCall(fetchImpl, url, token, init, label2) {
150
192
  const response = await fetchImpl(url, {
151
193
  method: init.method ?? "GET",
152
194
  headers: {
@@ -169,7 +211,7 @@ async function gitLabCall(fetchImpl, url, token, init, label) {
169
211
  } catch {
170
212
  detail = "";
171
213
  }
172
- throw new GitLabError(response.status, `${label} failed with HTTP ${response.status}${detail}`);
214
+ throw new GitLabError(response.status, `${label2} failed with HTTP ${response.status}${detail}`);
173
215
  }
174
216
  return response;
175
217
  }
@@ -287,6 +329,11 @@ async function runCommentCli(argv, io) {
287
329
  return skip(`could not read the comment, skipping: ${error2.message}`);
288
330
  }
289
331
  if (markdown.trim() === "") return skip("nothing to comment (empty input), the merge request is left as it is");
332
+ return postMergeRequestNote(markdown, io, COMMENT_MARKER, warnings);
333
+ }
334
+ async function postMergeRequestNote(markdown, io, marker, earlierWarnings = []) {
335
+ const warnings = [...earlierWarnings];
336
+ const skip = (message) => ({ stdout: null, warnings: [...warnings, message], exitCode: 0 });
290
337
  const { env } = io;
291
338
  if (env["GITLAB_CI"] !== "true") return skip("comment posts on GitLab merge requests and this is not a GitLab CI job, skipping (on GitHub and Bitbucket, use the README snippets)");
292
339
  const iid = env["CI_MERGE_REQUEST_IID"];
@@ -303,7 +350,7 @@ async function runCommentCli(argv, io) {
303
350
  if ("error" in server) return skip(`${server.error}, skipping the comment`);
304
351
  const fetchImpl = io.fetchImpl ?? fetch;
305
352
  const notesUrl = `${server.apiUrl}/projects/${target}/merge_requests/${iid}/notes`;
306
- const body2 = markdown.includes(COMMENT_MARKER) ? markdown : `${COMMENT_MARKER}
353
+ const body2 = markdown.includes(marker) ? markdown : `${marker}
307
354
  ${markdown}`;
308
355
  try {
309
356
  const me = await (await gitLabCall(fetchImpl, `${server.apiUrl}/user`, token, {}, "read token user")).json();
@@ -314,7 +361,7 @@ ${markdown}`;
314
361
  if (response.status === 404) throw new Error(`merge request !${iid} not found (does the token belong to this project?)`);
315
362
  const notes = await response.json();
316
363
  if (!Array.isArray(notes)) break;
317
- const mine = notes.find((n) => n.system !== true && n.author?.id === me.id && typeof n.body === "string" && n.body.includes(COMMENT_MARKER));
364
+ const mine = notes.find((n) => n.system !== true && n.author?.id === me.id && typeof n.body === "string" && n.body.includes(marker));
318
365
  if (mine && typeof mine.id === "number") existing = mine.id;
319
366
  if (response.headers.get("x-next-page") === "" || notes.length < 100) break;
320
367
  }
@@ -331,6 +378,9 @@ ${markdown}`;
331
378
  }
332
379
  }
333
380
 
381
+ // src/env-cost.ts
382
+ import { parseArgs as parseArgs3 } from "node:util";
383
+
334
384
  // ../../node_modules/zod/v4/core/util.js
335
385
  var util_exports = {};
336
386
  __export(util_exports, {
@@ -586,14 +636,14 @@ function promiseAllObject(promisesObj) {
586
636
  }
587
637
  function randomString(length = 10) {
588
638
  const chars = "abcdefghijklmnopqrstuvwxyz";
589
- let str = "";
639
+ let str2 = "";
590
640
  for (let i = 0; i < length; i++) {
591
- str += chars[Math.floor(Math.random() * chars.length)];
641
+ str2 += chars[Math.floor(Math.random() * chars.length)];
592
642
  }
593
- return str;
643
+ return str2;
594
644
  }
595
- function esc(str) {
596
- return JSON.stringify(str);
645
+ function esc(str2) {
646
+ return JSON.stringify(str2);
597
647
  }
598
648
  function slugify(input) {
599
649
  return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
@@ -707,8 +757,8 @@ var primitiveTypes = /* @__PURE__ */ new Set([
707
757
  "symbol",
708
758
  "undefined"
709
759
  ]);
710
- function escapeRegex(str) {
711
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
760
+ function escapeRegex(str2) {
761
+ return str2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
712
762
  }
713
763
  function clone(inst, def, params) {
714
764
  const cl = new inst._zod.constr(def ?? inst._zod.def);
@@ -974,13 +1024,13 @@ function getSizableOrigin(input) {
974
1024
  return "unknown";
975
1025
  }
976
1026
  var highSurrogate = /[\uD800-\uDBFF]/;
977
- function codePointLength(str) {
978
- const units = str.length;
979
- if (!highSurrogate.test(str))
1027
+ function codePointLength(str2) {
1028
+ const units = str2.length;
1029
+ if (!highSurrogate.test(str2))
980
1030
  return units;
981
1031
  let count = units;
982
1032
  for (let i = 0; i < units - 1; i++) {
983
- if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) {
1033
+ if ((str2.charCodeAt(i) & 64512) === 55296 && (str2.charCodeAt(i + 1) & 64512) === 56320) {
984
1034
  count--;
985
1035
  i++;
986
1036
  }
@@ -6799,12 +6849,224 @@ async function estimatePlan(projection, config2) {
6799
6849
  return aggregateEstimates(estimates);
6800
6850
  }
6801
6851
 
6852
+ // src/env-cost.ts
6853
+ var ENV_COST_USAGE = `Usage: iac-cost env-cost --env <name> [--comment] [--format text|markdown|json]
6854
+
6855
+ Prints the estimated cost of an AAA Sentinel environment (the resources tagged
6856
+ aaa-sentinel:env, or aaa-sentinel_env on GCP, or covered by a lease with that env):
6857
+ each resource, its monthly list cost, what it has cost so far over its days alive,
6858
+ and when its lease expires. The amounts are an estimate from list prices, in your
6859
+ organization currency, not the bill.
6860
+
6861
+ Options:
6862
+ --env <name> Environment name, e.g. pr-412 (also IAC_COST_ENV)
6863
+ --format <text|markdown|json>
6864
+ Output format (default: text; markdown with --comment)
6865
+ --comment Post the Markdown as a note on the GitLab merge request of
6866
+ this pipeline and update it on later runs, like
6867
+ iac-cost comment (needs GITLAB_TOKEN). On GitHub and
6868
+ Bitbucket, post stdout with the README snippets
6869
+ -h, --help Show this help
6870
+
6871
+ Environment:
6872
+ IAC_COST_CLIENT_ID / IAC_COST_CLIENT_SECRET
6873
+ OAuth2 application with the leases:read scope
6874
+ IAC_COST_BASE_URL API base URL (default https://api.aaa-sentinel.com)
6875
+
6876
+ It always exits 0, except for a missing or invalid --env (exit 2).`;
6877
+ var ENV_COST_MARKER = "<!-- aaa-sentinel:iac-cost-env -->";
6878
+ var SCOPE = "leases:read";
6879
+ var REQUEST_TIMEOUT_MS2 = 35e3;
6880
+ var RETRYABLE_STATUS2 = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
6881
+ var DEFAULT_BASE_URL = "https://api.aaa-sentinel.com";
6882
+ var ENV_RE = /^[a-z0-9][a-z0-9._-]{0,62}$/;
6883
+ var num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
6884
+ var str = (v) => typeof v === "string" && v !== "" ? v : null;
6885
+ function mapEnvCostResponse(raw, env) {
6886
+ if (!raw || typeof raw !== "object") throw new Error("iac_cost_env_cost_malformed");
6887
+ const body2 = raw;
6888
+ if (!Array.isArray(body2["resources"])) throw new Error("iac_cost_env_cost_malformed");
6889
+ const resources = [];
6890
+ for (const item of body2["resources"]) {
6891
+ if (!item || typeof item !== "object") continue;
6892
+ const r = item;
6893
+ const resourceId = str(r["resourceId"]);
6894
+ if (!resourceId) continue;
6895
+ const name = str(r["name"]);
6896
+ resources.push({
6897
+ accountId: str(r["accountId"]) ?? "",
6898
+ resourceId,
6899
+ provider: str(r["provider"]) ?? "",
6900
+ type: str(r["type"]) ?? "",
6901
+ region: str(r["region"]) ?? "",
6902
+ ...name ? { name } : {},
6903
+ monthlyCost: num(r["monthlyCost"]),
6904
+ estimatedCost: num(r["estimatedCost"]),
6905
+ leaseId: str(r["leaseId"]),
6906
+ expiresAt: str(r["expiresAt"])
6907
+ });
6908
+ }
6909
+ return {
6910
+ env: str(body2["env"]) ?? env,
6911
+ currency: str(body2["currency"]) ?? "USD",
6912
+ // Siempre es una estimación de precio de lista: solo un `false` explícito lo quita.
6913
+ approximate: body2["approximate"] !== false,
6914
+ monthlyCost: num(body2["monthlyCost"]),
6915
+ estimatedCost: num(body2["estimatedCost"]),
6916
+ expiresAt: str(body2["expiresAt"]),
6917
+ resources
6918
+ };
6919
+ }
6920
+ async function fetchEnvironmentCost(config2, env) {
6921
+ const fetchImpl = config2.fetchImpl ?? fetch;
6922
+ const sleepImpl = config2.sleepImpl ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
6923
+ const token = await fetchToken(config2, SCOPE);
6924
+ for (let attempt = 0; attempt < 2; attempt++) {
6925
+ const response = await fetchImpl(`${config2.baseUrl}/v1/environments/${encodeURIComponent(env)}/cost`, {
6926
+ method: "GET",
6927
+ headers: { authorization: `Bearer ${token}` },
6928
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
6929
+ });
6930
+ if (response.ok) return mapEnvCostResponse(await response.json(), env);
6931
+ if (response.status === 404) return "not_found";
6932
+ if (RETRYABLE_STATUS2.has(response.status) && attempt === 0) {
6933
+ await sleepImpl(1e3);
6934
+ continue;
6935
+ }
6936
+ const code2 = await apiErrorCode(response);
6937
+ throw new Error(`iac_cost_env_cost_http_${response.status}${code2 ? ` ${code2}` : ""}`);
6938
+ }
6939
+ throw new Error("iac_cost_env_cost_exhausted_retries");
6940
+ }
6941
+ function money(n, currency, approximate) {
6942
+ if (n === null) return "\u2014";
6943
+ let text;
6944
+ try {
6945
+ text = new Intl.NumberFormat("en-US", { style: "currency", currency }).format(n);
6946
+ } catch {
6947
+ text = `${n.toFixed(2)} ${currency}`;
6948
+ }
6949
+ return approximate ? `\u2248 ${text}` : text;
6950
+ }
6951
+ function expiryText(iso, now) {
6952
+ if (!iso) return "no lease";
6953
+ const t = Date.parse(iso);
6954
+ if (Number.isNaN(t)) return "no lease";
6955
+ const stamp = `${new Date(t).toISOString().slice(0, 16).replace("T", " ")} UTC`;
6956
+ const minutes = Math.round((t - now.getTime()) / 6e4);
6957
+ if (minutes <= 0) return `${stamp} (expired)`;
6958
+ const d = Math.floor(minutes / 1440);
6959
+ const h = Math.floor(minutes % 1440 / 60);
6960
+ const m = minutes % 60;
6961
+ const left = d > 0 ? `${d}d ${h}h` : h > 0 ? `${h}h ${m}m` : `${m}m`;
6962
+ return `${stamp} (in ${left})`;
6963
+ }
6964
+ var cell = (s) => s.replace(/[|\r\n`]+/g, " ").replace(/\s+/g, " ").trim();
6965
+ var label = (r) => r.name ? `${r.name} (${r.resourceId})` : r.resourceId;
6966
+ function renderEnvCostMarkdown(data, now) {
6967
+ const lines2 = [ENV_COST_MARKER, `### \u23F3 Environment \`${cell(data.env)}\``, ""];
6968
+ if (data.resources.length === 0) {
6969
+ lines2.push("No resources of this environment in the last inventory yet. New resources show up after the next daily scan.");
6970
+ return lines2.join("\n");
6971
+ }
6972
+ const approx = data.approximate;
6973
+ lines2.push(
6974
+ `**Cost so far:** ${money(data.estimatedCost, data.currency, approx)} \xB7 **Monthly at list price:** ${money(data.monthlyCost, data.currency, approx)} \xB7 **Expires:** ${expiryText(data.expiresAt, now)}`,
6975
+ "",
6976
+ "| Resource | Type | Account | Region | Monthly | So far | Expires |",
6977
+ "|---|---|---|---|---:|---:|---|"
6978
+ );
6979
+ for (const r of data.resources) {
6980
+ lines2.push(
6981
+ `| ${cell(label(r))} | ${cell(r.type)} | ${cell(r.accountId)} | ${cell(r.region)} | ${money(r.monthlyCost, data.currency, approx)} | ${money(r.estimatedCost, data.currency, approx)} | ${expiryText(r.expiresAt, now)} |`
6982
+ );
6983
+ }
6984
+ lines2.push("");
6985
+ if (approx) lines2.push("_\u2248 Estimate from list prices over each resource\u2019s days alive, in your organization currency: not the bill._");
6986
+ if (data.resources.some((r) => r.monthlyCost === null)) lines2.push("_\u2014 no known list price for that resource; it is not in the total._");
6987
+ return lines2.join("\n");
6988
+ }
6989
+ function pad(rows) {
6990
+ const widths = rows[0].map((_, i) => Math.max(...rows.map((row) => row[i].length)));
6991
+ return rows.map((row) => row.map((c, i) => c.padEnd(widths[i])).join(" ").trimEnd());
6992
+ }
6993
+ function renderEnvCostText(data, now) {
6994
+ const approx = data.approximate;
6995
+ const head = [
6996
+ `Environment ${data.env}`,
6997
+ ` Cost so far: ${money(data.estimatedCost, data.currency, approx)} Monthly at list price: ${money(data.monthlyCost, data.currency, approx)} Expires: ${expiryText(data.expiresAt, now)}`
6998
+ ];
6999
+ if (data.resources.length === 0) return [...head, " No resources of this environment in the last inventory yet."].join("\n");
7000
+ const rows = [
7001
+ ["RESOURCE", "TYPE", "ACCOUNT", "REGION", "MONTHLY", "SO FAR", "EXPIRES"],
7002
+ ...data.resources.map((r) => [
7003
+ label(r),
7004
+ r.type,
7005
+ r.accountId,
7006
+ r.region,
7007
+ money(r.monthlyCost, data.currency, approx),
7008
+ money(r.estimatedCost, data.currency, approx),
7009
+ expiryText(r.expiresAt, now)
7010
+ ])
7011
+ ];
7012
+ const tail = approx ? ["", "\u2248 estimate from list prices, not the bill."] : [];
7013
+ return [...head, "", ...pad(rows).map((line) => ` ${line}`), ...tail].join("\n");
7014
+ }
7015
+ async function runEnvCostCli(argv, io) {
7016
+ const warnings = [];
7017
+ const skip = (message) => ({ stdout: null, warnings: [...warnings, message], exitCode: 0 });
7018
+ const { values, positionals } = parseArgs3({
7019
+ args: [...argv],
7020
+ strict: false,
7021
+ allowPositionals: true,
7022
+ options: { env: { type: "string" }, format: { type: "string" }, comment: { type: "boolean" }, help: { type: "boolean", short: "h" } }
7023
+ });
7024
+ for (const name of Object.keys(values)) if (!["env", "format", "comment", "help", "h"].includes(name)) warnings.push(`unknown option --${name} ignored`);
7025
+ if (positionals.length > 0) warnings.push(`unexpected arguments ignored: ${positionals.join(" ")}`);
7026
+ if (values["help"] === true || values["h"] === true) return { stdout: ENV_COST_USAGE, warnings, exitCode: 0 };
7027
+ const rawEnv = typeof values["env"] === "string" ? values["env"] : io.env["IAC_COST_ENV"];
7028
+ const env = rawEnv?.trim().toLowerCase();
7029
+ if (!env || !ENV_RE.test(env)) {
7030
+ return { stdout: null, warnings: [...warnings, `${env ? `invalid --env "${env}"` : "--env is required"}: lowercase letters, digits, ".", "_" or "-", up to 63
7031
+
7032
+ ${ENV_COST_USAGE}`], exitCode: 2 };
7033
+ }
7034
+ const comment2 = values["comment"] === true;
7035
+ const format = typeof values["format"] === "string" ? values["format"] : comment2 ? "markdown" : "text";
7036
+ if (format !== "text" && format !== "markdown" && format !== "json") {
7037
+ return { stdout: null, warnings: [...warnings, `invalid --format "${format}": text, markdown or json
7038
+
7039
+ ${ENV_COST_USAGE}`], exitCode: 2 };
7040
+ }
7041
+ const baseUrl = resolveBaseUrl(io.env["IAC_COST_BASE_URL"] ?? DEFAULT_BASE_URL);
7042
+ if (!baseUrl) return skip("IAC_COST_BASE_URL must be an https URL, skipping the environment cost");
7043
+ const clientId = io.env["IAC_COST_CLIENT_ID"];
7044
+ const clientSecret = io.env["IAC_COST_CLIENT_SECRET"];
7045
+ if (!clientId || !clientSecret) return skip("IAC_COST_CLIENT_ID / IAC_COST_CLIENT_SECRET are not set, skipping the environment cost (the app needs the leases:read scope)");
7046
+ let data;
7047
+ try {
7048
+ data = await fetchEnvironmentCost(
7049
+ { baseUrl, clientId, clientSecret, ...io.fetchImpl ? { fetchImpl: io.fetchImpl } : {}, ...io.sleepImpl ? { sleepImpl: io.sleepImpl } : {} },
7050
+ env
7051
+ );
7052
+ } catch (error2) {
7053
+ return skip(`could not read the environment cost, continuing: ${error2.message}`);
7054
+ }
7055
+ if (data === "not_found") return skip(`environment "${env}" not found: no lease or tagged resource uses it yet (tags show up after the next daily scan)`);
7056
+ const now = (io.now ?? (() => /* @__PURE__ */ new Date()))();
7057
+ const markdown = renderEnvCostMarkdown(data, now);
7058
+ const stdout = format === "json" ? JSON.stringify(data, null, 2) : format === "markdown" ? markdown : renderEnvCostText(data, now);
7059
+ if (!comment2) return { stdout, warnings, exitCode: 0 };
7060
+ const posted = await postMergeRequestNote(markdown, io, ENV_COST_MARKER);
7061
+ return { stdout, warnings: [...warnings, ...posted.warnings, ...posted.stdout ? [posted.stdout] : []], exitCode: 0 };
7062
+ }
7063
+
6802
7064
  // src/fix/cli-fix.ts
6803
7065
  import path2 from "node:path";
6804
- import { parseArgs as parseArgs3 } from "node:util";
7066
+ import { parseArgs as parseArgs4 } from "node:util";
6805
7067
 
6806
7068
  // src/fix/api.ts
6807
- var SCOPE = "security:fix";
7069
+ var SCOPE2 = "security:fix";
6808
7070
  var TIMEOUT_MS2 = 35e3;
6809
7071
  var CodeFixApiError = class extends Error {
6810
7072
  constructor(status, code2, stage = "findings") {
@@ -6820,7 +7082,7 @@ function codeFixApi(config2) {
6820
7082
  let token = null;
6821
7083
  const bearer = async () => {
6822
7084
  try {
6823
- token ??= await fetchToken(config2, SCOPE);
7085
+ token ??= await fetchToken(config2, SCOPE2);
6824
7086
  } catch (error2) {
6825
7087
  if (error2 instanceof TokenHttpError) throw new CodeFixApiError(error2.status, error2.code, "token");
6826
7088
  throw error2;
@@ -6890,7 +7152,7 @@ var HostError = class extends Error {
6890
7152
  this.status = status;
6891
7153
  }
6892
7154
  };
6893
- async function call(fetchImpl, url, init, label) {
7155
+ async function call(fetchImpl, url, init, label2) {
6894
7156
  const response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(TIMEOUT_MS3) });
6895
7157
  if (!response.ok && response.status !== 404) {
6896
7158
  let detail = "";
@@ -6901,7 +7163,7 @@ async function call(fetchImpl, url, init, label) {
6901
7163
  } catch {
6902
7164
  detail = "";
6903
7165
  }
6904
- throw new HostError(response.status, `${label} failed with HTTP ${response.status}${detail}`);
7166
+ throw new HostError(response.status, `${label2} failed with HTTP ${response.status}${detail}`);
6905
7167
  }
6906
7168
  return response;
6907
7169
  }
@@ -6915,8 +7177,8 @@ function gitHubHost(config2) {
6915
7177
  "user-agent": "aaa-sentinel-iac-cost",
6916
7178
  "content-type": "application/json"
6917
7179
  };
6918
- const get = (path3, label) => call(fetchImpl, `${api}${path3}`, { headers }, label);
6919
- const post = (path3, body2, label) => call(fetchImpl, `${api}${path3}`, { method: "POST", headers, body: JSON.stringify(body2) }, label);
7180
+ const get = (path3, label2) => call(fetchImpl, `${api}${path3}`, { headers }, label2);
7181
+ const post = (path3, body2, label2) => call(fetchImpl, `${api}${path3}`, { method: "POST", headers, body: JSON.stringify(body2) }, label2);
6920
7182
  const owner = config2.repository.split("/")[0] ?? "";
6921
7183
  const stateOf = (pr) => typeof pr.merged_at === "string" && pr.merged_at !== "" ? "merged" : pr.state === "closed" ? "closed" : "open";
6922
7184
  return {
@@ -6985,7 +7247,7 @@ function bitbucketHost(config2) {
6985
7247
  const fetchImpl = config2.fetchImpl ?? fetch;
6986
7248
  const api = `${config2.apiUrl.replace(/\/+$/, "")}/repositories/${encodeURIComponent(config2.workspace)}/${encodeURIComponent(config2.repoSlug)}`;
6987
7249
  const auth = { authorization: `Bearer ${config2.token}`, accept: "application/json" };
6988
- const get = (path3, label) => call(fetchImpl, `${api}${path3}`, { headers: auth }, label);
7250
+ const get = (path3, label2) => call(fetchImpl, `${api}${path3}`, { headers: auth }, label2);
6989
7251
  const stateOf = (state) => state === "MERGED" ? "merged" : state === "OPEN" ? "open" : "closed";
6990
7252
  return {
6991
7253
  kind: "bitbucket",
@@ -7062,7 +7324,7 @@ var encodeGitLabPath = (value) => encodeURIComponent(value).replace(/\./g, "%2E"
7062
7324
  function gitLabHost(config2) {
7063
7325
  const fetchImpl = config2.fetchImpl ?? fetch;
7064
7326
  const api = `${config2.apiUrl}/projects/${encodeURIComponent(config2.projectId)}`;
7065
- const send = (path3, label, init = {}) => gitLabCall(fetchImpl, `${api}${path3}`, config2.token, init, label);
7327
+ const send = (path3, label2, init = {}) => gitLabCall(fetchImpl, `${api}${path3}`, config2.token, init, label2);
7066
7328
  const link = (iid) => pullRequestUrl("gitlab", config2.repository, iid, config2.server);
7067
7329
  const stateOf = (state) => state === "merged" ? "merged" : state === "closed" ? "closed" : "open";
7068
7330
  return {
@@ -7331,10 +7593,10 @@ function parseBody(text, start, end) {
7331
7593
  continue;
7332
7594
  }
7333
7595
  IDENT.lastIndex = j;
7334
- const label = IDENT.exec(text);
7335
- if (!label) throw new HclError(`unexpected token in block header at ${j}`);
7336
- labels.push(label[0]);
7337
- j += label[0].length;
7596
+ const label2 = IDENT.exec(text);
7597
+ if (!label2) throw new HclError(`unexpected token in block header at ${j}`);
7598
+ labels.push(label2[0]);
7599
+ j += label2[0].length;
7338
7600
  }
7339
7601
  const close = skipBalanced(text, j);
7340
7602
  if (close >= end) throw new HclError("block overflows its parent");
@@ -8828,7 +9090,7 @@ var VPC_INGRESS_RULE = {
8828
9090
  otherSources: [],
8829
9091
  singles: ["cidr_ipv4", "cidr_ipv6"]
8830
9092
  };
8831
- function judgeRule(text, block, items, shape, label) {
9093
+ function judgeRule(text, block, items, shape, label2) {
8832
9094
  const literalOfName = (name) => {
8833
9095
  const attr = attributeOf(items, name);
8834
9096
  return attr ? literalOf(text, attr) : void 0;
@@ -8894,7 +9156,7 @@ function judgeRule(text, block, items, shape, label) {
8894
9156
  const ports = fromPort !== null ? `port ${fromPort}` : "admin port";
8895
9157
  if (remaining.length === 0 && !others) {
8896
9158
  const attribute = shape === INLINE_RULE ? "ingress" : shape.lists[0] ?? shape.singles[0] ?? "ingress";
8897
- return { open: true, removesBlock: true, edits: [() => removeBlock(text, block)], attribute, changes: [`remove ${label} (${ports} open to the internet)`] };
9159
+ return { open: true, removesBlock: true, edits: [() => removeBlock(text, block)], attribute, changes: [`remove ${label2} (${ports} open to the internet)`] };
8898
9160
  }
8899
9161
  if (singles.length > 0) throw new Suggest("only_source", singles[0]?.name);
8900
9162
  return {
@@ -8902,7 +9164,7 @@ function judgeRule(text, block, items, shape, label) {
8902
9164
  removesBlock: false,
8903
9165
  attribute: lists.find(({ list }) => list.items.some((item) => OPEN_CIDRS.has(item.value)))?.attr.name ?? "cidr_blocks",
8904
9166
  edits: lists.filter(({ list }) => list.items.some((item) => OPEN_CIDRS.has(item.value))).map(({ attr, list }) => () => removeListItems(text, attr, list, (value) => OPEN_CIDRS.has(value))),
8905
- changes: lists.filter(({ list }) => list.items.some((item) => OPEN_CIDRS.has(item.value))).map(({ attr, list }) => `remove ${list.items.filter((i) => OPEN_CIDRS.has(i.value)).map((i) => `\`${i.value}\``).join(", ")} from \`${attr.name}\` in ${label} (${ports})`)
9167
+ changes: lists.filter(({ list }) => list.items.some((item) => OPEN_CIDRS.has(item.value))).map(({ attr, list }) => `remove ${list.items.filter((i) => OPEN_CIDRS.has(i.value)).map((i) => `\`${i.value}\``).join(", ")} from \`${attr.name}\` in ${label2} (${ports})`)
8906
9168
  };
8907
9169
  }
8908
9170
  function awsAdminOpen(ctx, builder) {
@@ -8912,8 +9174,8 @@ function awsAdminOpen(ctx, builder) {
8912
9174
  if (blocksOf(items, "dynamic").some((block) => block.labels[0] === "ingress")) throw new Suggest("dynamic_block", "ingress");
8913
9175
  if (attributeOf(items, "ingress")) throw new Suggest("value_from_expression", "ingress");
8914
9176
  let judged = 0;
8915
- const apply = (target, block, blockItems, shape, label, alignName = null) => {
8916
- const verdict = judgeRule(target.text, block, blockItems, shape, label);
9177
+ const apply = (target, block, blockItems, shape, label2, alignName = null) => {
9178
+ const verdict = judgeRule(target.text, block, blockItems, shape, label2);
8917
9179
  if (!verdict.open) return false;
8918
9180
  judged += 1;
8919
9181
  const lifecycleName = shape === INLINE_RULE ? "ingress" : verdict.removesBlock ? null : verdict.attribute;
@@ -9450,7 +9712,7 @@ Environment:
9450
9712
  async function runFixCli(argv, io) {
9451
9713
  const warnings = [];
9452
9714
  const fail = (message) => ({ stdout: null, warnings: [...warnings, message], exitCode: 2 });
9453
- const { values, positionals } = parseArgs3({
9715
+ const { values, positionals } = parseArgs4({
9454
9716
  args: [...argv],
9455
9717
  strict: false,
9456
9718
  allowPositionals: true,
@@ -9527,7 +9789,7 @@ ${FIX_USAGE}`);
9527
9789
  }
9528
9790
 
9529
9791
  // src/posture/posture.ts
9530
- import { parseArgs as parseArgs4 } from "node:util";
9792
+ import { parseArgs as parseArgs5 } from "node:util";
9531
9793
  var POSTURE_USAGE = `Usage: iac-cost posture --account <accountId> [options]
9532
9794
 
9533
9795
  Prints how the security posture of an AAA Sentinel account changed over a
@@ -9628,7 +9890,7 @@ async function fetchPostureHistory(config2) {
9628
9890
  async function runPostureCli(argv, io) {
9629
9891
  const warnings = [];
9630
9892
  const fail = (message) => ({ stdout: null, warnings: [...warnings, message], exitCode: 2 });
9631
- const { values, positionals } = parseArgs4({
9893
+ const { values, positionals } = parseArgs5({
9632
9894
  args: [...argv],
9633
9895
  strict: false,
9634
9896
  allowPositionals: true,
@@ -9822,18 +10084,103 @@ function parseTerraformPlan(plan) {
9822
10084
  };
9823
10085
  }
9824
10086
 
10087
+ // src/budget.ts
10088
+ var SCOPE3 = "budgets:read";
10089
+ var REQUEST_TIMEOUT_MS3 = 35e3;
10090
+ var RETRYABLE_STATUS3 = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
10091
+ async function checkBudgets(config2, input) {
10092
+ const fetchImpl = config2.fetchImpl ?? fetch;
10093
+ const sleepImpl = config2.sleepImpl ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
10094
+ const token = await fetchToken(config2, SCOPE3);
10095
+ for (let attempt = 0; attempt < 2; attempt++) {
10096
+ const response = await fetchImpl(`${config2.baseUrl}/v1/budgets/check`, {
10097
+ method: "POST",
10098
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
10099
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS3),
10100
+ body: JSON.stringify({ monthlyDeltaUsd: input.monthlyDeltaUsd, ...input.accountId ? { accountId: input.accountId } : {} })
10101
+ });
10102
+ if (response.ok) {
10103
+ const body2 = await response.json();
10104
+ if (!Array.isArray(body2.results)) throw new Error("iac_cost_budget_check_malformed");
10105
+ return { results: body2.results, approximate: body2.approximate === true };
10106
+ }
10107
+ if (RETRYABLE_STATUS3.has(response.status) && attempt === 0) {
10108
+ await sleepImpl(1e3);
10109
+ continue;
10110
+ }
10111
+ const code2 = await apiErrorCode(response);
10112
+ throw new Error(`iac_cost_budget_check_http_${response.status}${code2 ? ` ${code2}` : ""}`);
10113
+ }
10114
+ throw new Error("iac_cost_budget_check_exhausted_retries");
10115
+ }
10116
+ function evaluateBudgetGate(response, mode) {
10117
+ const over = response.results.filter((r) => r.status === "over").length;
10118
+ const unresolved = response.results.filter((r) => r.status === "unresolved").length + (response.results.length === 0 ? 1 : 0);
10119
+ return { over, unresolved, blocks: over > 0 || mode === "strict" && unresolved > 0 };
10120
+ }
10121
+ function money2(n, currency) {
10122
+ try {
10123
+ return new Intl.NumberFormat("en-US", { style: "currency", currency }).format(n);
10124
+ } catch {
10125
+ return `${n.toFixed(2)} ${currency}`;
10126
+ }
10127
+ }
10128
+ var signed = (n, currency) => `${n < 0 ? "-" : "+"}${money2(Math.abs(n), currency)}`;
10129
+ function scopeText(scope) {
10130
+ if (scope.kind === "org") return "organization";
10131
+ if (scope.kind === "account") return `account ${scope.accountId}`;
10132
+ return scope.accountId ? `${scope.service} in ${scope.accountId}` : scope.service;
10133
+ }
10134
+ var STATUS_TEXT = {
10135
+ ok: "\u2705 within budget",
10136
+ over: "\u274C over budget",
10137
+ unresolved: "\u26A0\uFE0F no forecast yet"
10138
+ };
10139
+ var cell2 = (s) => s.replace(/[|\r\n]+/g, " ").replace(/\s+/g, " ").trim();
10140
+ function renderBudgetMarkdown(response, mode) {
10141
+ const lines2 = ["### \u{1F3AF} Budgets", ""];
10142
+ if (response.results.length === 0) {
10143
+ lines2.push(
10144
+ 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`)."
10145
+ );
10146
+ return lines2.join("\n");
10147
+ }
10148
+ const approx = response.approximate ? "\u2248 " : "";
10149
+ lines2.push("| Budget | Scope | Monthly budget | This month at current pace | This change | Projected | Status |", "|---|---|---:|---:|---:|---:|---|");
10150
+ for (const r of response.results) {
10151
+ lines2.push(
10152
+ `| ${cell2(r.name)} | ${cell2(scopeText(r.scope))} | ${money2(r.amount, r.currency)} | ${r.forecast === null ? "\u2014" : approx + money2(r.forecast, r.currency)} | ${approx}${signed(r.delta, r.currency)} | ${r.projected === null ? "\u2014" : approx + money2(r.projected, r.currency)} | ${STATUS_TEXT[r.status]} |`
10153
+ );
10154
+ }
10155
+ lines2.push("");
10156
+ lines2.push("_The pace is this month\u2019s spend so far, scaled to the whole month. The change is the list-price estimate above._");
10157
+ if (response.approximate) lines2.push("_\u2248 converted from USD at today\u2019s rate._");
10158
+ if (mode === "normal" && response.results.some((r) => r.status === "unresolved")) {
10159
+ lines2.push("_A budget without a forecast does not fail the check; `--fail-on-budget=strict` makes it fail._");
10160
+ }
10161
+ return lines2.join("\n");
10162
+ }
10163
+ function renderBudgetText(response) {
10164
+ if (response.results.length === 0) return "Budgets\n No budget applies to this change.";
10165
+ const approx = response.approximate ? "~" : "";
10166
+ const rows = response.results.map(
10167
+ (r) => ` ${r.name} (${scopeText(r.scope)}): ${r.status}, budget ${money2(r.amount, r.currency)}, projected ${r.projected === null ? "unknown" : approx + money2(r.projected, r.currency)} (change ${approx}${signed(r.delta, r.currency)})`
10168
+ );
10169
+ return ["Budgets", ...rows].join("\n");
10170
+ }
10171
+
9825
10172
  // src/security/drift.ts
9826
- var SCOPE2 = "security:read";
9827
- var REQUEST_TIMEOUT_MS2 = 35e3;
10173
+ var SCOPE4 = "security:read";
10174
+ var REQUEST_TIMEOUT_MS4 = 35e3;
9828
10175
  var CAUSE_OUTSIDE_PLAN = /* @__PURE__ */ new Set(["SEC_AWS_LOGGING_VPC_SIN_FLOW_LOGS", "SEC_AWS_LOGGING_FLOW_LOGS_INCOMPLETOS"]);
9829
10176
  var REGIONAL_NAMES = /* @__PURE__ */ new Set(["lambda_function", "rds_instance"]);
9830
10177
  async function fetchLiveFindings(config2) {
9831
10178
  const fetchImpl = config2.fetchImpl ?? fetch;
9832
- const token = await fetchToken(config2, SCOPE2);
10179
+ const token = await fetchToken(config2, SCOPE4);
9833
10180
  const url = `${config2.baseUrl}/v1/security/findings?accountId=${encodeURIComponent(config2.accountId)}`;
9834
10181
  const response = await fetchImpl(url, {
9835
10182
  headers: { authorization: `Bearer ${token}` },
9836
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
10183
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS4)
9837
10184
  });
9838
10185
  if (!response.ok) throw new Error(`security_findings_http_${response.status}`);
9839
10186
  const body2 = await response.json();
@@ -13356,7 +13703,7 @@ function displayAddress(address) {
13356
13703
  return address.replace(/\["((?:[^"\\]|\\.)*)"\]/g, (_, key) => `[#${createHash2("sha256").update(key).digest("hex").slice(0, 8)}]`);
13357
13704
  }
13358
13705
  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, " ");
13706
+ var cell3 = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\|/g, "\\|").replace(/[\r\n]+/g, " ");
13360
13707
  function groupedGaps(items) {
13361
13708
  const seen = /* @__PURE__ */ new Set();
13362
13709
  return items.filter((item) => {
@@ -13391,7 +13738,7 @@ function renderSecurityMarkdown(report) {
13391
13738
  for (const { finding, count } of rows.values()) {
13392
13739
  const detail = [evidenceSummary(finding), count > 1 ? `\xD7${count}` : ""].filter(Boolean).join(" ");
13393
13740
  lines2.push(
13394
- `| ${BADGE[finding.severity]} | ${cell(ruleTitle(finding.ruleId))} | ${code(finding.address)} | ${ACTION[finding.action] ?? finding.action} | ${cell(detail) || "\u2014"} |`
13741
+ `| ${BADGE[finding.severity]} | ${cell3(ruleTitle(finding.ruleId))} | ${code(finding.address)} | ${ACTION[finding.action] ?? finding.action} | ${cell3(detail) || "\u2014"} |`
13395
13742
  );
13396
13743
  }
13397
13744
  }
@@ -13399,7 +13746,7 @@ function renderSecurityMarkdown(report) {
13399
13746
  lines2.push("", "**Toxic combinations** \u2014 findings that are worse together, fix these first:", "");
13400
13747
  lines2.push("| Severity | Combination | Resource |", "|---|---|---|");
13401
13748
  for (const combo of report.combos) {
13402
- lines2.push(`| ${BADGE[combo.severity]} | ${cell(comboTitle(combo.comboId))} | ${code(combo.address)} |`);
13749
+ lines2.push(`| ${BADGE[combo.severity]} | ${cell3(comboTitle(combo.comboId))} | ${code(combo.address)} |`);
13403
13750
  }
13404
13751
  }
13405
13752
  if (drift.length > 0) {
@@ -13407,7 +13754,7 @@ function renderSecurityMarkdown(report) {
13407
13754
  lines2.push("", `**Last scan vs. this plan** (AAA Sentinel scan${when}):`, "");
13408
13755
  lines2.push("| Severity | Rule | Resource | What it means |", "|---|---|---|---|");
13409
13756
  for (const item of drift) {
13410
- lines2.push(`| ${BADGE[item.severity]} | ${cell(ruleTitle(item.ruleId))} | ${code(item.address)} | ${DRIFT_TEXT[item.status]} |`);
13757
+ lines2.push(`| ${BADGE[item.severity]} | ${cell3(ruleTitle(item.ruleId))} | ${code(item.address)} | ${DRIFT_TEXT[item.status]} |`);
13411
13758
  }
13412
13759
  }
13413
13760
  if (report.drift?.truncated) {
@@ -13417,7 +13764,7 @@ function renderSecurityMarkdown(report) {
13417
13764
  if (gaps.length > 0) {
13418
13765
  lines2.push("", `<details><summary>Not evaluable before apply (${gaps.length})</summary>`, "");
13419
13766
  lines2.push("| Rule | Resource | Why |", "|---|---|---|");
13420
- for (const gap of gaps) lines2.push(`| ${cell(ruleTitle(gap.ruleId))} | ${code(gap.address)} | ${GAP_TEXT[gap.reason]} |`);
13767
+ for (const gap of gaps) lines2.push(`| ${cell3(ruleTitle(gap.ruleId))} | ${code(gap.address)} | ${GAP_TEXT[gap.reason]} |`);
13421
13768
  lines2.push("", "</details>");
13422
13769
  }
13423
13770
  const notes = [];
@@ -13516,10 +13863,11 @@ async function runCli(options, readPlan, credentials) {
13516
13863
  }
13517
13864
  } catch (error2) {
13518
13865
  warnings.push(`could not read the plan: ${error2.message}`);
13519
- return { stdout: null, warnings, exitCode: options.failOn && options.security ? 2 : 0 };
13866
+ return { stdout: null, warnings, exitCode: options.failOn && options.security || options.failOnBudget ? 2 : 0 };
13520
13867
  }
13521
13868
  let estimate = null;
13522
13869
  let costMarkdown = null;
13870
+ let costFailed = false;
13523
13871
  if (options.cost) {
13524
13872
  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
13873
  else if (!credentials.cost) warnings.push("IAC_COST_CLIENT_ID/IAC_COST_CLIENT_SECRET not set, skipping cost estimate.");
@@ -13530,12 +13878,14 @@ async function runCli(options, readPlan, credentials) {
13530
13878
  ...credentials.fetchImpl ? { fetchImpl: credentials.fetchImpl } : {}
13531
13879
  });
13532
13880
  if (result.warning) warnings.push(result.warning);
13881
+ costFailed = result.failed;
13533
13882
  estimate = result.estimate;
13534
13883
  costMarkdown = result.markdown;
13535
13884
  }
13536
13885
  }
13537
13886
  let report = null;
13538
13887
  let exitCode = 0;
13888
+ let gateUnavailable = false;
13539
13889
  if (options.security) {
13540
13890
  try {
13541
13891
  const evaluation = evaluatePlan(plan);
@@ -13562,27 +13912,58 @@ async function runCli(options, readPlan, credentials) {
13562
13912
  if (options.failOn && blockingCount(report, options.failOn) > 0) exitCode = 1;
13563
13913
  } catch (error2) {
13564
13914
  warnings.push(`Security check failed: ${error2.message}`);
13565
- if (options.failOn) exitCode = 2;
13915
+ if (options.failOn) gateUnavailable = true;
13916
+ }
13917
+ }
13918
+ let budgets = null;
13919
+ if (options.failOnBudget) {
13920
+ const mode = options.failOnBudget;
13921
+ if (!estimate) {
13922
+ if (costFailed || credentials.baseUrl === null || !credentials.cost) {
13923
+ warnings.push("Budget check unavailable: it needs the cost estimate.");
13924
+ gateUnavailable = true;
13925
+ }
13926
+ } else if (estimate.totalMonthlyDeltaUsd === null) {
13927
+ warnings.push("Budget check skipped: the estimate has no total (coverage too low).");
13928
+ if (mode === "strict") exitCode = 1;
13929
+ } else if (credentials.baseUrl !== null && credentials.cost) {
13930
+ try {
13931
+ budgets = await checkBudgets(
13932
+ { baseUrl: credentials.baseUrl, ...credentials.cost, ...credentials.fetchImpl ? { fetchImpl: credentials.fetchImpl } : {} },
13933
+ { monthlyDeltaUsd: estimate.totalMonthlyDeltaUsd, ...options.budgetAccount ? { accountId: options.budgetAccount } : {} }
13934
+ );
13935
+ if (evaluateBudgetGate(budgets, mode).blocks) exitCode = 1;
13936
+ } catch (error2) {
13937
+ warnings.push(`Budget check unavailable: ${error2.message}`);
13938
+ gateUnavailable = true;
13939
+ }
13566
13940
  }
13567
13941
  }
13942
+ if (exitCode === 0 && gateUnavailable) exitCode = 2;
13568
13943
  if (options.format === "json") {
13569
- return { stdout: JSON.stringify({ formatVersion: "1", cost: estimate, security: report, warnings }, null, 2), warnings, exitCode };
13944
+ return {
13945
+ stdout: JSON.stringify({ formatVersion: "1", cost: estimate, security: report, ...options.failOnBudget ? { budgets } : {}, warnings }, null, 2),
13946
+ warnings,
13947
+ exitCode
13948
+ };
13570
13949
  }
13571
13950
  if (options.format === "text") {
13572
- const parts = [estimate ? costText(estimate) : null, report ? renderSecurityText(report) : null].filter((p) => p !== null);
13951
+ const parts = [estimate ? costText(estimate) : null, report ? renderSecurityText(report) : null, budgets ? renderBudgetText(budgets) : null].filter(
13952
+ (p) => p !== null
13953
+ );
13573
13954
  return { stdout: parts.length > 0 ? parts.join("\n\n") : null, warnings, exitCode };
13574
13955
  }
13575
13956
  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 };
13957
+ const budgetMarkdown = budgets && options.failOnBudget ? renderBudgetMarkdown(budgets, options.failOnBudget) : null;
13958
+ const sections = [costMarkdown, securityMarkdown, budgetMarkdown].filter((p) => p !== null);
13959
+ if (sections.length === 0) return { stdout: null, warnings, exitCode };
13960
+ const body2 = sections.join("\n\n");
13961
+ return { stdout: costMarkdown ? body2 : `${COMMENT_MARKER}
13962
+ ${body2}`, warnings, exitCode };
13582
13963
  }
13583
13964
 
13584
13965
  // src/cli.ts
13585
- var DEFAULT_BASE_URL = "https://api.aaa-sentinel.com";
13966
+ var DEFAULT_BASE_URL2 = "https://api.aaa-sentinel.com";
13586
13967
  function pair(id, secret) {
13587
13968
  return id && secret ? { clientId: id, clientSecret: secret } : null;
13588
13969
  }
@@ -13611,10 +13992,17 @@ async function comment(argv) {
13611
13992
  if (outcome.stdout) console.log(outcome.stdout);
13612
13993
  process.exitCode = outcome.exitCode;
13613
13994
  }
13995
+ async function envCost(argv) {
13996
+ const outcome = await runEnvCostCli(argv, { env: process.env });
13997
+ for (const warning of outcome.warnings) console.warn(`iac-cost: ${warning}`);
13998
+ if (outcome.stdout) console.log(outcome.stdout);
13999
+ process.exitCode = outcome.exitCode;
14000
+ }
13614
14001
  async function main() {
13615
14002
  if (process.argv[2] === "fix") return fix(process.argv.slice(3));
13616
14003
  if (process.argv[2] === "posture") return posture(process.argv.slice(3));
13617
14004
  if (process.argv[2] === "comment") return comment(process.argv.slice(3));
14005
+ if (process.argv[2] === "env-cost") return envCost(process.argv.slice(3));
13618
14006
  const options = parseCliArgs(process.argv.slice(2), process.env);
13619
14007
  if ("error" in options) {
13620
14008
  console.error(`iac-cost: ${options.error}
@@ -13628,7 +14016,7 @@ ${USAGE}`);
13628
14016
  return;
13629
14017
  }
13630
14018
  const credentials = {
13631
- baseUrl: resolveBaseUrl(process.env["IAC_COST_BASE_URL"] ?? DEFAULT_BASE_URL),
14019
+ baseUrl: resolveBaseUrl(process.env["IAC_COST_BASE_URL"] ?? DEFAULT_BASE_URL2),
13632
14020
  cost: pair(process.env["IAC_COST_CLIENT_ID"], process.env["IAC_COST_CLIENT_SECRET"]),
13633
14021
  security: pair(process.env["IAC_SECURITY_CLIENT_ID"], process.env["IAC_SECURITY_CLIENT_SECRET"])
13634
14022
  };
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.9.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
+ }