@aaa-sentinel/iac-cost 0.4.1 → 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 +127 -4
- package/dist/cli.js +585 -117
- 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
|
|
|
@@ -139,8 +146,32 @@ or account ids. The JSON output does not: it is the complete evidence (see `--fo
|
|
|
139
146
|
`provider` block rather than the resource, so `terraform show -json` often leaves it unknown.
|
|
140
147
|
We say we do not know rather than substituting another region's price.
|
|
141
148
|
|
|
142
|
-
|
|
143
|
-
|
|
149
|
+
- **Usage is not guessed.** Only what the plan fixes is priced: the instance hours (730 a month)
|
|
150
|
+
and, for RDS, the allocated storage plus the IOPS and throughput provisioned above what the
|
|
151
|
+
volume includes. Usage-based charges — data transfer, backups beyond the allocated size, I/O
|
|
152
|
+
requests, CPU credits of burstable classes — are not added, nor storage growth from autoscaling
|
|
153
|
+
(`max_allocated_storage`), and neither are RDS Extended
|
|
154
|
+
Support (engine versions past standard support) or paid Performance Insights retention.
|
|
155
|
+
- **Every price-moving attribute must be known.** An `aws_db_instance` is priced only when the
|
|
156
|
+
plan resolves its engine, Multi-AZ, allocated storage, storage type (and IOPS/throughput where
|
|
157
|
+
they are billed, and the license model for Oracle SE2). An attribute you leave out of the
|
|
158
|
+
configuration shows as "known after apply"; the CLI reads the plan's `configuration` (modules,
|
|
159
|
+
`count` and `for_each` included) and, only when the attribute is not written at all, the AWS
|
|
160
|
+
default is applied: `multi_az` (optional in the RDS API, which creates a Single-AZ instance when
|
|
161
|
+
it is not sent), `storage_type` (`io1` with `iops`, otherwise `gp3`
|
|
162
|
+
per the RDS API; because the provider docs still say `gp2`, it is priced only where gp2 and gp3
|
|
163
|
+
cost the same) and the included gp3 baseline IOPS/throughput. Such rows are marked † in the
|
|
164
|
+
comment with the attributes assumed. Nothing is assumed on updates, when the instance is
|
|
165
|
+
restored from a snapshot or replica (its storage comes from the source), or when `iops` is an
|
|
166
|
+
expression. An attribute written as an expression that is only known after apply is never
|
|
167
|
+
guessed.
|
|
168
|
+
|
|
169
|
+
Currently priced: **AWS** (EC2 on demand and RDS `aws_db_instance`: MySQL, PostgreSQL, MariaDB,
|
|
170
|
+
Oracle and SQL Server, Single-AZ or Multi-AZ, gp2/gp3/io1/io2) and **Azure** (virtual machines).
|
|
171
|
+
Aurora (`aws_rds_cluster`, `aws_rds_cluster_instance`) is not priced: its instance price depends on
|
|
172
|
+
the cluster's storage configuration and its storage and I/O are billed by use. Anything else is
|
|
173
|
+
reported as not priced, never as free. Versions of the CLI before 0.5.0 do not send the RDS
|
|
174
|
+
storage attributes, so their RDS instances stay not priced.
|
|
144
175
|
|
|
145
176
|
## Security before deploy
|
|
146
177
|
|
|
@@ -392,6 +423,65 @@ pipelines:
|
|
|
392
423
|
> `content.raw`, hence the `// ""` — without it `jq` aborts and the comment is posted again
|
|
393
424
|
> instead of updated.
|
|
394
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
|
+
|
|
395
485
|
## Fixes as pull requests
|
|
396
486
|
|
|
397
487
|
If a resource is managed by Terraform, fixing it in the console creates drift: the next
|
|
@@ -457,7 +547,7 @@ the reason, and the app shows it that way:
|
|
|
457
547
|
| `no_public_access_block` | The bucket has no `aws_s3_bucket_public_access_block` to edit |
|
|
458
548
|
| `replacement_required` | The fix forces a new resource (RDS encryption, Cloud SQL CMEK) |
|
|
459
549
|
| `ignore_changes` | `lifecycle { ignore_changes }` covers the attribute (or has a comment inside the list): Terraform would not apply the change |
|
|
460
|
-
| `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 |
|
|
461
551
|
| `cause_not_in_code` | The open value is not in the code (added by hand, or a provider default) |
|
|
462
552
|
| `block_not_found` | The `resource` block could not be read (`.tf.json`, or a layout the editor does not handle) |
|
|
463
553
|
| `rule_not_automated` | No deterministic code fix for that rule |
|
|
@@ -474,7 +564,7 @@ review its `terraform plan` before merging. The finding closes after `terraform
|
|
|
474
564
|
| `--account <accountId>` | AAA Sentinel account id. Also `IAC_FIX_ACCOUNT_ID` |
|
|
475
565
|
| `--dir <path>` | Directory where `terraform plan` ran (default: current). The repository root is the nearest `.git` above it |
|
|
476
566
|
| `--max-prs <n>` | Pull requests opened per run (default 5, `0` records without opening) |
|
|
477
|
-
| `--host <github\|bitbucket>` | Git host. Detected from the CI by default |
|
|
567
|
+
| `--host <github\|bitbucket\|gitlab>` | Git host. Detected from the CI by default |
|
|
478
568
|
| `--dry-run` | Prints the changes; opens nothing and records nothing. Works without a git host |
|
|
479
569
|
| `--allow-public-repo` | Opens pull requests on a public repository too |
|
|
480
570
|
| `--format <text\|json>` | Output format |
|
|
@@ -547,6 +637,39 @@ pipelines:
|
|
|
547
637
|
|
|
548
638
|
The commit is created through the Bitbucket API (`POST /src`), so the clone needs no push access.
|
|
549
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
|
+
|
|
550
673
|
## Posture over time
|
|
551
674
|
|
|
552
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, {
|
|
@@ -2351,18 +2595,18 @@ var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
|
|
|
2351
2595
|
capSize(inst, arraySize);
|
|
2352
2596
|
});
|
|
2353
2597
|
function handlePropertyResult(result, final, key, input, optin, optout) {
|
|
2354
|
-
const
|
|
2598
|
+
const isPresent2 = key in input;
|
|
2355
2599
|
const isOptionalOut = optout === "optional";
|
|
2356
|
-
if (!
|
|
2600
|
+
if (!isPresent2 && isOptionalOut && optin === "optional") {
|
|
2357
2601
|
return;
|
|
2358
2602
|
}
|
|
2359
2603
|
if (result.issues.length) {
|
|
2360
|
-
if (optin !== void 0 && isOptionalOut && !
|
|
2604
|
+
if (optin !== void 0 && isOptionalOut && !isPresent2) {
|
|
2361
2605
|
return;
|
|
2362
2606
|
}
|
|
2363
2607
|
final.issues.push(...prefixIssues(key, result.issues));
|
|
2364
2608
|
}
|
|
2365
|
-
if (!
|
|
2609
|
+
if (!isPresent2 && optin === void 0) {
|
|
2366
2610
|
if (!result.issues.length) {
|
|
2367
2611
|
final.issues.push({
|
|
2368
2612
|
code: "invalid_type",
|
|
@@ -2374,7 +2618,7 @@ function handlePropertyResult(result, final, key, input, optin, optout) {
|
|
|
2374
2618
|
return;
|
|
2375
2619
|
}
|
|
2376
2620
|
if (result.value === void 0) {
|
|
2377
|
-
if (
|
|
2621
|
+
if (isPresent2 || optin === "defaulted" && !isOptionalOut) {
|
|
2378
2622
|
final.value[key] = void 0;
|
|
2379
2623
|
}
|
|
2380
2624
|
} else {
|
|
@@ -2563,7 +2807,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
|
|
|
2563
2807
|
continue;
|
|
2564
2808
|
const id = ids[key];
|
|
2565
2809
|
const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key);
|
|
2566
|
-
const
|
|
2810
|
+
const isPresent2 = `${k} in input`;
|
|
2567
2811
|
const schema = shape[key];
|
|
2568
2812
|
const optin = schema?._zod?.optin;
|
|
2569
2813
|
const isOptionalIn = optin !== void 0;
|
|
@@ -2572,7 +2816,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
|
|
|
2572
2816
|
if (isOptionalIn && isOptionalOut) {
|
|
2573
2817
|
const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;
|
|
2574
2818
|
doc.write(`
|
|
2575
|
-
const ${id}_present = ${
|
|
2819
|
+
const ${id}_present = ${isPresent2};
|
|
2576
2820
|
if (!${id}.issues.length || ${id}_present) {
|
|
2577
2821
|
if (${id}.issues.length) {${prefixStr(id, k)}
|
|
2578
2822
|
}
|
|
@@ -2585,7 +2829,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
|
|
|
2585
2829
|
`);
|
|
2586
2830
|
} else if (!isOptionalIn) {
|
|
2587
2831
|
doc.write(`
|
|
2588
|
-
const ${id}_present = ${
|
|
2832
|
+
const ${id}_present = ${isPresent2};
|
|
2589
2833
|
if (${id}.issues.length) {${prefixStr(id, k)}
|
|
2590
2834
|
}
|
|
2591
2835
|
if (!${id}_present && !${id}.issues.length) {
|
|
@@ -2615,7 +2859,7 @@ var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) =>
|
|
|
2615
2859
|
doc.write(`newResult[${k}] = ${id}.value;`);
|
|
2616
2860
|
} else {
|
|
2617
2861
|
doc.write(`
|
|
2618
|
-
if (${id}.value !== undefined || ${
|
|
2862
|
+
if (${id}.value !== undefined || ${isPresent2}) {
|
|
2619
2863
|
newResult[${k}] = ${id}.value;
|
|
2620
2864
|
}
|
|
2621
2865
|
`);
|
|
@@ -6265,6 +6509,8 @@ function iacProviderOf(resourceType) {
|
|
|
6265
6509
|
billing: !NON_BILLING_PROVIDERS.has(name)
|
|
6266
6510
|
};
|
|
6267
6511
|
}
|
|
6512
|
+
var IAC_UNSET_IN_CONFIG = "unset_in_config";
|
|
6513
|
+
var IAC_UNKNOWN_IN_PLAN = "unknown_in_plan";
|
|
6268
6514
|
var IAC_RESOURCE_SPECS = {
|
|
6269
6515
|
// ── Azure ──
|
|
6270
6516
|
azurerm_linux_virtual_machine: {
|
|
@@ -6295,16 +6541,35 @@ var IAC_RESOURCE_SPECS = {
|
|
|
6295
6541
|
instancesAttribute: "instances",
|
|
6296
6542
|
os: "windows"
|
|
6297
6543
|
},
|
|
6298
|
-
// ── AWS
|
|
6544
|
+
// ── AWS ──
|
|
6545
|
+
// hashicorp/aws 6.x admite `region` por recurso; sin escribirla el plan trae la del provider.
|
|
6299
6546
|
aws_instance: {
|
|
6300
6547
|
provider: "aws",
|
|
6301
|
-
attributes: ["instance_type"],
|
|
6302
|
-
sizeAttribute: "instance_type"
|
|
6548
|
+
attributes: ["instance_type", "region"],
|
|
6549
|
+
sizeAttribute: "instance_type",
|
|
6550
|
+
regionAttribute: "region",
|
|
6551
|
+
regionPlannedByProvider: true
|
|
6303
6552
|
},
|
|
6553
|
+
// Aurora (`aws_rds_cluster*`) no está: el precio de su instancia depende del `storage_type` del clúster, que es otro recurso.
|
|
6304
6554
|
aws_db_instance: {
|
|
6305
6555
|
provider: "aws",
|
|
6306
|
-
attributes: [
|
|
6307
|
-
|
|
6556
|
+
attributes: [
|
|
6557
|
+
"instance_class",
|
|
6558
|
+
"engine",
|
|
6559
|
+
"license_model",
|
|
6560
|
+
"multi_az",
|
|
6561
|
+
"allocated_storage",
|
|
6562
|
+
"storage_type",
|
|
6563
|
+
"iops",
|
|
6564
|
+
"storage_throughput",
|
|
6565
|
+
"region"
|
|
6566
|
+
],
|
|
6567
|
+
sizeAttribute: "instance_class",
|
|
6568
|
+
regionAttribute: "region",
|
|
6569
|
+
regionPlannedByProvider: true,
|
|
6570
|
+
unsetReportable: ["multi_az", "storage_type", "iops", "storage_throughput"],
|
|
6571
|
+
unsetBlockedBy: ["snapshot_identifier", "replicate_source_db"],
|
|
6572
|
+
unsetBlockedByBlocks: ["restore_to_point_in_time", "s3_import"]
|
|
6308
6573
|
},
|
|
6309
6574
|
// ── GCP: ídem ──
|
|
6310
6575
|
google_compute_instance: {
|
|
@@ -6378,7 +6643,7 @@ function aggregateEstimates(estimates) {
|
|
|
6378
6643
|
const pricedProviders = /* @__PURE__ */ new Set();
|
|
6379
6644
|
for (const estimate of estimates) {
|
|
6380
6645
|
for (const item of estimate.priced) {
|
|
6381
|
-
const key = keyOf(item)
|
|
6646
|
+
const key = `${keyOf(item)}#${(item.assumedDefaults ?? []).join(",")}`;
|
|
6382
6647
|
const found = priced.get(key);
|
|
6383
6648
|
if (!found) priced.set(key, { ...item });
|
|
6384
6649
|
else {
|
|
@@ -6521,17 +6786,11 @@ async function estimatePlan(projection, config2) {
|
|
|
6521
6786
|
|
|
6522
6787
|
// src/fix/cli-fix.ts
|
|
6523
6788
|
import path2 from "node:path";
|
|
6524
|
-
import { parseArgs as
|
|
6525
|
-
|
|
6526
|
-
// ../../shared/dist/security-code-fix.js
|
|
6527
|
-
var CODE_FIX_STATES = ["pending", "pr_open", "merged", "closed", "suggested"];
|
|
6528
|
-
var CODE_FIX_PR_STATES = ["pr_open", "merged", "closed"];
|
|
6529
|
-
var CODE_FIX_HOSTS = ["github", "bitbucket"];
|
|
6530
|
-
var CODE_FIX_REPORT_MAX = 100;
|
|
6789
|
+
import { parseArgs as parseArgs3 } from "node:util";
|
|
6531
6790
|
|
|
6532
6791
|
// src/fix/api.ts
|
|
6533
6792
|
var SCOPE = "security:fix";
|
|
6534
|
-
var
|
|
6793
|
+
var TIMEOUT_MS2 = 35e3;
|
|
6535
6794
|
function codeFixApi(config2) {
|
|
6536
6795
|
const fetchImpl = config2.fetchImpl ?? fetch;
|
|
6537
6796
|
const url = `${config2.baseUrl}/v1/security/code-fixes?accountId=${encodeURIComponent(config2.accountId)}`;
|
|
@@ -6542,7 +6801,7 @@ function codeFixApi(config2) {
|
|
|
6542
6801
|
};
|
|
6543
6802
|
return {
|
|
6544
6803
|
async load() {
|
|
6545
|
-
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) });
|
|
6546
6805
|
if (!response.ok) throw new Error(`code_fixes_http_${response.status}`);
|
|
6547
6806
|
const body2 = await response.json();
|
|
6548
6807
|
const findings = (body2.findings ?? []).flatMap(
|
|
@@ -6577,7 +6836,7 @@ function codeFixApi(config2) {
|
|
|
6577
6836
|
method: "POST",
|
|
6578
6837
|
headers: { authorization: `Bearer ${await bearer()}`, "content-type": "application/json" },
|
|
6579
6838
|
body: JSON.stringify({ fixes: fixes.slice(i, i + CODE_FIX_REPORT_MAX) }),
|
|
6580
|
-
signal: AbortSignal.timeout(
|
|
6839
|
+
signal: AbortSignal.timeout(TIMEOUT_MS2)
|
|
6581
6840
|
});
|
|
6582
6841
|
if (!response.ok) throw new Error(`code_fixes_report_http_${response.status}`);
|
|
6583
6842
|
const body2 = await response.json();
|
|
@@ -6596,7 +6855,7 @@ function codeFixApi(config2) {
|
|
|
6596
6855
|
// src/fix/hosts.ts
|
|
6597
6856
|
var encodePath = (path3) => path3.split("/").map(encodeURIComponent).join("/");
|
|
6598
6857
|
var decodeKeepingBom = (buffer) => new TextDecoder("utf-8", { ignoreBOM: true }).decode(buffer);
|
|
6599
|
-
var
|
|
6858
|
+
var TIMEOUT_MS3 = 3e4;
|
|
6600
6859
|
var HostError = class extends Error {
|
|
6601
6860
|
constructor(status, message) {
|
|
6602
6861
|
super(message);
|
|
@@ -6604,7 +6863,7 @@ var HostError = class extends Error {
|
|
|
6604
6863
|
}
|
|
6605
6864
|
};
|
|
6606
6865
|
async function call(fetchImpl, url, init, label) {
|
|
6607
|
-
const response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(
|
|
6866
|
+
const response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(TIMEOUT_MS3) });
|
|
6608
6867
|
if (!response.ok && response.status !== 404) {
|
|
6609
6868
|
let detail = "";
|
|
6610
6869
|
try {
|
|
@@ -6771,10 +7030,96 @@ function bitbucketHost(config2) {
|
|
|
6771
7030
|
}
|
|
6772
7031
|
};
|
|
6773
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
|
+
}
|
|
6774
7118
|
function detectHost(env, forced, fetchImpl) {
|
|
6775
|
-
const kind = forced ?? (env["GITHUB_ACTIONS"] === "true" ? "github" : env["BITBUCKET_BUILD_NUMBER"] ? "bitbucket" : null);
|
|
6776
|
-
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" };
|
|
6777
7121
|
const extra = fetchImpl ? { fetchImpl } : {};
|
|
7122
|
+
if (kind === "gitlab") return detectGitLab(env, extra);
|
|
6778
7123
|
if (kind === "github") {
|
|
6779
7124
|
if (env["GITHUB_EVENT_NAME"] === "pull_request" || env["GITHUB_EVENT_NAME"] === "pull_request_target") {
|
|
6780
7125
|
return { error: "fix runs on a branch build (push, schedule or workflow_dispatch), not on a pull request" };
|
|
@@ -7110,8 +7455,8 @@ function adjacent(text, previous, next) {
|
|
|
7110
7455
|
const eol = gap.indexOf("\n");
|
|
7111
7456
|
if (eol === -1 || gap.indexOf("\n", eol + 1) !== -1) return false;
|
|
7112
7457
|
const tail = gap.slice(0, eol).trim();
|
|
7113
|
-
const
|
|
7114
|
-
return
|
|
7458
|
+
const comment2 = tail === "" || tail.startsWith("#") || tail.startsWith("//") || tail.startsWith("/*") && tail.endsWith("*/");
|
|
7459
|
+
return comment2 && gap.slice(eol + 1).trim() === "";
|
|
7115
7460
|
}
|
|
7116
7461
|
function alignmentGroups(text, block) {
|
|
7117
7462
|
const groups = [];
|
|
@@ -8822,7 +9167,7 @@ async function runFix(options, deps) {
|
|
|
8822
9167
|
let opened = 0;
|
|
8823
9168
|
for (const finding of input.findings) {
|
|
8824
9169
|
const existing = input.fixes.get(finding.findingId);
|
|
8825
|
-
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);
|
|
8826
9171
|
if (existing && CODE_FIX_PR_STATES.includes(existing.state) && !sameRepo) continue;
|
|
8827
9172
|
if (existing?.state === "closed") continue;
|
|
8828
9173
|
if (existing && host && sameRepo && existing.state === "pr_open" && existing.pullRequest) {
|
|
@@ -8909,6 +9254,7 @@ async function runFix(options, deps) {
|
|
|
8909
9254
|
file: patch.file,
|
|
8910
9255
|
attribute: patch.attribute,
|
|
8911
9256
|
host: host.kind,
|
|
9257
|
+
...host.server !== void 0 ? { server: host.server } : {},
|
|
8912
9258
|
repository: host.repository,
|
|
8913
9259
|
pullRequest: { url: pr.url, number: pr.number }
|
|
8914
9260
|
});
|
|
@@ -9004,7 +9350,8 @@ Options:
|
|
|
9004
9350
|
--account <accountId> AAA Sentinel account id (acc_\u2026), or IAC_FIX_ACCOUNT_ID
|
|
9005
9351
|
--dir <path> Directory where terraform plan ran (default: current)
|
|
9006
9352
|
--max-prs <n> Pull requests opened per run (default: ${DEFAULT_MAX_PRS})
|
|
9007
|
-
--host <github|bitbucket>
|
|
9353
|
+
--host <github|bitbucket|gitlab>
|
|
9354
|
+
Git host (default: detected from the CI)
|
|
9008
9355
|
--dry-run Print what would change; open and record nothing
|
|
9009
9356
|
--allow-public-repo Open pull requests on a public repository too (they
|
|
9010
9357
|
describe a live finding to anyone)
|
|
@@ -9014,11 +9361,12 @@ Options:
|
|
|
9014
9361
|
Environment:
|
|
9015
9362
|
IAC_FIX_CLIENT_ID / IAC_FIX_CLIENT_SECRET OAuth2 app with the security:fix scope
|
|
9016
9363
|
GITHUB_TOKEN GitHub Actions token (contents and pull-requests: write)
|
|
9017
|
-
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`;
|
|
9018
9366
|
async function runFixCli(argv, io) {
|
|
9019
9367
|
const warnings = [];
|
|
9020
9368
|
const fail = (message) => ({ stdout: null, warnings: [...warnings, message], exitCode: 2 });
|
|
9021
|
-
const { values, positionals } =
|
|
9369
|
+
const { values, positionals } = parseArgs3({
|
|
9022
9370
|
args: [...argv],
|
|
9023
9371
|
strict: false,
|
|
9024
9372
|
allowPositionals: true,
|
|
@@ -9095,7 +9443,7 @@ ${FIX_USAGE}`);
|
|
|
9095
9443
|
}
|
|
9096
9444
|
|
|
9097
9445
|
// src/posture/posture.ts
|
|
9098
|
-
import { parseArgs as
|
|
9446
|
+
import { parseArgs as parseArgs4 } from "node:util";
|
|
9099
9447
|
var POSTURE_USAGE = `Usage: iac-cost posture --account <accountId> [options]
|
|
9100
9448
|
|
|
9101
9449
|
Prints how the security posture of an AAA Sentinel account changed over a
|
|
@@ -9121,7 +9469,7 @@ Environment:
|
|
|
9121
9469
|
var SEVERITIES2 = ["critical", "high", "medium", "low"];
|
|
9122
9470
|
var DAYS = [30, 90, 365];
|
|
9123
9471
|
var FORMATS2 = ["markdown", "text", "json"];
|
|
9124
|
-
var
|
|
9472
|
+
var TIMEOUT_MS4 = 35e3;
|
|
9125
9473
|
var APP_URL = "https://app.aaa-sentinel.com";
|
|
9126
9474
|
var total = (c) => SEVERITIES2.reduce((n, s) => n + (c[s] ?? 0), 0);
|
|
9127
9475
|
var bySeverity = (c) => SEVERITIES2.filter((s) => (c[s] ?? 0) > 0).map((s) => `${c[s]} ${s}`).join(", ");
|
|
@@ -9189,14 +9537,14 @@ async function fetchPostureHistory(config2) {
|
|
|
9189
9537
|
const fetchImpl = config2.fetchImpl ?? fetch;
|
|
9190
9538
|
const token = await fetchToken(config2, "security:read");
|
|
9191
9539
|
const url = `${config2.baseUrl}/v1/security/posture-history?accountId=${encodeURIComponent(config2.accountId)}&days=${config2.days}`;
|
|
9192
|
-
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) });
|
|
9193
9541
|
if (!response.ok) throw new Error(`posture_history_http_${response.status}`);
|
|
9194
9542
|
return await response.json();
|
|
9195
9543
|
}
|
|
9196
9544
|
async function runPostureCli(argv, io) {
|
|
9197
9545
|
const warnings = [];
|
|
9198
9546
|
const fail = (message) => ({ stdout: null, warnings: [...warnings, message], exitCode: 2 });
|
|
9199
|
-
const { values, positionals } =
|
|
9547
|
+
const { values, positionals } = parseArgs4({
|
|
9200
9548
|
args: [...argv],
|
|
9201
9549
|
strict: false,
|
|
9202
9550
|
allowPositionals: true,
|
|
@@ -9283,6 +9631,62 @@ function extractDefaultRegions(plan) {
|
|
|
9283
9631
|
}
|
|
9284
9632
|
return Object.keys(out).length > 0 ? out : void 0;
|
|
9285
9633
|
}
|
|
9634
|
+
function moduleNames(moduleAddress) {
|
|
9635
|
+
if (!moduleAddress) return [];
|
|
9636
|
+
const parts = moduleAddress.replace(/\[(?:\d+|"(?:[^"\\]|\\.)*")\]/g, "").split(".");
|
|
9637
|
+
if (parts.length % 2 !== 0) return null;
|
|
9638
|
+
const names = [];
|
|
9639
|
+
for (let i = 0; i < parts.length; i += 2) {
|
|
9640
|
+
if (parts[i] !== "module" || !/^[A-Za-z0-9_-]+$/.test(parts[i + 1] ?? "")) return null;
|
|
9641
|
+
names.push(parts[i + 1]);
|
|
9642
|
+
}
|
|
9643
|
+
return names;
|
|
9644
|
+
}
|
|
9645
|
+
function configExpressions(plan, change) {
|
|
9646
|
+
return configResource(plan, change)?.expressions;
|
|
9647
|
+
}
|
|
9648
|
+
function configResource(plan, change) {
|
|
9649
|
+
if (!change.name) return void 0;
|
|
9650
|
+
const path3 = moduleNames(change.module_address);
|
|
9651
|
+
if (path3 === null) return void 0;
|
|
9652
|
+
let module = plan.configuration?.root_module;
|
|
9653
|
+
for (const name of path3) module = module?.module_calls?.[name]?.module;
|
|
9654
|
+
const address = `${change.type}.${change.name}`;
|
|
9655
|
+
return module?.resources?.find((r) => r.address === address && (r.mode ?? "managed") === "managed");
|
|
9656
|
+
}
|
|
9657
|
+
function knownAtPlan(expression, inRoot) {
|
|
9658
|
+
if ("constant_value" in expression) return true;
|
|
9659
|
+
const references = Array.isArray(expression.references) ? expression.references : [];
|
|
9660
|
+
return inRoot && references.length > 0 && references.every((r) => typeof r === "string" && r.startsWith("var."));
|
|
9661
|
+
}
|
|
9662
|
+
function hasUnknown(value) {
|
|
9663
|
+
if (value === true) return true;
|
|
9664
|
+
if (Array.isArray(value)) return value.some(hasUnknown);
|
|
9665
|
+
if (typeof value === "object" && value !== null) return Object.values(value).some(hasUnknown);
|
|
9666
|
+
return false;
|
|
9667
|
+
}
|
|
9668
|
+
var isPresent = (value) => Array.isArray(value) ? value.length > 0 : value !== null && value !== void 0 && value !== "";
|
|
9669
|
+
function unsetInConfig(change, expressions, names, blockedBy = [], blockedByBlocks = []) {
|
|
9670
|
+
const unknownSide = change.after_unknown;
|
|
9671
|
+
if (!names || !unknownSide || !expressions) return void 0;
|
|
9672
|
+
if (blockedBy.some((name) => name in expressions || isPresent(change.after?.[name]))) return void 0;
|
|
9673
|
+
if (blockedByBlocks.some((name) => name in expressions || isPresent(change.after?.[name]) || hasUnknown(unknownSide[name]))) return void 0;
|
|
9674
|
+
const unset = names.filter((name) => unknownSide[name] === true && !(name in expressions));
|
|
9675
|
+
return unset.length > 0 ? unset.join(",") : void 0;
|
|
9676
|
+
}
|
|
9677
|
+
function regionUntrusted(plan, change, regionAttribute) {
|
|
9678
|
+
if (change.change.after_unknown?.[regionAttribute] === true) return true;
|
|
9679
|
+
if (!isPresent(change.change.after?.[regionAttribute])) return false;
|
|
9680
|
+
const resource = configResource(plan, change);
|
|
9681
|
+
if (!resource?.expressions) return true;
|
|
9682
|
+
const expression = resource.expressions[regionAttribute];
|
|
9683
|
+
if (expression !== void 0) return !knownAtPlan(expression, (moduleNames(change.module_address) ?? ["?"]).length === 0);
|
|
9684
|
+
const key = resource.provider_config_key;
|
|
9685
|
+
const provider = key === void 0 ? void 0 : plan.configuration?.provider_config?.[key];
|
|
9686
|
+
if (!provider) return true;
|
|
9687
|
+
const providerRegion = provider.expressions?.["region"];
|
|
9688
|
+
return providerRegion !== void 0 && !knownAtPlan(providerRegion, provider.module_address === void 0);
|
|
9689
|
+
}
|
|
9286
9690
|
function pickAttributes(side, unknownSide, attributeNames) {
|
|
9287
9691
|
if (!side) return void 0;
|
|
9288
9692
|
const attrs = {};
|
|
@@ -9290,6 +9694,7 @@ function pickAttributes(side, unknownSide, attributeNames) {
|
|
|
9290
9694
|
if (unknownSide?.[name] === true) continue;
|
|
9291
9695
|
const value = side[name];
|
|
9292
9696
|
if (typeof value === "string" || typeof value === "number") attrs[name] = value;
|
|
9697
|
+
else if (typeof value === "boolean") attrs[name] = String(value);
|
|
9293
9698
|
}
|
|
9294
9699
|
return Object.keys(attrs).length > 0 ? attrs : void 0;
|
|
9295
9700
|
}
|
|
@@ -9302,7 +9707,17 @@ function parseTerraformPlan(plan) {
|
|
|
9302
9707
|
if (!action) continue;
|
|
9303
9708
|
const spec = IAC_RESOURCE_SPECS[resourceChange.type];
|
|
9304
9709
|
const attributesBefore = spec ? pickAttributes(resourceChange.change.before, void 0, spec.attributes) : void 0;
|
|
9305
|
-
const
|
|
9710
|
+
const picked = spec ? pickAttributes(resourceChange.change.after, resourceChange.change.after_unknown, spec.attributes) : void 0;
|
|
9711
|
+
const expressions = spec?.unsetReportable || spec?.regionPlannedByProvider ? configExpressions(plan, resourceChange) : void 0;
|
|
9712
|
+
const creates = action === "create" || action === "replace";
|
|
9713
|
+
const unset = creates ? unsetInConfig(resourceChange.change, expressions, spec?.unsetReportable, spec?.unsetBlockedBy, spec?.unsetBlockedByBlocks) : void 0;
|
|
9714
|
+
const regionAttribute = spec?.regionPlannedByProvider ? spec.regionAttribute : void 0;
|
|
9715
|
+
const untrusted = picked !== void 0 && regionAttribute !== void 0 && regionUntrusted(plan, resourceChange, regionAttribute);
|
|
9716
|
+
let attributesAfter = unset === void 0 ? picked : { ...picked, [IAC_UNSET_IN_CONFIG]: unset };
|
|
9717
|
+
if (untrusted && attributesAfter) {
|
|
9718
|
+
const { [regionAttribute]: _dropped, ...rest } = attributesAfter;
|
|
9719
|
+
attributesAfter = { ...rest, [IAC_UNKNOWN_IN_PLAN]: regionAttribute };
|
|
9720
|
+
}
|
|
9306
9721
|
const change = {
|
|
9307
9722
|
type: resourceChange.type,
|
|
9308
9723
|
action,
|
|
@@ -9323,77 +9738,6 @@ function parseTerraformPlan(plan) {
|
|
|
9323
9738
|
};
|
|
9324
9739
|
}
|
|
9325
9740
|
|
|
9326
|
-
// src/render-comment.ts
|
|
9327
|
-
var COMMENT_MARKER = "<!-- aaa-sentinel:iac-cost -->";
|
|
9328
|
-
var REASON_TEXT = {
|
|
9329
|
-
provider_not_supported: "provider not covered yet",
|
|
9330
|
-
provider_not_priced: "provider recognized, pricing not connected yet",
|
|
9331
|
-
resource_type_not_priced: "resource type not in the priced catalog yet",
|
|
9332
|
-
region_unknown: "region could not be resolved from the plan",
|
|
9333
|
-
region_not_supported: "region not in the price catalog",
|
|
9334
|
-
size_unknown: "size/SKU could not be resolved from the plan",
|
|
9335
|
-
instance_count_unknown: "instance count could not be resolved from the plan",
|
|
9336
|
-
price_not_found: "no matching price found in the catalog"
|
|
9337
|
-
};
|
|
9338
|
-
var fmtUsd = (n) => `${n < 0 ? "-" : "+"}$${Math.abs(n).toFixed(2)}/mo`;
|
|
9339
|
-
function fmtConverted(n, currency) {
|
|
9340
|
-
const amount = new Intl.NumberFormat("en-US", { style: "currency", currency }).format(Math.abs(n));
|
|
9341
|
-
return `\u2248 ${n < 0 ? "-" : "+"}${amount}/mo`;
|
|
9342
|
-
}
|
|
9343
|
-
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.";
|
|
9344
|
-
var reasonText = (reason) => REASON_TEXT[reason] ?? reason;
|
|
9345
|
-
function actionVerb(action) {
|
|
9346
|
-
return action === "create" ? "new" : action === "delete" ? "removed" : action;
|
|
9347
|
-
}
|
|
9348
|
-
function renderComment(estimate) {
|
|
9349
|
-
const { coverage } = estimate;
|
|
9350
|
-
const lines2 = [COMMENT_MARKER, "### \u{1F4B2} Infrastructure cost estimate", ""];
|
|
9351
|
-
lines2.push(
|
|
9352
|
-
`**Coverage: ${coverage.pricedResources} of ${coverage.pricedResources + coverage.unpricedResources} billable resources priced** (${coverage.freeResources} more have no cost by design).`
|
|
9353
|
-
);
|
|
9354
|
-
lines2.push("");
|
|
9355
|
-
const display = estimate.displayCurrency?.approximate ? estimate.displayCurrency : null;
|
|
9356
|
-
const delta = (usd, converted) => display && typeof converted === "number" ? fmtConverted(converted, display.code) : fmtUsd(usd);
|
|
9357
|
-
if (estimate.totalMonthlyDeltaUsd !== null) {
|
|
9358
|
-
const total2 = delta(estimate.totalMonthlyDeltaUsd, estimate.totalMonthlyDelta);
|
|
9359
|
-
lines2.push(
|
|
9360
|
-
display ? `**Estimated change: ${total2}** (list price, ${fmtUsd(estimate.totalMonthlyDeltaUsd)} in USD)` : `**Estimated change: ${total2}** (list price, USD)`
|
|
9361
|
-
);
|
|
9362
|
-
} else {
|
|
9363
|
-
lines2.push(
|
|
9364
|
-
`_Coverage is below the threshold needed to publish a total \u2014 see the breakdown below instead of a number that wouldn't hold up._`
|
|
9365
|
-
);
|
|
9366
|
-
}
|
|
9367
|
-
lines2.push("");
|
|
9368
|
-
lines2.push(
|
|
9369
|
-
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}`
|
|
9370
|
-
);
|
|
9371
|
-
if (estimate.priced.length > 0) {
|
|
9372
|
-
lines2.push("", "| Resource | Change | Qty | Delta |", "|---|---|---|---|");
|
|
9373
|
-
for (const item of estimate.priced) {
|
|
9374
|
-
lines2.push(
|
|
9375
|
-
`| \`${item.type}\` | ${actionVerb(item.action)} | ${item.count} | ${delta(item.monthlyDeltaUsd, item.monthlyDelta)} |`
|
|
9376
|
-
);
|
|
9377
|
-
}
|
|
9378
|
-
}
|
|
9379
|
-
if (estimate.unpriced.length > 0) {
|
|
9380
|
-
lines2.push("", "<details><summary>Not priced (" + coverage.unpricedResources + " resources)</summary>", "");
|
|
9381
|
-
lines2.push("| Resource | Change | Qty | Why |", "|---|---|---|---|");
|
|
9382
|
-
for (const item of estimate.unpriced) {
|
|
9383
|
-
lines2.push(`| \`${item.type}\` | ${actionVerb(item.action)} | ${item.count} | ${reasonText(item.reason)} |`);
|
|
9384
|
-
}
|
|
9385
|
-
lines2.push("", "</details>");
|
|
9386
|
-
}
|
|
9387
|
-
const truncated = estimate.catalogs.filter((c) => c.truncated);
|
|
9388
|
-
if (truncated.length > 0) {
|
|
9389
|
-
lines2.push(
|
|
9390
|
-
"",
|
|
9391
|
-
`\u26A0\uFE0F The price catalog for ${truncated.map((c) => c.region).join(", ")} was truncated by pagination: some prices may be missing.`
|
|
9392
|
-
);
|
|
9393
|
-
}
|
|
9394
|
-
return lines2.join("\n");
|
|
9395
|
-
}
|
|
9396
|
-
|
|
9397
9741
|
// src/security/drift.ts
|
|
9398
9742
|
var SCOPE2 = "security:read";
|
|
9399
9743
|
var REQUEST_TIMEOUT_MS2 = 35e3;
|
|
@@ -10649,7 +10993,7 @@ var trailGestionIncompleta = {
|
|
|
10649
10993
|
evaluate: gestionIncompletaEvaluate
|
|
10650
10994
|
};
|
|
10651
10995
|
|
|
10652
|
-
// ../../
|
|
10996
|
+
// ../../shared/src/internet-exposure.ts
|
|
10653
10997
|
var ADMIN_PORTS2 = [22, 3389];
|
|
10654
10998
|
var DATABASE_PORTS = [1433, 1521, 2483, 2484, 3306, 5432, 6379, 9200, 9300, 27017, 27018, 27019];
|
|
10655
10999
|
var ETIQUETAS_INTERNET = /* @__PURE__ */ new Set(["*", "internet", "any", "/0"]);
|
|
@@ -10708,6 +11052,42 @@ function databasePortsReached(protocol, portRanges) {
|
|
|
10708
11052
|
if (adminPortsReached(protocol, portRanges).length > 0) return [];
|
|
10709
11053
|
return portsReached(DATABASE_PORTS, protocol, portRanges);
|
|
10710
11054
|
}
|
|
11055
|
+
var TODO_INTERNET = /* @__PURE__ */ new Set(["*", "internet", "any"]);
|
|
11056
|
+
function sourceCoversInternet(source) {
|
|
11057
|
+
return TODO_INTERNET.has(source.trim().toLowerCase());
|
|
11058
|
+
}
|
|
11059
|
+
function ipFamily(source) {
|
|
11060
|
+
const ip = source.trim().split("/")[0] ?? "";
|
|
11061
|
+
if (ip.includes(":")) return "v6";
|
|
11062
|
+
return /^\d{1,3}(\.\d{1,3}){3}$/.test(ip) ? "v4" : void 0;
|
|
11063
|
+
}
|
|
11064
|
+
function denySourceCovers(denySource, allowSource) {
|
|
11065
|
+
if (sourceCoversInternet(denySource)) return true;
|
|
11066
|
+
const partes = denySource.trim().split("/");
|
|
11067
|
+
if (partes.length !== 2 || partes[1] !== "0") return false;
|
|
11068
|
+
const familia = ipFamily(denySource);
|
|
11069
|
+
return familia !== void 0 && familia === ipFamily(allowSource);
|
|
11070
|
+
}
|
|
11071
|
+
function denyCoversEveryTarget(deny) {
|
|
11072
|
+
if ((deny.destinationAsgs ?? 0) > 0) return false;
|
|
11073
|
+
if ((deny.destinations ?? []).some((d) => !["*", "any"].includes(d.trim().toLowerCase()))) return false;
|
|
11074
|
+
return (deny.sourcePorts ?? []).every((p) => p.trim() === "*");
|
|
11075
|
+
}
|
|
11076
|
+
function deniedBeforeAllow(denies, allow, port) {
|
|
11077
|
+
const allowPriority = allow.priority;
|
|
11078
|
+
if (typeof allowPriority !== "number") return false;
|
|
11079
|
+
const abiertos = allow.sources.filter((s) => sourceOpensToInternet(s) === true);
|
|
11080
|
+
if (abiertos.length === 0) return false;
|
|
11081
|
+
const allowProtocol = protocolName(allow.protocol);
|
|
11082
|
+
return denies.some((deny) => {
|
|
11083
|
+
if (typeof deny.priority !== "number" || deny.priority >= allowPriority) return false;
|
|
11084
|
+
if (!denyCoversEveryTarget(deny)) return false;
|
|
11085
|
+
if (!abiertos.every((a) => deny.sources.some((d) => denySourceCovers(d, a)))) return false;
|
|
11086
|
+
const p = protocolName(deny.protocol);
|
|
11087
|
+
if (p !== "*" && p !== "any" && p !== "all" && p !== allowProtocol) return false;
|
|
11088
|
+
return deny.ports.length === 0 || deny.ports.some((rango) => cubrePuerto(rango, port));
|
|
11089
|
+
});
|
|
11090
|
+
}
|
|
10711
11091
|
function cadenas2(value) {
|
|
10712
11092
|
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
10713
11093
|
}
|
|
@@ -11397,7 +11777,9 @@ var AZURE_NSG_CHECKS = {
|
|
|
11397
11777
|
list: "azure:nsg:list"
|
|
11398
11778
|
};
|
|
11399
11779
|
var AZURE_STORAGE_CHECKS = {
|
|
11400
|
-
list: "azure:storage:list"
|
|
11780
|
+
list: "azure:storage:list",
|
|
11781
|
+
// Solo de las cuentas que permiten blobs públicos: dice a quien aprueba cerrarlo qué contenedores dejan de servirse.
|
|
11782
|
+
containers: "azure:storage:containers"
|
|
11401
11783
|
};
|
|
11402
11784
|
var AZURE_SQL_CHECKS = {
|
|
11403
11785
|
list: "azure:sql:list",
|
|
@@ -11418,7 +11800,12 @@ var AZURE_IAM_CHECKS = {
|
|
|
11418
11800
|
roleAssignments: "azure:iam:roleAssignments",
|
|
11419
11801
|
// Microsoft Graph, opcional: `Directory.Read.All` de aplicación (§16.7, F4).
|
|
11420
11802
|
principals: "azure:graph:directoryObjects.getByIds",
|
|
11421
|
-
groupMembers: "azure:graph:groups.members"
|
|
11803
|
+
groupMembers: "azure:graph:groups.members",
|
|
11804
|
+
// Tipo, estado y dominio de los usuarios con rol privilegiado, y los dominios federados: también con `Directory.Read.All`.
|
|
11805
|
+
users: "azure:graph:users",
|
|
11806
|
+
domains: "azure:graph:domains",
|
|
11807
|
+
// Métodos de autenticación registrados: `UserAuthenticationMethod.Read.All` de aplicación, opcional.
|
|
11808
|
+
authMethods: "azure:graph:users.authentication.methods"
|
|
11422
11809
|
};
|
|
11423
11810
|
var AZURE_LOGGING_CHECKS = {
|
|
11424
11811
|
diagnosticSettings: "azure:insights:diagnosticSettings"
|
|
@@ -11517,7 +11904,15 @@ function blobPublicoEvaluate(observation) {
|
|
|
11517
11904
|
return { status: "unknown", check: AZURE_STORAGE_CHECKS.list, attribute: "allowBlobPublicAccess" };
|
|
11518
11905
|
}
|
|
11519
11906
|
if (!permitido) return { status: "ok" };
|
|
11520
|
-
|
|
11907
|
+
const contenedores = observation.attributes.publicContainers;
|
|
11908
|
+
const lista = Array.isArray(contenedores) ? contenedores.filter((c) => typeof c === "string") : void 0;
|
|
11909
|
+
return {
|
|
11910
|
+
status: "finding",
|
|
11911
|
+
evidence: {
|
|
11912
|
+
allowBlobPublicAccess: true,
|
|
11913
|
+
...lista ? { publicContainers: lista, publicContainersTruncated: observation.attributes.publicContainersTruncated === true } : {}
|
|
11914
|
+
}
|
|
11915
|
+
};
|
|
11521
11916
|
}
|
|
11522
11917
|
var storageBlobPublico = {
|
|
11523
11918
|
id: "SEC_AZURE_EXPOSURE_BLOB_PUBLICO",
|
|
@@ -11590,6 +11985,44 @@ var rolPrivilegiado = {
|
|
|
11590
11985
|
requires: [AZURE_IAM_CHECKS.roleAssignments],
|
|
11591
11986
|
evaluate: evaluate4
|
|
11592
11987
|
};
|
|
11988
|
+
function sinMfaEvaluate(observation) {
|
|
11989
|
+
const role = observation.attributes.role;
|
|
11990
|
+
const atSubscription = observation.attributes.subscriptionScope;
|
|
11991
|
+
if (typeof role !== "string") return { status: "unknown", check: AZURE_IAM_CHECKS.roleAssignments, attribute: "role" };
|
|
11992
|
+
if (typeof atSubscription !== "boolean") return { status: "unknown", check: AZURE_IAM_CHECKS.roleAssignments, attribute: "subscriptionScope" };
|
|
11993
|
+
const privilegiado = role === "Owner" || role === "UserAccessAdministrator" || role === "Contributor" && atSubscription;
|
|
11994
|
+
if (!privilegiado || observation.attributes.principalType !== "User") return { status: "ok" };
|
|
11995
|
+
if (observation.attributes.principalExists === false) return { status: "ok" };
|
|
11996
|
+
if (observation.attributes.mfaSampled === false) {
|
|
11997
|
+
return { status: "unknown", check: AZURE_IAM_CHECKS.users, attribute: "mfaScope", reason: "sample_capped" };
|
|
11998
|
+
}
|
|
11999
|
+
const alcance = observation.attributes.mfaScope;
|
|
12000
|
+
if (typeof alcance !== "string") return { status: "unknown", check: AZURE_IAM_CHECKS.users, attribute: "mfaScope" };
|
|
12001
|
+
if (alcance !== "checked") return { status: "ok" };
|
|
12002
|
+
const segundo = observation.attributes.secondFactor;
|
|
12003
|
+
if (typeof segundo !== "boolean") return { status: "unknown", check: AZURE_IAM_CHECKS.authMethods, attribute: "secondFactor" };
|
|
12004
|
+
if (segundo) return { status: "ok" };
|
|
12005
|
+
return {
|
|
12006
|
+
status: "finding",
|
|
12007
|
+
evidence: {
|
|
12008
|
+
role,
|
|
12009
|
+
scope: observation.attributes.scope ?? null,
|
|
12010
|
+
authMethods: observation.attributes.authMethods ?? [],
|
|
12011
|
+
...pick2(observation, ["principalName"])
|
|
12012
|
+
}
|
|
12013
|
+
};
|
|
12014
|
+
}
|
|
12015
|
+
var adminSinMfa = {
|
|
12016
|
+
id: "SEC_AZURE_IAM_ADMIN_SIN_MFA",
|
|
12017
|
+
scope: "resource",
|
|
12018
|
+
category: "security_iam",
|
|
12019
|
+
severity: "high",
|
|
12020
|
+
provider: "azure",
|
|
12021
|
+
kinds: ["role_assignment"],
|
|
12022
|
+
requires: [AZURE_IAM_CHECKS.roleAssignments, AZURE_IAM_CHECKS.domains, AZURE_IAM_CHECKS.users, AZURE_IAM_CHECKS.authMethods],
|
|
12023
|
+
runtimeOnly: true,
|
|
12024
|
+
evaluate: sinMfaEvaluate
|
|
12025
|
+
};
|
|
11593
12026
|
function huerfanaEvaluate(observation) {
|
|
11594
12027
|
if (observation.attributes.orphanApplicable === false) return { status: "ok" };
|
|
11595
12028
|
const exists = observation.attributes.principalExists;
|
|
@@ -11690,6 +12123,23 @@ var vnetSinFlowLogs = {
|
|
|
11690
12123
|
};
|
|
11691
12124
|
|
|
11692
12125
|
// ../../services/security/src/rules/azure/network.ts
|
|
12126
|
+
function denyEntries(value) {
|
|
12127
|
+
if (!Array.isArray(value)) return [];
|
|
12128
|
+
return value.flatMap((entrada) => {
|
|
12129
|
+
if (typeof entrada !== "object" || entrada === null) return [];
|
|
12130
|
+
const regla = entrada;
|
|
12131
|
+
if (typeof regla.priority !== "number" || !Array.isArray(regla.destinations) || !Array.isArray(regla.sourcePorts)) return [];
|
|
12132
|
+
return [{
|
|
12133
|
+
protocol: typeof regla.protocol === "string" ? regla.protocol : "",
|
|
12134
|
+
sources: cadenas2(regla.sources),
|
|
12135
|
+
ports: cadenas2(regla.ports),
|
|
12136
|
+
priority: regla.priority,
|
|
12137
|
+
destinations: cadenas2(regla.destinations),
|
|
12138
|
+
destinationAsgs: typeof regla.destinationAsgs === "number" ? regla.destinationAsgs : 0,
|
|
12139
|
+
sourcePorts: cadenas2(regla.sourcePorts)
|
|
12140
|
+
}];
|
|
12141
|
+
});
|
|
12142
|
+
}
|
|
11693
12143
|
var evaluate6 = (observation) => nsgAbierto(observation, adminPortsReached);
|
|
11694
12144
|
function nsgAbierto(observation, reached) {
|
|
11695
12145
|
const ingress = observation.attributes.ingressRules;
|
|
@@ -11699,6 +12149,7 @@ function nsgAbierto(observation, reached) {
|
|
|
11699
12149
|
const openings = [];
|
|
11700
12150
|
const puertos = /* @__PURE__ */ new Set();
|
|
11701
12151
|
let indecisa = false;
|
|
12152
|
+
const denegaciones = denyEntries(observation.attributes.denyIngressRules);
|
|
11702
12153
|
for (const entrada of ingress) {
|
|
11703
12154
|
if (typeof entrada !== "object" || entrada === null) {
|
|
11704
12155
|
indecisa = true;
|
|
@@ -11713,10 +12164,16 @@ function nsgAbierto(observation, reached) {
|
|
|
11713
12164
|
}
|
|
11714
12165
|
if (!abierto) continue;
|
|
11715
12166
|
const protocol = typeof regla.protocol === "string" ? regla.protocol : "";
|
|
11716
|
-
const
|
|
12167
|
+
const priority = typeof regla.priority === "number" ? regla.priority : void 0;
|
|
12168
|
+
const alcanzados = reached(protocol, cadenas2(regla.ports)).filter((puerto) => !deniedBeforeAllow(denegaciones, { protocol, priority, sources }, puerto));
|
|
11717
12169
|
if (alcanzados.length === 0) continue;
|
|
11718
12170
|
for (const puerto of alcanzados) puertos.add(puerto);
|
|
11719
|
-
openings.push({
|
|
12171
|
+
openings.push({
|
|
12172
|
+
protocol: regla.protocol,
|
|
12173
|
+
ports: alcanzados,
|
|
12174
|
+
sources: regla.sources,
|
|
12175
|
+
...typeof regla.name === "string" ? { ruleName: regla.name } : {}
|
|
12176
|
+
});
|
|
11720
12177
|
}
|
|
11721
12178
|
if (openings.length > 0) {
|
|
11722
12179
|
return { status: "finding", evidence: { ports: [...puertos].sort((a, b) => a - b), openings } };
|
|
@@ -11759,6 +12216,7 @@ var AZURE_SECURITY_RULES = [
|
|
|
11759
12216
|
sqlSinTde,
|
|
11760
12217
|
rolPrivilegiado,
|
|
11761
12218
|
asignacionHuerfana,
|
|
12219
|
+
adminSinMfa,
|
|
11762
12220
|
sinDiagnosticSettings,
|
|
11763
12221
|
vnetSinFlowLogs
|
|
11764
12222
|
];
|
|
@@ -12896,9 +13354,19 @@ async function posture(argv) {
|
|
|
12896
13354
|
if (outcome.stdout) console.log(outcome.stdout);
|
|
12897
13355
|
process.exitCode = outcome.exitCode;
|
|
12898
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
|
+
}
|
|
12899
13366
|
async function main() {
|
|
12900
13367
|
if (process.argv[2] === "fix") return fix(process.argv.slice(3));
|
|
12901
13368
|
if (process.argv[2] === "posture") return posture(process.argv.slice(3));
|
|
13369
|
+
if (process.argv[2] === "comment") return comment(process.argv.slice(3));
|
|
12902
13370
|
const options = parseCliArgs(process.argv.slice(2), process.env);
|
|
12903
13371
|
if ("error" in options) {
|
|
12904
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",
|