@aaa-sentinel/iac-cost 0.5.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +119 -7
- package/dist/cli.js +460 -132
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -7,6 +7,17 @@ internet is caught in review instead of after the deploy. With `iac-cost fix`, t
|
|
|
7
7
|
your last scan on resources this Terraform manages come back to you as **pull requests**, not as
|
|
8
8
|
console changes (see [Fixes as pull requests](#fixes-as-pull-requests)).
|
|
9
9
|
|
|
10
|
+
> **Changed in 0.6.1:** `fix` says when the security add-on is not active on the account, names the
|
|
11
|
+
> fixes whose pull or merge request was closed without merging (they are not reopened), and says
|
|
12
|
+
> "merge request" on GitLab. The fix jobs below no longer end in `|| true` or `continue-on-error`, so a
|
|
13
|
+
> setup error (exit code 2) fails the job instead of passing unseen. Rejected OAuth app credentials
|
|
14
|
+
> (401) or an app without the `security:fix` scope (403) are now setup errors too: exit code 2.
|
|
15
|
+
|
|
16
|
+
> **New in 0.6.0:** GitLab CI, on gitlab.com and self-managed GitLab. The `comment` subcommand posts
|
|
17
|
+
> the output as a note on the merge request and updates it on later pushes (see [GitLab CI](#gitlab-ci)),
|
|
18
|
+
> and `fix` opens merge requests (see [GitLab CI](#gitlab-ci-1) under fixes). Nothing changes on GitHub
|
|
19
|
+
> or Bitbucket.
|
|
20
|
+
|
|
10
21
|
> **New in 0.4.0:** the `posture` subcommand prints how the security posture of an account changed
|
|
11
22
|
> over 30, 90 or 365 days, with an optional gate on new findings (see
|
|
12
23
|
> [Posture over time](#posture-over-time)). Nothing changes for `fix` or the existing command.
|
|
@@ -48,6 +59,8 @@ console changes (see [Fixes as pull requests](#fixes-as-pull-requests)).
|
|
|
48
59
|
- For **`iac-cost fix`**, an application with the `security:fix` scope, the security add-on on the
|
|
49
60
|
account, and a CI token that can push a branch and open a pull request (see
|
|
50
61
|
[Fixes as pull requests](#fixes-as-pull-requests)).
|
|
62
|
+
- On **GitLab**, a project access token of your own for the note or the merge request: the job
|
|
63
|
+
token (`CI_JOB_TOKEN`) cannot write notes or open merge requests (see [GitLab CI](#gitlab-ci)).
|
|
51
64
|
|
|
52
65
|
## Usage
|
|
53
66
|
|
|
@@ -416,6 +429,65 @@ pipelines:
|
|
|
416
429
|
> `content.raw`, hence the `// ""` — without it `jq` aborts and the comment is posted again
|
|
417
430
|
> instead of updated.
|
|
418
431
|
|
|
432
|
+
## GitLab CI
|
|
433
|
+
|
|
434
|
+
Works on gitlab.com and on self-managed GitLab. Instead of a shell snippet that calls the API, the CLI
|
|
435
|
+
posts the note itself: `iac-cost comment` reads the Markdown, finds the note it left
|
|
436
|
+
before on the merge request (by the hidden marker and the token's own user, across every page of
|
|
437
|
+
notes) and **updates it in place**, or creates it the first time.
|
|
438
|
+
|
|
439
|
+
`CI_JOB_TOKEN` cannot write notes through the API, so create a **project access token**
|
|
440
|
+
(*Settings → Access tokens*) with the **`api`** scope and the **Reporter** role, and store it as a
|
|
441
|
+
**masked** CI/CD variable named `GITLAB_TOKEN`. On gitlab.com, project and group access tokens are
|
|
442
|
+
Premium/Ultimate; on the Free tier use a
|
|
443
|
+
[service account](https://docs.gitlab.com/user/profile/service_accounts/) (up to 100 per top-level
|
|
444
|
+
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
|
|
445
|
+
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
|
|
446
|
+
request's source branch, which is usually not protected, and a protected variable would not reach it.
|
|
447
|
+
The same applies to `IAC_COST_CLIENT_ID`/`IAC_COST_CLIENT_SECRET`. If you protect your source
|
|
448
|
+
branches (or use protected variables only on protected branches on purpose), the comment is skipped
|
|
449
|
+
on the others.
|
|
450
|
+
|
|
451
|
+
```yaml
|
|
452
|
+
iac-cost:
|
|
453
|
+
image:
|
|
454
|
+
name: hashicorp/terraform:latest
|
|
455
|
+
entrypoint: [""]
|
|
456
|
+
rules:
|
|
457
|
+
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
|
|
458
|
+
script:
|
|
459
|
+
- apk add --no-cache nodejs npm
|
|
460
|
+
- terraform init
|
|
461
|
+
- terraform plan -out=plan.tfplan
|
|
462
|
+
- terraform show -json plan.tfplan > plan.json
|
|
463
|
+
- npx --yes @aaa-sentinel/iac-cost plan.json > comment.md
|
|
464
|
+
# GITLAB_TOKEN (Reporter, api), IAC_COST_CLIENT_ID and IAC_COST_CLIENT_SECRET: masked CI/CD variables.
|
|
465
|
+
- npx --yes @aaa-sentinel/iac-cost comment comment.md || true
|
|
466
|
+
# Optional gate: fails on critical or high findings.
|
|
467
|
+
- npx --yes @aaa-sentinel/iac-cost plan.json --no-cost --format text --fail-on high
|
|
468
|
+
```
|
|
469
|
+
|
|
470
|
+
`iac-cost comment` always exits 0: without `GITLAB_TOKEN`, outside a merge request pipeline, on a
|
|
471
|
+
merge request from a fork or when GitLab answers with an error, it prints one line saying why and the
|
|
472
|
+
pipeline goes on. The `|| true` only covers npm itself being unreachable.
|
|
473
|
+
|
|
474
|
+
- **Self-managed GitLab:** the server comes from `CI_SERVER_URL` and the API from `CI_API_V4_URL`,
|
|
475
|
+
which GitLab sets on every job. Before sending the token, the CLI checks that both are `https`, on
|
|
476
|
+
the same origin, name the server by its DNS name (not an IP address) and carry no credentials,
|
|
477
|
+
query or path (GitLab under a relative URL path, such as `https://example.com/gitlab`, is not
|
|
478
|
+
supported). It never follows a redirect with the token. This is defence in depth, not a boundary:
|
|
479
|
+
anyone who can push a branch can override those variables in that branch's `variables:`, and can
|
|
480
|
+
already read any unprotected variable that reaches it.
|
|
481
|
+
- **Merge requests from forks:** a pipeline that runs in the fork does not get the project's
|
|
482
|
+
variables, so there is no token. If you run pipelines **in the parent project** for merge requests
|
|
483
|
+
from forks, they run the fork's `.gitlab-ci.yml` with your unprotected variables, which the fork's
|
|
484
|
+
code can read whatever this CLI does: do not enable that while `GITLAB_TOKEN` is unprotected. In
|
|
485
|
+
both cases `iac-cost comment` skips the comment with a warning.
|
|
486
|
+
- Only notes written by the token's own user are updated: a note from anyone else that contains the
|
|
487
|
+
marker is left alone. Each project access token has its own bot user, so after rotating the token
|
|
488
|
+
the next run adds a new note instead of updating the old one (delete the old one by hand).
|
|
489
|
+
- With an empty input it prints a warning and leaves the merge request as it is.
|
|
490
|
+
|
|
419
491
|
## Fixes as pull requests
|
|
420
492
|
|
|
421
493
|
If a resource is managed by Terraform, fixing it in the console creates drift: the next
|
|
@@ -481,7 +553,7 @@ the reason, and the app shows it that way:
|
|
|
481
553
|
| `no_public_access_block` | The bucket has no `aws_s3_bucket_public_access_block` to edit |
|
|
482
554
|
| `replacement_required` | The fix forces a new resource (RDS encryption, Cloud SQL CMEK) |
|
|
483
555
|
| `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
|
|
556
|
+
| `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
557
|
| `cause_not_in_code` | The open value is not in the code (added by hand, or a provider default) |
|
|
486
558
|
| `block_not_found` | The `resource` block could not be read (`.tf.json`, or a layout the editor does not handle) |
|
|
487
559
|
| `rule_not_automated` | No deterministic code fix for that rule |
|
|
@@ -498,14 +570,21 @@ review its `terraform plan` before merging. The finding closes after `terraform
|
|
|
498
570
|
| `--account <accountId>` | AAA Sentinel account id. Also `IAC_FIX_ACCOUNT_ID` |
|
|
499
571
|
| `--dir <path>` | Directory where `terraform plan` ran (default: current). The repository root is the nearest `.git` above it |
|
|
500
572
|
| `--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 |
|
|
573
|
+
| `--host <github\|bitbucket\|gitlab>` | Git host. Detected from the CI by default |
|
|
502
574
|
| `--dry-run` | Prints the changes; opens nothing and records nothing. Works without a git host |
|
|
503
575
|
| `--allow-public-repo` | Opens pull requests on a public repository too |
|
|
504
576
|
| `--format <text\|json>` | Output format |
|
|
505
577
|
|
|
506
|
-
Exit code: `2` for a
|
|
507
|
-
|
|
508
|
-
|
|
578
|
+
Exit code: `2` for a setup error (no account, no git host or token, the run is a pull request build,
|
|
579
|
+
on GitLab a branch that is not protected, the input is not a plan; `IAC_FIX_CLIENT_ID` or
|
|
580
|
+
`IAC_FIX_CLIENT_SECRET` missing or rejected (401); an app without the `security:fix` scope or not allowed
|
|
581
|
+
on the account (403)); otherwise `0`, also when there is nothing to fix, when the security add-on is not
|
|
582
|
+
active on the account (402), and when the API is down (5xx), the network fails or the git host fails —
|
|
583
|
+
the step prints a warning and the findings stay `pending`. That is why the
|
|
584
|
+
jobs below do not end in `|| true` (or `continue-on-error` on GitHub): a `2` needs someone to fix the
|
|
585
|
+
pipeline and must show as a failed job, while an outage on our side never fails it. Run fixes in their
|
|
586
|
+
own workflow or job; if the job shares a GitLab pipeline with your deploy, add `allow_failure: true` to
|
|
587
|
+
it so a setup error shows as a warning without holding the later stages.
|
|
509
588
|
|
|
510
589
|
### GitHub Actions
|
|
511
590
|
|
|
@@ -540,7 +619,6 @@ jobs:
|
|
|
540
619
|
- run: terraform plan -out=plan.tfplan
|
|
541
620
|
- run: terraform show -json plan.tfplan > plan.json
|
|
542
621
|
- name: Open security fixes as pull requests
|
|
543
|
-
continue-on-error: true
|
|
544
622
|
env:
|
|
545
623
|
GITHUB_TOKEN: ${{ github.token }}
|
|
546
624
|
IAC_FIX_CLIENT_ID: ${{ secrets.IAC_FIX_CLIENT_ID }}
|
|
@@ -566,11 +644,45 @@ pipelines:
|
|
|
566
644
|
- terraform init
|
|
567
645
|
- terraform plan -out=plan.tfplan
|
|
568
646
|
- terraform show -json plan.tfplan > plan.json
|
|
569
|
-
- npx --yes @aaa-sentinel/iac-cost fix plan.json --account "$AAA_SENTINEL_ACCOUNT_ID"
|
|
647
|
+
- npx --yes @aaa-sentinel/iac-cost fix plan.json --account "$AAA_SENTINEL_ACCOUNT_ID"
|
|
570
648
|
```
|
|
571
649
|
|
|
572
650
|
The commit is created through the Bitbucket API (`POST /src`), so the clone needs no push access.
|
|
573
651
|
|
|
652
|
+
### GitLab CI
|
|
653
|
+
|
|
654
|
+
Opens one **merge request** per finding, on gitlab.com or self-managed GitLab (same checks on
|
|
655
|
+
`CI_SERVER_URL` and `CI_API_V4_URL` as [the comment](#gitlab-ci)). Create a **project access token**
|
|
656
|
+
with the **Developer** role and the **`api`** scope and store it as a **masked and protected** variable
|
|
657
|
+
named `GITLAB_FIX_TOKEN` (the job runs on the branch you deploy, which is protected); on the Free
|
|
658
|
+
tier of gitlab.com, the token of a service account with the Developer role. It never falls
|
|
659
|
+
back to `GITLAB_TOKEN`: that one is unprotected for the comment job, and a token that can push must not
|
|
660
|
+
be readable from every branch.
|
|
661
|
+
|
|
662
|
+
```yaml
|
|
663
|
+
security-fixes:
|
|
664
|
+
image:
|
|
665
|
+
name: hashicorp/terraform:latest
|
|
666
|
+
entrypoint: [""]
|
|
667
|
+
rules:
|
|
668
|
+
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
|
|
669
|
+
script:
|
|
670
|
+
- apk add --no-cache nodejs npm
|
|
671
|
+
- terraform init
|
|
672
|
+
- terraform plan -out=plan.tfplan
|
|
673
|
+
- terraform show -json plan.tfplan > plan.json
|
|
674
|
+
# GITLAB_FIX_TOKEN (Developer, api), IAC_FIX_CLIENT_ID and IAC_FIX_CLIENT_SECRET: masked, protected variables.
|
|
675
|
+
- npx --yes @aaa-sentinel/iac-cost fix plan.json --account "$AAA_SENTINEL_ACCOUNT_ID"
|
|
676
|
+
```
|
|
677
|
+
|
|
678
|
+
The branch and the commit are created in one call to the GitLab API (`POST /repository/commits` from
|
|
679
|
+
the deployed commit), so the clone needs no push access. A project with **internal** visibility counts
|
|
680
|
+
as public (every user of the server, or of gitlab.com, can read it): pass `--allow-public-repo` if
|
|
681
|
+
that is acceptable. It refuses to run on a merge request or tag pipeline, and on a branch that is not
|
|
682
|
+
protected (`CI_COMMIT_REF_PROTECTED` is not `true`) with exit code `2`, so the job fails: the token
|
|
683
|
+
that can push lives in a protected variable, so an unprotected branch means the setup is wrong.
|
|
684
|
+
Protect the branch you deploy.
|
|
685
|
+
|
|
574
686
|
## Posture over time
|
|
575
687
|
|
|
576
688
|
`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, {
|
|
@@ -6467,6 +6711,21 @@ function aggregateEstimates(estimates) {
|
|
|
6467
6711
|
catalogs: [...catalogs.values()]
|
|
6468
6712
|
};
|
|
6469
6713
|
}
|
|
6714
|
+
var TokenHttpError = class extends Error {
|
|
6715
|
+
constructor(status, code2) {
|
|
6716
|
+
super(`iac_cost_token_http_${status}`);
|
|
6717
|
+
this.status = status;
|
|
6718
|
+
this.code = code2;
|
|
6719
|
+
}
|
|
6720
|
+
};
|
|
6721
|
+
async function apiErrorCode(response) {
|
|
6722
|
+
try {
|
|
6723
|
+
const body2 = await response.json();
|
|
6724
|
+
return typeof body2.code === "string" && /^[A-Z][A-Z0-9_]{0,63}$/.test(body2.code) ? body2.code : null;
|
|
6725
|
+
} catch {
|
|
6726
|
+
return null;
|
|
6727
|
+
}
|
|
6728
|
+
}
|
|
6470
6729
|
async function fetchToken(config2, scope = TOKEN_SCOPE) {
|
|
6471
6730
|
const fetchImpl = config2.fetchImpl ?? fetch;
|
|
6472
6731
|
const response = await fetchImpl(`${config2.baseUrl}/v1/oauth/token`, {
|
|
@@ -6480,7 +6739,7 @@ async function fetchToken(config2, scope = TOKEN_SCOPE) {
|
|
|
6480
6739
|
scope
|
|
6481
6740
|
})
|
|
6482
6741
|
});
|
|
6483
|
-
if (!response.ok) throw new
|
|
6742
|
+
if (!response.ok) throw new TokenHttpError(response.status, await apiErrorCode(response));
|
|
6484
6743
|
const body2 = await response.json();
|
|
6485
6744
|
if (typeof body2.access_token !== "string") throw new Error("iac_cost_token_missing");
|
|
6486
6745
|
return body2.access_token;
|
|
@@ -6542,29 +6801,36 @@ async function estimatePlan(projection, config2) {
|
|
|
6542
6801
|
|
|
6543
6802
|
// src/fix/cli-fix.ts
|
|
6544
6803
|
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;
|
|
6804
|
+
import { parseArgs as parseArgs3 } from "node:util";
|
|
6552
6805
|
|
|
6553
6806
|
// src/fix/api.ts
|
|
6554
6807
|
var SCOPE = "security:fix";
|
|
6555
|
-
var
|
|
6808
|
+
var TIMEOUT_MS2 = 35e3;
|
|
6809
|
+
var CodeFixApiError = class extends Error {
|
|
6810
|
+
constructor(status, code2, stage = "findings") {
|
|
6811
|
+
super(`${stage === "token" ? "iac_cost_token_http_" : "code_fixes_http_"}${status}${code2 ? ` ${code2}` : ""}`);
|
|
6812
|
+
this.status = status;
|
|
6813
|
+
this.code = code2;
|
|
6814
|
+
this.stage = stage;
|
|
6815
|
+
}
|
|
6816
|
+
};
|
|
6556
6817
|
function codeFixApi(config2) {
|
|
6557
6818
|
const fetchImpl = config2.fetchImpl ?? fetch;
|
|
6558
6819
|
const url = `${config2.baseUrl}/v1/security/code-fixes?accountId=${encodeURIComponent(config2.accountId)}`;
|
|
6559
6820
|
let token = null;
|
|
6560
6821
|
const bearer = async () => {
|
|
6561
|
-
|
|
6822
|
+
try {
|
|
6823
|
+
token ??= await fetchToken(config2, SCOPE);
|
|
6824
|
+
} catch (error2) {
|
|
6825
|
+
if (error2 instanceof TokenHttpError) throw new CodeFixApiError(error2.status, error2.code, "token");
|
|
6826
|
+
throw error2;
|
|
6827
|
+
}
|
|
6562
6828
|
return token;
|
|
6563
6829
|
};
|
|
6564
6830
|
return {
|
|
6565
6831
|
async load() {
|
|
6566
|
-
const response = await fetchImpl(url, { headers: { authorization: `Bearer ${await bearer()}` }, signal: AbortSignal.timeout(
|
|
6567
|
-
if (!response.ok) throw new
|
|
6832
|
+
const response = await fetchImpl(url, { headers: { authorization: `Bearer ${await bearer()}` }, signal: AbortSignal.timeout(TIMEOUT_MS2) });
|
|
6833
|
+
if (!response.ok) throw new CodeFixApiError(response.status, await apiErrorCode(response));
|
|
6568
6834
|
const body2 = await response.json();
|
|
6569
6835
|
const findings = (body2.findings ?? []).flatMap(
|
|
6570
6836
|
(f) => typeof f.findingId === "string" && typeof f.ruleId === "string" && typeof f.resourceId === "string" ? [{
|
|
@@ -6598,7 +6864,7 @@ function codeFixApi(config2) {
|
|
|
6598
6864
|
method: "POST",
|
|
6599
6865
|
headers: { authorization: `Bearer ${await bearer()}`, "content-type": "application/json" },
|
|
6600
6866
|
body: JSON.stringify({ fixes: fixes.slice(i, i + CODE_FIX_REPORT_MAX) }),
|
|
6601
|
-
signal: AbortSignal.timeout(
|
|
6867
|
+
signal: AbortSignal.timeout(TIMEOUT_MS2)
|
|
6602
6868
|
});
|
|
6603
6869
|
if (!response.ok) throw new Error(`code_fixes_report_http_${response.status}`);
|
|
6604
6870
|
const body2 = await response.json();
|
|
@@ -6617,7 +6883,7 @@ function codeFixApi(config2) {
|
|
|
6617
6883
|
// src/fix/hosts.ts
|
|
6618
6884
|
var encodePath = (path3) => path3.split("/").map(encodeURIComponent).join("/");
|
|
6619
6885
|
var decodeKeepingBom = (buffer) => new TextDecoder("utf-8", { ignoreBOM: true }).decode(buffer);
|
|
6620
|
-
var
|
|
6886
|
+
var TIMEOUT_MS3 = 3e4;
|
|
6621
6887
|
var HostError = class extends Error {
|
|
6622
6888
|
constructor(status, message) {
|
|
6623
6889
|
super(message);
|
|
@@ -6625,7 +6891,7 @@ var HostError = class extends Error {
|
|
|
6625
6891
|
}
|
|
6626
6892
|
};
|
|
6627
6893
|
async function call(fetchImpl, url, init, label) {
|
|
6628
|
-
const response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(
|
|
6894
|
+
const response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(TIMEOUT_MS3) });
|
|
6629
6895
|
if (!response.ok && response.status !== 404) {
|
|
6630
6896
|
let detail = "";
|
|
6631
6897
|
try {
|
|
@@ -6792,10 +7058,96 @@ function bitbucketHost(config2) {
|
|
|
6792
7058
|
}
|
|
6793
7059
|
};
|
|
6794
7060
|
}
|
|
7061
|
+
var encodeGitLabPath = (value) => encodeURIComponent(value).replace(/\./g, "%2E");
|
|
7062
|
+
function gitLabHost(config2) {
|
|
7063
|
+
const fetchImpl = config2.fetchImpl ?? fetch;
|
|
7064
|
+
const api = `${config2.apiUrl}/projects/${encodeURIComponent(config2.projectId)}`;
|
|
7065
|
+
const send = (path3, label, init = {}) => gitLabCall(fetchImpl, `${api}${path3}`, config2.token, init, label);
|
|
7066
|
+
const link = (iid) => pullRequestUrl("gitlab", config2.repository, iid, config2.server);
|
|
7067
|
+
const stateOf = (state) => state === "merged" ? "merged" : state === "closed" ? "closed" : "open";
|
|
7068
|
+
return {
|
|
7069
|
+
kind: "gitlab",
|
|
7070
|
+
repository: config2.repository,
|
|
7071
|
+
server: config2.server,
|
|
7072
|
+
baseBranch: config2.baseBranch,
|
|
7073
|
+
baseSha: config2.baseSha,
|
|
7074
|
+
unsupported: false,
|
|
7075
|
+
async branchExists(branch) {
|
|
7076
|
+
const response = await send(`/repository/branches/${encodeGitLabPath(branch)}`, "read branch");
|
|
7077
|
+
return response.status !== 404;
|
|
7078
|
+
},
|
|
7079
|
+
async findPullRequest(branch) {
|
|
7080
|
+
const q = `source_branch=${encodeURIComponent(branch)}&state=all&order_by=created_at&sort=desc&per_page=100`;
|
|
7081
|
+
const response = await send(`/merge_requests?${q}`, "list merge requests");
|
|
7082
|
+
if (response.status === 404) return null;
|
|
7083
|
+
const list = await response.json();
|
|
7084
|
+
const project = Number(config2.projectId);
|
|
7085
|
+
const mr = Array.isArray(list) ? list.find((m) => m.source_branch === branch && m.source_project_id === project && m.target_project_id === project) : void 0;
|
|
7086
|
+
if (!mr || typeof mr.iid !== "number") return null;
|
|
7087
|
+
return { url: link(mr.iid), number: mr.iid, state: stateOf(mr.state) };
|
|
7088
|
+
},
|
|
7089
|
+
async createBranchWithCommit(branch, message, files) {
|
|
7090
|
+
const response = await send("/repository/commits", "create commit", {
|
|
7091
|
+
method: "POST",
|
|
7092
|
+
body: {
|
|
7093
|
+
branch,
|
|
7094
|
+
start_sha: config2.baseSha,
|
|
7095
|
+
commit_message: message,
|
|
7096
|
+
actions: files.map((file) => ({ action: "update", file_path: file.path, content: file.content }))
|
|
7097
|
+
}
|
|
7098
|
+
});
|
|
7099
|
+
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?)");
|
|
7100
|
+
},
|
|
7101
|
+
async openPullRequest(branch, title2, body2) {
|
|
7102
|
+
const response = await send("/merge_requests", "open merge request", {
|
|
7103
|
+
method: "POST",
|
|
7104
|
+
body: { source_branch: branch, target_branch: config2.baseBranch, title: title2, description: body2, remove_source_branch: true }
|
|
7105
|
+
});
|
|
7106
|
+
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?)");
|
|
7107
|
+
const mr = await response.json();
|
|
7108
|
+
if (typeof mr.iid !== "number") throw new HostError(500, "merge request without iid");
|
|
7109
|
+
return { url: link(mr.iid), number: mr.iid };
|
|
7110
|
+
},
|
|
7111
|
+
async pullRequestState(number3) {
|
|
7112
|
+
const response = await send(`/merge_requests/${number3}`, "read merge request");
|
|
7113
|
+
if (response.status === 404) return "closed";
|
|
7114
|
+
return stateOf((await response.json()).state);
|
|
7115
|
+
},
|
|
7116
|
+
async fileAtBase(path3) {
|
|
7117
|
+
const response = await send(`/repository/files/${encodeGitLabPath(path3)}/raw?ref=${encodeURIComponent(config2.baseSha)}`, "read file at base commit", { accept: "*/*" });
|
|
7118
|
+
return response.status === 404 ? null : decodeKeepingBom(await response.arrayBuffer());
|
|
7119
|
+
},
|
|
7120
|
+
async isPrivate() {
|
|
7121
|
+
const response = await send("", "read project");
|
|
7122
|
+
if (response.status === 404) throw new HostError(404, "project not found");
|
|
7123
|
+
return (await response.json()).visibility === "private";
|
|
7124
|
+
}
|
|
7125
|
+
};
|
|
7126
|
+
}
|
|
7127
|
+
function detectGitLab(env, extra) {
|
|
7128
|
+
if (env["CI_MERGE_REQUEST_IID"]) return { error: "fix runs on a branch pipeline, not on a merge request pipeline" };
|
|
7129
|
+
if (env["CI_COMMIT_TAG"]) return { error: "fix runs on a branch, not on a tag" };
|
|
7130
|
+
if (env["CI_COMMIT_REF_PROTECTED"] !== "true") {
|
|
7131
|
+
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" };
|
|
7132
|
+
}
|
|
7133
|
+
const projectId = env["CI_PROJECT_ID"];
|
|
7134
|
+
const repository = env["CI_PROJECT_PATH"];
|
|
7135
|
+
const baseBranch = env["CI_COMMIT_BRANCH"];
|
|
7136
|
+
const baseSha = env["CI_COMMIT_SHA"];
|
|
7137
|
+
if (!projectId || !repository || !baseBranch || !baseSha) return { error: "CI_PROJECT_ID, CI_PROJECT_PATH, CI_COMMIT_BRANCH and CI_COMMIT_SHA are required" };
|
|
7138
|
+
if (!isNumericId(projectId)) return { error: "CI_PROJECT_ID must be numeric" };
|
|
7139
|
+
if (!CODE_FIX_GITLAB_REPOSITORY_PATTERN.test(repository)) return { error: `CI_PROJECT_PATH "${repository.slice(0, 100)}" is not a GitLab project path` };
|
|
7140
|
+
const token = env["GITLAB_FIX_TOKEN"];
|
|
7141
|
+
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)" };
|
|
7142
|
+
const server = resolveGitLabServer(env);
|
|
7143
|
+
if ("error" in server) return { error: server.error };
|
|
7144
|
+
return { host: gitLabHost({ apiUrl: server.apiUrl, server: server.server, projectId, repository, token, baseBranch, baseSha, ...extra }) };
|
|
7145
|
+
}
|
|
6795
7146
|
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
|
|
7147
|
+
const kind = forced ?? (env["GITHUB_ACTIONS"] === "true" ? "github" : env["BITBUCKET_BUILD_NUMBER"] ? "bitbucket" : env["GITLAB_CI"] === "true" ? "gitlab" : null);
|
|
7148
|
+
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
7149
|
const extra = fetchImpl ? { fetchImpl } : {};
|
|
7150
|
+
if (kind === "gitlab") return detectGitLab(env, extra);
|
|
6799
7151
|
if (kind === "github") {
|
|
6800
7152
|
if (env["GITHUB_EVENT_NAME"] === "pull_request" || env["GITHUB_EVENT_NAME"] === "pull_request_target") {
|
|
6801
7153
|
return { error: "fix runs on a branch build (push, schedule or workflow_dispatch), not on a pull request" };
|
|
@@ -7131,8 +7483,8 @@ function adjacent(text, previous, next) {
|
|
|
7131
7483
|
const eol = gap.indexOf("\n");
|
|
7132
7484
|
if (eol === -1 || gap.indexOf("\n", eol + 1) !== -1) return false;
|
|
7133
7485
|
const tail = gap.slice(0, eol).trim();
|
|
7134
|
-
const
|
|
7135
|
-
return
|
|
7486
|
+
const comment2 = tail === "" || tail.startsWith("#") || tail.startsWith("//") || tail.startsWith("/*") && tail.endsWith("*/");
|
|
7487
|
+
return comment2 && gap.slice(eol + 1).trim() === "";
|
|
7136
7488
|
}
|
|
7137
7489
|
function alignmentGroups(text, block) {
|
|
7138
7490
|
const groups = [];
|
|
@@ -8764,7 +9116,7 @@ function title(ruleId) {
|
|
|
8764
9116
|
function pullRequestTitle(ruleId, address) {
|
|
8765
9117
|
return `fix(security): ${title(ruleId)} on ${address}`.slice(0, 250);
|
|
8766
9118
|
}
|
|
8767
|
-
function pullRequestBody(finding, outcome, accountId) {
|
|
9119
|
+
function pullRequestBody(finding, outcome, accountId, kind = "pull request") {
|
|
8768
9120
|
return [
|
|
8769
9121
|
`<!-- aaa-sentinel:code-fix ${finding.findingId} -->`,
|
|
8770
9122
|
"### \u{1F512} Security fix from AAA Sentinel",
|
|
@@ -8778,7 +9130,7 @@ function pullRequestBody(finding, outcome, accountId) {
|
|
|
8778
9130
|
`Files: ${outcome.patches.map((patch) => `\`${patch.file}\``).join(", ")}`,
|
|
8779
9131
|
"",
|
|
8780
9132
|
"Only literal values in the resource block were edited. Review the `terraform plan` of this branch before merging;",
|
|
8781
|
-
|
|
9133
|
+
`the finding closes after \`terraform apply\` and the next scan. Close this ${kind} to decline the fix.`
|
|
8782
9134
|
].join("\n");
|
|
8783
9135
|
}
|
|
8784
9136
|
function allObservations(index) {
|
|
@@ -8807,6 +9159,31 @@ function anchorFor(index, observations, finding, input) {
|
|
|
8807
9159
|
const scope = cloudScopeOf(resource);
|
|
8808
9160
|
return scope === null || scope.toLowerCase() === input.cloudAccountId.toLowerCase() ? resource : null;
|
|
8809
9161
|
}
|
|
9162
|
+
function loadFailure(error2, accountId) {
|
|
9163
|
+
if (!(error2 instanceof CodeFixApiError)) return { message: `could not read the open findings, nothing to fix: ${error2.message}`, setup: false };
|
|
9164
|
+
const { status, code: code2, stage } = error2;
|
|
9165
|
+
const tag = `${status}${code2 ? ` ${code2}` : ""}`;
|
|
9166
|
+
if (stage === "token" && status === 401) {
|
|
9167
|
+
return { message: `AAA Sentinel rejected the OAuth app credentials (${tag}): check IAC_FIX_CLIENT_ID and IAC_FIX_CLIENT_SECRET`, setup: true };
|
|
9168
|
+
}
|
|
9169
|
+
if (stage === "token" && code2 === "INVALID_SCOPE") {
|
|
9170
|
+
return { message: `the OAuth app in IAC_FIX_CLIENT_ID does not have the security:fix scope (${tag}): create an app with that scope`, setup: true };
|
|
9171
|
+
}
|
|
9172
|
+
if (stage === "findings" && status === 401) {
|
|
9173
|
+
return { message: `AAA Sentinel rejected the access token of the OAuth app (${tag}): check IAC_FIX_CLIENT_ID and IAC_FIX_CLIENT_SECRET`, setup: true };
|
|
9174
|
+
}
|
|
9175
|
+
if (stage === "findings" && status === 403) {
|
|
9176
|
+
const detail = code2 === "INSUFFICIENT_SCOPE" ? "the OAuth app in IAC_FIX_CLIENT_ID does not have the security:fix scope: create an app with that scope" : `the OAuth app in IAC_FIX_CLIENT_ID cannot use account ${accountId}: check --account and the accounts the app is limited to`;
|
|
9177
|
+
return { message: `${detail} (${tag})`, setup: true };
|
|
9178
|
+
}
|
|
9179
|
+
if (code2 === "SECURITY_ADDON_INACTIVE") {
|
|
9180
|
+
return { message: `the security add-on is not active on account ${accountId} (402 SECURITY_ADDON_INACTIVE): activate it in AAA Sentinel to get fixes; nothing to fix`, setup: false };
|
|
9181
|
+
}
|
|
9182
|
+
if (code2 === "PLAN_SECURITY_ADDON") {
|
|
9183
|
+
return { message: `the plan of this organization does not include the security add-on (402 PLAN_SECURITY_ADDON): fixes need the Pro or Business plan with the add-on; nothing to fix`, setup: false };
|
|
9184
|
+
}
|
|
9185
|
+
return { message: `could not read the open findings, nothing to fix: ${error2.message}`, setup: false };
|
|
9186
|
+
}
|
|
8810
9187
|
function prState(state) {
|
|
8811
9188
|
return state === "open" ? "pr_open" : state;
|
|
8812
9189
|
}
|
|
@@ -8817,14 +9194,20 @@ function carry(findingId, fix2, state) {
|
|
|
8817
9194
|
async function runFix(options, deps) {
|
|
8818
9195
|
const warnings = [];
|
|
8819
9196
|
const lines2 = [];
|
|
9197
|
+
const declined = [];
|
|
8820
9198
|
const reports = [];
|
|
8821
9199
|
const { host } = deps;
|
|
9200
|
+
const mr = host?.kind === "gitlab";
|
|
9201
|
+
const kind = mr ? "merge request" : "pull request";
|
|
9202
|
+
const ref = (n) => mr ? `!${n}` : `#${n}`;
|
|
9203
|
+
const hostTag = host ? { host: host.kind } : {};
|
|
8822
9204
|
let input;
|
|
8823
9205
|
try {
|
|
8824
9206
|
input = await deps.api.load();
|
|
8825
9207
|
} catch (error2) {
|
|
8826
|
-
|
|
8827
|
-
|
|
9208
|
+
const failure2 = loadFailure(error2, deps.accountId);
|
|
9209
|
+
warnings.push(failure2.message);
|
|
9210
|
+
return { stdout: render(options, { lines: lines2, declined, mr }, deps.accountId, null), warnings, lines: lines2, declined, reported: 0, setupError: failure2.setup };
|
|
8828
9211
|
}
|
|
8829
9212
|
if (input.truncated) warnings.push("the account has more open findings than the API returns (500 most severe): the rest are left for a later run");
|
|
8830
9213
|
let publicRepo = false;
|
|
@@ -8834,24 +9217,29 @@ async function runFix(options, deps) {
|
|
|
8834
9217
|
publicRepo = !await host.isPrivate();
|
|
8835
9218
|
} catch (error2) {
|
|
8836
9219
|
publicRepo = true;
|
|
8837
|
-
warnings.push(`could not tell whether the repository is private, no
|
|
9220
|
+
warnings.push(`could not tell whether the repository is private, no ${kind} opened: ${error2.message}`);
|
|
8838
9221
|
}
|
|
8839
|
-
if (publicRepo) warnings.push(
|
|
9222
|
+
if (publicRepo) warnings.push(`the repository is public: no ${kind} opened (pass --allow-public-repo to open them anyway)`);
|
|
8840
9223
|
}
|
|
8841
9224
|
const index = new PlanIndex(deps.plan);
|
|
8842
9225
|
const observations = allObservations(index);
|
|
8843
9226
|
let opened = 0;
|
|
8844
9227
|
for (const finding of input.findings) {
|
|
8845
9228
|
const existing = input.fixes.get(finding.findingId);
|
|
8846
|
-
const sameRepo = Boolean(existing && host && existing.host === host.kind && existing.repository === host.repository);
|
|
9229
|
+
const sameRepo = Boolean(existing && host && existing.host === host.kind && existing.repository === host.repository && existing.server === host.server);
|
|
8847
9230
|
if (existing && CODE_FIX_PR_STATES.includes(existing.state) && !sameRepo) continue;
|
|
8848
|
-
if (existing?.state === "closed")
|
|
9231
|
+
if (existing?.state === "closed") {
|
|
9232
|
+
if (anchorFor(index, observations, finding, input)) {
|
|
9233
|
+
declined.push({ findingId: finding.findingId, ruleId: finding.ruleId, address: existing.address, ...existing.pullRequest ? { pullRequest: existing.pullRequest.url } : {} });
|
|
9234
|
+
}
|
|
9235
|
+
continue;
|
|
9236
|
+
}
|
|
8849
9237
|
if (existing && host && sameRepo && existing.state === "pr_open" && existing.pullRequest) {
|
|
8850
9238
|
let state = "pr_open";
|
|
8851
9239
|
try {
|
|
8852
9240
|
state = prState(await host.pullRequestState(existing.pullRequest.number));
|
|
8853
9241
|
} catch (error2) {
|
|
8854
|
-
warnings.push(`could not read
|
|
9242
|
+
warnings.push(`could not read ${kind} ${ref(existing.pullRequest.number)}: ${error2.message}`);
|
|
8855
9243
|
}
|
|
8856
9244
|
if (state !== "merged") {
|
|
8857
9245
|
reports.push(carry(finding.findingId, existing, state));
|
|
@@ -8888,19 +9276,20 @@ async function runFix(options, deps) {
|
|
|
8888
9276
|
reason: outcome.reason,
|
|
8889
9277
|
address: outcome.address,
|
|
8890
9278
|
...outcome.file !== void 0 ? { file: outcome.file } : {},
|
|
8891
|
-
...outcome.attribute !== void 0 ? { attribute: outcome.attribute } : {}
|
|
9279
|
+
...outcome.attribute !== void 0 ? { attribute: outcome.attribute } : {},
|
|
9280
|
+
...hostTag
|
|
8892
9281
|
});
|
|
8893
9282
|
lines2.push({ ...base, outcome: "suggested", reason: outcome.reason, ...outcome.file !== void 0 ? { file: outcome.file } : {} });
|
|
8894
9283
|
continue;
|
|
8895
9284
|
}
|
|
8896
9285
|
if (outcome.kind === "fixed_in_code") {
|
|
8897
|
-
reports.push({ findingId: finding.findingId, state: "pending", reason: "fixed_in_code", address: outcome.address, file: outcome.file, attribute: outcome.attribute });
|
|
9286
|
+
reports.push({ findingId: finding.findingId, state: "pending", reason: "fixed_in_code", address: outcome.address, file: outcome.file, attribute: outcome.attribute, ...hostTag });
|
|
8898
9287
|
lines2.push({ ...base, outcome: "pending", reason: "fixed_in_code", file: outcome.file });
|
|
8899
9288
|
continue;
|
|
8900
9289
|
}
|
|
8901
9290
|
const patch = outcome;
|
|
8902
9291
|
const pending = (reason) => {
|
|
8903
|
-
reports.push({ findingId: finding.findingId, state: "pending", reason, address: patch.address, file: patch.file, attribute: patch.attribute });
|
|
9292
|
+
reports.push({ findingId: finding.findingId, state: "pending", reason, address: patch.address, file: patch.file, attribute: patch.attribute, ...hostTag });
|
|
8904
9293
|
lines2.push({ ...base, outcome: "pending", reason, file: patch.file, changes: patch.changes });
|
|
8905
9294
|
};
|
|
8906
9295
|
if (options.dryRun || !host) {
|
|
@@ -8908,7 +9297,7 @@ async function runFix(options, deps) {
|
|
|
8908
9297
|
continue;
|
|
8909
9298
|
}
|
|
8910
9299
|
if (host.unsupported) {
|
|
8911
|
-
reports.push({ findingId: finding.findingId, state: "suggested", reason: "unsupported_host", address: patch.address, file: patch.file, attribute: patch.attribute });
|
|
9300
|
+
reports.push({ findingId: finding.findingId, state: "suggested", reason: "unsupported_host", address: patch.address, file: patch.file, attribute: patch.attribute, ...hostTag });
|
|
8912
9301
|
lines2.push({ ...base, outcome: "suggested", reason: "unsupported_host", file: patch.file, changes: patch.changes });
|
|
8913
9302
|
continue;
|
|
8914
9303
|
}
|
|
@@ -8930,6 +9319,7 @@ async function runFix(options, deps) {
|
|
|
8930
9319
|
file: patch.file,
|
|
8931
9320
|
attribute: patch.attribute,
|
|
8932
9321
|
host: host.kind,
|
|
9322
|
+
...host.server !== void 0 ? { server: host.server } : {},
|
|
8933
9323
|
repository: host.repository,
|
|
8934
9324
|
pullRequest: { url: pr.url, number: pr.number }
|
|
8935
9325
|
});
|
|
@@ -8942,7 +9332,7 @@ async function runFix(options, deps) {
|
|
|
8942
9332
|
record2(pr2, prState(pr2.state));
|
|
8943
9333
|
continue;
|
|
8944
9334
|
}
|
|
8945
|
-
const reopened = await host.openPullRequest(branch, title2, pullRequestBody(finding, patch, deps.accountId));
|
|
9335
|
+
const reopened = await host.openPullRequest(branch, title2, pullRequestBody(finding, patch, deps.accountId, kind));
|
|
8946
9336
|
opened += 1;
|
|
8947
9337
|
record2(reopened, "pr_open");
|
|
8948
9338
|
continue;
|
|
@@ -8962,12 +9352,12 @@ async function runFix(options, deps) {
|
|
|
8962
9352
|
return { path: file.file, content: atBase === file.original ? patched : likeBase(patched, atBase) };
|
|
8963
9353
|
});
|
|
8964
9354
|
await host.createBranchWithCommit(branch, title2, files);
|
|
8965
|
-
const pr = await host.openPullRequest(branch, title2, pullRequestBody(finding, patch, deps.accountId));
|
|
9355
|
+
const pr = await host.openPullRequest(branch, title2, pullRequestBody(finding, patch, deps.accountId, kind));
|
|
8966
9356
|
opened += 1;
|
|
8967
9357
|
record2(pr, "pr_open");
|
|
8968
9358
|
} catch (error2) {
|
|
8969
9359
|
if (error2 instanceof SkipFinding) continue;
|
|
8970
|
-
warnings.push(`could not open the
|
|
9360
|
+
warnings.push(`could not open the ${kind} for ${patch.address}: ${error2.message}`);
|
|
8971
9361
|
pending("pr_failed");
|
|
8972
9362
|
}
|
|
8973
9363
|
}
|
|
@@ -8978,12 +9368,12 @@ async function runFix(options, deps) {
|
|
|
8978
9368
|
reported = result.accepted;
|
|
8979
9369
|
if (result.notFound > 0) warnings.push(`${result.notFound} fixes were not recorded: their findings are no longer open`);
|
|
8980
9370
|
if (result.duplicates > 0) warnings.push(`${result.duplicates} fixes were not recorded: the same finding was reported twice in one run`);
|
|
8981
|
-
if (result.stale > 0) warnings.push(`${result.stale} fixes were not recorded: AAA Sentinel already has a newer
|
|
9371
|
+
if (result.stale > 0) warnings.push(`${result.stale} fixes were not recorded: AAA Sentinel already has a newer ${kind} state for them`);
|
|
8982
9372
|
} catch (error2) {
|
|
8983
9373
|
warnings.push(`could not record the fixes in AAA Sentinel: ${error2.message}`);
|
|
8984
9374
|
}
|
|
8985
9375
|
}
|
|
8986
|
-
return { stdout: render(options, lines2, deps.accountId, input.scanAt), warnings, lines: lines2, reported };
|
|
9376
|
+
return { stdout: render(options, { lines: lines2, declined, mr }, deps.accountId, input.scanAt), warnings, lines: lines2, declined, reported, setupError: false };
|
|
8987
9377
|
}
|
|
8988
9378
|
var SkipFinding = class extends Error {
|
|
8989
9379
|
};
|
|
@@ -9002,15 +9392,23 @@ var OUTCOME_TEXT = {
|
|
|
9002
9392
|
pending: "pending",
|
|
9003
9393
|
suggested: "change suggested, no pull request"
|
|
9004
9394
|
};
|
|
9005
|
-
function render(options, lines2, accountId, scanAt) {
|
|
9006
|
-
if (options.format === "json") return JSON.stringify({ formatVersion: "1", accountId, scanAt, dryRun: options.dryRun, fixes: lines2 }, null, 2);
|
|
9007
|
-
|
|
9008
|
-
const out = [
|
|
9395
|
+
function render(options, { lines: lines2, declined, mr }, accountId, scanAt) {
|
|
9396
|
+
if (options.format === "json") return JSON.stringify({ formatVersion: "1", accountId, scanAt, dryRun: options.dryRun, fixes: lines2, declined }, null, 2);
|
|
9397
|
+
const kind = mr ? "merge request" : "pull request";
|
|
9398
|
+
const out = [];
|
|
9399
|
+
if (lines2.length === 0 && declined.length === 0) return `No open finding of account ${accountId} matches a resource of this plan.`;
|
|
9400
|
+
const dryRun = options.dryRun ? " (dry run: nothing opened or recorded)" : "";
|
|
9401
|
+
if (lines2.length === 0) out.push(`No new fix for account ${accountId}${dryRun}.`);
|
|
9402
|
+
else out.push(`Security fixes for account ${accountId}${dryRun}`);
|
|
9009
9403
|
for (const line of lines2) {
|
|
9010
9404
|
const detail = [line.reason, line.file, line.pullRequest].filter(Boolean).join(", ");
|
|
9011
|
-
out.push(` ${line.address} \u2014 ${title(line.ruleId)}: ${OUTCOME_TEXT[line.outcome]}${detail ? ` (${detail})` : ""}`);
|
|
9405
|
+
out.push(` ${line.address} \u2014 ${title(line.ruleId)}: ${OUTCOME_TEXT[line.outcome].replace("pull request", kind)}${detail ? ` (${detail})` : ""}`);
|
|
9012
9406
|
for (const change of line.changes ?? []) out.push(` ${change}`);
|
|
9013
9407
|
}
|
|
9408
|
+
if (declined.length > 0) {
|
|
9409
|
+
out.push(`${declined.length} earlier ${declined.length === 1 ? "fix was" : "fixes were"} declined: ${declined.length === 1 ? "its" : "their"} ${kind}${declined.length === 1 ? " was" : "s were"} closed without merging and no new one is opened:`);
|
|
9410
|
+
for (const fix2 of declined) out.push(` ${fix2.findingId.slice(0, 12)} ${fix2.address} \u2014 ${title(fix2.ruleId)}${fix2.pullRequest ? `: ${fix2.pullRequest}` : ""}`);
|
|
9411
|
+
}
|
|
9014
9412
|
return out.join("\n");
|
|
9015
9413
|
}
|
|
9016
9414
|
|
|
@@ -9025,7 +9423,8 @@ Options:
|
|
|
9025
9423
|
--account <accountId> AAA Sentinel account id (acc_\u2026), or IAC_FIX_ACCOUNT_ID
|
|
9026
9424
|
--dir <path> Directory where terraform plan ran (default: current)
|
|
9027
9425
|
--max-prs <n> Pull requests opened per run (default: ${DEFAULT_MAX_PRS})
|
|
9028
|
-
--host <github|bitbucket>
|
|
9426
|
+
--host <github|bitbucket|gitlab>
|
|
9427
|
+
Git host (default: detected from the CI)
|
|
9029
9428
|
--dry-run Print what would change; open and record nothing
|
|
9030
9429
|
--allow-public-repo Open pull requests on a public repository too (they
|
|
9031
9430
|
describe a live finding to anyone)
|
|
@@ -9035,11 +9434,12 @@ Options:
|
|
|
9035
9434
|
Environment:
|
|
9036
9435
|
IAC_FIX_CLIENT_ID / IAC_FIX_CLIENT_SECRET OAuth2 app with the security:fix scope
|
|
9037
9436
|
GITHUB_TOKEN GitHub Actions token (contents and pull-requests: write)
|
|
9038
|
-
BB_TOKEN Bitbucket repository access token (repository:write, pullrequest:write)
|
|
9437
|
+
BB_TOKEN Bitbucket repository access token (repository:write, pullrequest:write)
|
|
9438
|
+
GITLAB_FIX_TOKEN GitLab token with the Developer role and the api scope`;
|
|
9039
9439
|
async function runFixCli(argv, io) {
|
|
9040
9440
|
const warnings = [];
|
|
9041
9441
|
const fail = (message) => ({ stdout: null, warnings: [...warnings, message], exitCode: 2 });
|
|
9042
|
-
const { values, positionals } =
|
|
9442
|
+
const { values, positionals } = parseArgs3({
|
|
9043
9443
|
args: [...argv],
|
|
9044
9444
|
strict: false,
|
|
9045
9445
|
allowPositionals: true,
|
|
@@ -9112,11 +9512,11 @@ ${FIX_USAGE}`);
|
|
|
9112
9512
|
}
|
|
9113
9513
|
const locator = new SourceLocator(configurationOf(plan), workDir, repoRoot ?? workDir);
|
|
9114
9514
|
const result = await runFix({ dryRun, maxPrs, format, allowPublicRepo: values["allow-public-repo"] === true }, { plan, api, host, locator, accountId: account });
|
|
9115
|
-
return { stdout: result.stdout, warnings: [...warnings, ...result.warnings], exitCode: 0 };
|
|
9515
|
+
return { stdout: result.stdout, warnings: [...warnings, ...result.warnings], exitCode: result.setupError ? 2 : 0 };
|
|
9116
9516
|
}
|
|
9117
9517
|
|
|
9118
9518
|
// src/posture/posture.ts
|
|
9119
|
-
import { parseArgs as
|
|
9519
|
+
import { parseArgs as parseArgs4 } from "node:util";
|
|
9120
9520
|
var POSTURE_USAGE = `Usage: iac-cost posture --account <accountId> [options]
|
|
9121
9521
|
|
|
9122
9522
|
Prints how the security posture of an AAA Sentinel account changed over a
|
|
@@ -9142,7 +9542,7 @@ Environment:
|
|
|
9142
9542
|
var SEVERITIES2 = ["critical", "high", "medium", "low"];
|
|
9143
9543
|
var DAYS = [30, 90, 365];
|
|
9144
9544
|
var FORMATS2 = ["markdown", "text", "json"];
|
|
9145
|
-
var
|
|
9545
|
+
var TIMEOUT_MS4 = 35e3;
|
|
9146
9546
|
var APP_URL = "https://app.aaa-sentinel.com";
|
|
9147
9547
|
var total = (c) => SEVERITIES2.reduce((n, s) => n + (c[s] ?? 0), 0);
|
|
9148
9548
|
var bySeverity = (c) => SEVERITIES2.filter((s) => (c[s] ?? 0) > 0).map((s) => `${c[s]} ${s}`).join(", ");
|
|
@@ -9210,14 +9610,14 @@ async function fetchPostureHistory(config2) {
|
|
|
9210
9610
|
const fetchImpl = config2.fetchImpl ?? fetch;
|
|
9211
9611
|
const token = await fetchToken(config2, "security:read");
|
|
9212
9612
|
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(
|
|
9613
|
+
const response = await fetchImpl(url, { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(TIMEOUT_MS4) });
|
|
9214
9614
|
if (!response.ok) throw new Error(`posture_history_http_${response.status}`);
|
|
9215
9615
|
return await response.json();
|
|
9216
9616
|
}
|
|
9217
9617
|
async function runPostureCli(argv, io) {
|
|
9218
9618
|
const warnings = [];
|
|
9219
9619
|
const fail = (message) => ({ stdout: null, warnings: [...warnings, message], exitCode: 2 });
|
|
9220
|
-
const { values, positionals } =
|
|
9620
|
+
const { values, positionals } = parseArgs4({
|
|
9221
9621
|
args: [...argv],
|
|
9222
9622
|
strict: false,
|
|
9223
9623
|
allowPositionals: true,
|
|
@@ -9411,88 +9811,6 @@ function parseTerraformPlan(plan) {
|
|
|
9411
9811
|
};
|
|
9412
9812
|
}
|
|
9413
9813
|
|
|
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
9814
|
// src/security/drift.ts
|
|
9497
9815
|
var SCOPE2 = "security:read";
|
|
9498
9816
|
var REQUEST_TIMEOUT_MS2 = 35e3;
|
|
@@ -13109,9 +13427,19 @@ async function posture(argv) {
|
|
|
13109
13427
|
if (outcome.stdout) console.log(outcome.stdout);
|
|
13110
13428
|
process.exitCode = outcome.exitCode;
|
|
13111
13429
|
}
|
|
13430
|
+
async function comment(argv) {
|
|
13431
|
+
const outcome = await runCommentCli(argv, {
|
|
13432
|
+
env: process.env,
|
|
13433
|
+
readBody: (file) => decodePlan(file ? readFileSync2(file) : readFileSync2(0))
|
|
13434
|
+
});
|
|
13435
|
+
for (const warning of outcome.warnings) console.warn(`iac-cost: ${warning}`);
|
|
13436
|
+
if (outcome.stdout) console.log(outcome.stdout);
|
|
13437
|
+
process.exitCode = outcome.exitCode;
|
|
13438
|
+
}
|
|
13112
13439
|
async function main() {
|
|
13113
13440
|
if (process.argv[2] === "fix") return fix(process.argv.slice(3));
|
|
13114
13441
|
if (process.argv[2] === "posture") return posture(process.argv.slice(3));
|
|
13442
|
+
if (process.argv[2] === "comment") return comment(process.argv.slice(3));
|
|
13115
13443
|
const options = parseCliArgs(process.argv.slice(2), process.env);
|
|
13116
13444
|
if ("error" in options) {
|
|
13117
13445
|
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.1",
|
|
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",
|