@aaa-sentinel/iac-cost 0.5.0 → 0.6.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.
- package/README.md +101 -2
- package/dist/cli.js +361 -106
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -7,6 +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.6.0:** GitLab CI, on gitlab.com and self-managed GitLab. The `comment` subcommand posts
|
|
11
|
+
> the output as a note on the merge request and updates it on later pushes (see [GitLab CI](#gitlab-ci)),
|
|
12
|
+
> and `fix` opens merge requests (see [GitLab CI](#gitlab-ci-1) under fixes). Nothing changes on GitHub
|
|
13
|
+
> or Bitbucket.
|
|
14
|
+
|
|
10
15
|
> **New in 0.4.0:** the `posture` subcommand prints how the security posture of an account changed
|
|
11
16
|
> over 30, 90 or 365 days, with an optional gate on new findings (see
|
|
12
17
|
> [Posture over time](#posture-over-time)). Nothing changes for `fix` or the existing command.
|
|
@@ -48,6 +53,8 @@ console changes (see [Fixes as pull requests](#fixes-as-pull-requests)).
|
|
|
48
53
|
- For **`iac-cost fix`**, an application with the `security:fix` scope, the security add-on on the
|
|
49
54
|
account, and a CI token that can push a branch and open a pull request (see
|
|
50
55
|
[Fixes as pull requests](#fixes-as-pull-requests)).
|
|
56
|
+
- On **GitLab**, a project access token of your own for the note or the merge request: the job
|
|
57
|
+
token (`CI_JOB_TOKEN`) cannot write notes or open merge requests (see [GitLab CI](#gitlab-ci)).
|
|
51
58
|
|
|
52
59
|
## Usage
|
|
53
60
|
|
|
@@ -416,6 +423,65 @@ pipelines:
|
|
|
416
423
|
> `content.raw`, hence the `// ""` — without it `jq` aborts and the comment is posted again
|
|
417
424
|
> instead of updated.
|
|
418
425
|
|
|
426
|
+
## GitLab CI
|
|
427
|
+
|
|
428
|
+
Works on gitlab.com and on self-managed GitLab. Instead of a shell snippet that calls the API, the CLI
|
|
429
|
+
posts the note itself: `iac-cost comment` reads the Markdown, finds the note it left
|
|
430
|
+
before on the merge request (by the hidden marker and the token's own user, across every page of
|
|
431
|
+
notes) and **updates it in place**, or creates it the first time.
|
|
432
|
+
|
|
433
|
+
`CI_JOB_TOKEN` cannot write notes through the API, so create a **project access token**
|
|
434
|
+
(*Settings → Access tokens*) with the **`api`** scope and the **Reporter** role, and store it as a
|
|
435
|
+
**masked** CI/CD variable named `GITLAB_TOKEN`. On gitlab.com, project and group access tokens are
|
|
436
|
+
Premium/Ultimate; on the Free tier use a
|
|
437
|
+
[service account](https://docs.gitlab.com/user/profile/service_accounts/) (up to 100 per top-level
|
|
438
|
+
group), add it to the project with the Reporter role and use its token with the `api` scope. Keep this token at Reporter: it is readable by
|
|
439
|
+
every branch's pipeline (see below), so it must not be the token that can push. Do not mark it *protected*: the job runs on the merge
|
|
440
|
+
request's source branch, which is usually not protected, and a protected variable would not reach it.
|
|
441
|
+
The same applies to `IAC_COST_CLIENT_ID`/`IAC_COST_CLIENT_SECRET`. If you protect your source
|
|
442
|
+
branches (or use protected variables only on protected branches on purpose), the comment is skipped
|
|
443
|
+
on the others.
|
|
444
|
+
|
|
445
|
+
```yaml
|
|
446
|
+
iac-cost:
|
|
447
|
+
image:
|
|
448
|
+
name: hashicorp/terraform:latest
|
|
449
|
+
entrypoint: [""]
|
|
450
|
+
rules:
|
|
451
|
+
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
|
|
452
|
+
script:
|
|
453
|
+
- apk add --no-cache nodejs npm
|
|
454
|
+
- terraform init
|
|
455
|
+
- terraform plan -out=plan.tfplan
|
|
456
|
+
- terraform show -json plan.tfplan > plan.json
|
|
457
|
+
- npx --yes @aaa-sentinel/iac-cost plan.json > comment.md
|
|
458
|
+
# GITLAB_TOKEN (Reporter, api), IAC_COST_CLIENT_ID and IAC_COST_CLIENT_SECRET: masked CI/CD variables.
|
|
459
|
+
- npx --yes @aaa-sentinel/iac-cost comment comment.md || true
|
|
460
|
+
# Optional gate: fails on critical or high findings.
|
|
461
|
+
- npx --yes @aaa-sentinel/iac-cost plan.json --no-cost --format text --fail-on high
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
`iac-cost comment` always exits 0: without `GITLAB_TOKEN`, outside a merge request pipeline, on a
|
|
465
|
+
merge request from a fork or when GitLab answers with an error, it prints one line saying why and the
|
|
466
|
+
pipeline goes on. The `|| true` only covers npm itself being unreachable.
|
|
467
|
+
|
|
468
|
+
- **Self-managed GitLab:** the server comes from `CI_SERVER_URL` and the API from `CI_API_V4_URL`,
|
|
469
|
+
which GitLab sets on every job. Before sending the token, the CLI checks that both are `https`, on
|
|
470
|
+
the same origin, name the server by its DNS name (not an IP address) and carry no credentials,
|
|
471
|
+
query or path (GitLab under a relative URL path, such as `https://example.com/gitlab`, is not
|
|
472
|
+
supported). It never follows a redirect with the token. This is defence in depth, not a boundary:
|
|
473
|
+
anyone who can push a branch can override those variables in that branch's `variables:`, and can
|
|
474
|
+
already read any unprotected variable that reaches it.
|
|
475
|
+
- **Merge requests from forks:** a pipeline that runs in the fork does not get the project's
|
|
476
|
+
variables, so there is no token. If you run pipelines **in the parent project** for merge requests
|
|
477
|
+
from forks, they run the fork's `.gitlab-ci.yml` with your unprotected variables, which the fork's
|
|
478
|
+
code can read whatever this CLI does: do not enable that while `GITLAB_TOKEN` is unprotected. In
|
|
479
|
+
both cases `iac-cost comment` skips the comment with a warning.
|
|
480
|
+
- Only notes written by the token's own user are updated: a note from anyone else that contains the
|
|
481
|
+
marker is left alone. Each project access token has its own bot user, so after rotating the token
|
|
482
|
+
the next run adds a new note instead of updating the old one (delete the old one by hand).
|
|
483
|
+
- With an empty input it prints a warning and leaves the merge request as it is.
|
|
484
|
+
|
|
419
485
|
## Fixes as pull requests
|
|
420
486
|
|
|
421
487
|
If a resource is managed by Terraform, fixing it in the console creates drift: the next
|
|
@@ -481,7 +547,7 @@ the reason, and the app shows it that way:
|
|
|
481
547
|
| `no_public_access_block` | The bucket has no `aws_s3_bucket_public_access_block` to edit |
|
|
482
548
|
| `replacement_required` | The fix forces a new resource (RDS encryption, Cloud SQL CMEK) |
|
|
483
549
|
| `ignore_changes` | `lifecycle { ignore_changes }` covers the attribute (or has a comment inside the list): Terraform would not apply the change |
|
|
484
|
-
| `unsupported_host` | GitHub Enterprise Server (`GITHUB_API_URL` is not `https://api.github.com`): not supported yet, the app only links pull requests on github.com
|
|
550
|
+
| `unsupported_host` | GitHub Enterprise Server (`GITHUB_API_URL` is not `https://api.github.com`): not supported yet, the app only links pull requests on github.com, bitbucket.org and GitLab |
|
|
485
551
|
| `cause_not_in_code` | The open value is not in the code (added by hand, or a provider default) |
|
|
486
552
|
| `block_not_found` | The `resource` block could not be read (`.tf.json`, or a layout the editor does not handle) |
|
|
487
553
|
| `rule_not_automated` | No deterministic code fix for that rule |
|
|
@@ -498,7 +564,7 @@ review its `terraform plan` before merging. The finding closes after `terraform
|
|
|
498
564
|
| `--account <accountId>` | AAA Sentinel account id. Also `IAC_FIX_ACCOUNT_ID` |
|
|
499
565
|
| `--dir <path>` | Directory where `terraform plan` ran (default: current). The repository root is the nearest `.git` above it |
|
|
500
566
|
| `--max-prs <n>` | Pull requests opened per run (default 5, `0` records without opening) |
|
|
501
|
-
| `--host <github\|bitbucket>` | Git host. Detected from the CI by default |
|
|
567
|
+
| `--host <github\|bitbucket\|gitlab>` | Git host. Detected from the CI by default |
|
|
502
568
|
| `--dry-run` | Prints the changes; opens nothing and records nothing. Works without a git host |
|
|
503
569
|
| `--allow-public-repo` | Opens pull requests on a public repository too |
|
|
504
570
|
| `--format <text\|json>` | Output format |
|
|
@@ -571,6 +637,39 @@ pipelines:
|
|
|
571
637
|
|
|
572
638
|
The commit is created through the Bitbucket API (`POST /src`), so the clone needs no push access.
|
|
573
639
|
|
|
640
|
+
### GitLab CI
|
|
641
|
+
|
|
642
|
+
Opens one **merge request** per finding, on gitlab.com or self-managed GitLab (same checks on
|
|
643
|
+
`CI_SERVER_URL` and `CI_API_V4_URL` as [the comment](#gitlab-ci)). Create a **project access token**
|
|
644
|
+
with the **Developer** role and the **`api`** scope and store it as a **masked and protected** variable
|
|
645
|
+
named `GITLAB_FIX_TOKEN` (the job runs on the branch you deploy, which is protected); on the Free
|
|
646
|
+
tier of gitlab.com, the token of a service account with the Developer role. It never falls
|
|
647
|
+
back to `GITLAB_TOKEN`: that one is unprotected for the comment job, and a token that can push must not
|
|
648
|
+
be readable from every branch.
|
|
649
|
+
|
|
650
|
+
```yaml
|
|
651
|
+
security-fixes:
|
|
652
|
+
image:
|
|
653
|
+
name: hashicorp/terraform:latest
|
|
654
|
+
entrypoint: [""]
|
|
655
|
+
rules:
|
|
656
|
+
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
|
|
657
|
+
script:
|
|
658
|
+
- apk add --no-cache nodejs npm
|
|
659
|
+
- terraform init
|
|
660
|
+
- terraform plan -out=plan.tfplan
|
|
661
|
+
- terraform show -json plan.tfplan > plan.json
|
|
662
|
+
# GITLAB_FIX_TOKEN (Developer, api), IAC_FIX_CLIENT_ID and IAC_FIX_CLIENT_SECRET: masked, protected variables.
|
|
663
|
+
- npx --yes @aaa-sentinel/iac-cost fix plan.json --account "$AAA_SENTINEL_ACCOUNT_ID" || true
|
|
664
|
+
```
|
|
665
|
+
|
|
666
|
+
The branch and the commit are created in one call to the GitLab API (`POST /repository/commits` from
|
|
667
|
+
the deployed commit), so the clone needs no push access. A project with **internal** visibility counts
|
|
668
|
+
as public (every user of the server, or of gitlab.com, can read it): pass `--allow-public-repo` if
|
|
669
|
+
that is acceptable. It refuses to run on a merge request or tag pipeline, and on a branch that is not
|
|
670
|
+
protected (`CI_COMMIT_REF_PROTECTED` is not `true`): the token that can push lives in a protected
|
|
671
|
+
variable, so an unprotected branch means the setup is wrong. Protect the branch you deploy.
|
|
672
|
+
|
|
574
673
|
## Posture over time
|
|
575
674
|
|
|
576
675
|
`iac-cost posture` reads `GET /v1/security/posture-history` and prints, for one account and a
|
package/dist/cli.js
CHANGED
|
@@ -15,6 +15,7 @@ var SEVERITIES = ["critical", "high", "medium", "low"];
|
|
|
15
15
|
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
|
+
iac-cost comment [comment.md] (note on the GitLab merge request, see iac-cost comment --help)
|
|
18
19
|
|
|
19
20
|
Reads \`terraform show -json\` output from the file or from stdin.
|
|
20
21
|
|
|
@@ -87,6 +88,249 @@ function parseCliArgs(argv, env) {
|
|
|
87
88
|
};
|
|
88
89
|
}
|
|
89
90
|
|
|
91
|
+
// src/comment.ts
|
|
92
|
+
import { parseArgs as parseArgs2 } from "node:util";
|
|
93
|
+
|
|
94
|
+
// ../../shared/dist/security-code-fix.js
|
|
95
|
+
var CODE_FIX_STATES = ["pending", "pr_open", "merged", "closed", "suggested"];
|
|
96
|
+
var CODE_FIX_PR_STATES = ["pr_open", "merged", "closed"];
|
|
97
|
+
var CODE_FIX_HOSTS = ["github", "bitbucket", "gitlab"];
|
|
98
|
+
var CODE_FIX_SERVER_PATTERN = /^(?=[^:]{1,253}(:|$))([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]([a-z0-9-]{0,61}[a-z0-9])?(:[1-9][0-9]{0,4})?$/;
|
|
99
|
+
function isCodeFixServer(server) {
|
|
100
|
+
if (!CODE_FIX_SERVER_PATTERN.test(server))
|
|
101
|
+
return false;
|
|
102
|
+
const port = server.split(":")[1];
|
|
103
|
+
return port === void 0 || Number(port) <= 65535 && port !== "443";
|
|
104
|
+
}
|
|
105
|
+
var GITLAB_COM = "gitlab.com";
|
|
106
|
+
var CODE_FIX_GITLAB_REPOSITORY_PATTERN = /^[A-Za-z0-9_][\w.-]*(\/[A-Za-z0-9_][\w.-]*){1,19}$/;
|
|
107
|
+
function pullRequestUrl(host, repository, number3, server) {
|
|
108
|
+
if (host === "gitlab")
|
|
109
|
+
return `https://${server ?? GITLAB_COM}/${repository}/-/merge_requests/${number3}`;
|
|
110
|
+
return host === "github" ? `https://github.com/${repository}/pull/${number3}` : `https://bitbucket.org/${repository}/pull-requests/${number3}`;
|
|
111
|
+
}
|
|
112
|
+
var CODE_FIX_REPORT_MAX = 100;
|
|
113
|
+
|
|
114
|
+
// src/gitlab.ts
|
|
115
|
+
function parseHttps(raw, name) {
|
|
116
|
+
let url;
|
|
117
|
+
try {
|
|
118
|
+
url = new URL(raw);
|
|
119
|
+
} catch {
|
|
120
|
+
return { error: `${name} is not a URL` };
|
|
121
|
+
}
|
|
122
|
+
if (url.protocol !== "https:") return { error: `${name} must be an https URL: the GitLab token is never sent over plain HTTP` };
|
|
123
|
+
if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") {
|
|
124
|
+
return { error: `${name} must not carry credentials, a query or a fragment` };
|
|
125
|
+
}
|
|
126
|
+
return url;
|
|
127
|
+
}
|
|
128
|
+
function resolveGitLabServer(env) {
|
|
129
|
+
const server = parseHttps(env["CI_SERVER_URL"] || `https://${GITLAB_COM}`, "CI_SERVER_URL");
|
|
130
|
+
if ("error" in server) return server;
|
|
131
|
+
if (server.pathname !== "/" && server.pathname !== "") return { error: "CI_SERVER_URL must be the root of the GitLab server: GitLab under a relative URL path is not supported" };
|
|
132
|
+
const host = server.host.replace(/\.(?=:|$)/, "");
|
|
133
|
+
if (host !== GITLAB_COM && !isCodeFixServer(host)) {
|
|
134
|
+
return { error: "CI_SERVER_URL must name the GitLab server by its DNS name (not an IP address or a single-label name)" };
|
|
135
|
+
}
|
|
136
|
+
const api = parseHttps(env["CI_API_V4_URL"] || `${server.origin}/api/v4`, "CI_API_V4_URL");
|
|
137
|
+
if ("error" in api) return api;
|
|
138
|
+
if (api.origin !== server.origin) return { error: "CI_API_V4_URL must be on the same server as CI_SERVER_URL" };
|
|
139
|
+
if (api.pathname.replace(/\/+$/, "") !== "/api/v4") return { error: "CI_API_V4_URL must be <CI_SERVER_URL>/api/v4" };
|
|
140
|
+
return { apiUrl: `${server.origin}/api/v4`, server: host === GITLAB_COM ? void 0 : host };
|
|
141
|
+
}
|
|
142
|
+
var TIMEOUT_MS = 3e4;
|
|
143
|
+
var GitLabError = class extends Error {
|
|
144
|
+
constructor(status, message) {
|
|
145
|
+
super(message);
|
|
146
|
+
this.status = status;
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
async function gitLabCall(fetchImpl, url, token, init, label) {
|
|
150
|
+
const response = await fetchImpl(url, {
|
|
151
|
+
method: init.method ?? "GET",
|
|
152
|
+
headers: {
|
|
153
|
+
"private-token": token,
|
|
154
|
+
accept: init.accept ?? "application/json",
|
|
155
|
+
"user-agent": "aaa-sentinel-iac-cost",
|
|
156
|
+
...init.body !== void 0 ? { "content-type": "application/json" } : {}
|
|
157
|
+
},
|
|
158
|
+
...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {},
|
|
159
|
+
// Una redirección podría llevar el token a otro origen: se corta en vez de seguirla.
|
|
160
|
+
redirect: "error",
|
|
161
|
+
signal: AbortSignal.timeout(TIMEOUT_MS)
|
|
162
|
+
});
|
|
163
|
+
if (!response.ok && response.status !== 404) {
|
|
164
|
+
let detail = "";
|
|
165
|
+
try {
|
|
166
|
+
const body2 = await response.json();
|
|
167
|
+
const message = typeof body2.message === "string" ? body2.message : body2.message !== void 0 ? JSON.stringify(body2.message) : typeof body2.error === "string" ? body2.error : "";
|
|
168
|
+
detail = message ? `: ${message.slice(0, 200)}` : "";
|
|
169
|
+
} catch {
|
|
170
|
+
detail = "";
|
|
171
|
+
}
|
|
172
|
+
throw new GitLabError(response.status, `${label} failed with HTTP ${response.status}${detail}`);
|
|
173
|
+
}
|
|
174
|
+
return response;
|
|
175
|
+
}
|
|
176
|
+
var isNumericId = (value) => value !== void 0 && /^[1-9][0-9]{0,18}$/.test(value);
|
|
177
|
+
|
|
178
|
+
// src/render-comment.ts
|
|
179
|
+
var COMMENT_MARKER = "<!-- aaa-sentinel:iac-cost -->";
|
|
180
|
+
var REASON_TEXT = {
|
|
181
|
+
provider_not_supported: "provider not covered yet",
|
|
182
|
+
provider_not_priced: "provider recognized, pricing not connected yet",
|
|
183
|
+
resource_type_not_priced: "resource type not in the priced catalog yet",
|
|
184
|
+
region_unknown: "region could not be resolved from the plan",
|
|
185
|
+
region_not_supported: "region not in the price catalog",
|
|
186
|
+
size_unknown: "size/SKU could not be resolved from the plan",
|
|
187
|
+
instance_count_unknown: "instance count could not be resolved from the plan",
|
|
188
|
+
attribute_unknown: "a price-relevant attribute (engine, Multi-AZ, storage\u2026) could not be resolved from the plan",
|
|
189
|
+
price_unavailable: "the price catalog did not answer this time; a later run retries",
|
|
190
|
+
price_lookup_limit: "too many distinct database configurations in one plan to look up in a single request",
|
|
191
|
+
price_not_found: "no matching price found in the catalog"
|
|
192
|
+
};
|
|
193
|
+
var fmtUsd = (n) => `${n < 0 ? "-" : "+"}$${Math.abs(n).toFixed(2)}/mo`;
|
|
194
|
+
function fmtConverted(n, currency) {
|
|
195
|
+
const amount = new Intl.NumberFormat("en-US", { style: "currency", currency }).format(Math.abs(n));
|
|
196
|
+
return `\u2248 ${n < 0 ? "-" : "+"}${amount}/mo`;
|
|
197
|
+
}
|
|
198
|
+
var LIST_PRICE_CAVEAT = "They also do not reflect committed-use discounts (EDP/EA/CUD) or existing reservations/Savings Plans that may already cover a resource. Usage-based charges (data transfer, backups beyond the allocated storage, I/O requests, CPU credits), storage growth from autoscaling (`max_allocated_storage`), RDS Extended Support and paid Performance Insights retention are not included.";
|
|
199
|
+
var reasonText = (reason) => REASON_TEXT[reason] ?? reason;
|
|
200
|
+
function actionVerb(action) {
|
|
201
|
+
return action === "create" ? "new" : action === "delete" ? "removed" : action;
|
|
202
|
+
}
|
|
203
|
+
function renderComment(estimate) {
|
|
204
|
+
const { coverage } = estimate;
|
|
205
|
+
const lines2 = [COMMENT_MARKER, "### \u{1F4B2} Infrastructure cost estimate", ""];
|
|
206
|
+
lines2.push(
|
|
207
|
+
`**Coverage: ${coverage.pricedResources} of ${coverage.pricedResources + coverage.unpricedResources} billable resources priced** (${coverage.freeResources} more have no cost by design).`
|
|
208
|
+
);
|
|
209
|
+
lines2.push("");
|
|
210
|
+
const display = estimate.displayCurrency?.approximate ? estimate.displayCurrency : null;
|
|
211
|
+
const delta = (usd, converted) => display && typeof converted === "number" ? fmtConverted(converted, display.code) : fmtUsd(usd);
|
|
212
|
+
if (estimate.totalMonthlyDeltaUsd !== null) {
|
|
213
|
+
const total2 = delta(estimate.totalMonthlyDeltaUsd, estimate.totalMonthlyDelta);
|
|
214
|
+
lines2.push(
|
|
215
|
+
display ? `**Estimated change: ${total2}** (list price, ${fmtUsd(estimate.totalMonthlyDeltaUsd)} in USD)` : `**Estimated change: ${total2}** (list price, USD)`
|
|
216
|
+
);
|
|
217
|
+
} else {
|
|
218
|
+
lines2.push(
|
|
219
|
+
`_Coverage is below the threshold needed to publish a total \u2014 see the breakdown below instead of a number that wouldn't hold up._`
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
lines2.push("");
|
|
223
|
+
lines2.push(
|
|
224
|
+
display ? `> These are **list prices**, not what you actually pay. Cloud providers publish them in USD; the amounts shown are **approximate**, converted to ${display.code} at the ECB reference rate${display.rateDate ? ` of ${display.rateDate}` : ""} (1 USD = ${display.rate} ${display.code}). ` + LIST_PRICE_CAVEAT : `> These are **list prices in USD**, not what you actually pay. Cloud providers set their list prices in USD, so showing this in another billing currency would be an estimate on top of an estimate. ${LIST_PRICE_CAVEAT}`
|
|
225
|
+
);
|
|
226
|
+
if (estimate.priced.length > 0) {
|
|
227
|
+
lines2.push("", "| Resource | Change | Qty | Delta |", "|---|---|---|---|");
|
|
228
|
+
for (const item of estimate.priced) {
|
|
229
|
+
const assumed = item.assumedDefaults?.length ? " \u2020" : "";
|
|
230
|
+
lines2.push(
|
|
231
|
+
`| \`${item.type}\`${assumed} | ${actionVerb(item.action)} | ${item.count} | ${delta(item.monthlyDeltaUsd, item.monthlyDelta)} |`
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
const assumedNames = [...new Set(estimate.priced.flatMap((i) => i.assumedDefaults ?? []))].sort();
|
|
235
|
+
if (assumedNames.length > 0) {
|
|
236
|
+
lines2.push(
|
|
237
|
+
"",
|
|
238
|
+
`\u2020 Not set in the Terraform configuration, so the AWS default was assumed for: ${assumedNames.map((n) => `\`${n}\``).join(", ")}. Set them explicitly if your deployment differs.`
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (estimate.unpriced.length > 0) {
|
|
243
|
+
lines2.push("", "<details><summary>Not priced (" + coverage.unpricedResources + " resources)</summary>", "");
|
|
244
|
+
lines2.push("| Resource | Change | Qty | Why |", "|---|---|---|---|");
|
|
245
|
+
for (const item of estimate.unpriced) {
|
|
246
|
+
lines2.push(`| \`${item.type}\` | ${actionVerb(item.action)} | ${item.count} | ${reasonText(item.reason)} |`);
|
|
247
|
+
}
|
|
248
|
+
lines2.push("", "</details>");
|
|
249
|
+
}
|
|
250
|
+
const truncated = estimate.catalogs.filter((c) => c.truncated);
|
|
251
|
+
if (truncated.length > 0) {
|
|
252
|
+
lines2.push(
|
|
253
|
+
"",
|
|
254
|
+
`\u26A0\uFE0F The price catalog for ${truncated.map((c) => c.region).join(", ")} was truncated by pagination: some prices may be missing.`
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
return lines2.join("\n");
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// src/comment.ts
|
|
261
|
+
var COMMENT_USAGE = `Usage: iac-cost comment [comment.md]
|
|
262
|
+
|
|
263
|
+
Posts the Markdown written by iac-cost (from the file or stdin) as a note on
|
|
264
|
+
the GitLab merge request of this pipeline, and updates that note on later runs
|
|
265
|
+
instead of adding another. Run it in a merge request pipeline
|
|
266
|
+
(rules: if $CI_PIPELINE_SOURCE == "merge_request_event").
|
|
267
|
+
|
|
268
|
+
Environment:
|
|
269
|
+
GITLAB_TOKEN Token with the api scope and the Reporter role: a project access
|
|
270
|
+
token, or on gitlab.com Free the token of a service account
|
|
271
|
+
added to the project. CI_JOB_TOKEN cannot write notes.
|
|
272
|
+
|
|
273
|
+
It always exits 0: when it cannot comment it prints why and the pipeline goes on.
|
|
274
|
+
On GitHub Actions and Bitbucket Pipelines, use the snippets in the README.`;
|
|
275
|
+
var MAX_NOTE_PAGES = 100;
|
|
276
|
+
async function runCommentCli(argv, io) {
|
|
277
|
+
const warnings = [];
|
|
278
|
+
const skip = (message) => ({ stdout: null, warnings: [...warnings, message], exitCode: 0 });
|
|
279
|
+
const { values, positionals } = parseArgs2({ args: [...argv], strict: false, allowPositionals: true, options: { help: { type: "boolean", short: "h" } } });
|
|
280
|
+
for (const name of Object.keys(values)) if (name !== "help" && name !== "h") warnings.push(`unknown option --${name} ignored`);
|
|
281
|
+
if (values["help"] === true || values["h"] === true) return { stdout: COMMENT_USAGE, warnings, exitCode: 0 };
|
|
282
|
+
if (positionals.length > 1) warnings.push(`only one file is read, ignoring ${positionals.slice(1).join(" ")}`);
|
|
283
|
+
let markdown;
|
|
284
|
+
try {
|
|
285
|
+
markdown = io.readBody(positionals[0] ?? null);
|
|
286
|
+
} catch (error2) {
|
|
287
|
+
return skip(`could not read the comment, skipping: ${error2.message}`);
|
|
288
|
+
}
|
|
289
|
+
if (markdown.trim() === "") return skip("nothing to comment (empty input), the merge request is left as it is");
|
|
290
|
+
const { env } = io;
|
|
291
|
+
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
|
+
const iid = env["CI_MERGE_REQUEST_IID"];
|
|
293
|
+
if (!iid) return skip('not a merge request pipeline, skipping the comment: run the job with `rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event"`');
|
|
294
|
+
const target = env["CI_MERGE_REQUEST_PROJECT_ID"] ?? env["CI_PROJECT_ID"];
|
|
295
|
+
const source = env["CI_MERGE_REQUEST_SOURCE_PROJECT_ID"];
|
|
296
|
+
if (source !== void 0 && target !== void 0 && source !== target) {
|
|
297
|
+
return skip("merge request from a fork, skipping the comment");
|
|
298
|
+
}
|
|
299
|
+
const token = env["GITLAB_TOKEN"];
|
|
300
|
+
if (!token) return skip("GITLAB_TOKEN is not set, skipping the comment: store a token with the api scope and the Reporter role as a masked variable (CI_JOB_TOKEN cannot write notes)");
|
|
301
|
+
if (!isNumericId(iid) || !isNumericId(target)) return skip("CI_MERGE_REQUEST_IID and CI_MERGE_REQUEST_PROJECT_ID must be numeric, skipping the comment");
|
|
302
|
+
const server = resolveGitLabServer(env);
|
|
303
|
+
if ("error" in server) return skip(`${server.error}, skipping the comment`);
|
|
304
|
+
const fetchImpl = io.fetchImpl ?? fetch;
|
|
305
|
+
const notesUrl = `${server.apiUrl}/projects/${target}/merge_requests/${iid}/notes`;
|
|
306
|
+
const body2 = markdown.includes(COMMENT_MARKER) ? markdown : `${COMMENT_MARKER}
|
|
307
|
+
${markdown}`;
|
|
308
|
+
try {
|
|
309
|
+
const me = await (await gitLabCall(fetchImpl, `${server.apiUrl}/user`, token, {}, "read token user")).json();
|
|
310
|
+
if (typeof me.id !== "number") throw new Error("read token user returned no id");
|
|
311
|
+
let existing = null;
|
|
312
|
+
for (let page = 1; page <= MAX_NOTE_PAGES && existing === null; page++) {
|
|
313
|
+
const response = await gitLabCall(fetchImpl, `${notesUrl}?sort=asc&order_by=created_at&per_page=100&page=${page}`, token, {}, "list merge request notes");
|
|
314
|
+
if (response.status === 404) throw new Error(`merge request !${iid} not found (does the token belong to this project?)`);
|
|
315
|
+
const notes = await response.json();
|
|
316
|
+
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));
|
|
318
|
+
if (mine && typeof mine.id === "number") existing = mine.id;
|
|
319
|
+
if (response.headers.get("x-next-page") === "" || notes.length < 100) break;
|
|
320
|
+
}
|
|
321
|
+
if (existing !== null) {
|
|
322
|
+
const updated = await gitLabCall(fetchImpl, `${notesUrl}/${existing}`, token, { method: "PUT", body: { body: body2 } }, "update note");
|
|
323
|
+
if (updated.status === 404) throw new Error("update note failed with HTTP 404");
|
|
324
|
+
return { stdout: `Updated the note on merge request !${iid}`, warnings, exitCode: 0 };
|
|
325
|
+
}
|
|
326
|
+
const created = await gitLabCall(fetchImpl, notesUrl, token, { method: "POST", body: { body: body2 } }, "create note");
|
|
327
|
+
if (created.status === 404) throw new Error("create note failed with HTTP 404 (does the token have the api scope?)");
|
|
328
|
+
return { stdout: `Commented on merge request !${iid}`, warnings, exitCode: 0 };
|
|
329
|
+
} catch (error2) {
|
|
330
|
+
return skip(`could not comment on the merge request, continuing: ${error2.message}`);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
90
334
|
// ../../node_modules/zod/v4/core/util.js
|
|
91
335
|
var util_exports = {};
|
|
92
336
|
__export(util_exports, {
|
|
@@ -6542,17 +6786,11 @@ async function estimatePlan(projection, config2) {
|
|
|
6542
6786
|
|
|
6543
6787
|
// src/fix/cli-fix.ts
|
|
6544
6788
|
import path2 from "node:path";
|
|
6545
|
-
import { parseArgs as
|
|
6546
|
-
|
|
6547
|
-
// ../../shared/dist/security-code-fix.js
|
|
6548
|
-
var CODE_FIX_STATES = ["pending", "pr_open", "merged", "closed", "suggested"];
|
|
6549
|
-
var CODE_FIX_PR_STATES = ["pr_open", "merged", "closed"];
|
|
6550
|
-
var CODE_FIX_HOSTS = ["github", "bitbucket"];
|
|
6551
|
-
var CODE_FIX_REPORT_MAX = 100;
|
|
6789
|
+
import { parseArgs as parseArgs3 } from "node:util";
|
|
6552
6790
|
|
|
6553
6791
|
// src/fix/api.ts
|
|
6554
6792
|
var SCOPE = "security:fix";
|
|
6555
|
-
var
|
|
6793
|
+
var TIMEOUT_MS2 = 35e3;
|
|
6556
6794
|
function codeFixApi(config2) {
|
|
6557
6795
|
const fetchImpl = config2.fetchImpl ?? fetch;
|
|
6558
6796
|
const url = `${config2.baseUrl}/v1/security/code-fixes?accountId=${encodeURIComponent(config2.accountId)}`;
|
|
@@ -6563,7 +6801,7 @@ function codeFixApi(config2) {
|
|
|
6563
6801
|
};
|
|
6564
6802
|
return {
|
|
6565
6803
|
async load() {
|
|
6566
|
-
const response = await fetchImpl(url, { headers: { authorization: `Bearer ${await bearer()}` }, signal: AbortSignal.timeout(
|
|
6804
|
+
const response = await fetchImpl(url, { headers: { authorization: `Bearer ${await bearer()}` }, signal: AbortSignal.timeout(TIMEOUT_MS2) });
|
|
6567
6805
|
if (!response.ok) throw new Error(`code_fixes_http_${response.status}`);
|
|
6568
6806
|
const body2 = await response.json();
|
|
6569
6807
|
const findings = (body2.findings ?? []).flatMap(
|
|
@@ -6598,7 +6836,7 @@ function codeFixApi(config2) {
|
|
|
6598
6836
|
method: "POST",
|
|
6599
6837
|
headers: { authorization: `Bearer ${await bearer()}`, "content-type": "application/json" },
|
|
6600
6838
|
body: JSON.stringify({ fixes: fixes.slice(i, i + CODE_FIX_REPORT_MAX) }),
|
|
6601
|
-
signal: AbortSignal.timeout(
|
|
6839
|
+
signal: AbortSignal.timeout(TIMEOUT_MS2)
|
|
6602
6840
|
});
|
|
6603
6841
|
if (!response.ok) throw new Error(`code_fixes_report_http_${response.status}`);
|
|
6604
6842
|
const body2 = await response.json();
|
|
@@ -6617,7 +6855,7 @@ function codeFixApi(config2) {
|
|
|
6617
6855
|
// src/fix/hosts.ts
|
|
6618
6856
|
var encodePath = (path3) => path3.split("/").map(encodeURIComponent).join("/");
|
|
6619
6857
|
var decodeKeepingBom = (buffer) => new TextDecoder("utf-8", { ignoreBOM: true }).decode(buffer);
|
|
6620
|
-
var
|
|
6858
|
+
var TIMEOUT_MS3 = 3e4;
|
|
6621
6859
|
var HostError = class extends Error {
|
|
6622
6860
|
constructor(status, message) {
|
|
6623
6861
|
super(message);
|
|
@@ -6625,7 +6863,7 @@ var HostError = class extends Error {
|
|
|
6625
6863
|
}
|
|
6626
6864
|
};
|
|
6627
6865
|
async function call(fetchImpl, url, init, label) {
|
|
6628
|
-
const response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(
|
|
6866
|
+
const response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(TIMEOUT_MS3) });
|
|
6629
6867
|
if (!response.ok && response.status !== 404) {
|
|
6630
6868
|
let detail = "";
|
|
6631
6869
|
try {
|
|
@@ -6792,10 +7030,96 @@ function bitbucketHost(config2) {
|
|
|
6792
7030
|
}
|
|
6793
7031
|
};
|
|
6794
7032
|
}
|
|
7033
|
+
var encodeGitLabPath = (value) => encodeURIComponent(value).replace(/\./g, "%2E");
|
|
7034
|
+
function gitLabHost(config2) {
|
|
7035
|
+
const fetchImpl = config2.fetchImpl ?? fetch;
|
|
7036
|
+
const api = `${config2.apiUrl}/projects/${encodeURIComponent(config2.projectId)}`;
|
|
7037
|
+
const send = (path3, label, init = {}) => gitLabCall(fetchImpl, `${api}${path3}`, config2.token, init, label);
|
|
7038
|
+
const link = (iid) => pullRequestUrl("gitlab", config2.repository, iid, config2.server);
|
|
7039
|
+
const stateOf = (state) => state === "merged" ? "merged" : state === "closed" ? "closed" : "open";
|
|
7040
|
+
return {
|
|
7041
|
+
kind: "gitlab",
|
|
7042
|
+
repository: config2.repository,
|
|
7043
|
+
server: config2.server,
|
|
7044
|
+
baseBranch: config2.baseBranch,
|
|
7045
|
+
baseSha: config2.baseSha,
|
|
7046
|
+
unsupported: false,
|
|
7047
|
+
async branchExists(branch) {
|
|
7048
|
+
const response = await send(`/repository/branches/${encodeGitLabPath(branch)}`, "read branch");
|
|
7049
|
+
return response.status !== 404;
|
|
7050
|
+
},
|
|
7051
|
+
async findPullRequest(branch) {
|
|
7052
|
+
const q = `source_branch=${encodeURIComponent(branch)}&state=all&order_by=created_at&sort=desc&per_page=100`;
|
|
7053
|
+
const response = await send(`/merge_requests?${q}`, "list merge requests");
|
|
7054
|
+
if (response.status === 404) return null;
|
|
7055
|
+
const list = await response.json();
|
|
7056
|
+
const project = Number(config2.projectId);
|
|
7057
|
+
const mr = Array.isArray(list) ? list.find((m) => m.source_branch === branch && m.source_project_id === project && m.target_project_id === project) : void 0;
|
|
7058
|
+
if (!mr || typeof mr.iid !== "number") return null;
|
|
7059
|
+
return { url: link(mr.iid), number: mr.iid, state: stateOf(mr.state) };
|
|
7060
|
+
},
|
|
7061
|
+
async createBranchWithCommit(branch, message, files) {
|
|
7062
|
+
const response = await send("/repository/commits", "create commit", {
|
|
7063
|
+
method: "POST",
|
|
7064
|
+
body: {
|
|
7065
|
+
branch,
|
|
7066
|
+
start_sha: config2.baseSha,
|
|
7067
|
+
commit_message: message,
|
|
7068
|
+
actions: files.map((file) => ({ action: "update", file_path: file.path, content: file.content }))
|
|
7069
|
+
}
|
|
7070
|
+
});
|
|
7071
|
+
if (response.status === 404) throw new HostError(404, "create commit failed with HTTP 404 (does the token have the Developer role and the api scope?)");
|
|
7072
|
+
},
|
|
7073
|
+
async openPullRequest(branch, title2, body2) {
|
|
7074
|
+
const response = await send("/merge_requests", "open merge request", {
|
|
7075
|
+
method: "POST",
|
|
7076
|
+
body: { source_branch: branch, target_branch: config2.baseBranch, title: title2, description: body2, remove_source_branch: true }
|
|
7077
|
+
});
|
|
7078
|
+
if (response.status === 404) throw new HostError(404, "open merge request failed with HTTP 404 (does the token have the Developer role and the api scope?)");
|
|
7079
|
+
const mr = await response.json();
|
|
7080
|
+
if (typeof mr.iid !== "number") throw new HostError(500, "merge request without iid");
|
|
7081
|
+
return { url: link(mr.iid), number: mr.iid };
|
|
7082
|
+
},
|
|
7083
|
+
async pullRequestState(number3) {
|
|
7084
|
+
const response = await send(`/merge_requests/${number3}`, "read merge request");
|
|
7085
|
+
if (response.status === 404) return "closed";
|
|
7086
|
+
return stateOf((await response.json()).state);
|
|
7087
|
+
},
|
|
7088
|
+
async fileAtBase(path3) {
|
|
7089
|
+
const response = await send(`/repository/files/${encodeGitLabPath(path3)}/raw?ref=${encodeURIComponent(config2.baseSha)}`, "read file at base commit", { accept: "*/*" });
|
|
7090
|
+
return response.status === 404 ? null : decodeKeepingBom(await response.arrayBuffer());
|
|
7091
|
+
},
|
|
7092
|
+
async isPrivate() {
|
|
7093
|
+
const response = await send("", "read project");
|
|
7094
|
+
if (response.status === 404) throw new HostError(404, "project not found");
|
|
7095
|
+
return (await response.json()).visibility === "private";
|
|
7096
|
+
}
|
|
7097
|
+
};
|
|
7098
|
+
}
|
|
7099
|
+
function detectGitLab(env, extra) {
|
|
7100
|
+
if (env["CI_MERGE_REQUEST_IID"]) return { error: "fix runs on a branch pipeline, not on a merge request pipeline" };
|
|
7101
|
+
if (env["CI_COMMIT_TAG"]) return { error: "fix runs on a branch, not on a tag" };
|
|
7102
|
+
if (env["CI_COMMIT_REF_PROTECTED"] !== "true") {
|
|
7103
|
+
return { error: "fix runs on a protected branch (the one you deploy): CI_COMMIT_REF_PROTECTED is not true, protect the branch and keep GITLAB_FIX_TOKEN protected" };
|
|
7104
|
+
}
|
|
7105
|
+
const projectId = env["CI_PROJECT_ID"];
|
|
7106
|
+
const repository = env["CI_PROJECT_PATH"];
|
|
7107
|
+
const baseBranch = env["CI_COMMIT_BRANCH"];
|
|
7108
|
+
const baseSha = env["CI_COMMIT_SHA"];
|
|
7109
|
+
if (!projectId || !repository || !baseBranch || !baseSha) return { error: "CI_PROJECT_ID, CI_PROJECT_PATH, CI_COMMIT_BRANCH and CI_COMMIT_SHA are required" };
|
|
7110
|
+
if (!isNumericId(projectId)) return { error: "CI_PROJECT_ID must be numeric" };
|
|
7111
|
+
if (!CODE_FIX_GITLAB_REPOSITORY_PATTERN.test(repository)) return { error: `CI_PROJECT_PATH "${repository.slice(0, 100)}" is not a GitLab project path` };
|
|
7112
|
+
const token = env["GITLAB_FIX_TOKEN"];
|
|
7113
|
+
if (!token) return { error: "GITLAB_FIX_TOKEN is not set: create a token with the Developer role and the api scope and store it as a masked, protected variable (CI_JOB_TOKEN cannot open merge requests)" };
|
|
7114
|
+
const server = resolveGitLabServer(env);
|
|
7115
|
+
if ("error" in server) return { error: server.error };
|
|
7116
|
+
return { host: gitLabHost({ apiUrl: server.apiUrl, server: server.server, projectId, repository, token, baseBranch, baseSha, ...extra }) };
|
|
7117
|
+
}
|
|
6795
7118
|
function detectHost(env, forced, fetchImpl) {
|
|
6796
|
-
const kind = forced ?? (env["GITHUB_ACTIONS"] === "true" ? "github" : env["BITBUCKET_BUILD_NUMBER"] ? "bitbucket" : null);
|
|
6797
|
-
if (kind === null) return { error: "could not tell the git host: run it in GitHub Actions or
|
|
7119
|
+
const kind = forced ?? (env["GITHUB_ACTIONS"] === "true" ? "github" : env["BITBUCKET_BUILD_NUMBER"] ? "bitbucket" : env["GITLAB_CI"] === "true" ? "gitlab" : null);
|
|
7120
|
+
if (kind === null) return { error: "could not tell the git host: run it in GitHub Actions, Bitbucket Pipelines or GitLab CI, or pass --host" };
|
|
6798
7121
|
const extra = fetchImpl ? { fetchImpl } : {};
|
|
7122
|
+
if (kind === "gitlab") return detectGitLab(env, extra);
|
|
6799
7123
|
if (kind === "github") {
|
|
6800
7124
|
if (env["GITHUB_EVENT_NAME"] === "pull_request" || env["GITHUB_EVENT_NAME"] === "pull_request_target") {
|
|
6801
7125
|
return { error: "fix runs on a branch build (push, schedule or workflow_dispatch), not on a pull request" };
|
|
@@ -7131,8 +7455,8 @@ function adjacent(text, previous, next) {
|
|
|
7131
7455
|
const eol = gap.indexOf("\n");
|
|
7132
7456
|
if (eol === -1 || gap.indexOf("\n", eol + 1) !== -1) return false;
|
|
7133
7457
|
const tail = gap.slice(0, eol).trim();
|
|
7134
|
-
const
|
|
7135
|
-
return
|
|
7458
|
+
const comment2 = tail === "" || tail.startsWith("#") || tail.startsWith("//") || tail.startsWith("/*") && tail.endsWith("*/");
|
|
7459
|
+
return comment2 && gap.slice(eol + 1).trim() === "";
|
|
7136
7460
|
}
|
|
7137
7461
|
function alignmentGroups(text, block) {
|
|
7138
7462
|
const groups = [];
|
|
@@ -8843,7 +9167,7 @@ async function runFix(options, deps) {
|
|
|
8843
9167
|
let opened = 0;
|
|
8844
9168
|
for (const finding of input.findings) {
|
|
8845
9169
|
const existing = input.fixes.get(finding.findingId);
|
|
8846
|
-
const sameRepo = Boolean(existing && host && existing.host === host.kind && existing.repository === host.repository);
|
|
9170
|
+
const sameRepo = Boolean(existing && host && existing.host === host.kind && existing.repository === host.repository && existing.server === host.server);
|
|
8847
9171
|
if (existing && CODE_FIX_PR_STATES.includes(existing.state) && !sameRepo) continue;
|
|
8848
9172
|
if (existing?.state === "closed") continue;
|
|
8849
9173
|
if (existing && host && sameRepo && existing.state === "pr_open" && existing.pullRequest) {
|
|
@@ -8930,6 +9254,7 @@ async function runFix(options, deps) {
|
|
|
8930
9254
|
file: patch.file,
|
|
8931
9255
|
attribute: patch.attribute,
|
|
8932
9256
|
host: host.kind,
|
|
9257
|
+
...host.server !== void 0 ? { server: host.server } : {},
|
|
8933
9258
|
repository: host.repository,
|
|
8934
9259
|
pullRequest: { url: pr.url, number: pr.number }
|
|
8935
9260
|
});
|
|
@@ -9025,7 +9350,8 @@ Options:
|
|
|
9025
9350
|
--account <accountId> AAA Sentinel account id (acc_\u2026), or IAC_FIX_ACCOUNT_ID
|
|
9026
9351
|
--dir <path> Directory where terraform plan ran (default: current)
|
|
9027
9352
|
--max-prs <n> Pull requests opened per run (default: ${DEFAULT_MAX_PRS})
|
|
9028
|
-
--host <github|bitbucket>
|
|
9353
|
+
--host <github|bitbucket|gitlab>
|
|
9354
|
+
Git host (default: detected from the CI)
|
|
9029
9355
|
--dry-run Print what would change; open and record nothing
|
|
9030
9356
|
--allow-public-repo Open pull requests on a public repository too (they
|
|
9031
9357
|
describe a live finding to anyone)
|
|
@@ -9035,11 +9361,12 @@ Options:
|
|
|
9035
9361
|
Environment:
|
|
9036
9362
|
IAC_FIX_CLIENT_ID / IAC_FIX_CLIENT_SECRET OAuth2 app with the security:fix scope
|
|
9037
9363
|
GITHUB_TOKEN GitHub Actions token (contents and pull-requests: write)
|
|
9038
|
-
BB_TOKEN Bitbucket repository access token (repository:write, pullrequest:write)
|
|
9364
|
+
BB_TOKEN Bitbucket repository access token (repository:write, pullrequest:write)
|
|
9365
|
+
GITLAB_FIX_TOKEN GitLab token with the Developer role and the api scope`;
|
|
9039
9366
|
async function runFixCli(argv, io) {
|
|
9040
9367
|
const warnings = [];
|
|
9041
9368
|
const fail = (message) => ({ stdout: null, warnings: [...warnings, message], exitCode: 2 });
|
|
9042
|
-
const { values, positionals } =
|
|
9369
|
+
const { values, positionals } = parseArgs3({
|
|
9043
9370
|
args: [...argv],
|
|
9044
9371
|
strict: false,
|
|
9045
9372
|
allowPositionals: true,
|
|
@@ -9116,7 +9443,7 @@ ${FIX_USAGE}`);
|
|
|
9116
9443
|
}
|
|
9117
9444
|
|
|
9118
9445
|
// src/posture/posture.ts
|
|
9119
|
-
import { parseArgs as
|
|
9446
|
+
import { parseArgs as parseArgs4 } from "node:util";
|
|
9120
9447
|
var POSTURE_USAGE = `Usage: iac-cost posture --account <accountId> [options]
|
|
9121
9448
|
|
|
9122
9449
|
Prints how the security posture of an AAA Sentinel account changed over a
|
|
@@ -9142,7 +9469,7 @@ Environment:
|
|
|
9142
9469
|
var SEVERITIES2 = ["critical", "high", "medium", "low"];
|
|
9143
9470
|
var DAYS = [30, 90, 365];
|
|
9144
9471
|
var FORMATS2 = ["markdown", "text", "json"];
|
|
9145
|
-
var
|
|
9472
|
+
var TIMEOUT_MS4 = 35e3;
|
|
9146
9473
|
var APP_URL = "https://app.aaa-sentinel.com";
|
|
9147
9474
|
var total = (c) => SEVERITIES2.reduce((n, s) => n + (c[s] ?? 0), 0);
|
|
9148
9475
|
var bySeverity = (c) => SEVERITIES2.filter((s) => (c[s] ?? 0) > 0).map((s) => `${c[s]} ${s}`).join(", ");
|
|
@@ -9210,14 +9537,14 @@ async function fetchPostureHistory(config2) {
|
|
|
9210
9537
|
const fetchImpl = config2.fetchImpl ?? fetch;
|
|
9211
9538
|
const token = await fetchToken(config2, "security:read");
|
|
9212
9539
|
const url = `${config2.baseUrl}/v1/security/posture-history?accountId=${encodeURIComponent(config2.accountId)}&days=${config2.days}`;
|
|
9213
|
-
const response = await fetchImpl(url, { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(
|
|
9540
|
+
const response = await fetchImpl(url, { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(TIMEOUT_MS4) });
|
|
9214
9541
|
if (!response.ok) throw new Error(`posture_history_http_${response.status}`);
|
|
9215
9542
|
return await response.json();
|
|
9216
9543
|
}
|
|
9217
9544
|
async function runPostureCli(argv, io) {
|
|
9218
9545
|
const warnings = [];
|
|
9219
9546
|
const fail = (message) => ({ stdout: null, warnings: [...warnings, message], exitCode: 2 });
|
|
9220
|
-
const { values, positionals } =
|
|
9547
|
+
const { values, positionals } = parseArgs4({
|
|
9221
9548
|
args: [...argv],
|
|
9222
9549
|
strict: false,
|
|
9223
9550
|
allowPositionals: true,
|
|
@@ -9411,88 +9738,6 @@ function parseTerraformPlan(plan) {
|
|
|
9411
9738
|
};
|
|
9412
9739
|
}
|
|
9413
9740
|
|
|
9414
|
-
// src/render-comment.ts
|
|
9415
|
-
var COMMENT_MARKER = "<!-- aaa-sentinel:iac-cost -->";
|
|
9416
|
-
var REASON_TEXT = {
|
|
9417
|
-
provider_not_supported: "provider not covered yet",
|
|
9418
|
-
provider_not_priced: "provider recognized, pricing not connected yet",
|
|
9419
|
-
resource_type_not_priced: "resource type not in the priced catalog yet",
|
|
9420
|
-
region_unknown: "region could not be resolved from the plan",
|
|
9421
|
-
region_not_supported: "region not in the price catalog",
|
|
9422
|
-
size_unknown: "size/SKU could not be resolved from the plan",
|
|
9423
|
-
instance_count_unknown: "instance count could not be resolved from the plan",
|
|
9424
|
-
attribute_unknown: "a price-relevant attribute (engine, Multi-AZ, storage\u2026) could not be resolved from the plan",
|
|
9425
|
-
price_unavailable: "the price catalog did not answer this time; a later run retries",
|
|
9426
|
-
price_lookup_limit: "too many distinct database configurations in one plan to look up in a single request",
|
|
9427
|
-
price_not_found: "no matching price found in the catalog"
|
|
9428
|
-
};
|
|
9429
|
-
var fmtUsd = (n) => `${n < 0 ? "-" : "+"}$${Math.abs(n).toFixed(2)}/mo`;
|
|
9430
|
-
function fmtConverted(n, currency) {
|
|
9431
|
-
const amount = new Intl.NumberFormat("en-US", { style: "currency", currency }).format(Math.abs(n));
|
|
9432
|
-
return `\u2248 ${n < 0 ? "-" : "+"}${amount}/mo`;
|
|
9433
|
-
}
|
|
9434
|
-
var LIST_PRICE_CAVEAT = "They also do not reflect committed-use discounts (EDP/EA/CUD) or existing reservations/Savings Plans that may already cover a resource. Usage-based charges (data transfer, backups beyond the allocated storage, I/O requests, CPU credits), storage growth from autoscaling (`max_allocated_storage`), RDS Extended Support and paid Performance Insights retention are not included.";
|
|
9435
|
-
var reasonText = (reason) => REASON_TEXT[reason] ?? reason;
|
|
9436
|
-
function actionVerb(action) {
|
|
9437
|
-
return action === "create" ? "new" : action === "delete" ? "removed" : action;
|
|
9438
|
-
}
|
|
9439
|
-
function renderComment(estimate) {
|
|
9440
|
-
const { coverage } = estimate;
|
|
9441
|
-
const lines2 = [COMMENT_MARKER, "### \u{1F4B2} Infrastructure cost estimate", ""];
|
|
9442
|
-
lines2.push(
|
|
9443
|
-
`**Coverage: ${coverage.pricedResources} of ${coverage.pricedResources + coverage.unpricedResources} billable resources priced** (${coverage.freeResources} more have no cost by design).`
|
|
9444
|
-
);
|
|
9445
|
-
lines2.push("");
|
|
9446
|
-
const display = estimate.displayCurrency?.approximate ? estimate.displayCurrency : null;
|
|
9447
|
-
const delta = (usd, converted) => display && typeof converted === "number" ? fmtConverted(converted, display.code) : fmtUsd(usd);
|
|
9448
|
-
if (estimate.totalMonthlyDeltaUsd !== null) {
|
|
9449
|
-
const total2 = delta(estimate.totalMonthlyDeltaUsd, estimate.totalMonthlyDelta);
|
|
9450
|
-
lines2.push(
|
|
9451
|
-
display ? `**Estimated change: ${total2}** (list price, ${fmtUsd(estimate.totalMonthlyDeltaUsd)} in USD)` : `**Estimated change: ${total2}** (list price, USD)`
|
|
9452
|
-
);
|
|
9453
|
-
} else {
|
|
9454
|
-
lines2.push(
|
|
9455
|
-
`_Coverage is below the threshold needed to publish a total \u2014 see the breakdown below instead of a number that wouldn't hold up._`
|
|
9456
|
-
);
|
|
9457
|
-
}
|
|
9458
|
-
lines2.push("");
|
|
9459
|
-
lines2.push(
|
|
9460
|
-
display ? `> These are **list prices**, not what you actually pay. Cloud providers publish them in USD; the amounts shown are **approximate**, converted to ${display.code} at the ECB reference rate${display.rateDate ? ` of ${display.rateDate}` : ""} (1 USD = ${display.rate} ${display.code}). ` + LIST_PRICE_CAVEAT : `> These are **list prices in USD**, not what you actually pay. Cloud providers set their list prices in USD, so showing this in another billing currency would be an estimate on top of an estimate. ${LIST_PRICE_CAVEAT}`
|
|
9461
|
-
);
|
|
9462
|
-
if (estimate.priced.length > 0) {
|
|
9463
|
-
lines2.push("", "| Resource | Change | Qty | Delta |", "|---|---|---|---|");
|
|
9464
|
-
for (const item of estimate.priced) {
|
|
9465
|
-
const assumed = item.assumedDefaults?.length ? " \u2020" : "";
|
|
9466
|
-
lines2.push(
|
|
9467
|
-
`| \`${item.type}\`${assumed} | ${actionVerb(item.action)} | ${item.count} | ${delta(item.monthlyDeltaUsd, item.monthlyDelta)} |`
|
|
9468
|
-
);
|
|
9469
|
-
}
|
|
9470
|
-
const assumedNames = [...new Set(estimate.priced.flatMap((i) => i.assumedDefaults ?? []))].sort();
|
|
9471
|
-
if (assumedNames.length > 0) {
|
|
9472
|
-
lines2.push(
|
|
9473
|
-
"",
|
|
9474
|
-
`\u2020 Not set in the Terraform configuration, so the AWS default was assumed for: ${assumedNames.map((n) => `\`${n}\``).join(", ")}. Set them explicitly if your deployment differs.`
|
|
9475
|
-
);
|
|
9476
|
-
}
|
|
9477
|
-
}
|
|
9478
|
-
if (estimate.unpriced.length > 0) {
|
|
9479
|
-
lines2.push("", "<details><summary>Not priced (" + coverage.unpricedResources + " resources)</summary>", "");
|
|
9480
|
-
lines2.push("| Resource | Change | Qty | Why |", "|---|---|---|---|");
|
|
9481
|
-
for (const item of estimate.unpriced) {
|
|
9482
|
-
lines2.push(`| \`${item.type}\` | ${actionVerb(item.action)} | ${item.count} | ${reasonText(item.reason)} |`);
|
|
9483
|
-
}
|
|
9484
|
-
lines2.push("", "</details>");
|
|
9485
|
-
}
|
|
9486
|
-
const truncated = estimate.catalogs.filter((c) => c.truncated);
|
|
9487
|
-
if (truncated.length > 0) {
|
|
9488
|
-
lines2.push(
|
|
9489
|
-
"",
|
|
9490
|
-
`\u26A0\uFE0F The price catalog for ${truncated.map((c) => c.region).join(", ")} was truncated by pagination: some prices may be missing.`
|
|
9491
|
-
);
|
|
9492
|
-
}
|
|
9493
|
-
return lines2.join("\n");
|
|
9494
|
-
}
|
|
9495
|
-
|
|
9496
9741
|
// src/security/drift.ts
|
|
9497
9742
|
var SCOPE2 = "security:read";
|
|
9498
9743
|
var REQUEST_TIMEOUT_MS2 = 35e3;
|
|
@@ -13109,9 +13354,19 @@ async function posture(argv) {
|
|
|
13109
13354
|
if (outcome.stdout) console.log(outcome.stdout);
|
|
13110
13355
|
process.exitCode = outcome.exitCode;
|
|
13111
13356
|
}
|
|
13357
|
+
async function comment(argv) {
|
|
13358
|
+
const outcome = await runCommentCli(argv, {
|
|
13359
|
+
env: process.env,
|
|
13360
|
+
readBody: (file) => decodePlan(file ? readFileSync2(file) : readFileSync2(0))
|
|
13361
|
+
});
|
|
13362
|
+
for (const warning of outcome.warnings) console.warn(`iac-cost: ${warning}`);
|
|
13363
|
+
if (outcome.stdout) console.log(outcome.stdout);
|
|
13364
|
+
process.exitCode = outcome.exitCode;
|
|
13365
|
+
}
|
|
13112
13366
|
async function main() {
|
|
13113
13367
|
if (process.argv[2] === "fix") return fix(process.argv.slice(3));
|
|
13114
13368
|
if (process.argv[2] === "posture") return posture(process.argv.slice(3));
|
|
13369
|
+
if (process.argv[2] === "comment") return comment(process.argv.slice(3));
|
|
13115
13370
|
const options = parseCliArgs(process.argv.slice(2), process.env);
|
|
13116
13371
|
if ("error" in options) {
|
|
13117
13372
|
console.error(`iac-cost: ${options.error}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aaa-sentinel/iac-cost",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.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",
|