- Prowler is the Open Cloud Security Platform trusted by thousands to automate security and compliance in any cloud environment. With hundreds of ready-to-use checks and compliance frameworks, Prowler delivers real-time, customizable monitoring and seamless integrations, making cloud security simple, scalable, and cost-effective for organizations of any size.
+ Prowler is the Open Cloud Security Platform trusted by thousands to automate security and compliance in any cloud environment. With thousands of ready-to-use checks and compliance frameworks, Prowler delivers real-time, customizable monitoring and seamless integrations, making cloud security simple, scalable, and cost-effective for organizations of any size.
Secure ANY cloud at AI Speed at prowler.com
@@ -21,7 +21,7 @@
-
+
@@ -41,7 +41,7 @@
# Description
-**Prowler** is the world’s most widely used _Open-Source Cloud Security Platform_ that automates security and compliance across **any cloud environment**. With hundreds of ready-to-use security checks, remediation guidance, and compliance frameworks, Prowler is built to _“Secure ANY Cloud at AI Speed”_. Prowler delivers **AI-driven**, **customizable**, and **easy-to-use** assessments, dashboards, reports, and integrations, making cloud security **simple**, **scalable**, and **cost-effective** for organizations of any size.
+**Prowler** is the world’s most widely used _Open-Source Cloud Security Platform_ that automates security and compliance across **any cloud environment**. With thousands of ready-to-use security checks, remediation guidance, and compliance frameworks, Prowler is built to _“Secure ANY Cloud at AI Speed”_. Prowler delivers **AI-driven**, **customizable**, and **easy-to-use** assessments, dashboards, reports, and integrations, making cloud security **simple**, **scalable**, and **cost-effective** for organizations of any size.
Prowler includes hundreds of built-in controls to ensure compliance with standards and frameworks, including:
@@ -54,16 +54,16 @@ Prowler includes hundreds of built-in controls to ensure compliance with standar
- **National Security Standards:** ENS (Spanish National Security Scheme) and KISA ISMS-P (Korean)
- **Custom Security Frameworks:** Tailored to your needs
-## Prowler App / Prowler Cloud
+## Prowler Cloud & Prowler Local Server
-Prowler App / [Prowler Cloud](https://cloud.prowler.com/) is a web-based application that simplifies running Prowler across your cloud provider accounts. It provides a user-friendly interface to visualize the results and streamline your security assessments.
+[Prowler Cloud](https://cloud.prowler.com/) and Prowler Local Server, its self-hosted open-source version, are web applications that simplify running Prowler across your cloud provider accounts. They provide a user-friendly interface to visualize the results and streamline your security assessments.
-
+


->For more details, refer to the [Prowler App Documentation](https://docs.prowler.com/projects/prowler-open-source/en/latest/#prowler-app-installation)
+>For more details, refer to the [Prowler Local Server documentation](https://docs.prowler.com/getting-started/installation/prowler-app)
## Prowler CLI
@@ -73,26 +73,45 @@ prowler

-## Prowler Dashboard
+## Prowler Local Dashboard
```console
prowler dashboard
```
-
+
## Attack Paths
-Attack Paths automatically extends every completed AWS scan with a Neo4j graph that combines Cartography's cloud inventory with Prowler findings. The feature runs in the API worker after each scan and therefore requires:
+Attack Paths automatically extends every completed AWS scan with a graph that combines Cartography's cloud inventory with Prowler findings. The feature runs in the API worker after each scan.
-- An accessible Neo4j instance (the Docker Compose files already ships a `neo4j` service).
-- The following environment variables so Django and Celery can connect:
+Two graph backends are supported as the long-lived sink:
- | Variable | Description | Default |
- | --- | --- | --- |
- | `NEO4J_HOST` | Hostname used by the API containers. | `neo4j` |
- | `NEO4J_PORT` | Bolt port exposed by Neo4j. | `7687` |
- | `NEO4J_USER` / `NEO4J_PASSWORD` | Credentials with rights to create per-tenant databases. | `neo4j` / `neo4j_password` |
+- **Neo4j** (default; the Docker Compose files already ship a `neo4j` service).
+- **Amazon Neptune** (cloud-managed; opt-in).
+
+Select the sink with `ATTACK_PATHS_SINK_DATABASE` (`neo4j` or `neptune`; default `neo4j`).
+
+> Note: Cartography ingestion always uses a temporary Neo4j database, regardless of the configured sink. The `NEO4J_*` variables below must remain set even when `ATTACK_PATHS_SINK_DATABASE=neptune`.
+
+### Neo4j sink
+
+| Variable | Description | Default |
+| --- | --- | --- |
+| `NEO4J_HOST` | Hostname used by the API containers. | `neo4j` |
+| `NEO4J_PORT` | Bolt port exposed by Neo4j. | `7687` |
+| `NEO4J_USER` / `NEO4J_PASSWORD` | Credentials with rights to create per-tenant databases. | `neo4j` / `neo4j_password` |
+
+### Neptune sink
+
+| Variable | Description | Default |
+| --- | --- | --- |
+| `NEPTUNE_WRITER_ENDPOINT` | Bolt host for the Neptune writer instance. Required when sink is `neptune`. | _empty_ |
+| `NEPTUNE_READER_ENDPOINT` | Optional reader endpoint for read-only queries. Falls back to the writer when unset. | _empty_ |
+| `NEPTUNE_PORT` | Bolt port exposed by Neptune. | `8182` |
+| `AWS_REGION` | Region the Neptune cluster lives in. Required when sink is `neptune`. | _empty_ |
+
+Neptune authenticates with SigV4 using the standard boto3 credential chain. The worker's IAM role (or `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`) supplies the credentials. There is no Neptune password variable.
Every AWS provider scan will enqueue an Attack Paths ingestion job automatically. Other cloud providers will be added in future iterations.
@@ -102,29 +121,30 @@ Every AWS provider scan will enqueue an Attack Paths ingestion job automatically
> For the most accurate and up-to-date information about checks, services, frameworks, and categories, visit [**Prowler Hub**](https://hub.prowler.com).
-| Provider | Checks | Services | [Compliance Frameworks](https://docs.prowler.com/projects/prowler-open-source/en/latest/tutorials/compliance/) | [Categories](https://docs.prowler.com/projects/prowler-open-source/en/latest/tutorials/misc/#categories) | Support | Interface |
+| Provider | Checks | Services | [Compliance Frameworks](https://docs.prowler.com/user-guide/compliance/tutorials/compliance) | [Categories](https://docs.prowler.com/user-guide/cli/tutorials/misc#categories) | Support | Interface |
|---|---|---|---|---|---|---|
-| AWS | 613 | 86 | 46 | 19 | Official | UI, API, CLI |
-| Azure | 190 | 22 | 20 | 16 | Official | UI, API, CLI |
-| GCP | 109 | 20 | 18 | 12 | Official | UI, API, CLI |
-| Kubernetes | 90 | 7 | 7 | 11 | Official | UI, API, CLI |
-| GitHub | 24 | 3 | 1 | 5 | Official | UI, API, CLI |
-| M365 | 107 | 10 | 4 | 10 | Official | UI, API, CLI |
-| OCI | 52 | 14 | 4 | 10 | Official | UI, API, CLI |
-| Alibaba Cloud | 63 | 9 | 5 | 9 | Official | UI, API, CLI |
-| Cloudflare | 29 | 3 | 1 | 5 | Official | UI, API, CLI |
+| AWS | 615 | 86 | 47 | 19 | Official | UI, API, CLI |
+| Azure | 190 | 22 | 21 | 16 | Official | UI, API, CLI |
+| GCP | 109 | 20 | 19 | 12 | Official | UI, API, CLI |
+| Kubernetes | 90 | 7 | 8 | 11 | Official | UI, API, CLI |
+| GitHub | 24 | 3 | 2 | 5 | Official | UI, API, CLI |
+| M365 | 109 | 10 | 6 | 10 | Official | UI, API, CLI |
+| OCI | 52 | 14 | 5 | 10 | Official | UI, API, CLI |
+| Alibaba Cloud | 63 | 9 | 6 | 9 | Official | UI, API, CLI |
+| Cloudflare | 29 | 3 | 2 | 5 | Official | UI, API, CLI |
| IaC | [See `trivy` docs.](https://trivy.dev/latest/docs/coverage/iac/) | N/A | N/A | N/A | Official | UI, API, CLI |
-| MongoDB Atlas | 10 | 3 | 0 | 8 | Official | UI, API, CLI |
+| MongoDB Atlas | 10 | 3 | 1 | 8 | Official | UI, API, CLI |
| LLM | [See `promptfoo` docs.](https://www.promptfoo.dev/docs/red-team/plugins/) | N/A | N/A | N/A | Official | CLI |
| Image | N/A | N/A | N/A | N/A | Official | CLI, API |
-| Google Workspace | 65 | 11 | 2 | 6 | Official | UI, API, CLI |
-| OpenStack | 34 | 5 | 0 | 9 | Official | UI, API, CLI |
-| Vercel | 26 | 6 | 0 | 8 | Official | UI, API, CLI |
-| Okta | 29 | 8 | 1 | 2 | Official | UI, API, CLI |
-| Linode [Contact us](https://prowler.com/contact) | 10 | 3 | 0 | 4 | Unofficial | CLI |
-| Scaleway [Contact us](https://prowler.com/contact) | 1 | 1 | 0 | 1 | Unofficial | CLI |
-| StackIT [Contact us](https://prowler.com/contact) | 7 | 2 | 0 | 3 | Unofficial | CLI |
-| NHN | 6 | 2 | 1 | 0 | Unofficial | CLI |
+| Google Workspace | 65 | 11 | 3 | 6 | Official | UI, API, CLI |
+| OpenStack | 34 | 5 | 1 | 9 | Official | UI, API, CLI |
+| Vercel | 26 | 6 | 1 | 8 | Official | UI, API, CLI |
+| Okta | 29 | 8 | 2 | 2 | Official | UI, API, CLI |
+| Linode [Contact us](https://prowler.com/contact) | 10 | 3 | 1 | 4 | Unofficial | CLI |
+| E2E Networks [Contact us](https://prowler.com/contact) | 27 | 6 | 0 | 2 | Unofficial | CLI |
+| Scaleway [Contact us](https://prowler.com/contact) | 1 | 1 | 1 | 1 | Unofficial | CLI |
+| StackIT [Contact us](https://prowler.com/contact) | 7 | 2 | 1 | 3 | Unofficial | CLI |
+| NHN | 6 | 2 | 2 | 0 | Unofficial | CLI |
> [!Note]
> The numbers in the table are updated periodically.
@@ -140,11 +160,11 @@ Every AWS provider scan will enqueue an Attack Paths ingestion job automatically
# 💻 Installation
-## Prowler App
+## Prowler Local Server
-Prowler App offers flexible installation methods tailored to various environments:
+Prowler Local Server offers flexible installation methods tailored to various environments:
-> For detailed instructions on using Prowler App, refer to the [Prowler App Usage Guide](https://docs.prowler.com/projects/prowler-open-source/en/latest/tutorials/prowler-app/).
+> For detailed instructions on using Prowler Local Server, refer to the [usage guide](https://docs.prowler.com/user-guide/tutorials/prowler-app).
### Docker Compose
@@ -177,7 +197,7 @@ docker compose up -d
> [!WARNING]
> 🔒 For a secure setup, the API auto-generates a unique key pair, `DJANGO_TOKEN_SIGNING_KEY` and `DJANGO_TOKEN_VERIFYING_KEY`, and stores it in `~/.config/prowler-api` (non-container) or the bound Docker volume in `_data/api` (container). Never commit or reuse static/default keys. To rotate keys, delete the stored key files and restart the API.
-Once configured, access the Prowler App at http://localhost:3000. Sign up using your email and password to get started.
+Once configured, access Prowler Local Server at http://localhost:3000. Sign up using your email and password to get started.
### Common Issues with Docker Pull Installation
@@ -249,7 +269,7 @@ pnpm run build
pnpm start
```
-> Once configured, access the Prowler App at http://localhost:3000. Sign up using your email and password to get started.
+> Once configured, access Prowler Local Server at http://localhost:3000. Sign up using your email and password to get started.
#### Pre-commit Hooks Setup
@@ -267,7 +287,7 @@ Prowler CLI is available as a project in [PyPI](https://pypi.org/project/prowler
pip install prowler
prowler -v
```
->For further guidance, refer to [https://docs.prowler.com](https://docs.prowler.com/projects/prowler-open-source/en/latest/#prowler-cli-installation)
+>For further guidance, refer to [https://docs.prowler.com](https://docs.prowler.com/getting-started/installation/prowler-cli)
### Containers
@@ -287,7 +307,7 @@ The container images are available here:
- Prowler CLI:
- [DockerHub](https://hub.docker.com/r/prowlercloud/prowler/tags)
- [AWS Public ECR](https://gallery.ecr.aws/prowler-cloud/prowler)
-- Prowler App:
+- Prowler Local Server:
- [DockerHub - Prowler UI](https://hub.docker.com/r/prowlercloud/prowler-ui/tags)
- [DockerHub - Prowler API](https://hub.docker.com/r/prowlercloud/prowler-api/tags)
@@ -337,17 +357,55 @@ Full configuration, per-provider authentication, and SARIF examples: [Prowler Gi
# ✏️ High level architecture
-## Prowler App
-**Prowler App** is composed of four key components:
+## Prowler Local Server
+**Prowler Local Server** is composed of four key components:
- **Prowler UI**: A web-based interface, built with Next.js, providing a user-friendly experience for executing Prowler scans and visualizing results.
- **Prowler API**: A backend service, developed with Django REST Framework, responsible for running Prowler scans and storing the generated results.
- **Prowler SDK**: A Python SDK designed to extend the functionality of the Prowler CLI for advanced capabilities.
- **Prowler MCP Server**: A Model Context Protocol server that provides AI tools for Lighthouse, the AI-powered security assistant. This is a critical dependency for Lighthouse functionality.
-
+```mermaid
+flowchart TB
+ user([User / Security Team])
+ cli([Prowler CLI])
-
+ subgraph APP["Prowler Local Server"]
+ ui["Prowler UI (Next.js)"]
+ api["Prowler API (Django REST Framework)"]
+ worker["API Worker (Celery)"]
+ beat["API Scheduler (Celery Beat)"]
+ mcp["Prowler MCP Server (Lighthouse AI tools)"]
+ end
+
+ sdk["Prowler SDK (Python)"]
+
+ subgraph DATA["Data Layer"]
+ pg[("PostgreSQL")]
+ valkey[("Valkey / Redis")]
+ neo4j[("Neo4j")]
+ end
+
+ providers["Providers"]
+
+ user --> ui
+ user --> cli
+ ui -->|REST| api
+ ui -->|MCP HTTP| mcp
+ mcp -->|REST| api
+ api --> pg
+ api --> valkey
+ beat -->|enqueue jobs| valkey
+ valkey -->|dispatch| worker
+ worker --> pg
+ worker -->|Attack Paths| neo4j
+ worker -->|invokes| sdk
+ cli --> sdk
+
+ sdk --> providers
+```
+
+
## Prowler CLI
diff --git a/api/CHANGELOG.md b/api/CHANGELOG.md
index 3d7abfab2e..1b26c2b014 100644
--- a/api/CHANGELOG.md
+++ b/api/CHANGELOG.md
@@ -2,6 +2,107 @@
All notable changes to the **Prowler API** are documented in this file.
+
+
+## [1.36.0] (Prowler v5.35.0)
+
+### 🐞 Fixed
+
+- `attack-paths-scan-perform` Celery tasks now use the configurable long-task time limits instead of the six-hour defaults [(#12009)](https://github.com/prowler-cloud/prowler/pull/12009)
+- Attack Paths scans handle provider deletion races cleanly, detect stale tasks after 16 hours, use backend-specific graph synchronization batches, and report exhausted Neptune write retries with the original database error [(#12019)](https://github.com/prowler-cloud/prowler/pull/12019)
+
+### 🔐 Security
+
+- Jira integration credentials only accept bare Atlassian site names containing letters, numbers, and hyphens [(#12012)](https://github.com/prowler-cloud/prowler/pull/12012)
+- Social account linking requires a verified matching email from both the identity provider and the existing user account without sending account connection notifications [(#12013)](https://github.com/prowler-cloud/prowler/pull/12013)
+
+---
+
+## [1.35.0] (Prowler v5.34.0)
+
+### 🐞 Fixed
+
+- `rls_transaction` now falls back directly to the primary DB for connection-level mid-query read replica failures via `execute_wrapper`, reducing non-streaming read crashes during replica recovery [(#10379)](https://github.com/prowler-cloud/prowler/pull/10379)
+- RBAC permission gates now combine permissions from every role assigned to a user in the active tenant [(#11979)](https://github.com/prowler-cloud/prowler/pull/11979)
+- `attack-paths-cleanup-stale-scans` now retries worker pings and checks recent scan activity before failing scans and removing temporary databases [(#11986)](https://github.com/prowler-cloud/prowler/pull/11986)
+
+### 🔐 Security
+
+- User role relationship updates are limited to the active tenant to preserve role assignments in other tenants [(#11903)](https://github.com/prowler-cloud/prowler/pull/11903)
+- `api` container image removes the unused Debian `libxml2` runtime package and scopes the `CVE-2026-13221` Trivy exception to unaffected Perl 5.36 packages [(#11991)](https://github.com/prowler-cloud/prowler/pull/11991)
+
+---
+
+## [1.34.2] (Prowler v5.33.2)
+
+### 🐞 Fixed
+
+- Attack Paths graph mutations now retry transient Neptune concurrency and deadline failures, while Neo4j mutations use managed transaction retries [(#11968)](https://github.com/prowler-cloud/prowler/pull/11968)
+- Attack Paths scans now use bounded child node identifiers for normalized list values in Neo4j and Neptune, preventing Neo4j RANGE index key size failures [(#11969)](https://github.com/prowler-cloud/prowler/pull/11969)
+- `scan-summary` aggregation now upserts summaries in deterministic conflict-key order, preventing PostgreSQL deadlocks during concurrent reaggregation [(#11971)](https://github.com/prowler-cloud/prowler/pull/11971)
+
+---
+
+## [1.34.1] (Prowler v5.33.1)
+
+### 🐞 Fixed
+
+- Session tokens are rejected after account password updates [(#11914)](https://github.com/prowler-cloud/prowler/pull/11914)
+- Jira dispatch task results now surface user-facing Jira failure messages [(#11925)](https://github.com/prowler-cloud/prowler/pull/11925)
+- AWS Attack Paths privilege escalation queries no longer fail on Neo4j with `Aggregation column contains implicit grouping expressions` [(#11939)](https://github.com/prowler-cloud/prowler/pull/11939)
+
+### 🔐 Security
+
+- OpenAI-compatible Lighthouse provider base URLs are restricted before connection checks [(#11940)](https://github.com/prowler-cloud/prowler/pull/11940)
+- `LIGHTHOUSE_AI_OPENAI_COMPATIBLE_ALLOWED_HOSTS` environment variable to allow internal hosts as OpenAI-compatible Lighthouse AI base URLs [(#11942)](https://github.com/prowler-cloud/prowler/pull/11942)
+
+---
+
+## [1.34.0] (Prowler v5.33.0)
+
+### 🚀 Added
+
+- Compliance PDF reports no longer require provider credentials: findings are enriched from the provider metadata stored in the database, so reports generate even after the provider secret is deleted or its credentials become invalid [(#11845)](https://github.com/prowler-cloud/prowler/pull/11845)
+
+### 🐞 Fixed
+
+- Provider scans now queue behind active provider scans instead of dispatching concurrently, and resource failed-finding counters retry database conflicts with stable row locking [(#11848)](https://github.com/prowler-cloud/prowler/pull/11848)
+
+---
+
+## [1.33.1] (Prowler v5.32.1)
+
+### 🐞 Fixed
+
+- Attack Paths: Scan rows now have database defaults for `is_migrated` and `sink_backend` so `scan-perform-scheduled` inserts survive deploy skew [(#11826)](https://github.com/prowler-cloud/prowler/pull/11826)
+- Invited users now keep their invitation context when completing authentication with Google, GitHub, or SAML, so the invitation is accepted during login [(#11752)](https://github.com/prowler-cloud/prowler/pull/11752)
+
+### 🔐 Security
+
+- User profile updates now allow users to update their own account while requiring user-management permissions to update other users in the same tenant [(#11792)](https://github.com/prowler-cloud/prowler/pull/11792)
+- Kubernetes provider credentials now reject kubeconfigs using `exec` authentication in Prowler Cloud, preventing user-supplied commands from running on Cloud workers [(#11753)](https://github.com/prowler-cloud/prowler/pull/11753)
+
+---
+
+## [1.33.0] (Prowler v5.32.0)
+
+### 🚀 Added
+
+- Timestamp precision support for `/api/v1/findings` `inserted_at` and `updated_at` filters [(#11754)](https://github.com/prowler-cloud/prowler/pull/11754)
+
+### 🔄 Changed
+
+- Attack Paths: AWS Neptune is now supported as a persistent sink database, selectable via `ATTACK_PATHS_SINK_DATABASE=neptune` (default `neo4j`), Cartography's (bumped to 0.138.1) per-scan ingest database stays on Neo4j [(#11524)](https://github.com/prowler-cloud/prowler/pull/11524)
+- Attack Paths: Scan task now checks the ingest Neo4j database and configured graph sink before starting graph ingestion [(#11743)](https://github.com/prowler-cloud/prowler/pull/11743)
+- Disable PowerShell telemetry in the API container image [(#11746)](https://github.com/prowler-cloud/prowler/pull/11746)
+
+### 🐞 Fixed
+
+- Attack Paths: Provider graph cleanup now deletes Neo4j and Neptune relationships in directed batches before deleting nodes [(#11755)](https://github.com/prowler-cloud/prowler/pull/11755)
+- `scan-perform` no longer reports an error when a provider is deleted during a running scan [(#11696)](https://github.com/prowler-cloud/prowler/pull/11696)
+
+---
+
## [1.32.1] (Prowler v5.31.1)
### 🐞 Fixed
diff --git a/api/Dockerfile b/api/Dockerfile
index bb9da0b280..8d6923bbfc 100644
--- a/api/Dockerfile
+++ b/api/Dockerfile
@@ -1,11 +1,13 @@
-FROM python:3.12.13-slim-bookworm@sha256:76d4b7b6305788c6b4c6a19d6a22a3921bf802e9af4d5e1e5bd771208dba74bf AS build
+FROM python:3.12.13-slim-bookworm@sha256:8a7e7cc04fd3e2bd787f7f24e22d5d119aa590d429b50c95dfe12b3abe52f48b AS build
LABEL maintainer="https://github.com/prowler-cloud/api"
ARG POWERSHELL_VERSION=7.5.0
ENV POWERSHELL_VERSION=${POWERSHELL_VERSION}
+# Opt out of PowerShell telemetry (Application Insights -> dc.services.visualstudio.com)
+ENV POWERSHELL_TELEMETRY_OPTOUT=1
-ARG TRIVY_VERSION=0.71.0
+ARG TRIVY_VERSION=0.71.2
ENV TRIVY_VERSION=${TRIVY_VERSION}
ARG ZIZMOR_VERSION=1.24.1
@@ -102,6 +104,24 @@ RUN uv sync --locked --no-install-project && \
RUN .venv/bin/python .venv/lib/python3.12/site-packages/prowler/providers/m365/lib/powershell/m365_powershell.py
+USER root
+
+# Remove build-only packages from the final image after Python dependencies are installed.
+RUN apt-get purge -y --auto-remove \
+ gcc \
+ g++ \
+ make \
+ libxml2-dev \
+ libxmlsec1-dev \
+ libxmlsec1-openssl \
+ pkg-config \
+ libtool \
+ libxslt1-dev \
+ python3-dev \
+ && rm -rf /var/lib/apt/lists/*
+
+USER prowler
+
COPY --chown=prowler:prowler src/backend/ ./backend/
COPY --chown=prowler:prowler docker-entrypoint.sh ./docker-entrypoint.sh
diff --git a/tests/__init__.py b/api/changelog.d/.gitkeep
similarity index 100%
rename from tests/__init__.py
rename to api/changelog.d/.gitkeep
diff --git a/api/changelog.d/README.md b/api/changelog.d/README.md
new file mode 100644
index 0000000000..0853174f30
--- /dev/null
+++ b/api/changelog.d/README.md
@@ -0,0 +1,10 @@
+# Changelog fragments
+
+Each PR adds one small file here instead of editing `CHANGELOG.md` directly, so concurrent PRs never conflict.
+
+- Filename: `..md`, e.g. `my-new-check.added.md` (slug is free-form: letters, digits, `.`, `_`, `-`)
+- `` is one of: `added`, `changed`, `deprecated`, `removed`, `fixed`, `security`
+- Content: one line with the changelog entry text, without the PR link and without a trailing period (the PR link is attached automatically at release time)
+- A PR adds as many fragment files as entries it needs, freely mixing types (one file per entry); same-type entries just use different slugs
+
+Fragments are compiled into `CHANGELOG.md` when a release is prepared. Full conventions: `skills/prowler-changelog/SKILL.md`.
diff --git a/api/changelog.d/oci-regionless-api-legacy-region.changed.md b/api/changelog.d/oci-regionless-api-legacy-region.changed.md
new file mode 100644
index 0000000000..087b027c88
--- /dev/null
+++ b/api/changelog.d/oci-regionless-api-legacy-region.changed.md
@@ -0,0 +1 @@
+OCI provider secrets no longer require `region`; legacy `region` input is accepted for backwards compatibility but ignored before storing or scanning
diff --git a/api/pyproject.toml b/api/pyproject.toml
index 4036aac9a9..607a8c7348 100644
--- a/api/pyproject.toml
+++ b/api/pyproject.toml
@@ -58,7 +58,7 @@ dependencies = [
"matplotlib (==3.10.8)",
"reportlab (==4.4.10)",
"neo4j (==6.1.0)",
- "cartography (==0.135.0)",
+ "cartography (==0.138.1)",
"gevent (==25.9.1)",
"werkzeug (==3.1.7)",
"sqlparse (==0.5.5)",
@@ -71,7 +71,7 @@ name = "prowler-api"
package-mode = false
# Needed for the SDK compatibility
requires-python = ">=3.11,<3.13"
-version = "1.33.0"
+version = "1.37.0"
# Shared ruff baseline (kept in sync with mcp_server/pyproject.toml).
# target-version tracks this project's lowest supported Python.
@@ -193,7 +193,7 @@ constraint-dependencies = [
"blinker==1.9.0",
"boto3==1.40.61",
"botocore==1.40.61",
- "cartography==0.135.0",
+ "cartography==0.138.1",
"celery==5.6.2",
"certifi==2026.1.4",
"cffi==2.0.0",
@@ -218,7 +218,6 @@ constraint-dependencies = [
"debugpy==1.8.20",
"decorator==5.2.1",
"defusedxml==0.7.1",
- "detect-secrets==1.5.0",
"dill==0.4.1",
"distro==1.9.0",
"dj-rest-auth==7.0.1",
@@ -301,6 +300,7 @@ constraint-dependencies = [
"jsonschema==4.23.0",
"jsonschema-specifications==2025.9.1",
"keystoneauth1==5.13.0",
+ "kingfisher-bin==1.104.0",
"kiwisolver==1.4.9",
"knack==0.11.0",
"kombu==5.6.2",
@@ -447,7 +447,7 @@ constraint-dependencies = [
"wcwidth==0.5.3",
"websocket-client==1.9.0",
"werkzeug==3.1.7",
- "workos==6.0.4",
+ "workos==6.0.8",
"wrapt==1.17.3",
"xlsxwriter==3.2.9",
"xmlsec==1.3.17",
@@ -458,8 +458,13 @@ constraint-dependencies = [
"zope-interface==8.2",
"zstd==1.5.7.3"
]
-# prowler@master needs okta==3.4.2; cartography 0.135.0 declares okta<1.0.0 for an
-# integration prowler does not import.
+# prowler@master needs okta==3.4.2, but cartography 0.138.1 requires okta<1.0.0.
+# Attack Paths does not ingest Okta today, so override the Cartography
+# dependency to the Prowler pin.
+#
+# prowler@master needs azure-mgmt-containerservice==34.1.0, but cartography
+# 0.138.1 requires azure-mgmt-containerservice>=41.0.0. Attack Paths does not
+# ingest Azure today, so override the Cartography dependency to the Prowler pin.
#
# prowler@master hard-pins microsoft-kiota-abstractions==1.9.2 in [project.dependencies].
# The microsoft-kiota-http security bump to 1.9.9 (GHSA-7j59-v9qr-6fq9) requires
@@ -475,6 +480,7 @@ constraint-dependencies = [
# that request pyjwt[crypto] and leave cryptography (needed for RS256) only transitive.
override-dependencies = [
"okta==3.4.2",
+ "azure-mgmt-containerservice==34.1.0",
"microsoft-kiota-abstractions==1.9.9",
"dulwich==1.2.5",
"pyjwt[crypto]==2.13.0"
diff --git a/api/src/backend/api/adapters.py b/api/src/backend/api/adapters.py
index cbd6795731..99ab88bf81 100644
--- a/api/src/backend/api/adapters.py
+++ b/api/src/backend/api/adapters.py
@@ -1,3 +1,5 @@
+from allauth.account.models import EmailAddress
+from allauth.core.exceptions import ImmediateHttpResponse
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from api.db_router import MainRouter
from api.db_utils import rls_transaction
@@ -9,7 +11,9 @@ from api.models import (
User,
UserRoleRelationship,
)
+from api.utils import accept_invitation_for_user
from django.db import transaction
+from django.http import HttpResponseForbidden
class ProwlerSocialAccountAdapter(DefaultSocialAccountAdapter):
@@ -20,9 +24,30 @@ class ProwlerSocialAccountAdapter(DefaultSocialAccountAdapter):
except User.DoesNotExist:
return None
+ @staticmethod
+ def _get_invitation_token(request):
+ for source_name in ("data", "POST"):
+ data = getattr(request, source_name, None) or {}
+ if not hasattr(data, "get"):
+ continue
+ invitation_token = data.get("invitation_token")
+ if invitation_token:
+ return invitation_token
+
+ wrapped_request = getattr(request, "_request", None)
+ if wrapped_request and wrapped_request is not request:
+ return ProwlerSocialAccountAdapter._get_invitation_token(wrapped_request)
+
+ return None
+
def pre_social_login(self, request, sociallogin):
- # Link existing accounts with the same email address
- email = sociallogin.account.extra_data.get("email")
+ # The provider account is already bound, so no email-based linking is needed.
+ if sociallogin.account.pk:
+ return
+
+ # Prefer the normalized email populated by allauth. GitHub can return the
+ # primary email separately from the profile stored in extra_data.
+ email = sociallogin.user.email or sociallogin.account.extra_data.get("email")
if sociallogin.provider.id == "saml":
# For SAML, the asserted NameID email cannot be trusted on its own:
# any tenant can claim any email domain in its SAML configuration. To
@@ -63,6 +88,17 @@ class ProwlerSocialAccountAdapter(DefaultSocialAccountAdapter):
if email:
existing_user = self.get_user_by_email(email)
if existing_user:
+ email_is_verified = EmailAddress.objects.filter(
+ user=existing_user,
+ email__iexact=email,
+ verified=True,
+ ).exists()
+ provider_verified_email = any(
+ address.verified and address.email.casefold() == email.casefold()
+ for address in sociallogin.email_addresses
+ )
+ if not email_is_verified or not provider_verified_email:
+ raise ImmediateHttpResponse(HttpResponseForbidden())
sociallogin.connect(request, existing_user)
def save_user(self, request, sociallogin, form=None):
@@ -83,29 +119,38 @@ class ProwlerSocialAccountAdapter(DefaultSocialAccountAdapter):
user.name = social_account_name
user.save(using=MainRouter.admin_db)
- tenant = Tenant.objects.using(MainRouter.admin_db).create(
- name=f"{user.email.split('@')[0]} default tenant"
- )
- with rls_transaction(str(tenant.id)):
- Membership.objects.using(MainRouter.admin_db).create(
- user=user, tenant=tenant, role=Membership.RoleChoices.OWNER
- )
- role = Role.objects.using(MainRouter.admin_db).create(
- name="admin",
- tenant_id=tenant.id,
- manage_users=True,
- manage_account=True,
- manage_billing=True,
- manage_providers=True,
- manage_integrations=True,
- manage_scans=True,
- unlimited_visibility=True,
- )
- UserRoleRelationship.objects.using(MainRouter.admin_db).create(
+ invitation_token = self._get_invitation_token(request)
+ if invitation_token:
+ invitation, _ = accept_invitation_for_user(
user=user,
- role=role,
- tenant_id=tenant.id,
+ invitation_token=invitation_token,
)
+ request.prowler_invitation_token = invitation_token
+ request.prowler_invitation_tenant_id = str(invitation.tenant_id)
+ else:
+ tenant = Tenant.objects.using(MainRouter.admin_db).create(
+ name=f"{user.email.split('@')[0]} default tenant"
+ )
+ with rls_transaction(str(tenant.id)):
+ Membership.objects.using(MainRouter.admin_db).create(
+ user=user, tenant=tenant, role=Membership.RoleChoices.OWNER
+ )
+ role = Role.objects.using(MainRouter.admin_db).create(
+ name="admin",
+ tenant_id=tenant.id,
+ manage_users=True,
+ manage_account=True,
+ manage_billing=True,
+ manage_providers=True,
+ manage_integrations=True,
+ manage_scans=True,
+ unlimited_visibility=True,
+ )
+ UserRoleRelationship.objects.using(MainRouter.admin_db).create(
+ user=user,
+ role=role,
+ tenant_id=tenant.id,
+ )
else:
request.session["saml_user_created"] = str(user.id)
diff --git a/api/src/backend/api/apps.py b/api/src/backend/api/apps.py
index 90ba96c124..1aa0f8f54f 100644
--- a/api/src/backend/api/apps.py
+++ b/api/src/backend/api/apps.py
@@ -42,9 +42,6 @@ class ApiConfig(AppConfig):
):
self._ensure_crypto_keys()
- # Neo4j driver is created lazily on first use (see api.attack_paths.database).
- # App init never contacts Neo4j, so a Neo4j outage cannot block API startup.
-
def _ensure_crypto_keys(self):
"""
Orchestrator method that ensures all required cryptographic keys are present.
diff --git a/api/src/backend/api/attack_paths/cypher_sanitizer.py b/api/src/backend/api/attack_paths/cypher_sanitizer.py
index f08172114e..35752b3ec9 100644
--- a/api/src/backend/api/attack_paths/cypher_sanitizer.py
+++ b/api/src/backend/api/attack_paths/cypher_sanitizer.py
@@ -4,10 +4,10 @@ Cypher sanitizer for custom (user-supplied) Attack Paths queries.
Two responsibilities:
1. **Validation** - reject queries containing SSRF or dangerous procedure
- patterns (defense-in-depth; the primary control is ``neo4j.READ_ACCESS``).
+ patterns (defense-in-depth; the primary control is `neo4j.READ_ACCESS`).
2. **Provider-scoped label injection** - inject a dynamic
- ``_Provider_{uuid}`` label into every node pattern so the database can
+ `_Provider_{uuid}` label into every node pattern so the database can
use its native label index for provider isolation.
Label-injection pipeline:
@@ -25,13 +25,13 @@ from rest_framework.exceptions import ValidationError
from tasks.jobs.attack_paths.config import get_provider_label
# Step 1 - String / comment protection
-# Single combined regex: strings first, then line comments.
+# Single combined regex: strings first, then line comments
# The regex engine finds the leftmost match, so a string like 'https://prowler.com'
-# is consumed as a string before the // inside it can match as a comment.
+# is consumed as a string before the // inside it can match as a comment
_PROTECTED_RE = re.compile(r"'(?:[^'\\]|\\.)*'|\"(?:[^\"\\]|\\.)*\"|//[^\n]*")
# Step 2 - Clause splitting
-# OPTIONAL MATCH must come before MATCH to avoid partial matching.
+# `OPTIONAL MATCH` must come before `MATCH` to avoid partial matching
_CLAUSE_RE = re.compile(
r"\b(OPTIONAL\s+MATCH|MATCH|WHERE|RETURN|WITH|ORDER\s+BY"
r"|SKIP|LIMIT|UNION|UNWIND|CALL)\b",
@@ -39,10 +39,10 @@ _CLAUSE_RE = re.compile(
)
# Pass A - Labeled node patterns (all segments)
-# Matches node patterns that have at least one :Label.
-# (? str:
node pattern.
"""
label = get_provider_label(provider_id)
+ return inject_label(cypher, label)
+
+
+def inject_label(cypher: str, label: str) -> str:
+ """Rewrite a Cypher query to append a label to every node pattern."""
# Step 1: Protect strings and comments (single pass, leftmost-first)
protected: list[str] = []
@@ -134,9 +139,7 @@ def inject_provider_label(cypher: str, provider_id: str) -> str:
return work
-# ---------------------------------------------------------------------------
# Validation
-# ---------------------------------------------------------------------------
# Patterns that indicate SSRF or dangerous procedure calls
# Defense-in-depth layer - the primary control is `neo4j.READ_ACCESS`
diff --git a/api/src/backend/api/attack_paths/database.py b/api/src/backend/api/attack_paths/database.py
index 4745cf79a1..3ef55b7eca 100644
--- a/api/src/backend/api/attack_paths/database.py
+++ b/api/src/backend/api/attack_paths/database.py
@@ -1,261 +1,33 @@
-import atexit
-import logging
-import threading
-from collections.abc import Iterator
-from contextlib import contextmanager
+"""Backwards-compatible facade over the ingest and sink modules.
+
+Historically this module owned a single Neo4j driver used for both the
+cartography temp database and the per-tenant sink database. The port to AWS
+Neptune split those roles: the cartography ingest (temp) database is always
+Neo4j and lives in `api.attack_paths.ingest`; the sink is configurable
+(Neo4j or Neptune) and lives in `api.attack_paths.sink`. This shim preserves
+the public API that `tasks/` and `api/v1/views.py` already depend on, and
+dispatches to the right module by database-name prefix.
+
+A database name starting with `db-tmp-scan-` is a cartography temp DB and
+routes to ingest. Everything else routes to the configured sink.
+"""
+
+from contextlib import AbstractContextManager
from typing import Any
from uuid import UUID
-import neo4j
-import neo4j.exceptions
-from api.attack_paths.retryable_session import RetryableSession
+import neo4j # noqa: F401 - kept for tests that patch api.attack_paths.database.neo4j
+from api.attack_paths import ingest
+from api.attack_paths import sink as sink_module
from config.env import env
-from django.conf import settings
-from tasks.jobs.attack_paths.config import (
- BATCH_SIZE,
- PROVIDER_RESOURCE_LABEL,
- get_provider_label,
+from django.conf import (
+ settings, # noqa: F401 - kept for tests that patch ...database.settings
)
-# Without this Celery goes crazy with Neo4j logging
-logging.getLogger("neo4j").setLevel(logging.ERROR)
-logging.getLogger("neo4j").propagate = False
-
-SERVICE_UNAVAILABLE_MAX_RETRIES = env.int(
- "ATTACK_PATHS_SERVICE_UNAVAILABLE_MAX_RETRIES", default=3
-)
-READ_QUERY_TIMEOUT_SECONDS = env.int(
- "ATTACK_PATHS_READ_QUERY_TIMEOUT_SECONDS", default=30
-)
MAX_CUSTOM_QUERY_NODES = env.int("ATTACK_PATHS_MAX_CUSTOM_QUERY_NODES", default=250)
-# Shorter than CONN_ACQUISITION_TIMEOUT — the driver requires acquisition to be
-# the longer of the two (it may include opening a new connection).
-CONNECTION_TIMEOUT = env.int("NEO4J_CONNECTION_TIMEOUT", default=5)
-CONN_ACQUISITION_TIMEOUT = env.int("NEO4J_CONN_ACQUISITION_TIMEOUT", default=15)
-READ_EXCEPTION_CODES = [
- "Neo.ClientError.Statement.AccessMode",
- "Neo.ClientError.Procedure.ProcedureNotFound",
-]
-CLIENT_STATEMENT_EXCEPTION_PREFIX = "Neo.ClientError.Statement."
-# Module-level process-wide driver singleton
-_driver: neo4j.Driver | None = None
-_lock = threading.Lock()
-
-# Base Neo4j functions
-
-
-def get_uri() -> str:
- host = settings.DATABASES["neo4j"]["HOST"]
- port = settings.DATABASES["neo4j"]["PORT"]
- return f"bolt://{host}:{port}"
-
-
-def init_driver() -> neo4j.Driver:
- global _driver
- if _driver is not None:
- return _driver
-
- with _lock:
- if _driver is None:
- uri = get_uri()
- config = settings.DATABASES["neo4j"]
-
- driver = neo4j.GraphDatabase.driver(
- uri,
- auth=(config["USER"], config["PASSWORD"]),
- keep_alive=True,
- max_connection_lifetime=7200,
- connection_timeout=CONNECTION_TIMEOUT,
- connection_acquisition_timeout=CONN_ACQUISITION_TIMEOUT,
- max_connection_pool_size=50,
- )
- # Publish the singleton only after connectivity is verified so a
- # failed probe does not leave an unverified driver behind. Close the
- # driver on failure so a repeatedly-probed outage cannot leak pools.
- try:
- driver.verify_connectivity()
- except Exception:
- driver.close()
- raise
- _driver = driver
-
- # Register cleanup handler (only runs once since we're inside the _driver is None block)
- atexit.register(close_driver)
-
- return _driver
-
-
-def get_driver() -> neo4j.Driver:
- return init_driver()
-
-
-def close_driver() -> None: # TODO: Use it
- global _driver
- with _lock:
- if _driver is not None:
- try:
- _driver.close()
-
- finally:
- _driver = None
-
-
-@contextmanager
-def get_session(
- database: str | None = None, default_access_mode: str | None = None
-) -> Iterator[RetryableSession]:
- session_wrapper: RetryableSession | None = None
-
- try:
- session_wrapper = RetryableSession(
- session_factory=lambda: get_driver().session(
- database=database, default_access_mode=default_access_mode
- ),
- max_retries=SERVICE_UNAVAILABLE_MAX_RETRIES,
- )
- yield session_wrapper
-
- except neo4j.exceptions.Neo4jError as exc:
- if (
- default_access_mode == neo4j.READ_ACCESS
- and exc.code
- and exc.code in READ_EXCEPTION_CODES
- ):
- message = "Read query not allowed"
- code = READ_EXCEPTION_CODES[0]
- raise WriteQueryNotAllowedException(message=message, code=code)
-
- message = exc.message if exc.message is not None else str(exc)
-
- if exc.code and exc.code.startswith(CLIENT_STATEMENT_EXCEPTION_PREFIX):
- raise ClientStatementException(message=message, code=exc.code)
-
- raise GraphDatabaseQueryException(message=message, code=exc.code)
-
- finally:
- if session_wrapper is not None:
- session_wrapper.close()
-
-
-def execute_read_query(
- database: str,
- cypher: str,
- parameters: dict[str, Any] | None = None,
-) -> neo4j.graph.Graph:
- with get_session(database, default_access_mode=neo4j.READ_ACCESS) as session:
-
- def _run(tx: neo4j.ManagedTransaction) -> neo4j.graph.Graph:
- result = tx.run(
- cypher, parameters or {}, timeout=READ_QUERY_TIMEOUT_SECONDS
- )
- return result.graph()
-
- return session.execute_read(_run)
-
-
-def create_database(database: str) -> None:
- query = "CREATE DATABASE $database IF NOT EXISTS"
- parameters = {"database": database}
-
- with get_session() as session:
- session.run(query, parameters)
-
-
-def drop_database(database: str) -> None:
- query = f"DROP DATABASE `{database}` IF EXISTS DESTROY DATA"
-
- with get_session() as session:
- session.run(query)
-
-
-def drop_subgraph(database: str, provider_id: str) -> int:
- """
- Delete all nodes for a provider from the tenant database.
-
- Deletes relationships then nodes in batches (not `DETACH DELETE`) so a dense
- provider's graph cannot exceed Neo4j's transaction memory limit.
- Silently returns 0 if the database doesn't exist.
- """
- provider_label = get_provider_label(provider_id)
- deleted_nodes = 0
-
- try:
- with get_session(database) as session:
- # Phase 1: delete relationships incident to provider nodes in batches.
- deleted_count = 1
- while deleted_count > 0:
- result = session.run(
- f"""
- MATCH (:`{provider_label}`)-[r]-()
- WITH DISTINCT r LIMIT $batch_size
- DELETE r
- RETURN COUNT(r) AS deleted_rels_count
- """,
- {"batch_size": BATCH_SIZE},
- )
- deleted_count = result.single().get("deleted_rels_count", 0)
-
- # Phase 2: delete the now relationship-free nodes in batches.
- deleted_count = 1
- while deleted_count > 0:
- result = session.run(
- f"""
- MATCH (n:{PROVIDER_RESOURCE_LABEL}:`{provider_label}`)
- WITH n LIMIT $batch_size
- DELETE n
- RETURN COUNT(n) AS deleted_nodes_count
- """,
- {"batch_size": BATCH_SIZE},
- )
- deleted_count = result.single().get("deleted_nodes_count", 0)
- deleted_nodes += deleted_count
-
- except GraphDatabaseQueryException as exc:
- if exc.code == "Neo.ClientError.Database.DatabaseNotFound":
- return 0
- raise
-
- return deleted_nodes
-
-
-def has_provider_data(database: str, provider_id: str) -> bool:
- """
- Check if any ProviderResource node exists for this provider.
-
- Returns `False` if the database doesn't exist.
- """
- provider_label = get_provider_label(provider_id)
- query = f"MATCH (n:{PROVIDER_RESOURCE_LABEL}:`{provider_label}`) RETURN 1 LIMIT 1"
-
- try:
- with get_session(database, default_access_mode=neo4j.READ_ACCESS) as session:
- result = session.run(query)
- return result.single() is not None
-
- except GraphDatabaseQueryException as exc:
- if exc.code == "Neo.ClientError.Database.DatabaseNotFound":
- return False
- raise
-
-
-def clear_cache(database: str) -> None:
- query = "CALL db.clearQueryCaches()"
-
- try:
- with get_session(database) as session:
- session.run(query)
-
- except GraphDatabaseQueryException as exc:
- logging.warning(f"Failed to clear query cache for database `{database}`: {exc}")
-
-
-# Neo4j functions related to Prowler + Cartography
-
-
-def get_database_name(entity_id: str | UUID, temporary: bool = False) -> str:
- prefix = "tmp-scan" if temporary else "tenant"
- return f"db-{prefix}-{str(entity_id).lower()}"
+TEMP_DB_PREFIX = "db-tmp-scan-"
+DATABASE_NOT_FOUND_CODE = "Neo.ClientError.Database.DatabaseNotFound"
# Exceptions
@@ -270,13 +42,190 @@ class GraphDatabaseQueryException(Exception):
def __str__(self) -> str:
if self.code:
return f"{self.code}: {self.message}"
-
return self.message
+class NeptuneWriteRetryExhaustedException(GraphDatabaseQueryException):
+ pass
+
+
class WriteQueryNotAllowedException(GraphDatabaseQueryException):
pass
class ClientStatementException(GraphDatabaseQueryException):
pass
+
+
+# Routing
+
+
+def _is_ingest_database(database: str | None) -> bool:
+ return bool(database) and database.startswith(TEMP_DB_PREFIX)
+
+
+# Driver lifecycle
+
+
+def init_driver() -> Any:
+ """Initialize the configured sink backend.
+
+ The ingest driver (Neo4j for cartography temp DBs) stays lazy: it is
+ only initialized when a temp-DB operation actually runs, which never
+ happens on API pods.
+ """
+ return sink_module.init()
+
+
+def close_driver() -> None:
+ """Close every driver held by this process."""
+ sink_module.close()
+ ingest.close_driver()
+
+
+def get_driver() -> neo4j.Driver:
+ """Return the sink backend's underlying driver.
+
+ Only meaningful for the Neo4j sink (where the backend has a single Neo4j
+ driver). On Neptune this returns the writer driver. Kept for tests and
+ legacy call-sites; prefer `get_session` for new code.
+ """
+ backend = sink_module.get_backend()
+
+ # Neo4jSink exposes get_driver(); NeptuneSink exposes get_writer()
+ if hasattr(backend, "get_driver"):
+ return backend.get_driver()
+
+ if hasattr(backend, "get_writer"):
+ return backend.get_writer()
+
+ raise RuntimeError("Active sink backend does not expose a driver handle")
+
+
+def verify_connectivity() -> None:
+ """Raise if the configured graph database is unreachable on the API read path.
+
+ Backend-agnostic entry point for the readiness probe: Neo4j verifies its
+ driver, Neptune verifies the reader endpoint.
+ """
+ sink_module.get_backend().verify_connectivity()
+
+
+def verify_scan_databases_available() -> None:
+ """Raise if either graph database needed by an Attack Paths scan is unavailable."""
+ errors: list[str] = []
+ first_error: Exception | None = None
+
+ try:
+ ingest.get_driver().verify_connectivity()
+ except Exception as exc:
+ errors.append(f"ingest Neo4j: {exc}")
+ first_error = exc
+
+ try:
+ get_driver().verify_connectivity()
+ except Exception as exc:
+ errors.append(f"sink {settings.ATTACK_PATHS_SINK_DATABASE}: {exc}")
+ if first_error is None:
+ first_error = exc
+
+ if errors:
+ raise RuntimeError(
+ "Attack Paths graph database unavailable before scan start: "
+ + "; ".join(errors)
+ ) from first_error
+
+
+def get_uri() -> str:
+ """Return the sink URI. Retained for backwards compatibility."""
+ if settings.ATTACK_PATHS_SINK_DATABASE == "neptune":
+ cfg = settings.DATABASES["neptune"]
+ return f"bolt+s://{cfg['WRITER_ENDPOINT']}:{cfg['PORT']}"
+
+ cfg = settings.DATABASES["neo4j"]
+ return f"bolt://{cfg['HOST']}:{cfg['PORT']}"
+
+
+def get_ingest_uri() -> str:
+ """Neo4j URI for the cartography temp (ingest) database, which is always
+ Neo4j regardless of the configured sink."""
+ return ingest.get_uri()
+
+
+# Session API
+
+
+def get_session(
+ database: str | None = None,
+ default_access_mode: str | None = None,
+) -> AbstractContextManager:
+ """Return a session against the right backend.
+
+ - `database` names starting with `db-tmp-scan-` always go to ingest.
+ - No database name → ingest (used for CREATE / DROP DATABASE admin ops).
+ - Any other name → sink.
+ """
+ if _is_ingest_database(database) or database is None:
+ return ingest.get_session(
+ database=database, default_access_mode=default_access_mode
+ )
+
+ return sink_module.get_backend().get_session(
+ database=database, default_access_mode=default_access_mode
+ )
+
+
+def execute_read_query(
+ database: str,
+ cypher: str,
+ parameters: dict[str, Any] | None = None,
+) -> neo4j.graph.Graph:
+ """Read-only query against the sink."""
+ return sink_module.get_backend().execute_read_query(database, cypher, parameters)
+
+
+def create_database(database: str) -> None:
+ """Create a database. Temp DBs always land on ingest (Neo4j).
+
+ On the Neo4j sink, tenant DBs also route to ingest because both drivers
+ connect to the same Neo4j cluster. On the Neptune sink, tenant DB creates
+ are no-ops.
+ """
+ if _is_ingest_database(database):
+ ingest.create_database(database)
+ return
+
+ sink_module.get_backend().create_database(database)
+
+
+def drop_database(database: str) -> None:
+ """Drop a database. Mirrors `create_database` routing."""
+ if _is_ingest_database(database):
+ ingest.drop_database(database)
+ return
+
+ sink_module.get_backend().drop_database(database)
+
+
+def drop_subgraph(database: str, provider_id: str) -> int:
+ return sink_module.get_backend().drop_subgraph(database, provider_id)
+
+
+def has_provider_data(database: str, provider_id: str) -> bool:
+ return sink_module.get_backend().has_provider_data(database, provider_id)
+
+
+def clear_cache(database: str) -> None:
+ if _is_ingest_database(database):
+ ingest.clear_cache(database)
+ return
+
+ sink_module.get_backend().clear_cache(database)
+
+
+# Name helper
+
+
+def get_database_name(entity_id: str | UUID, temporary: bool = False) -> str:
+ prefix = "tmp-scan" if temporary else "tenant"
+ return f"db-{prefix}-{str(entity_id).lower()}"
diff --git a/api/src/backend/api/attack_paths/ingest/__init__.py b/api/src/backend/api/attack_paths/ingest/__init__.py
new file mode 100644
index 0000000000..5833b8b373
--- /dev/null
+++ b/api/src/backend/api/attack_paths/ingest/__init__.py
@@ -0,0 +1,29 @@
+"""Cartography ingest layer.
+
+Public surface for the per-scan Neo4j temp database driver. Implementation
+lives in `api.attack_paths.ingest.driver`.
+"""
+
+from api.attack_paths.ingest.driver import (
+ clear_cache,
+ close_driver,
+ create_database,
+ drop_database,
+ get_driver,
+ get_session,
+ get_uri,
+ init_driver,
+ run_cypher,
+)
+
+__all__ = [
+ "clear_cache",
+ "close_driver",
+ "create_database",
+ "drop_database",
+ "get_driver",
+ "get_session",
+ "get_uri",
+ "init_driver",
+ "run_cypher",
+]
diff --git a/api/src/backend/api/attack_paths/ingest/driver.py b/api/src/backend/api/attack_paths/ingest/driver.py
new file mode 100644
index 0000000000..1b05c721e7
--- /dev/null
+++ b/api/src/backend/api/attack_paths/ingest/driver.py
@@ -0,0 +1,187 @@
+"""Cartography ingest driver: per-scan throw-away Neo4j database.
+
+Cartography writes each scan's graph into a throw-away Neo4j database named
+`db-tmp-scan-{scan_uuid}`. This is always Neo4j, regardless of the configured
+sink: Neptune is single-database and cannot host per-scan throw-away
+databases. This module owns the Neo4j driver used for those temp DBs and the
+admin ops they need (CREATE / DROP DATABASE).
+"""
+
+import atexit
+import logging
+import threading
+from collections.abc import Iterator
+from contextlib import contextmanager
+from typing import Any
+
+import neo4j
+import neo4j.exceptions
+from api.attack_paths.retryable_session import RetryableSession
+from config.env import env
+from django.conf import settings
+
+logging.getLogger("neo4j").setLevel(logging.ERROR)
+logging.getLogger("neo4j").propagate = False
+
+SERVICE_UNAVAILABLE_MAX_RETRIES = env.int(
+ "ATTACK_PATHS_SERVICE_UNAVAILABLE_MAX_RETRIES", default=3
+)
+CONN_ACQUISITION_TIMEOUT = env.int("NEO4J_CONN_ACQUISITION_TIMEOUT", default=15)
+# TCP connect timeout, ordered below the acquisition timeout so an unreachable
+# host can't pin a worker on a temp-DB op longer than this.
+CONNECTION_TIMEOUT = env.int("NEO4J_CONNECTION_TIMEOUT", default=5)
+MAX_CONNECTION_LIFETIME = env.int("NEO4J_MAX_CONNECTION_LIFETIME", default=7200)
+MAX_CONNECTION_POOL_SIZE = env.int("NEO4J_MAX_CONNECTION_POOL_SIZE", default=50)
+
+_driver: neo4j.Driver | None = None
+_lock = threading.Lock()
+
+
+def _neo4j_config() -> dict:
+ return settings.DATABASES["neo4j"]
+
+
+def get_uri() -> str:
+ """Bolt URI for the Neo4j temp (ingest) database. Always Neo4j."""
+ config = _neo4j_config()
+ host = config["HOST"]
+ port = config["PORT"]
+ if not host or not port:
+ raise RuntimeError(
+ "NEO4J_HOST / NEO4J_PORT must be set to use the attack-paths "
+ "temp database. Workers require Neo4j env even when the sink is Neptune."
+ )
+
+ return f"bolt://{host}:{port}"
+
+
+def init_driver() -> neo4j.Driver:
+ """Initialize the temp-database Neo4j driver. Idempotent."""
+ global _driver
+ if _driver is not None:
+ return _driver
+
+ with _lock:
+ if _driver is None:
+ config = _neo4j_config()
+ _driver = neo4j.GraphDatabase.driver(
+ get_uri(),
+ auth=(config["USER"], config["PASSWORD"]),
+ keep_alive=True,
+ max_connection_lifetime=MAX_CONNECTION_LIFETIME,
+ connection_timeout=CONNECTION_TIMEOUT,
+ connection_acquisition_timeout=CONN_ACQUISITION_TIMEOUT,
+ max_connection_pool_size=MAX_CONNECTION_POOL_SIZE,
+ )
+ # Best-effort connectivity check: a Neo4j that is down at boot must
+ # not crash the worker. The driver reconnects lazily on first use.
+ try:
+ _driver.verify_connectivity()
+
+ except Exception:
+ logging.warning(
+ "Neo4j temp-database unreachable at init; continuing with a "
+ "lazily-reconnecting driver",
+ exc_info=True,
+ )
+
+ atexit.register(close_driver)
+
+ return _driver
+
+
+def get_driver() -> neo4j.Driver:
+ return init_driver()
+
+
+def close_driver() -> None:
+ global _driver
+ with _lock:
+ if _driver is not None:
+ try:
+ _driver.close()
+ finally:
+ _driver = None
+
+
+@contextmanager
+def get_session(
+ database: str | None = None,
+ default_access_mode: str | None = None,
+) -> Iterator[RetryableSession]:
+ """Session against the Neo4j temp-database cluster. Used for temp DB sessions
+ and for admin operations (CREATE / DROP DATABASE) when `database` is None."""
+ from api.attack_paths.database import (
+ ClientStatementException,
+ GraphDatabaseQueryException,
+ WriteQueryNotAllowedException,
+ )
+
+ READ_EXCEPTION_CODES = [
+ "Neo.ClientError.Statement.AccessMode",
+ "Neo.ClientError.Procedure.ProcedureNotFound",
+ ]
+ CLIENT_STATEMENT_EXCEPTION_PREFIX = "Neo.ClientError.Statement."
+
+ session_wrapper: RetryableSession | None = None
+ try:
+ session_wrapper = RetryableSession(
+ session_factory=lambda: get_driver().session(
+ database=database, default_access_mode=default_access_mode
+ ),
+ max_retries=SERVICE_UNAVAILABLE_MAX_RETRIES,
+ )
+ yield session_wrapper
+
+ except neo4j.exceptions.Neo4jError as exc:
+ if (
+ default_access_mode == neo4j.READ_ACCESS
+ and exc.code
+ and exc.code in READ_EXCEPTION_CODES
+ ):
+ raise WriteQueryNotAllowedException(
+ message="Read query not allowed", code=READ_EXCEPTION_CODES[0]
+ )
+
+ message = exc.message if exc.message is not None else str(exc)
+ if exc.code and exc.code.startswith(CLIENT_STATEMENT_EXCEPTION_PREFIX):
+ raise ClientStatementException(message=message, code=exc.code)
+ raise GraphDatabaseQueryException(message=message, code=exc.code)
+
+ finally:
+ if session_wrapper is not None:
+ session_wrapper.close()
+
+
+def create_database(database: str) -> None:
+ """Create a database on the Neo4j cluster. Used for temp scan DBs."""
+ with get_session() as session:
+ session.run("CREATE DATABASE $database IF NOT EXISTS", {"database": database})
+
+
+def drop_database(database: str) -> None:
+ """Drop a database on the Neo4j cluster. Used for temp scan DBs."""
+ with get_session() as session:
+ session.run(f"DROP DATABASE `{database}` IF EXISTS DESTROY DATA")
+
+
+def clear_cache(database: str) -> None:
+ """Best-effort cache clear for a Neo4j database."""
+ from api.attack_paths.database import GraphDatabaseQueryException
+
+ try:
+ with get_session(database) as session:
+ session.run("CALL db.clearQueryCaches()")
+
+ except GraphDatabaseQueryException as exc:
+ logging.warning(f"Failed to clear query cache for database `{database}`: {exc}")
+
+
+def run_cypher(
+ database: str | None,
+ cypher: str,
+ parameters: dict[str, Any] | None = None,
+) -> Any:
+ """Execute Cypher directly without the context manager. Thin helper."""
+ with get_session(database) as session:
+ return session.run(cypher, parameters or {})
diff --git a/api/src/backend/api/attack_paths/queries/aws.py b/api/src/backend/api/attack_paths/queries/aws.py
index d9792845c0..60660a1632 100644
--- a/api/src/backend/api/attack_paths/queries/aws.py
+++ b/api/src/backend/api/attack_paths/queries/aws.py
@@ -6,7 +6,6 @@ from api.attack_paths.queries.types import (
from tasks.jobs.attack_paths.config import PROWLER_FINDING_LABEL
# Custom Attack Path Queries
-# --------------------------
AWS_INTERNET_EXPOSED_EC2_SENSITIVE_S3_ACCESS = AttackPathsQueryDefinition(
id="aws-internet-exposed-ec2-sensitive-s3-access",
@@ -22,14 +21,18 @@ AWS_INTERNET_EXPOSED_EC2_SENSITIVE_S3_ACCESS = AttackPathsQueryDefinition(
WHERE ec2.exposed_internet = true
AND ipi.toport = 22
- MATCH path_role = (r:AWSRole)--(pol:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE ANY(x IN stmt.resource WHERE x CONTAINS s3.name)
- AND ANY(x IN stmt.action WHERE toLower(x) =~ 's3:(listbucket|getobject).*')
+ MATCH path_role = (r:AWSRole)-[:POLICY]->(pol:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement)
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value CONTAINS s3.name
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) STARTS WITH 's3:listbucket'
+ OR toLower(act.value) STARTS WITH 's3:getobject'
MATCH path_assume_role = (ec2)-[p:STS_ASSUMEROLE_ALLOW*1..9]-(r:AWSRole)
OPTIONAL MATCH (internet:Internet)-[can_access:CAN_ACCESS]->(ec2)
+ WITH DISTINCT path_s3, path_ec2, path_role, path_assume_role, internet, can_access
WITH collect(path_s3) + collect(path_ec2) + collect(path_role) + collect(path_assume_role) AS paths,
head(collect(internet)) AS internet, collect(can_access) AS can_access
UNWIND paths AS p
@@ -37,7 +40,7 @@ AWS_INTERNET_EXPOSED_EC2_SENSITIVE_S3_ACCESS = AttackPathsQueryDefinition(
WITH paths, internet, can_access, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr, internet, can_access
""",
@@ -59,7 +62,6 @@ AWS_INTERNET_EXPOSED_EC2_SENSITIVE_S3_ACCESS = AttackPathsQueryDefinition(
# Basic Resource Queries
-# ----------------------
AWS_RDS_INSTANCES = AttackPathsQueryDefinition(
id="aws-rds-instances",
@@ -76,7 +78,7 @@ AWS_RDS_INSTANCES = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -99,7 +101,7 @@ AWS_RDS_UNENCRYPTED_STORAGE = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -122,7 +124,7 @@ AWS_S3_ANONYMOUS_ACCESS_BUCKETS = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -136,17 +138,18 @@ AWS_IAM_STATEMENTS_ALLOW_ALL_ACTIONS = AttackPathsQueryDefinition(
description="Find IAM policy statements that allow all actions via '*' within the selected account.",
provider="aws",
cypher=f"""
- MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(pol:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(x IN stmt.action WHERE x = '*')
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(pol:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE act.value = '*'
+ WITH DISTINCT path
WITH collect(path) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]->(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -160,17 +163,18 @@ AWS_IAM_STATEMENTS_ALLOW_DELETE_POLICY = AttackPathsQueryDefinition(
description="Find IAM policy statements that allow the iam:DeletePolicy action within the selected account.",
provider="aws",
cypher=f"""
- MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(pol:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(x IN stmt.action WHERE x = "iam:DeletePolicy")
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(pol:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE act.value = 'iam:DeletePolicy'
+ WITH DISTINCT path
WITH collect(path) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -184,17 +188,18 @@ AWS_IAM_STATEMENTS_ALLOW_CREATE_ACTIONS = AttackPathsQueryDefinition(
description="Find IAM policy statements that allow actions containing 'create' within the selected account.",
provider="aws",
cypher=f"""
- MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(pol:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = "Allow"
- AND any(x IN stmt.action WHERE toLower(x) CONTAINS "create")
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(pol:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) CONTAINS 'create'
+ WITH DISTINCT path
WITH collect(path) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -203,7 +208,6 @@ AWS_IAM_STATEMENTS_ALLOW_CREATE_ACTIONS = AttackPathsQueryDefinition(
# Network Exposure Queries
-# ------------------------
AWS_EC2_INSTANCES_INTERNET_EXPOSED = AttackPathsQueryDefinition(
id="aws-ec2-instances-internet-exposed",
@@ -223,7 +227,7 @@ AWS_EC2_INSTANCES_INTERNET_EXPOSED = AttackPathsQueryDefinition(
WITH paths, internet, can_access, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr, internet, can_access
""",
@@ -249,7 +253,7 @@ AWS_SECURITY_GROUPS_OPEN_INTERNET_FACING = AttackPathsQueryDefinition(
WITH paths, internet, can_access, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr, internet, can_access
""",
@@ -274,7 +278,7 @@ AWS_CLASSIC_ELB_INTERNET_EXPOSED = AttackPathsQueryDefinition(
WITH paths, internet, can_access, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr, internet, can_access
""",
@@ -299,7 +303,7 @@ AWS_ELBV2_INTERNET_EXPOSED = AttackPathsQueryDefinition(
WITH paths, internet, can_access, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr, internet, can_access
""",
@@ -327,7 +331,7 @@ AWS_PUBLIC_IP_RESOURCE_LOOKUP = AttackPathsQueryDefinition(
WITH paths, internet, can_access, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr, internet, can_access
""",
@@ -343,7 +347,6 @@ AWS_PUBLIC_IP_RESOURCE_LOOKUP = AttackPathsQueryDefinition(
# Privilege Escalation Queries (based on pathfinding.cloud research)
# https://github.com/DataDog/pathfinding.cloud
-# -------------------------------------------------------------------
# APPRUNNER-001
AWS_APPRUNNER_PRIVESC_PASSROLE_CREATE_SERVICE = AttackPathsQueryDefinition(
@@ -358,31 +361,27 @@ AWS_APPRUNNER_PRIVESC_PASSROLE_CREATE_SERVICE = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find apprunner:CreateService permission
- MATCH (principal)--(apprunner_policy:AWSPolicy)--(stmt_apprunner:AWSPolicyStatement)
- WHERE stmt_apprunner.effect = 'Allow'
- AND any(action IN stmt_apprunner.action WHERE
- toLower(action) = 'apprunner:createservice'
- OR toLower(action) = 'apprunner:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(apprunner_policy:AWSPolicy)-[:STATEMENT]->(stmt_apprunner:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_apprunner)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['apprunner:*', 'apprunner:createservice']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust App Runner tasks service (can be passed to App Runner)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'tasks.apprunner.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -390,7 +389,7 @@ AWS_APPRUNNER_PRIVESC_PASSROLE_CREATE_SERVICE = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -410,25 +409,24 @@ AWS_APPRUNNER_PRIVESC_UPDATE_SERVICE = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with apprunner:UpdateService permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(update_policy:AWSPolicy)--(stmt_update:AWSPolicyStatement)
- WHERE stmt_update.effect = 'Allow'
- AND any(action IN stmt_update.action WHERE
- toLower(action) = 'apprunner:updateservice'
- OR toLower(action) = 'apprunner:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(update_policy:AWSPolicy)-[:STATEMENT]->(stmt_update:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_update)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['apprunner:*', 'apprunner:updateservice']
+ OR act.value = '*'
+ WITH aws, collect(DISTINCT path_principal) AS principal_paths
// Find existing App Runner services with roles attached (potential targets)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'tasks.apprunner.amazonaws.com'}})
- WITH collect(path_principal) + collect(path_target) AS paths
+ WITH principal_paths, collect(DISTINCT path_target) AS target_paths
+ WITH principal_paths + target_paths AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -448,49 +446,41 @@ AWS_BEDROCK_PRIVESC_PASSROLE_CODE_INTERPRETER = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find bedrock-agentcore:CreateCodeInterpreter permission
- MATCH (principal)--(bedrock_policy:AWSPolicy)--(stmt_bedrock:AWSPolicyStatement)
- WHERE stmt_bedrock.effect = 'Allow'
- AND any(action IN stmt_bedrock.action WHERE
- toLower(action) = 'bedrock-agentcore:createcodeinterpreter'
- OR toLower(action) = 'bedrock-agentcore:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(bedrock_policy:AWSPolicy)-[:STATEMENT]->(stmt_bedrock:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_bedrock)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['bedrock-agentcore:*', 'bedrock-agentcore:createcodeinterpreter']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find bedrock-agentcore:StartCodeInterpreterSession permission
- MATCH (principal)--(session_policy:AWSPolicy)--(stmt_session:AWSPolicyStatement)
- WHERE stmt_session.effect = 'Allow'
- AND any(action IN stmt_session.action WHERE
- toLower(action) = 'bedrock-agentcore:startcodeinterpretersession'
- OR toLower(action) = 'bedrock-agentcore:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(session_policy:AWSPolicy)-[:STATEMENT]->(stmt_session:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_session)-[:HAS_ACTION]->(act3:AWSPolicyStatementActionItem)
+ WHERE toLower(act3.value) IN ['bedrock-agentcore:*', 'bedrock-agentcore:startcodeinterpretersession']
+ OR act3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find bedrock-agentcore:InvokeCodeInterpreter permission
- MATCH (principal)--(invoke_policy:AWSPolicy)--(stmt_invoke:AWSPolicyStatement)
- WHERE stmt_invoke.effect = 'Allow'
- AND any(action IN stmt_invoke.action WHERE
- toLower(action) = 'bedrock-agentcore:invokecodeinterpreter'
- OR toLower(action) = 'bedrock-agentcore:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(invoke_policy:AWSPolicy)-[:STATEMENT]->(stmt_invoke:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_invoke)-[:HAS_ACTION]->(act4:AWSPolicyStatementActionItem)
+ WHERE toLower(act4.value) IN ['bedrock-agentcore:*', 'bedrock-agentcore:invokecodeinterpreter']
+ OR act4.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust the Bedrock AgentCore service (can be passed to a code interpreter)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'bedrock-agentcore.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -498,7 +488,7 @@ AWS_BEDROCK_PRIVESC_PASSROLE_CODE_INTERPRETER = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -518,34 +508,31 @@ AWS_BEDROCK_PRIVESC_INVOKE_CODE_INTERPRETER = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with bedrock-agentcore:StartCodeInterpreterSession permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(session_policy:AWSPolicy)--(stmt_session:AWSPolicyStatement)
- WHERE stmt_session.effect = 'Allow'
- AND any(action IN stmt_session.action WHERE
- toLower(action) = 'bedrock-agentcore:startcodeinterpretersession'
- OR toLower(action) = 'bedrock-agentcore:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(session_policy:AWSPolicy)-[:STATEMENT]->(stmt_session:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_session)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['bedrock-agentcore:*', 'bedrock-agentcore:startcodeinterpretersession']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, path_principal
// Find bedrock-agentcore:InvokeCodeInterpreter permission
- MATCH (principal)--(invoke_policy:AWSPolicy)--(stmt_invoke:AWSPolicyStatement)
- WHERE stmt_invoke.effect = 'Allow'
- AND any(action IN stmt_invoke.action WHERE
- toLower(action) = 'bedrock-agentcore:invokecodeinterpreter'
- OR toLower(action) = 'bedrock-agentcore:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(invoke_policy:AWSPolicy)-[:STATEMENT]->(stmt_invoke:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_invoke)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['bedrock-agentcore:*', 'bedrock-agentcore:invokecodeinterpreter']
+ OR act2.value = '*'
+ WITH aws, collect(DISTINCT path_principal) AS principal_paths
// Find roles that trust the Bedrock AgentCore service (already attached to existing code interpreters)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'bedrock-agentcore.amazonaws.com'}})
- WITH collect(path_principal) + collect(path_target) AS paths
+ WITH principal_paths, collect(DISTINCT path_target) AS target_paths
+ WITH principal_paths + target_paths AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -565,31 +552,27 @@ AWS_CLOUDFORMATION_PRIVESC_PASSROLE_CREATE_STACK = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find cloudformation:CreateStack permission
- MATCH (principal)--(cfn_policy:AWSPolicy)--(stmt_cfn:AWSPolicyStatement)
- WHERE stmt_cfn.effect = 'Allow'
- AND any(action IN stmt_cfn.action WHERE
- toLower(action) = 'cloudformation:createstack'
- OR toLower(action) = 'cloudformation:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(cfn_policy:AWSPolicy)-[:STATEMENT]->(stmt_cfn:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_cfn)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['cloudformation:*', 'cloudformation:createstack']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust CloudFormation service (can be passed to CloudFormation)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'cloudformation.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -597,7 +580,7 @@ AWS_CLOUDFORMATION_PRIVESC_PASSROLE_CREATE_STACK = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -617,25 +600,24 @@ AWS_CLOUDFORMATION_PRIVESC_UPDATE_STACK = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with cloudformation:UpdateStack permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(update_policy:AWSPolicy)--(stmt_update:AWSPolicyStatement)
- WHERE stmt_update.effect = 'Allow'
- AND any(action IN stmt_update.action WHERE
- toLower(action) = 'cloudformation:updatestack'
- OR toLower(action) = 'cloudformation:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(update_policy:AWSPolicy)-[:STATEMENT]->(stmt_update:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_update)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['cloudformation:*', 'cloudformation:updatestack']
+ OR act.value = '*'
+ WITH aws, collect(DISTINCT path_principal) AS principal_paths
// Find roles that trust CloudFormation service (already attached to existing stacks)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'cloudformation.amazonaws.com'}})
- WITH collect(path_principal) + collect(path_target) AS paths
+ WITH principal_paths, collect(DISTINCT path_target) AS target_paths
+ WITH principal_paths + target_paths AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -655,40 +637,34 @@ AWS_CLOUDFORMATION_PRIVESC_PASSROLE_CREATE_STACKSET = AttackPathsQueryDefinition
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find cloudformation:CreateStackSet permission
- MATCH (principal)--(cfn_policy:AWSPolicy)--(stmt_cfn:AWSPolicyStatement)
- WHERE stmt_cfn.effect = 'Allow'
- AND any(action IN stmt_cfn.action WHERE
- toLower(action) = 'cloudformation:createstackset'
- OR toLower(action) = 'cloudformation:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(cfn_policy:AWSPolicy)-[:STATEMENT]->(stmt_cfn:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_cfn)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['cloudformation:*', 'cloudformation:createstackset']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find cloudformation:CreateStackInstances permission
- MATCH (principal)--(cfn_instances_policy:AWSPolicy)--(stmt_cfn_instances:AWSPolicyStatement)
- WHERE stmt_cfn_instances.effect = 'Allow'
- AND any(action IN stmt_cfn_instances.action WHERE
- toLower(action) = 'cloudformation:createstackinstances'
- OR toLower(action) = 'cloudformation:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(cfn_instances_policy:AWSPolicy)-[:STATEMENT]->(stmt_cfn_instances:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_cfn_instances)-[:HAS_ACTION]->(act3:AWSPolicyStatementActionItem)
+ WHERE toLower(act3.value) IN ['cloudformation:*', 'cloudformation:createstackinstances']
+ OR act3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust CloudFormation service (can be passed as execution role)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'cloudformation.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -696,7 +672,7 @@ AWS_CLOUDFORMATION_PRIVESC_PASSROLE_CREATE_STACKSET = AttackPathsQueryDefinition
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -716,31 +692,27 @@ AWS_CLOUDFORMATION_PRIVESC_PASSROLE_UPDATE_STACKSET = AttackPathsQueryDefinition
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find cloudformation:UpdateStackSet permission
- MATCH (principal)--(cfn_policy:AWSPolicy)--(stmt_cfn:AWSPolicyStatement)
- WHERE stmt_cfn.effect = 'Allow'
- AND any(action IN stmt_cfn.action WHERE
- toLower(action) = 'cloudformation:updatestackset'
- OR toLower(action) = 'cloudformation:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(cfn_policy:AWSPolicy)-[:STATEMENT]->(stmt_cfn:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_cfn)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['cloudformation:*', 'cloudformation:updatestackset']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust CloudFormation service (can be passed as execution role)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'cloudformation.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -748,7 +720,7 @@ AWS_CLOUDFORMATION_PRIVESC_PASSROLE_UPDATE_STACKSET = AttackPathsQueryDefinition
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -768,34 +740,31 @@ AWS_CLOUDFORMATION_PRIVESC_CHANGESET = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with cloudformation:CreateChangeSet permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(create_policy:AWSPolicy)--(stmt_create:AWSPolicyStatement)
- WHERE stmt_create.effect = 'Allow'
- AND any(action IN stmt_create.action WHERE
- toLower(action) = 'cloudformation:createchangeset'
- OR toLower(action) = 'cloudformation:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(create_policy:AWSPolicy)-[:STATEMENT]->(stmt_create:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_create)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['cloudformation:*', 'cloudformation:createchangeset']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, path_principal
// Find cloudformation:ExecuteChangeSet permission
- MATCH (principal)--(exec_policy:AWSPolicy)--(stmt_exec:AWSPolicyStatement)
- WHERE stmt_exec.effect = 'Allow'
- AND any(action IN stmt_exec.action WHERE
- toLower(action) = 'cloudformation:executechangeset'
- OR toLower(action) = 'cloudformation:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(exec_policy:AWSPolicy)-[:STATEMENT]->(stmt_exec:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_exec)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['cloudformation:*', 'cloudformation:executechangeset']
+ OR act2.value = '*'
+ WITH aws, collect(DISTINCT path_principal) AS principal_paths
// Find roles that trust CloudFormation service (already attached to existing stacks)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'cloudformation.amazonaws.com'}})
- WITH collect(path_principal) + collect(path_target) AS paths
+ WITH principal_paths, collect(DISTINCT path_target) AS target_paths
+ WITH principal_paths + target_paths AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -815,40 +784,34 @@ AWS_CODEBUILD_PRIVESC_PASSROLE_CREATE_PROJECT = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find codebuild:CreateProject permission
- MATCH (principal)--(create_policy:AWSPolicy)--(stmt_create:AWSPolicyStatement)
- WHERE stmt_create.effect = 'Allow'
- AND any(action IN stmt_create.action WHERE
- toLower(action) = 'codebuild:createproject'
- OR toLower(action) = 'codebuild:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(create_policy:AWSPolicy)-[:STATEMENT]->(stmt_create:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_create)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['codebuild:*', 'codebuild:createproject']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find codebuild:StartBuild permission
- MATCH (principal)--(build_policy:AWSPolicy)--(stmt_build:AWSPolicyStatement)
- WHERE stmt_build.effect = 'Allow'
- AND any(action IN stmt_build.action WHERE
- toLower(action) = 'codebuild:startbuild'
- OR toLower(action) = 'codebuild:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(build_policy:AWSPolicy)-[:STATEMENT]->(stmt_build:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_build)-[:HAS_ACTION]->(act3:AWSPolicyStatementActionItem)
+ WHERE toLower(act3.value) IN ['codebuild:*', 'codebuild:startbuild']
+ OR act3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust CodeBuild service (can be passed to CodeBuild)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'codebuild.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -856,7 +819,7 @@ AWS_CODEBUILD_PRIVESC_PASSROLE_CREATE_PROJECT = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -876,25 +839,24 @@ AWS_CODEBUILD_PRIVESC_START_BUILD = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with codebuild:StartBuild permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(build_policy:AWSPolicy)--(stmt_build:AWSPolicyStatement)
- WHERE stmt_build.effect = 'Allow'
- AND any(action IN stmt_build.action WHERE
- toLower(action) = 'codebuild:startbuild'
- OR toLower(action) = 'codebuild:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(build_policy:AWSPolicy)-[:STATEMENT]->(stmt_build:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_build)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['codebuild:*', 'codebuild:startbuild']
+ OR act.value = '*'
+ WITH aws, collect(DISTINCT path_principal) AS principal_paths
// Find roles that trust CodeBuild service (already attached to existing projects)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'codebuild.amazonaws.com'}})
- WITH collect(path_principal) + collect(path_target) AS paths
+ WITH principal_paths, collect(DISTINCT path_target) AS target_paths
+ WITH principal_paths + target_paths AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -914,25 +876,24 @@ AWS_CODEBUILD_PRIVESC_START_BUILD_BATCH = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with codebuild:StartBuildBatch permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(build_policy:AWSPolicy)--(stmt_build:AWSPolicyStatement)
- WHERE stmt_build.effect = 'Allow'
- AND any(action IN stmt_build.action WHERE
- toLower(action) = 'codebuild:startbuildbatch'
- OR toLower(action) = 'codebuild:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(build_policy:AWSPolicy)-[:STATEMENT]->(stmt_build:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_build)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['codebuild:*', 'codebuild:startbuildbatch']
+ OR act.value = '*'
+ WITH aws, collect(DISTINCT path_principal) AS principal_paths
// Find roles that trust CodeBuild service (already attached to existing projects)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'codebuild.amazonaws.com'}})
- WITH collect(path_principal) + collect(path_target) AS paths
+ WITH principal_paths, collect(DISTINCT path_target) AS target_paths
+ WITH principal_paths + target_paths AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -952,40 +913,34 @@ AWS_CODEBUILD_PRIVESC_PASSROLE_CREATE_PROJECT_BATCH = AttackPathsQueryDefinition
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find codebuild:CreateProject permission
- MATCH (principal)--(create_policy:AWSPolicy)--(stmt_create:AWSPolicyStatement)
- WHERE stmt_create.effect = 'Allow'
- AND any(action IN stmt_create.action WHERE
- toLower(action) = 'codebuild:createproject'
- OR toLower(action) = 'codebuild:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(create_policy:AWSPolicy)-[:STATEMENT]->(stmt_create:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_create)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['codebuild:*', 'codebuild:createproject']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find codebuild:StartBuildBatch permission
- MATCH (principal)--(batch_policy:AWSPolicy)--(stmt_batch:AWSPolicyStatement)
- WHERE stmt_batch.effect = 'Allow'
- AND any(action IN stmt_batch.action WHERE
- toLower(action) = 'codebuild:startbuildbatch'
- OR toLower(action) = 'codebuild:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(batch_policy:AWSPolicy)-[:STATEMENT]->(stmt_batch:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_batch)-[:HAS_ACTION]->(act3:AWSPolicyStatementActionItem)
+ WHERE toLower(act3.value) IN ['codebuild:*', 'codebuild:startbuildbatch']
+ OR act3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust CodeBuild service (can be passed to CodeBuild)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'codebuild.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -993,7 +948,7 @@ AWS_CODEBUILD_PRIVESC_PASSROLE_CREATE_PROJECT_BATCH = AttackPathsQueryDefinition
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1013,50 +968,42 @@ AWS_DATAPIPELINE_PRIVESC_PASSROLE_CREATE_PIPELINE = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find datapipeline:CreatePipeline permission
- MATCH (principal)--(create_policy:AWSPolicy)--(stmt_create:AWSPolicyStatement)
- WHERE stmt_create.effect = 'Allow'
- AND any(action IN stmt_create.action WHERE
- toLower(action) = 'datapipeline:createpipeline'
- OR toLower(action) = 'datapipeline:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(create_policy:AWSPolicy)-[:STATEMENT]->(stmt_create:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_create)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['datapipeline:*', 'datapipeline:createpipeline']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find datapipeline:PutPipelineDefinition permission
- MATCH (principal)--(put_policy:AWSPolicy)--(stmt_put:AWSPolicyStatement)
- WHERE stmt_put.effect = 'Allow'
- AND any(action IN stmt_put.action WHERE
- toLower(action) = 'datapipeline:putpipelinedefinition'
- OR toLower(action) = 'datapipeline:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(put_policy:AWSPolicy)-[:STATEMENT]->(stmt_put:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_put)-[:HAS_ACTION]->(act3:AWSPolicyStatementActionItem)
+ WHERE toLower(act3.value) IN ['datapipeline:*', 'datapipeline:putpipelinedefinition']
+ OR act3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find datapipeline:ActivatePipeline permission
- MATCH (principal)--(activate_policy:AWSPolicy)--(stmt_activate:AWSPolicyStatement)
- WHERE stmt_activate.effect = 'Allow'
- AND any(action IN stmt_activate.action WHERE
- toLower(action) = 'datapipeline:activatepipeline'
- OR toLower(action) = 'datapipeline:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(activate_policy:AWSPolicy)-[:STATEMENT]->(stmt_activate:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_activate)-[:HAS_ACTION]->(act4:AWSPolicyStatementActionItem)
+ WHERE toLower(act4.value) IN ['datapipeline:*', 'datapipeline:activatepipeline']
+ OR act4.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust Data Pipeline or EMR service (can be passed to DataPipeline)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(trusted_principal:AWSPrincipal)
WHERE trusted_principal.arn IN ['datapipeline.amazonaws.com', 'elasticmapreduce.amazonaws.com']
- AND any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -1064,7 +1011,7 @@ AWS_DATAPIPELINE_PRIVESC_PASSROLE_CREATE_PIPELINE = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1084,31 +1031,27 @@ AWS_EC2_PRIVESC_PASSROLE_IAM = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find ec2:RunInstances permission
- MATCH (principal)--(ec2_policy:AWSPolicy)--(stmt_ec2:AWSPolicyStatement)
- WHERE stmt_ec2.effect = 'Allow'
- AND any(action IN stmt_ec2.action WHERE
- toLower(action) = 'ec2:runinstances'
- OR toLower(action) = 'ec2:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(ec2_policy:AWSPolicy)-[:STATEMENT]->(stmt_ec2:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_ec2)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['ec2:*', 'ec2:runinstances']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust EC2 service (can be passed to EC2)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'ec2.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -1116,7 +1059,7 @@ AWS_EC2_PRIVESC_PASSROLE_IAM = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1136,43 +1079,38 @@ AWS_EC2_PRIVESC_MODIFY_INSTANCE_ATTRIBUTE = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with ec2:ModifyInstanceAttribute permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(modify_policy:AWSPolicy)--(stmt_modify:AWSPolicyStatement)
- WHERE stmt_modify.effect = 'Allow'
- AND any(action IN stmt_modify.action WHERE
- toLower(action) = 'ec2:modifyinstanceattribute'
- OR toLower(action) = 'ec2:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(modify_policy:AWSPolicy)-[:STATEMENT]->(stmt_modify:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_modify)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['ec2:*', 'ec2:modifyinstanceattribute']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, path_principal
// Find ec2:StopInstances permission (can be same or different policy)
- MATCH (principal)--(stop_policy:AWSPolicy)--(stmt_stop:AWSPolicyStatement)
- WHERE stmt_stop.effect = 'Allow'
- AND any(action IN stmt_stop.action WHERE
- toLower(action) = 'ec2:stopinstances'
- OR toLower(action) = 'ec2:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(stop_policy:AWSPolicy)-[:STATEMENT]->(stmt_stop:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_stop)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['ec2:*', 'ec2:stopinstances']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, path_principal
// Find ec2:StartInstances permission (can be same or different policy)
- MATCH (principal)--(start_policy:AWSPolicy)--(stmt_start:AWSPolicyStatement)
- WHERE stmt_start.effect = 'Allow'
- AND any(action IN stmt_start.action WHERE
- toLower(action) = 'ec2:startinstances'
- OR toLower(action) = 'ec2:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(start_policy:AWSPolicy)-[:STATEMENT]->(stmt_start:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_start)-[:HAS_ACTION]->(act3:AWSPolicyStatementActionItem)
+ WHERE toLower(act3.value) IN ['ec2:*', 'ec2:startinstances']
+ OR act3.value = '*'
+ WITH aws, collect(DISTINCT path_principal) AS principal_paths
// Find EC2 instances with instance profiles (potential targets)
MATCH path_target = (aws)--(ec2:EC2Instance)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
- WITH collect(path_principal) + collect(path_target) AS paths
+ WITH principal_paths, collect(DISTINCT path_target) AS target_paths
+ WITH principal_paths + target_paths AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1192,31 +1130,27 @@ AWS_EC2_PRIVESC_PASSROLE_SPOT_INSTANCES = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find ec2:RequestSpotInstances permission
- MATCH (principal)--(spot_policy:AWSPolicy)--(stmt_spot:AWSPolicyStatement)
- WHERE stmt_spot.effect = 'Allow'
- AND any(action IN stmt_spot.action WHERE
- toLower(action) = 'ec2:requestspotinstances'
- OR toLower(action) = 'ec2:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(spot_policy:AWSPolicy)-[:STATEMENT]->(stmt_spot:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_spot)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['ec2:*', 'ec2:requestspotinstances']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust EC2 service (can be passed to EC2 spot instances)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'ec2.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -1224,7 +1158,7 @@ AWS_EC2_PRIVESC_PASSROLE_SPOT_INSTANCES = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1244,34 +1178,31 @@ AWS_EC2_PRIVESC_LAUNCH_TEMPLATE = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with ec2:CreateLaunchTemplateVersion permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(create_policy:AWSPolicy)--(stmt_create:AWSPolicyStatement)
- WHERE stmt_create.effect = 'Allow'
- AND any(action IN stmt_create.action WHERE
- toLower(action) = 'ec2:createlaunchtemplateversion'
- OR toLower(action) = 'ec2:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(create_policy:AWSPolicy)-[:STATEMENT]->(stmt_create:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_create)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['ec2:*', 'ec2:createlaunchtemplateversion']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, path_principal
// Find ec2:ModifyLaunchTemplate permission
- MATCH (principal)--(modify_policy:AWSPolicy)--(stmt_modify:AWSPolicyStatement)
- WHERE stmt_modify.effect = 'Allow'
- AND any(action IN stmt_modify.action WHERE
- toLower(action) = 'ec2:modifylaunchtemplate'
- OR toLower(action) = 'ec2:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(modify_policy:AWSPolicy)-[:STATEMENT]->(stmt_modify:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_modify)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['ec2:*', 'ec2:modifylaunchtemplate']
+ OR act2.value = '*'
+ WITH aws, collect(DISTINCT path_principal) AS principal_paths
// Find launch templates in the account (potential targets)
MATCH path_target = (aws)--(template:LaunchTemplate)
- WITH collect(path_principal) + collect(path_target) AS paths
+ WITH principal_paths, collect(DISTINCT path_target) AS target_paths
+ WITH principal_paths + target_paths AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1291,25 +1222,24 @@ AWS_EC2INSTANCECONNECT_PRIVESC_SEND_SSH_PUBLIC_KEY = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with ec2-instance-connect:SendSSHPublicKey permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(connect_policy:AWSPolicy)--(stmt_connect:AWSPolicyStatement)
- WHERE stmt_connect.effect = 'Allow'
- AND any(action IN stmt_connect.action WHERE
- toLower(action) = 'ec2-instance-connect:sendsshpublickey'
- OR toLower(action) = 'ec2-instance-connect:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(connect_policy:AWSPolicy)-[:STATEMENT]->(stmt_connect:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_connect)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['ec2-instance-connect:*', 'ec2-instance-connect:sendsshpublickey']
+ OR act.value = '*'
+ WITH aws, collect(DISTINCT path_principal) AS principal_paths
// Find EC2 instances with attached roles (targets for credential theft via IMDS)
MATCH path_target = (aws)--(ec2:EC2Instance)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
- WITH collect(path_principal) + collect(path_target) AS paths
+ WITH principal_paths, collect(DISTINCT path_target) AS target_paths
+ WITH principal_paths + target_paths AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1328,58 +1258,46 @@ AWS_ECS_PRIVESC_PASSROLE_CREATE_SERVICE = AttackPathsQueryDefinition(
link="https://pathfinding.cloud/paths/ecs-001",
),
cypher=f"""
- // Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find principals with iam:PassRole permission (this IS path_principal)
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
- // Find ecs:CreateCluster permission
- MATCH (principal)--(cluster_policy:AWSPolicy)--(stmt_cluster:AWSPolicyStatement)
- WHERE stmt_cluster.effect = 'Allow'
- AND any(action IN stmt_cluster.action WHERE
- toLower(action) = 'ecs:createcluster'
- OR toLower(action) = 'ecs:*'
- OR action = '*'
- )
+ // Gate: ecs:CreateCluster (existence only)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(:AWSPolicyStatement {{effect: 'Allow'}})-[:HAS_ACTION]->(a2:AWSPolicyStatementActionItem)
+ WHERE toLower(a2.value) IN ['ecs:*', 'ecs:createcluster']
+ OR a2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
- // Find ecs:RegisterTaskDefinition permission
- MATCH (principal)--(taskdef_policy:AWSPolicy)--(stmt_taskdef:AWSPolicyStatement)
- WHERE stmt_taskdef.effect = 'Allow'
- AND any(action IN stmt_taskdef.action WHERE
- toLower(action) = 'ecs:registertaskdefinition'
- OR toLower(action) = 'ecs:*'
- OR action = '*'
- )
+ // Gate: ecs:RegisterTaskDefinition (existence only)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(:AWSPolicyStatement {{effect: 'Allow'}})-[:HAS_ACTION]->(a3:AWSPolicyStatementActionItem)
+ WHERE toLower(a3.value) IN ['ecs:*', 'ecs:registertaskdefinition']
+ OR a3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
- // Find ecs:CreateService permission
- MATCH (principal)--(service_policy:AWSPolicy)--(stmt_service:AWSPolicyStatement)
- WHERE stmt_service.effect = 'Allow'
- AND any(action IN stmt_service.action WHERE
- toLower(action) = 'ecs:createservice'
- OR toLower(action) = 'ecs:*'
- OR action = '*'
- )
+ // Gate: ecs:CreateService (existence only)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(:AWSPolicyStatement {{effect: 'Allow'}})-[:HAS_ACTION]->(a4:AWSPolicyStatementActionItem)
+ WHERE toLower(a4.value) IN ['ecs:*', 'ecs:createservice']
+ OR a4.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
- // Find roles that trust ECS tasks service (can be passed to ECS tasks)
+ // Target: a role trusting ECS tasks that the passrole resource can target
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'ecs-tasks.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
-
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1398,58 +1316,48 @@ AWS_ECS_PRIVESC_PASSROLE_RUN_TASK = AttackPathsQueryDefinition(
),
provider="aws",
cypher=f"""
- // Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find principals with iam:PassRole permission (this IS path_principal)
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
- // Find ecs:CreateCluster permission
- MATCH (principal)--(cluster_policy:AWSPolicy)--(stmt_cluster:AWSPolicyStatement)
- WHERE stmt_cluster.effect = 'Allow'
- AND any(action IN stmt_cluster.action WHERE
- toLower(action) = 'ecs:createcluster'
- OR toLower(action) = 'ecs:*'
- OR action = '*'
- )
+ // Collapse: one row per (passrole chain), independent of how many action items matched
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
- // Find ecs:RegisterTaskDefinition permission
- MATCH (principal)--(taskdef_policy:AWSPolicy)--(stmt_taskdef:AWSPolicyStatement)
- WHERE stmt_taskdef.effect = 'Allow'
- AND any(action IN stmt_taskdef.action WHERE
- toLower(action) = 'ecs:registertaskdefinition'
- OR toLower(action) = 'ecs:*'
- OR action = '*'
- )
+ // Gate: ecs:CreateCluster exists on the principal -> collapse back to one row
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(s2:AWSPolicyStatement {{effect: 'Allow'}})-[:HAS_ACTION]->(a2:AWSPolicyStatementActionItem)
+ WHERE toLower(a2.value) IN ['ecs:*', 'ecs:createcluster']
+ OR a2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
- // Find ecs:RunTask permission
- MATCH (principal)--(runtask_policy:AWSPolicy)--(stmt_runtask:AWSPolicyStatement)
- WHERE stmt_runtask.effect = 'Allow'
- AND any(action IN stmt_runtask.action WHERE
- toLower(action) = 'ecs:runtask'
- OR toLower(action) = 'ecs:*'
- OR action = '*'
- )
+ // Gate: ecs:RegisterTaskDefinition exists on the principal
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(s3:AWSPolicyStatement {{effect: 'Allow'}})-[:HAS_ACTION]->(a3:AWSPolicyStatementActionItem)
+ WHERE toLower(a3.value) IN ['ecs:*', 'ecs:registertaskdefinition']
+ OR a3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
- // Find roles that trust ECS tasks service (can be passed to ECS tasks)
+ // Gate: ecs:RunTask exists on the principal
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(s4:AWSPolicyStatement {{effect: 'Allow'}})-[:HAS_ACTION]->(a4:AWSPolicyStatementActionItem)
+ WHERE toLower(a4.value) IN ['ecs:*', 'ecs:runtask']
+ OR a4.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
+
+ // Target: a role that trusts ECS tasks and that the passrole resource can target
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'ecs-tasks.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
-
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1468,49 +1376,40 @@ AWS_ECS_PRIVESC_PASSROLE_CREATE_SERVICE_EXISTING_CLUSTER = AttackPathsQueryDefin
),
provider="aws",
cypher=f"""
- // Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find principals with iam:PassRole permission (this IS path_principal)
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
- // Find ecs:RegisterTaskDefinition permission
- MATCH (principal)--(taskdef_policy:AWSPolicy)--(stmt_taskdef:AWSPolicyStatement)
- WHERE stmt_taskdef.effect = 'Allow'
- AND any(action IN stmt_taskdef.action WHERE
- toLower(action) = 'ecs:registertaskdefinition'
- OR toLower(action) = 'ecs:*'
- OR action = '*'
- )
+ // Gate: ecs:RegisterTaskDefinition (existence only)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(:AWSPolicyStatement {{effect: 'Allow'}})-[:HAS_ACTION]->(a2:AWSPolicyStatementActionItem)
+ WHERE toLower(a2.value) IN ['ecs:*', 'ecs:registertaskdefinition']
+ OR a2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
- // Find ecs:CreateService permission
- MATCH (principal)--(service_policy:AWSPolicy)--(stmt_service:AWSPolicyStatement)
- WHERE stmt_service.effect = 'Allow'
- AND any(action IN stmt_service.action WHERE
- toLower(action) = 'ecs:createservice'
- OR toLower(action) = 'ecs:*'
- OR action = '*'
- )
+ // Gate: ecs:CreateService (existence only)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(:AWSPolicyStatement {{effect: 'Allow'}})-[:HAS_ACTION]->(a3:AWSPolicyStatementActionItem)
+ WHERE toLower(a3.value) IN ['ecs:*', 'ecs:createservice']
+ OR a3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
- // Find roles that trust ECS tasks service (can be passed to ECS tasks)
+ // Target: a role trusting ECS tasks that the passrole resource can target
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'ecs-tasks.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
-
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1529,49 +1428,40 @@ AWS_ECS_PRIVESC_PASSROLE_RUN_TASK_EXISTING_CLUSTER = AttackPathsQueryDefinition(
),
provider="aws",
cypher=f"""
- // Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find principals with iam:PassRole permission (this IS path_principal)
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
- // Find ecs:RegisterTaskDefinition permission
- MATCH (principal)--(taskdef_policy:AWSPolicy)--(stmt_taskdef:AWSPolicyStatement)
- WHERE stmt_taskdef.effect = 'Allow'
- AND any(action IN stmt_taskdef.action WHERE
- toLower(action) = 'ecs:registertaskdefinition'
- OR toLower(action) = 'ecs:*'
- OR action = '*'
- )
+ // Gate: ecs:RegisterTaskDefinition (existence only)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(:AWSPolicyStatement {{effect: 'Allow'}})-[:HAS_ACTION]->(a2:AWSPolicyStatementActionItem)
+ WHERE toLower(a2.value) IN ['ecs:*', 'ecs:registertaskdefinition']
+ OR a2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
- // Find ecs:RunTask permission
- MATCH (principal)--(runtask_policy:AWSPolicy)--(stmt_runtask:AWSPolicyStatement)
- WHERE stmt_runtask.effect = 'Allow'
- AND any(action IN stmt_runtask.action WHERE
- toLower(action) = 'ecs:runtask'
- OR toLower(action) = 'ecs:*'
- OR action = '*'
- )
+ // Gate: ecs:RunTask (existence only)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(:AWSPolicyStatement {{effect: 'Allow'}})-[:HAS_ACTION]->(a3:AWSPolicyStatementActionItem)
+ WHERE toLower(a3.value) IN ['ecs:*', 'ecs:runtask']
+ OR a3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
- // Find roles that trust ECS tasks service (can be passed to ECS tasks)
+ // Target: a role trusting ECS tasks that the passrole resource can target
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'ecs-tasks.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
-
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1590,49 +1480,40 @@ AWS_ECS_PRIVESC_PASSROLE_START_TASK_EXISTING_CLUSTER = AttackPathsQueryDefinitio
),
provider="aws",
cypher=f"""
- // Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find principals with iam:PassRole permission (this IS path_principal)
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
- // Find ecs:RegisterTaskDefinition permission
- MATCH (principal)--(taskdef_policy:AWSPolicy)--(stmt_taskdef:AWSPolicyStatement)
- WHERE stmt_taskdef.effect = 'Allow'
- AND any(action IN stmt_taskdef.action WHERE
- toLower(action) = 'ecs:registertaskdefinition'
- OR toLower(action) = 'ecs:*'
- OR action = '*'
- )
+ // Gate: ecs:RegisterTaskDefinition (existence only)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(:AWSPolicyStatement {{effect: 'Allow'}})-[:HAS_ACTION]->(a2:AWSPolicyStatementActionItem)
+ WHERE toLower(a2.value) IN ['ecs:*', 'ecs:registertaskdefinition']
+ OR a2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
- // Find ecs:StartTask permission
- MATCH (principal)--(starttask_policy:AWSPolicy)--(stmt_starttask:AWSPolicyStatement)
- WHERE stmt_starttask.effect = 'Allow'
- AND any(action IN stmt_starttask.action WHERE
- toLower(action) = 'ecs:starttask'
- OR toLower(action) = 'ecs:*'
- OR action = '*'
- )
+ // Gate: ecs:StartTask (existence only)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(:AWSPolicyStatement {{effect: 'Allow'}})-[:HAS_ACTION]->(a3:AWSPolicyStatementActionItem)
+ WHERE toLower(a3.value) IN ['ecs:*', 'ecs:starttask']
+ OR a3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
- // Find roles that trust ECS tasks service (can be passed to ECS tasks)
+ // Target: a role trusting ECS tasks that the passrole resource can target
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'ecs-tasks.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
-
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1651,35 +1532,30 @@ AWS_ECS_PRIVESC_EXECUTE_COMMAND = AttackPathsQueryDefinition(
),
provider="aws",
cypher=f"""
- // Find principals with ecs:ExecuteCommand permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(exec_policy:AWSPolicy)--(stmt_exec:AWSPolicyStatement)
- WHERE stmt_exec.effect = 'Allow'
- AND any(action IN stmt_exec.action WHERE
- toLower(action) = 'ecs:executecommand'
- OR toLower(action) = 'ecs:*'
- OR action = '*'
- )
+ // Find principals with ecs:ExecuteCommand permission (this IS path_principal)
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(exec_policy:AWSPolicy)-[:STATEMENT]->(stmt_exec:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_exec)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['ecs:*', 'ecs:executecommand']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, path_principal
- // Find ecs:DescribeTasks permission (required by AWS CLI to get container runtime ID)
- MATCH (principal)--(describe_policy:AWSPolicy)--(stmt_describe:AWSPolicyStatement)
- WHERE stmt_describe.effect = 'Allow'
- AND any(action IN stmt_describe.action WHERE
- toLower(action) = 'ecs:describetasks'
- OR toLower(action) = 'ecs:*'
- OR action = '*'
- )
+ // Gate: ecs:DescribeTasks (existence only)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(:AWSPolicyStatement {{effect: 'Allow'}})-[:HAS_ACTION]->(a2:AWSPolicyStatementActionItem)
+ WHERE toLower(a2.value) IN ['ecs:*', 'ecs:describetasks']
+ OR a2.value = '*'
+ WITH aws, collect(DISTINCT path_principal) AS principal_paths
- // Find roles that trust ECS tasks service (already attached to running tasks)
+ // Target: roles already attached to running tasks (trust ECS tasks service)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'ecs-tasks.amazonaws.com'}})
- WITH collect(path_principal) + collect(path_target) AS paths
+ WITH principal_paths, collect(DISTINCT path_target) AS target_paths
+ WITH principal_paths + target_paths AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
-
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1699,31 +1575,27 @@ AWS_GLUE_PRIVESC_PASSROLE_DEV_ENDPOINT = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find glue:CreateDevEndpoint permission
- MATCH (principal)--(glue_policy:AWSPolicy)--(stmt_glue:AWSPolicyStatement)
- WHERE stmt_glue.effect = 'Allow'
- AND any(action IN stmt_glue.action WHERE
- toLower(action) = 'glue:createdevendpoint'
- OR toLower(action) = 'glue:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(glue_policy:AWSPolicy)-[:STATEMENT]->(stmt_glue:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_glue)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['glue:*', 'glue:createdevendpoint']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust Glue service (can be passed to Glue)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'glue.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -1731,7 +1603,7 @@ AWS_GLUE_PRIVESC_PASSROLE_DEV_ENDPOINT = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1751,25 +1623,24 @@ AWS_GLUE_PRIVESC_UPDATE_DEV_ENDPOINT = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with glue:UpdateDevEndpoint permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'glue:updatedevendpoint'
- OR toLower(action) = 'glue:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['glue:*', 'glue:updatedevendpoint']
+ OR act.value = '*'
+ WITH aws, collect(DISTINCT path_principal) AS principal_paths
// Find roles that trust Glue service (already attached to existing dev endpoints)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'glue.amazonaws.com'}})
- WITH collect(path_principal) + collect(path_target) AS paths
+ WITH principal_paths, collect(DISTINCT path_target) AS target_paths
+ WITH principal_paths + target_paths AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1789,40 +1660,34 @@ AWS_GLUE_PRIVESC_PASSROLE_CREATE_JOB = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find glue:CreateJob permission
- MATCH (principal)--(createjob_policy:AWSPolicy)--(stmt_createjob:AWSPolicyStatement)
- WHERE stmt_createjob.effect = 'Allow'
- AND any(action IN stmt_createjob.action WHERE
- toLower(action) = 'glue:createjob'
- OR toLower(action) = 'glue:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(createjob_policy:AWSPolicy)-[:STATEMENT]->(stmt_createjob:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_createjob)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['glue:*', 'glue:createjob']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find glue:StartJobRun permission
- MATCH (principal)--(startjob_policy:AWSPolicy)--(stmt_startjob:AWSPolicyStatement)
- WHERE stmt_startjob.effect = 'Allow'
- AND any(action IN stmt_startjob.action WHERE
- toLower(action) = 'glue:startjobrun'
- OR toLower(action) = 'glue:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(startjob_policy:AWSPolicy)-[:STATEMENT]->(stmt_startjob:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_startjob)-[:HAS_ACTION]->(act3:AWSPolicyStatementActionItem)
+ WHERE toLower(act3.value) IN ['glue:*', 'glue:startjobrun']
+ OR act3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust Glue service (can be passed to Glue jobs)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'glue.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -1830,7 +1695,7 @@ AWS_GLUE_PRIVESC_PASSROLE_CREATE_JOB = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1850,40 +1715,34 @@ AWS_GLUE_PRIVESC_PASSROLE_CREATE_JOB_TRIGGER = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find glue:CreateJob permission
- MATCH (principal)--(createjob_policy:AWSPolicy)--(stmt_createjob:AWSPolicyStatement)
- WHERE stmt_createjob.effect = 'Allow'
- AND any(action IN stmt_createjob.action WHERE
- toLower(action) = 'glue:createjob'
- OR toLower(action) = 'glue:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(createjob_policy:AWSPolicy)-[:STATEMENT]->(stmt_createjob:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_createjob)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['glue:*', 'glue:createjob']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find glue:CreateTrigger permission
- MATCH (principal)--(trigger_policy:AWSPolicy)--(stmt_trigger:AWSPolicyStatement)
- WHERE stmt_trigger.effect = 'Allow'
- AND any(action IN stmt_trigger.action WHERE
- toLower(action) = 'glue:createtrigger'
- OR toLower(action) = 'glue:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(trigger_policy:AWSPolicy)-[:STATEMENT]->(stmt_trigger:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_trigger)-[:HAS_ACTION]->(act3:AWSPolicyStatementActionItem)
+ WHERE toLower(act3.value) IN ['glue:*', 'glue:createtrigger']
+ OR act3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust Glue service (can be passed to Glue jobs)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'glue.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -1891,7 +1750,7 @@ AWS_GLUE_PRIVESC_PASSROLE_CREATE_JOB_TRIGGER = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1911,40 +1770,34 @@ AWS_GLUE_PRIVESC_PASSROLE_UPDATE_JOB = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find glue:UpdateJob permission
- MATCH (principal)--(updatejob_policy:AWSPolicy)--(stmt_updatejob:AWSPolicyStatement)
- WHERE stmt_updatejob.effect = 'Allow'
- AND any(action IN stmt_updatejob.action WHERE
- toLower(action) = 'glue:updatejob'
- OR toLower(action) = 'glue:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(updatejob_policy:AWSPolicy)-[:STATEMENT]->(stmt_updatejob:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_updatejob)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['glue:*', 'glue:updatejob']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find glue:StartJobRun permission
- MATCH (principal)--(startjob_policy:AWSPolicy)--(stmt_startjob:AWSPolicyStatement)
- WHERE stmt_startjob.effect = 'Allow'
- AND any(action IN stmt_startjob.action WHERE
- toLower(action) = 'glue:startjobrun'
- OR toLower(action) = 'glue:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(startjob_policy:AWSPolicy)-[:STATEMENT]->(stmt_startjob:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_startjob)-[:HAS_ACTION]->(act3:AWSPolicyStatementActionItem)
+ WHERE toLower(act3.value) IN ['glue:*', 'glue:startjobrun']
+ OR act3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust Glue service (can be passed to Glue jobs)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'glue.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -1952,7 +1805,7 @@ AWS_GLUE_PRIVESC_PASSROLE_UPDATE_JOB = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -1972,40 +1825,34 @@ AWS_GLUE_PRIVESC_PASSROLE_UPDATE_JOB_TRIGGER = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find glue:UpdateJob permission
- MATCH (principal)--(updatejob_policy:AWSPolicy)--(stmt_updatejob:AWSPolicyStatement)
- WHERE stmt_updatejob.effect = 'Allow'
- AND any(action IN stmt_updatejob.action WHERE
- toLower(action) = 'glue:updatejob'
- OR toLower(action) = 'glue:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(updatejob_policy:AWSPolicy)-[:STATEMENT]->(stmt_updatejob:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_updatejob)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['glue:*', 'glue:updatejob']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find glue:CreateTrigger permission
- MATCH (principal)--(trigger_policy:AWSPolicy)--(stmt_trigger:AWSPolicyStatement)
- WHERE stmt_trigger.effect = 'Allow'
- AND any(action IN stmt_trigger.action WHERE
- toLower(action) = 'glue:createtrigger'
- OR toLower(action) = 'glue:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(trigger_policy:AWSPolicy)-[:STATEMENT]->(stmt_trigger:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_trigger)-[:HAS_ACTION]->(act3:AWSPolicyStatementActionItem)
+ WHERE toLower(act3.value) IN ['glue:*', 'glue:createtrigger']
+ OR act3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust Glue service (can be passed to Glue jobs)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'glue.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -2013,7 +1860,7 @@ AWS_GLUE_PRIVESC_PASSROLE_UPDATE_JOB_TRIGGER = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2033,22 +1880,20 @@ AWS_IAM_PRIVESC_CREATE_POLICY_VERSION = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:CreatePolicyVersion permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:createpolicyversion'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:createpolicyversion']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
// Find customer-managed policies attached to the same principal that can be overwritten
MATCH path_target = (aws)--(target_policy:AWSPolicy)--(principal)
WHERE target_policy.arn CONTAINS $provider_uid
- AND any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_policy.arn CONTAINS resource
- )
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR target_policy.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -2056,7 +1901,7 @@ AWS_IAM_PRIVESC_CREATE_POLICY_VERSION = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2076,22 +1921,20 @@ AWS_IAM_PRIVESC_CREATE_ACCESS_KEY = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:CreateAccessKey permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:createaccesskey'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:createaccesskey']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
// Find target users that the principal can create access keys for
MATCH path_target = (aws)--(target_user:AWSUser)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_user.arn CONTAINS resource
- OR resource CONTAINS target_user.name
- )
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_user.name
+ OR target_user.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -2099,7 +1942,7 @@ AWS_IAM_PRIVESC_CREATE_ACCESS_KEY = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2118,45 +1961,39 @@ AWS_IAM_PRIVESC_DELETE_CREATE_ACCESS_KEY = AttackPathsQueryDefinition(
),
provider="aws",
cypher=f"""
- // Find principals with iam:CreateAccessKey permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:createaccesskey'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find principals with iam:CreateAccessKey permission (this IS path_principal)
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:createaccesskey']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
- // Find iam:DeleteAccessKey permission
- MATCH (principal)--(delete_policy:AWSPolicy)--(stmt_delete:AWSPolicyStatement)
- WHERE stmt_delete.effect = 'Allow'
- AND any(action IN stmt_delete.action WHERE
- toLower(action) = 'iam:deleteaccesskey'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find iam:DeleteAccessKey permission (keep stmt2: its resource is checked)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(stmt2:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt2)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['iam:*', 'iam:deleteaccesskey']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt, stmt2, path_principal
// Find target users that the principal can rotate access keys for
MATCH path_target = (aws)--(target_user:AWSUser)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_user.arn CONTAINS resource
- OR resource CONTAINS target_user.name
- )
- AND any(resource IN stmt_delete.resource WHERE
- resource = '*'
- OR target_user.arn CONTAINS resource
- OR resource CONTAINS target_user.name
- )
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_user.name
+ OR target_user.arn CONTAINS res.value
+ MATCH (stmt2)-[:HAS_RESOURCE]->(res2:AWSPolicyStatementResourceItem)
+ WHERE res2.value = '*'
+ OR res2.value CONTAINS target_user.name
+ OR target_user.arn CONTAINS res2.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
-
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2176,22 +2013,20 @@ AWS_IAM_PRIVESC_CREATE_LOGIN_PROFILE = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:CreateLoginProfile permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:createloginprofile'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:createloginprofile']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
// Find target users that the principal can create login profiles for
MATCH path_target = (aws)--(target_user:AWSUser)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_user.arn CONTAINS resource
- OR resource CONTAINS target_user.name
- )
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_user.name
+ OR target_user.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -2199,7 +2034,7 @@ AWS_IAM_PRIVESC_CREATE_LOGIN_PROFILE = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2219,19 +2054,16 @@ AWS_IAM_PRIVESC_PUT_ROLE_POLICY = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find roles with iam:PutRolePolicy permission scoped to themselves
- MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(role:AWSRole)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:putrolepolicy'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
- AND any(resource IN stmt.resource WHERE
- resource = '*'
- OR role.arn CONTAINS resource
- OR resource CONTAINS role.name
- )
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(role:AWSRole)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:putrolepolicy']
+ OR act.value = '*'
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS role.name
+ OR role.arn CONTAINS res.value
+ WITH DISTINCT path
WITH collect(path) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -2239,7 +2071,7 @@ AWS_IAM_PRIVESC_PUT_ROLE_POLICY = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2259,22 +2091,20 @@ AWS_IAM_PRIVESC_UPDATE_LOGIN_PROFILE = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:UpdateLoginProfile permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:updateloginprofile'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:updateloginprofile']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
// Find target users that the principal can update login profiles for
MATCH path_target = (aws)--(target_user:AWSUser)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_user.arn CONTAINS resource
- OR resource CONTAINS target_user.name
- )
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_user.name
+ OR target_user.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -2282,7 +2112,7 @@ AWS_IAM_PRIVESC_UPDATE_LOGIN_PROFILE = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2302,19 +2132,16 @@ AWS_IAM_PRIVESC_PUT_USER_POLICY = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find users with iam:PutUserPolicy permission scoped to themselves
- MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(user:AWSUser)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:putuserpolicy'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
- AND any(resource IN stmt.resource WHERE
- resource = '*'
- OR user.arn CONTAINS resource
- OR resource CONTAINS user.name
- )
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(user:AWSUser)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:putuserpolicy']
+ OR act.value = '*'
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS user.name
+ OR user.arn CONTAINS res.value
+ WITH DISTINCT path
WITH collect(path) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -2322,7 +2149,7 @@ AWS_IAM_PRIVESC_PUT_USER_POLICY = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2342,19 +2169,16 @@ AWS_IAM_PRIVESC_ATTACH_USER_POLICY = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find users with iam:AttachUserPolicy permission scoped to themselves
- MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(user:AWSUser)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:attachuserpolicy'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
- AND any(resource IN stmt.resource WHERE
- resource = '*'
- OR user.arn CONTAINS resource
- OR resource CONTAINS user.name
- )
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(user:AWSUser)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:attachuserpolicy']
+ OR act.value = '*'
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS user.name
+ OR user.arn CONTAINS res.value
+ WITH DISTINCT path
WITH collect(path) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -2362,7 +2186,7 @@ AWS_IAM_PRIVESC_ATTACH_USER_POLICY = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2382,19 +2206,16 @@ AWS_IAM_PRIVESC_ATTACH_ROLE_POLICY = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find roles with iam:AttachRolePolicy permission scoped to themselves
- MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(role:AWSRole)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:attachrolepolicy'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
- AND any(resource IN stmt.resource WHERE
- resource = '*'
- OR role.arn CONTAINS resource
- OR resource CONTAINS role.name
- )
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(role:AWSRole)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:attachrolepolicy']
+ OR act.value = '*'
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS role.name
+ OR role.arn CONTAINS res.value
+ WITH DISTINCT path
WITH collect(path) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -2402,7 +2223,7 @@ AWS_IAM_PRIVESC_ATTACH_ROLE_POLICY = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2422,22 +2243,20 @@ AWS_IAM_PRIVESC_ATTACH_GROUP_POLICY = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find users with iam:AttachGroupPolicy permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(user:AWSUser)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:attachgrouppolicy'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(user:AWSUser)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:attachgrouppolicy']
+ OR act.value = '*'
+ WITH DISTINCT aws, user, stmt, path_principal
// Find groups the user is a member of and can attach policies to
- MATCH path_target = (aws)-[:RESOURCE]->(target_group:AWSGroup)<-[:MEMBER_AWS_GROUP]-(user)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_group.arn CONTAINS resource
- OR resource CONTAINS target_group.name
- )
+ MATCH path_target = (aws)--(target_group:AWSGroup)<-[:MEMBER_AWS_GROUP]-(user)
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_group.name
+ OR target_group.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -2445,7 +2264,7 @@ AWS_IAM_PRIVESC_ATTACH_GROUP_POLICY = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2465,22 +2284,20 @@ AWS_IAM_PRIVESC_PUT_GROUP_POLICY = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find users with iam:PutGroupPolicy permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(user:AWSUser)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:putgrouppolicy'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(user:AWSUser)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:putgrouppolicy']
+ OR act.value = '*'
+ WITH DISTINCT aws, user, stmt, path_principal
// Find groups the user is a member of and can put policies on
- MATCH path_target = (aws)-[:RESOURCE]->(target_group:AWSGroup)<-[:MEMBER_AWS_GROUP]-(user)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_group.arn CONTAINS resource
- OR resource CONTAINS target_group.name
- )
+ MATCH path_target = (aws)--(target_group:AWSGroup)<-[:MEMBER_AWS_GROUP]-(user)
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_group.name
+ OR target_group.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -2488,7 +2305,7 @@ AWS_IAM_PRIVESC_PUT_GROUP_POLICY = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2507,31 +2324,30 @@ AWS_IAM_PRIVESC_UPDATE_ASSUME_ROLE_POLICY = AttackPathsQueryDefinition(
),
provider="aws",
cypher=f"""
- // Find principals with iam:UpdateAssumeRolePolicy permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:updateassumerolepolicy'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find principals with iam:UpdateAssumeRolePolicy permission (this IS path_principal)
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:updateassumerolepolicy']
+ OR act.value = '*'
- // Find target roles whose trust policy can be modified
+ // Collapse the action-item fan-out: one row per (statement chain), not per matching action
+ WITH DISTINCT aws, stmt, path_principal
+
+ // Find target roles whose trust policy this statement's resource can target
MATCH path_target = (aws)--(target_role:AWSRole)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
-
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2551,22 +2367,20 @@ AWS_IAM_PRIVESC_ADD_USER_TO_GROUP = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:AddUserToGroup permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:addusertogroup'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:addusertogroup']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
// Find target groups the principal can add users to
- MATCH path_target = (aws)-[:RESOURCE]->(target_group:AWSGroup)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_group.arn CONTAINS resource
- OR resource CONTAINS target_group.name
- )
+ MATCH path_target = (aws)--(target_group:AWSGroup)
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_group.name
+ OR target_group.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -2574,7 +2388,7 @@ AWS_IAM_PRIVESC_ADD_USER_TO_GROUP = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2594,22 +2408,20 @@ AWS_IAM_PRIVESC_ATTACH_ROLE_POLICY_ASSUME_ROLE = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:AttachRolePolicy permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:attachrolepolicy'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:attachrolepolicy']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
// Find target roles the principal can assume and attach policies to
MATCH path_target = (aws)--(target_role:AWSRole)<-[:STS_ASSUMEROLE_ALLOW]-(principal)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -2617,7 +2429,7 @@ AWS_IAM_PRIVESC_ATTACH_ROLE_POLICY_ASSUME_ROLE = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2636,45 +2448,39 @@ AWS_IAM_PRIVESC_ATTACH_USER_POLICY_CREATE_ACCESS_KEY = AttackPathsQueryDefinitio
),
provider="aws",
cypher=f"""
- // Find principals with iam:AttachUserPolicy permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:attachuserpolicy'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find principals with iam:AttachUserPolicy permission (this IS path_principal)
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:attachuserpolicy']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
- // Find iam:CreateAccessKey permission
- MATCH (principal)--(policy2:AWSPolicy)--(stmt2:AWSPolicyStatement)
- WHERE stmt2.effect = 'Allow'
- AND any(action IN stmt2.action WHERE
- toLower(action) = 'iam:createaccesskey'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find iam:CreateAccessKey permission (keep stmt2: its resource is checked)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(stmt2:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt2)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['iam:*', 'iam:createaccesskey']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt, stmt2, path_principal
// Find target users the principal can attach policies to and create keys for
MATCH path_target = (aws)--(target_user:AWSUser)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_user.arn CONTAINS resource
- OR resource CONTAINS target_user.name
- )
- AND any(resource IN stmt2.resource WHERE
- resource = '*'
- OR target_user.arn CONTAINS resource
- OR resource CONTAINS target_user.name
- )
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_user.name
+ OR target_user.arn CONTAINS res.value
+ MATCH (stmt2)-[:HAS_RESOURCE]->(res2:AWSPolicyStatementResourceItem)
+ WHERE res2.value = '*'
+ OR res2.value CONTAINS target_user.name
+ OR target_user.arn CONTAINS res2.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
-
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2694,23 +2500,21 @@ AWS_IAM_PRIVESC_CREATE_POLICY_VERSION_ASSUME_ROLE = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:CreatePolicyVersion permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:createpolicyversion'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:createpolicyversion']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
// Find target roles the principal can assume that have customer-managed policies the principal can modify
MATCH path_target = (aws)--(target_role:AWSRole)<-[:STS_ASSUMEROLE_ALLOW]-(principal)
MATCH (target_role)--(target_policy:AWSPolicy)
WHERE target_policy.arn CONTAINS $provider_uid
- AND any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_policy.arn CONTAINS resource
- )
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR target_policy.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -2718,7 +2522,7 @@ AWS_IAM_PRIVESC_CREATE_POLICY_VERSION_ASSUME_ROLE = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2738,22 +2542,20 @@ AWS_IAM_PRIVESC_PUT_ROLE_POLICY_ASSUME_ROLE = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:PutRolePolicy permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:putrolepolicy'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:putrolepolicy']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
// Find target roles the principal can assume and put inline policies on
MATCH path_target = (aws)--(target_role:AWSRole)<-[:STS_ASSUMEROLE_ALLOW]-(principal)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -2761,7 +2563,7 @@ AWS_IAM_PRIVESC_PUT_ROLE_POLICY_ASSUME_ROLE = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2780,45 +2582,39 @@ AWS_IAM_PRIVESC_PUT_USER_POLICY_CREATE_ACCESS_KEY = AttackPathsQueryDefinition(
),
provider="aws",
cypher=f"""
- // Find principals with iam:PutUserPolicy permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:putuserpolicy'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find principals with iam:PutUserPolicy permission (this IS path_principal)
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:putuserpolicy']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
- // Find iam:CreateAccessKey permission
- MATCH (principal)--(policy2:AWSPolicy)--(stmt2:AWSPolicyStatement)
- WHERE stmt2.effect = 'Allow'
- AND any(action IN stmt2.action WHERE
- toLower(action) = 'iam:createaccesskey'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find iam:CreateAccessKey permission (keep stmt2: its resource is checked)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(stmt2:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt2)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['iam:*', 'iam:createaccesskey']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt, stmt2, path_principal
// Find target users the principal can put policies on and create keys for
MATCH path_target = (aws)--(target_user:AWSUser)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_user.arn CONTAINS resource
- OR resource CONTAINS target_user.name
- )
- AND any(resource IN stmt2.resource WHERE
- resource = '*'
- OR target_user.arn CONTAINS resource
- OR resource CONTAINS target_user.name
- )
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_user.name
+ OR target_user.arn CONTAINS res.value
+ MATCH (stmt2)-[:HAS_RESOURCE]->(res2:AWSPolicyStatementResourceItem)
+ WHERE res2.value = '*'
+ OR res2.value CONTAINS target_user.name
+ OR target_user.arn CONTAINS res2.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
-
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2837,45 +2633,39 @@ AWS_IAM_PRIVESC_ATTACH_ROLE_POLICY_UPDATE_ASSUME_ROLE = AttackPathsQueryDefiniti
),
provider="aws",
cypher=f"""
- // Find principals with iam:AttachRolePolicy permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:attachrolepolicy'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find principals with iam:AttachRolePolicy permission (this IS path_principal)
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:attachrolepolicy']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
- // Find iam:UpdateAssumeRolePolicy permission
- MATCH (principal)--(policy2:AWSPolicy)--(stmt2:AWSPolicyStatement)
- WHERE stmt2.effect = 'Allow'
- AND any(action IN stmt2.action WHERE
- toLower(action) = 'iam:updateassumerolepolicy'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find iam:UpdateAssumeRolePolicy permission (keep stmt2: its resource is checked)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(stmt2:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt2)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['iam:*', 'iam:updateassumerolepolicy']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt, stmt2, path_principal
// Find target roles the principal can attach policies to and update trust policy for
MATCH path_target = (aws)--(target_role:AWSRole)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
- AND any(resource IN stmt2.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ MATCH (stmt2)-[:HAS_RESOURCE]->(res2:AWSPolicyStatementResourceItem)
+ WHERE res2.value = '*'
+ OR res2.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res2.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
-
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2894,46 +2684,40 @@ AWS_IAM_PRIVESC_CREATE_POLICY_VERSION_UPDATE_ASSUME_ROLE = AttackPathsQueryDefin
),
provider="aws",
cypher=f"""
- // Find principals with iam:CreatePolicyVersion permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:createpolicyversion'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find principals with iam:CreatePolicyVersion permission (this IS path_principal)
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:createpolicyversion']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
- // Find iam:UpdateAssumeRolePolicy permission
- MATCH (principal)--(policy2:AWSPolicy)--(stmt2:AWSPolicyStatement)
- WHERE stmt2.effect = 'Allow'
- AND any(action IN stmt2.action WHERE
- toLower(action) = 'iam:updateassumerolepolicy'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find iam:UpdateAssumeRolePolicy permission (keep stmt2: its resource is checked)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(stmt2:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt2)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['iam:*', 'iam:updateassumerolepolicy']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt, stmt2, path_principal
// Find target roles with customer-managed policies the principal can modify and update trust policy for
MATCH path_target = (aws)--(target_role:AWSRole)
- WHERE any(resource IN stmt2.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
- MATCH (target_role)--(target_policy:AWSPolicy)
+ MATCH (stmt2)-[:HAS_RESOURCE]->(res2:AWSPolicyStatementResourceItem)
+ WHERE res2.value = '*'
+ OR res2.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res2.value
+ MATCH (target_role)-[:POLICY]->(target_policy:AWSPolicy)
WHERE target_policy.arn CONTAINS $provider_uid
- AND any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_policy.arn CONTAINS resource
- )
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR target_policy.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
-
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -2952,45 +2736,39 @@ AWS_IAM_PRIVESC_PUT_ROLE_POLICY_UPDATE_ASSUME_ROLE = AttackPathsQueryDefinition(
),
provider="aws",
cypher=f"""
- // Find principals with iam:PutRolePolicy permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'iam:putrolepolicy'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find principals with iam:PutRolePolicy permission (this IS path_principal)
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:putrolepolicy']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
- // Find iam:UpdateAssumeRolePolicy permission
- MATCH (principal)--(policy2:AWSPolicy)--(stmt2:AWSPolicyStatement)
- WHERE stmt2.effect = 'Allow'
- AND any(action IN stmt2.action WHERE
- toLower(action) = 'iam:updateassumerolepolicy'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ // Find iam:UpdateAssumeRolePolicy permission (keep stmt2: its resource is checked)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(stmt2:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt2)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['iam:*', 'iam:updateassumerolepolicy']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt, stmt2, path_principal
// Find target roles the principal can put inline policies on and update trust policy for
MATCH path_target = (aws)--(target_role:AWSRole)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
- AND any(resource IN stmt2.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ MATCH (stmt2)-[:HAS_RESOURCE]->(res2:AWSPolicyStatementResourceItem)
+ WHERE res2.value = '*'
+ OR res2.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res2.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
-
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -3010,40 +2788,34 @@ AWS_LAMBDA_PRIVESC_PASSROLE_CREATE_FUNCTION = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find lambda:CreateFunction permission
- MATCH (principal)--(create_policy:AWSPolicy)--(stmt_create:AWSPolicyStatement)
- WHERE stmt_create.effect = 'Allow'
- AND any(action IN stmt_create.action WHERE
- toLower(action) = 'lambda:createfunction'
- OR toLower(action) = 'lambda:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(create_policy:AWSPolicy)-[:STATEMENT]->(stmt_create:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_create)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['lambda:*', 'lambda:createfunction']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find lambda:InvokeFunction permission
- MATCH (principal)--(invoke_policy:AWSPolicy)--(stmt_invoke:AWSPolicyStatement)
- WHERE stmt_invoke.effect = 'Allow'
- AND any(action IN stmt_invoke.action WHERE
- toLower(action) = 'lambda:invokefunction'
- OR toLower(action) = 'lambda:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(invoke_policy:AWSPolicy)-[:STATEMENT]->(stmt_invoke:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_invoke)-[:HAS_ACTION]->(act3:AWSPolicyStatementActionItem)
+ WHERE toLower(act3.value) IN ['lambda:*', 'lambda:invokefunction']
+ OR act3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust Lambda service (can be passed to Lambda)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'lambda.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -3051,7 +2823,7 @@ AWS_LAMBDA_PRIVESC_PASSROLE_CREATE_FUNCTION = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -3071,40 +2843,34 @@ AWS_LAMBDA_PRIVESC_PASSROLE_CREATE_FUNCTION_EVENT_SOURCE = AttackPathsQueryDefin
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find lambda:CreateFunction permission
- MATCH (principal)--(create_policy:AWSPolicy)--(stmt_create:AWSPolicyStatement)
- WHERE stmt_create.effect = 'Allow'
- AND any(action IN stmt_create.action WHERE
- toLower(action) = 'lambda:createfunction'
- OR toLower(action) = 'lambda:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(create_policy:AWSPolicy)-[:STATEMENT]->(stmt_create:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_create)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['lambda:*', 'lambda:createfunction']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find lambda:CreateEventSourceMapping permission
- MATCH (principal)--(event_policy:AWSPolicy)--(stmt_event:AWSPolicyStatement)
- WHERE stmt_event.effect = 'Allow'
- AND any(action IN stmt_event.action WHERE
- toLower(action) = 'lambda:createeventsourcemapping'
- OR toLower(action) = 'lambda:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(event_policy:AWSPolicy)-[:STATEMENT]->(stmt_event:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_event)-[:HAS_ACTION]->(act3:AWSPolicyStatementActionItem)
+ WHERE toLower(act3.value) IN ['lambda:*', 'lambda:createeventsourcemapping']
+ OR act3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust Lambda service (can be passed to Lambda)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'lambda.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -3112,7 +2878,7 @@ AWS_LAMBDA_PRIVESC_PASSROLE_CREATE_FUNCTION_EVENT_SOURCE = AttackPathsQueryDefin
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -3132,22 +2898,20 @@ AWS_LAMBDA_PRIVESC_UPDATE_FUNCTION_CODE = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with lambda:UpdateFunctionCode permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'lambda:updatefunctioncode'
- OR toLower(action) = 'lambda:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['lambda:*', 'lambda:updatefunctioncode']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
// Find existing Lambda functions with execution roles
- MATCH path_target = (aws)-[:RESOURCE]->(lambda_fn:AWSLambda)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR lambda_fn.arn CONTAINS resource
- OR resource CONTAINS lambda_fn.name
- )
+ MATCH path_target = (aws)--(lambda_fn:AWSLambda)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS lambda_fn.name
+ OR lambda_fn.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -3155,7 +2919,7 @@ AWS_LAMBDA_PRIVESC_UPDATE_FUNCTION_CODE = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -3174,45 +2938,39 @@ AWS_LAMBDA_PRIVESC_UPDATE_FUNCTION_CODE_INVOKE = AttackPathsQueryDefinition(
),
provider="aws",
cypher=f"""
- // Find principals with lambda:UpdateFunctionCode permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'lambda:updatefunctioncode'
- OR toLower(action) = 'lambda:*'
- OR action = '*'
- )
+ // Find principals with lambda:UpdateFunctionCode permission (this IS path_principal)
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['lambda:*', 'lambda:updatefunctioncode']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
- // Find lambda:InvokeFunction permission
- MATCH (principal)--(policy2:AWSPolicy)--(stmt2:AWSPolicyStatement)
- WHERE stmt2.effect = 'Allow'
- AND any(action IN stmt2.action WHERE
- toLower(action) = 'lambda:invokefunction'
- OR toLower(action) = 'lambda:*'
- OR action = '*'
- )
+ // Find lambda:InvokeFunction permission (keep stmt2: its resource is checked)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(stmt2:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt2)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['lambda:*', 'lambda:invokefunction']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt, stmt2, path_principal
// Find existing Lambda functions with execution roles
- MATCH path_target = (aws)-[:RESOURCE]->(lambda_fn:AWSLambda)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR lambda_fn.arn CONTAINS resource
- OR resource CONTAINS lambda_fn.name
- )
- AND any(resource IN stmt2.resource WHERE
- resource = '*'
- OR lambda_fn.arn CONTAINS resource
- OR resource CONTAINS lambda_fn.name
- )
+ MATCH path_target = (aws)--(lambda_fn:AWSLambda)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS lambda_fn.name
+ OR lambda_fn.arn CONTAINS res.value
+ MATCH (stmt2)-[:HAS_RESOURCE]->(res2:AWSPolicyStatementResourceItem)
+ WHERE res2.value = '*'
+ OR res2.value CONTAINS lambda_fn.name
+ OR lambda_fn.arn CONTAINS res2.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
-
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -3231,45 +2989,39 @@ AWS_LAMBDA_PRIVESC_UPDATE_FUNCTION_CODE_ADD_PERMISSION = AttackPathsQueryDefinit
),
provider="aws",
cypher=f"""
- // Find principals with lambda:UpdateFunctionCode permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'lambda:updatefunctioncode'
- OR toLower(action) = 'lambda:*'
- OR action = '*'
- )
+ // Find principals with lambda:UpdateFunctionCode permission (this IS path_principal)
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['lambda:*', 'lambda:updatefunctioncode']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
- // Find lambda:AddPermission permission
- MATCH (principal)--(policy2:AWSPolicy)--(stmt2:AWSPolicyStatement)
- WHERE stmt2.effect = 'Allow'
- AND any(action IN stmt2.action WHERE
- toLower(action) = 'lambda:addpermission'
- OR toLower(action) = 'lambda:*'
- OR action = '*'
- )
+ // Find lambda:AddPermission permission (keep stmt2: its resource is checked)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(stmt2:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt2)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['lambda:*', 'lambda:addpermission']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt, stmt2, path_principal
// Find existing Lambda functions with execution roles
- MATCH path_target = (aws)-[:RESOURCE]->(lambda_fn:AWSLambda)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR lambda_fn.arn CONTAINS resource
- OR resource CONTAINS lambda_fn.name
- )
- AND any(resource IN stmt2.resource WHERE
- resource = '*'
- OR lambda_fn.arn CONTAINS resource
- OR resource CONTAINS lambda_fn.name
- )
+ MATCH path_target = (aws)--(lambda_fn:AWSLambda)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS lambda_fn.name
+ OR lambda_fn.arn CONTAINS res.value
+ MATCH (stmt2)-[:HAS_RESOURCE]->(res2:AWSPolicyStatementResourceItem)
+ WHERE res2.value = '*'
+ OR res2.value CONTAINS lambda_fn.name
+ OR lambda_fn.arn CONTAINS res2.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
-
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -3289,40 +3041,34 @@ AWS_LAMBDA_PRIVESC_PASSROLE_CREATE_FUNCTION_ADD_PERMISSION = AttackPathsQueryDef
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find lambda:CreateFunction permission
- MATCH (principal)--(create_policy:AWSPolicy)--(stmt_create:AWSPolicyStatement)
- WHERE stmt_create.effect = 'Allow'
- AND any(action IN stmt_create.action WHERE
- toLower(action) = 'lambda:createfunction'
- OR toLower(action) = 'lambda:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(create_policy:AWSPolicy)-[:STATEMENT]->(stmt_create:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_create)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['lambda:*', 'lambda:createfunction']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find lambda:AddPermission permission
- MATCH (principal)--(perm_policy:AWSPolicy)--(stmt_perm:AWSPolicyStatement)
- WHERE stmt_perm.effect = 'Allow'
- AND any(action IN stmt_perm.action WHERE
- toLower(action) = 'lambda:addpermission'
- OR toLower(action) = 'lambda:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(perm_policy:AWSPolicy)-[:STATEMENT]->(stmt_perm:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_perm)-[:HAS_ACTION]->(act3:AWSPolicyStatementActionItem)
+ WHERE toLower(act3.value) IN ['lambda:*', 'lambda:addpermission']
+ OR act3.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust Lambda service (can be passed to Lambda)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'lambda.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -3330,7 +3076,7 @@ AWS_LAMBDA_PRIVESC_PASSROLE_CREATE_FUNCTION_ADD_PERMISSION = AttackPathsQueryDef
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -3350,31 +3096,27 @@ AWS_SAGEMAKER_PRIVESC_PASSROLE_CREATE_NOTEBOOK = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find sagemaker:CreateNotebookInstance permission
- MATCH (principal)--(sm_policy:AWSPolicy)--(stmt_sm:AWSPolicyStatement)
- WHERE stmt_sm.effect = 'Allow'
- AND any(action IN stmt_sm.action WHERE
- toLower(action) = 'sagemaker:createnotebookinstance'
- OR toLower(action) = 'sagemaker:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(sm_policy:AWSPolicy)-[:STATEMENT]->(stmt_sm:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_sm)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['sagemaker:*', 'sagemaker:createnotebookinstance']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust SageMaker service (can be passed to SageMaker)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'sagemaker.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -3382,7 +3124,7 @@ AWS_SAGEMAKER_PRIVESC_PASSROLE_CREATE_NOTEBOOK = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -3402,31 +3144,27 @@ AWS_SAGEMAKER_PRIVESC_PASSROLE_CREATE_TRAINING_JOB = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find sagemaker:CreateTrainingJob permission
- MATCH (principal)--(sm_policy:AWSPolicy)--(stmt_sm:AWSPolicyStatement)
- WHERE stmt_sm.effect = 'Allow'
- AND any(action IN stmt_sm.action WHERE
- toLower(action) = 'sagemaker:createtrainingjob'
- OR toLower(action) = 'sagemaker:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(sm_policy:AWSPolicy)-[:STATEMENT]->(stmt_sm:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_sm)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['sagemaker:*', 'sagemaker:createtrainingjob']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust SageMaker service (can be passed to SageMaker)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'sagemaker.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -3434,7 +3172,7 @@ AWS_SAGEMAKER_PRIVESC_PASSROLE_CREATE_TRAINING_JOB = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -3454,31 +3192,27 @@ AWS_SAGEMAKER_PRIVESC_PASSROLE_CREATE_PROCESSING_JOB = AttackPathsQueryDefinitio
provider="aws",
cypher=f"""
// Find principals with iam:PassRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
- WHERE stmt_passrole.effect = 'Allow'
- AND any(action IN stmt_passrole.action WHERE
- toLower(action) = 'iam:passrole'
- OR toLower(action) = 'iam:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(passrole_policy:AWSPolicy)-[:STATEMENT]->(stmt_passrole:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_passrole)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['iam:*', 'iam:passrole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find sagemaker:CreateProcessingJob permission
- MATCH (principal)--(sm_policy:AWSPolicy)--(stmt_sm:AWSPolicyStatement)
- WHERE stmt_sm.effect = 'Allow'
- AND any(action IN stmt_sm.action WHERE
- toLower(action) = 'sagemaker:createprocessingjob'
- OR toLower(action) = 'sagemaker:*'
- OR action = '*'
- )
+ MATCH (principal)-[:POLICY]->(sm_policy:AWSPolicy)-[:STATEMENT]->(stmt_sm:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt_sm)-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['sagemaker:*', 'sagemaker:createprocessingjob']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt_passrole, path_principal
// Find roles that trust SageMaker service (can be passed to SageMaker)
MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'sagemaker.amazonaws.com'}})
- WHERE any(resource IN stmt_passrole.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt_passrole)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -3486,7 +3220,7 @@ AWS_SAGEMAKER_PRIVESC_PASSROLE_CREATE_PROCESSING_JOB = AttackPathsQueryDefinitio
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -3506,22 +3240,20 @@ AWS_SAGEMAKER_PRIVESC_PRESIGNED_NOTEBOOK_URL = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with sagemaker:CreatePresignedNotebookInstanceUrl permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'sagemaker:createpresignednotebookinstanceurl'
- OR toLower(action) = 'sagemaker:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['sagemaker:*', 'sagemaker:createpresignednotebookinstanceurl']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
// Find existing SageMaker notebook instances with execution roles
- MATCH path_target = (aws)-[:RESOURCE]->(notebook:AWSSageMakerNotebookInstance)-[:HAS_EXECUTION_ROLE]->(target_role:AWSRole)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR notebook.arn CONTAINS resource
- OR resource CONTAINS notebook.notebook_instance_name
- )
+ MATCH path_target = (aws)--(notebook:AWSSageMakerNotebookInstance)-[:HAS_EXECUTION_ROLE]->(target_role:AWSRole)
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS notebook.notebook_instance_name
+ OR notebook.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -3529,7 +3261,7 @@ AWS_SAGEMAKER_PRIVESC_PRESIGNED_NOTEBOOK_URL = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -3548,58 +3280,46 @@ AWS_SAGEMAKER_PRIVESC_LIFECYCLE_CONFIG_NOTEBOOK = AttackPathsQueryDefinition(
),
provider="aws",
cypher=f"""
- // Find principals with sagemaker:CreateNotebookInstanceLifecycleConfig permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'sagemaker:createnotebookinstancelifecycleconfig'
- OR toLower(action) = 'sagemaker:*'
- OR action = '*'
- )
+ // Find principals with sagemaker:CreateNotebookInstanceLifecycleConfig permission (this IS path_principal)
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['sagemaker:*', 'sagemaker:createnotebookinstancelifecycleconfig']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, path_principal
- // Find sagemaker:UpdateNotebookInstance permission
- MATCH (principal)--(policy2:AWSPolicy)--(stmt2:AWSPolicyStatement)
- WHERE stmt2.effect = 'Allow'
- AND any(action IN stmt2.action WHERE
- toLower(action) = 'sagemaker:updatenotebookinstance'
- OR toLower(action) = 'sagemaker:*'
- OR action = '*'
- )
+ // Gate: sagemaker:UpdateNotebookInstance (keep stmt2: its resource is checked)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(stmt2:AWSPolicyStatement {{effect: 'Allow'}})-[:HAS_ACTION]->(act2:AWSPolicyStatementActionItem)
+ WHERE toLower(act2.value) IN ['sagemaker:*', 'sagemaker:updatenotebookinstance']
+ OR act2.value = '*'
+ WITH DISTINCT aws, principal, stmt2, path_principal
- // Find sagemaker:StopNotebookInstance permission
- MATCH (principal)--(policy3:AWSPolicy)--(stmt3:AWSPolicyStatement)
- WHERE stmt3.effect = 'Allow'
- AND any(action IN stmt3.action WHERE
- toLower(action) = 'sagemaker:stopnotebookinstance'
- OR toLower(action) = 'sagemaker:*'
- OR action = '*'
- )
+ // Gate: sagemaker:StopNotebookInstance (existence only)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(:AWSPolicyStatement {{effect: 'Allow'}})-[:HAS_ACTION]->(act3:AWSPolicyStatementActionItem)
+ WHERE toLower(act3.value) IN ['sagemaker:*', 'sagemaker:stopnotebookinstance']
+ OR act3.value = '*'
+ WITH DISTINCT aws, principal, stmt2, path_principal
- // Find sagemaker:StartNotebookInstance permission
- MATCH (principal)--(policy4:AWSPolicy)--(stmt4:AWSPolicyStatement)
- WHERE stmt4.effect = 'Allow'
- AND any(action IN stmt4.action WHERE
- toLower(action) = 'sagemaker:startnotebookinstance'
- OR toLower(action) = 'sagemaker:*'
- OR action = '*'
- )
+ // Gate: sagemaker:StartNotebookInstance (existence only)
+ MATCH (principal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(:AWSPolicyStatement {{effect: 'Allow'}})-[:HAS_ACTION]->(act4:AWSPolicyStatementActionItem)
+ WHERE toLower(act4.value) IN ['sagemaker:*', 'sagemaker:startnotebookinstance']
+ OR act4.value = '*'
+ WITH DISTINCT aws, principal, stmt2, path_principal
// Find existing SageMaker notebook instances with execution roles
- MATCH path_target = (aws)-[:RESOURCE]->(notebook:AWSSageMakerNotebookInstance)-[:HAS_EXECUTION_ROLE]->(target_role:AWSRole)
- WHERE any(resource IN stmt2.resource WHERE
- resource = '*'
- OR notebook.arn CONTAINS resource
- OR resource CONTAINS notebook.notebook_instance_name
- )
+ MATCH path_target = (aws)--(notebook:AWSSageMakerNotebookInstance)-[:HAS_EXECUTION_ROLE]->(target_role:AWSRole)
+ MATCH (stmt2)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS notebook.notebook_instance_name
+ OR notebook.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
-
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -3619,25 +3339,24 @@ AWS_SSM_PRIVESC_START_SESSION = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with ssm:StartSession permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'ssm:startsession'
- OR toLower(action) = 'ssm:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['ssm:*', 'ssm:startsession']
+ OR act.value = '*'
+ WITH aws, collect(DISTINCT path_principal) AS principal_paths
// Find EC2 instances with attached roles (targets for credential theft via IMDS)
MATCH path_target = (aws)--(ec2:EC2Instance)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
- WITH collect(path_principal) + collect(path_target) AS paths
+ WITH principal_paths, collect(DISTINCT path_target) AS target_paths
+ WITH principal_paths + target_paths AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -3657,25 +3376,24 @@ AWS_SSM_PRIVESC_SEND_COMMAND = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with ssm:SendCommand permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'ssm:sendcommand'
- OR toLower(action) = 'ssm:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['ssm:*', 'ssm:sendcommand']
+ OR act.value = '*'
+ WITH aws, collect(DISTINCT path_principal) AS principal_paths
// Find EC2 instances with attached roles (targets for credential theft via IMDS)
MATCH path_target = (aws)--(ec2:EC2Instance)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
- WITH collect(path_principal) + collect(path_target) AS paths
+ WITH principal_paths, collect(DISTINCT path_target) AS target_paths
+ WITH principal_paths + target_paths AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -3695,22 +3413,20 @@ AWS_STS_PRIVESC_ASSUME_ROLE = AttackPathsQueryDefinition(
provider="aws",
cypher=f"""
// Find principals with sts:AssumeRole permission
- MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
- WHERE stmt.effect = 'Allow'
- AND any(action IN stmt.action WHERE
- toLower(action) = 'sts:assumerole'
- OR toLower(action) = 'sts:*'
- OR action = '*'
- )
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)-[:POLICY]->(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {{effect: 'Allow'}})
+ MATCH (stmt)-[:HAS_ACTION]->(act:AWSPolicyStatementActionItem)
+ WHERE toLower(act.value) IN ['sts:*', 'sts:assumerole']
+ OR act.value = '*'
+ WITH DISTINCT aws, principal, stmt, path_principal
// Find target roles the principal can assume (bidirectional trust via Cartography)
MATCH path_target = (aws)--(target_role:AWSRole)<-[:STS_ASSUMEROLE_ALLOW]-(principal)
- WHERE any(resource IN stmt.resource WHERE
- resource = '*'
- OR target_role.arn CONTAINS resource
- OR resource CONTAINS target_role.name
- )
+ MATCH (stmt)-[:HAS_RESOURCE]->(res:AWSPolicyStatementResourceItem)
+ WHERE res.value = '*'
+ OR res.value CONTAINS target_role.name
+ OR target_role.arn CONTAINS res.value
+ WITH DISTINCT path_principal, path_target
WITH collect(path_principal) + collect(path_target) AS paths
UNWIND paths AS p
UNWIND nodes(p) AS n
@@ -3718,7 +3434,7 @@ AWS_STS_PRIVESC_ASSUME_ROLE = AttackPathsQueryDefinition(
WITH paths, collect(DISTINCT n) AS unique_nodes
UNWIND unique_nodes AS n
- OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+ OPTIONAL MATCH (n)-[pfr:HAS_FINDING]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
""",
@@ -3726,7 +3442,6 @@ AWS_STS_PRIVESC_ASSUME_ROLE = AttackPathsQueryDefinition(
)
# AWS Queries List
-# ----------------
AWS_QUERIES: list[AttackPathsQueryDefinition] = [
AWS_INTERNET_EXPOSED_EC2_SENSITIVE_S3_ACCESS,
diff --git a/api/src/backend/api/attack_paths/queries/aws_deprecated.py b/api/src/backend/api/attack_paths/queries/aws_deprecated.py
new file mode 100644
index 0000000000..b94c329202
--- /dev/null
+++ b/api/src/backend/api/attack_paths/queries/aws_deprecated.py
@@ -0,0 +1,3819 @@
+# TODO: drop after Neptune cutover
+#
+# Pre-cutover query catalog for AWS scans whose graph data was written under
+# the previous schema, where list-typed policy properties were serialised as
+# comma-delimited strings on the parent node. The registry routes scans with
+# `is_migrated=False` to this module; all other scans use `aws.py`. Both
+# files expose the same query IDs and parameter shapes so the API surface
+# stays uniform across the cutover window. This file is deleted, along with
+# `AttackPathsScan.is_migrated`, once the legacy data is fully drained.
+from api.attack_paths.queries.types import (
+ AttackPathsQueryAttribution,
+ AttackPathsQueryDefinition,
+ AttackPathsQueryParameterDefinition,
+)
+from tasks.jobs.attack_paths.config import PROWLER_FINDING_LABEL
+
+# Custom Attack Path Queries
+# --------------------------
+
+AWS_INTERNET_EXPOSED_EC2_SENSITIVE_S3_ACCESS = AttackPathsQueryDefinition(
+ id="aws-internet-exposed-ec2-sensitive-s3-access",
+ name="Internet-Exposed EC2 with Sensitive S3 Access",
+ short_description="Find SSH-exposed EC2 instances that can assume roles to read tagged sensitive S3 buckets.",
+ description="Detect EC2 instances with SSH exposed to the internet that can assume higher-privileged roles to read tagged sensitive S3 buckets despite bucket-level public access blocks.",
+ provider="aws",
+ cypher=f"""
+ MATCH path_s3 = (aws:AWSAccount {{id: $provider_uid}})--(s3:S3Bucket)--(t:AWSTag)
+ WHERE toLower(t.key) = toLower($tag_key) AND toLower(t.value) = toLower($tag_value)
+
+ MATCH path_ec2 = (aws)--(ec2:EC2Instance)--(sg:EC2SecurityGroup)--(ipi:IpPermissionInbound)
+ WHERE ec2.exposed_internet = true
+ AND ipi.toport = 22
+
+ MATCH path_role = (r:AWSRole)--(pol:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE ANY(x IN stmt.resource WHERE x CONTAINS s3.name)
+ AND ANY(x IN stmt.action WHERE toLower(x) =~ 's3:(listbucket|getobject).*')
+
+ MATCH path_assume_role = (ec2)-[p:STS_ASSUMEROLE_ALLOW*1..9]-(r:AWSRole)
+
+ OPTIONAL MATCH (internet:Internet)-[can_access:CAN_ACCESS]->(ec2)
+
+ WITH collect(path_s3) + collect(path_ec2) + collect(path_role) + collect(path_assume_role) AS paths,
+ head(collect(internet)) AS internet, collect(can_access) AS can_access
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, internet, can_access, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr, internet, can_access
+ """,
+ parameters=[
+ AttackPathsQueryParameterDefinition(
+ name="tag_key",
+ label="Tag key",
+ description="Tag key to filter the S3 bucket, e.g. DataClassification.",
+ placeholder="DataClassification",
+ ),
+ AttackPathsQueryParameterDefinition(
+ name="tag_value",
+ label="Tag value",
+ description="Tag value to filter the S3 bucket, e.g. Sensitive.",
+ placeholder="Sensitive",
+ ),
+ ],
+)
+
+
+# Basic Resource Queries
+# ----------------------
+
+AWS_RDS_INSTANCES = AttackPathsQueryDefinition(
+ id="aws-rds-instances",
+ name="RDS Instances Inventory",
+ short_description="List all provisioned RDS database instances in the account.",
+ description="List the selected AWS account alongside the RDS instances it owns.",
+ provider="aws",
+ cypher=f"""
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(rds:RDSInstance)
+
+ WITH collect(path) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+AWS_RDS_UNENCRYPTED_STORAGE = AttackPathsQueryDefinition(
+ id="aws-rds-unencrypted-storage",
+ name="Unencrypted RDS Instances",
+ short_description="Find RDS instances with storage encryption disabled.",
+ description="Find RDS instances with storage encryption disabled within the selected account.",
+ provider="aws",
+ cypher=f"""
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(rds:RDSInstance)
+ WHERE rds.storage_encrypted = false
+
+ WITH collect(path) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+AWS_S3_ANONYMOUS_ACCESS_BUCKETS = AttackPathsQueryDefinition(
+ id="aws-s3-anonymous-access-buckets",
+ name="S3 Buckets with Anonymous Access",
+ short_description="Find S3 buckets that allow anonymous access.",
+ description="Find S3 buckets that allow anonymous access within the selected account.",
+ provider="aws",
+ cypher=f"""
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(s3:S3Bucket)
+ WHERE s3.anonymous_access = true
+
+ WITH collect(path) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+AWS_IAM_STATEMENTS_ALLOW_ALL_ACTIONS = AttackPathsQueryDefinition(
+ id="aws-iam-statements-allow-all-actions",
+ name="IAM Statements Allowing All Actions",
+ short_description="Find IAM policy statements that allow all actions via wildcard (*).",
+ description="Find IAM policy statements that allow all actions via '*' within the selected account.",
+ provider="aws",
+ cypher=f"""
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(pol:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(x IN stmt.action WHERE x = '*')
+
+ WITH collect(path) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+AWS_IAM_STATEMENTS_ALLOW_DELETE_POLICY = AttackPathsQueryDefinition(
+ id="aws-iam-statements-allow-delete-policy",
+ name="IAM Statements Allowing Policy Deletion",
+ short_description="Find IAM policy statements that allow iam:DeletePolicy.",
+ description="Find IAM policy statements that allow the iam:DeletePolicy action within the selected account.",
+ provider="aws",
+ cypher=f"""
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(pol:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(x IN stmt.action WHERE x = "iam:DeletePolicy")
+
+ WITH collect(path) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+AWS_IAM_STATEMENTS_ALLOW_CREATE_ACTIONS = AttackPathsQueryDefinition(
+ id="aws-iam-statements-allow-create-actions",
+ name="IAM Statements Allowing Create Actions",
+ short_description="Find IAM policy statements that allow any create action.",
+ description="Find IAM policy statements that allow actions containing 'create' within the selected account.",
+ provider="aws",
+ cypher=f"""
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(pol:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = "Allow"
+ AND any(x IN stmt.action WHERE toLower(x) CONTAINS "create")
+
+ WITH collect(path) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+
+# Network Exposure Queries
+# ------------------------
+
+AWS_EC2_INSTANCES_INTERNET_EXPOSED = AttackPathsQueryDefinition(
+ id="aws-ec2-instances-internet-exposed",
+ name="Internet-Exposed EC2 Instances",
+ short_description="Find EC2 instances flagged as exposed to the internet.",
+ description="Find EC2 instances flagged as exposed to the internet within the selected account.",
+ provider="aws",
+ cypher=f"""
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(ec2:EC2Instance)
+ WHERE ec2.exposed_internet = true
+
+ OPTIONAL MATCH (internet:Internet)-[can_access:CAN_ACCESS]->(ec2)
+
+ WITH collect(path) AS paths, head(collect(internet)) AS internet, collect(can_access) AS can_access
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, internet, can_access, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr, internet, can_access
+ """,
+ parameters=[],
+)
+
+AWS_SECURITY_GROUPS_OPEN_INTERNET_FACING = AttackPathsQueryDefinition(
+ id="aws-security-groups-open-internet-facing",
+ name="Open Security Groups on Internet-Facing Resources",
+ short_description="Find internet-facing resources with security groups allowing inbound from 0.0.0.0/0.",
+ description="Find internet-facing resources associated with security groups that allow inbound access from '0.0.0.0/0'.",
+ provider="aws",
+ cypher=f"""
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(ec2:EC2Instance)--(sg:EC2SecurityGroup)--(ipi:IpPermissionInbound)--(ir:IpRange)
+ WHERE ec2.exposed_internet = true
+ AND ir.range = "0.0.0.0/0"
+
+ OPTIONAL MATCH (internet:Internet)-[can_access:CAN_ACCESS]->(ec2)
+
+ WITH collect(path) AS paths, head(collect(internet)) AS internet, collect(can_access) AS can_access
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, internet, can_access, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr, internet, can_access
+ """,
+ parameters=[],
+)
+
+AWS_CLASSIC_ELB_INTERNET_EXPOSED = AttackPathsQueryDefinition(
+ id="aws-classic-elb-internet-exposed",
+ name="Internet-Exposed Classic Load Balancers",
+ short_description="Find Classic Load Balancers exposed to the internet with their listeners.",
+ description="Find Classic Load Balancers exposed to the internet along with their listeners.",
+ provider="aws",
+ cypher=f"""
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(elb:LoadBalancer)--(listener:ELBListener)
+ WHERE elb.exposed_internet = true
+
+ OPTIONAL MATCH (internet:Internet)-[can_access:CAN_ACCESS]->(elb)
+
+ WITH collect(path) AS paths, head(collect(internet)) AS internet, collect(can_access) AS can_access
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, internet, can_access, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr, internet, can_access
+ """,
+ parameters=[],
+)
+
+AWS_ELBV2_INTERNET_EXPOSED = AttackPathsQueryDefinition(
+ id="aws-elbv2-internet-exposed",
+ name="Internet-Exposed ALB/NLB Load Balancers",
+ short_description="Find ELBv2 (ALB/NLB) load balancers exposed to the internet with their listeners.",
+ description="Find ELBv2 load balancers exposed to the internet along with their listeners.",
+ provider="aws",
+ cypher=f"""
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(elbv2:LoadBalancerV2)--(listener:ELBV2Listener)
+ WHERE elbv2.exposed_internet = true
+
+ OPTIONAL MATCH (internet:Internet)-[can_access:CAN_ACCESS]->(elbv2)
+
+ WITH collect(path) AS paths, head(collect(internet)) AS internet, collect(can_access) AS can_access
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, internet, can_access, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr, internet, can_access
+ """,
+ parameters=[],
+)
+
+AWS_PUBLIC_IP_RESOURCE_LOOKUP = AttackPathsQueryDefinition(
+ id="aws-public-ip-resource-lookup",
+ name="Resource Lookup by Public IP",
+ short_description="Find the AWS resource associated with a given public IP address.",
+ description="Given a public IP address, find the related AWS resource and its adjacent node within the selected account.",
+ provider="aws",
+ cypher=f"""
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})-[r]-(x)-[q]-(y)
+ WHERE (x:EC2PrivateIp AND x.public_ip = $ip)
+ OR (x:EC2Instance AND x.publicipaddress = $ip)
+ OR (x:NetworkInterface AND x.public_ip = $ip)
+ OR (x:ElasticIPAddress AND x.public_ip = $ip)
+
+ OPTIONAL MATCH (internet:Internet)-[can_access:CAN_ACCESS]->(x)
+
+ WITH collect(path) AS paths, head(collect(internet)) AS internet, collect(can_access) AS can_access
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, internet, can_access, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr, internet, can_access
+ """,
+ parameters=[
+ AttackPathsQueryParameterDefinition(
+ name="ip",
+ label="IP address",
+ description="Public IP address, e.g. 192.0.2.0.",
+ placeholder="192.0.2.0",
+ ),
+ ],
+)
+
+# Privilege Escalation Queries (based on pathfinding.cloud research)
+# https://github.com/DataDog/pathfinding.cloud
+# -------------------------------------------------------------------
+
+# APPRUNNER-001
+AWS_APPRUNNER_PRIVESC_PASSROLE_CREATE_SERVICE = AttackPathsQueryDefinition(
+ id="aws-apprunner-privesc-passrole-create-service",
+ name="App Runner Service Creation with Privileged Role (APPRUNNER-001)",
+ short_description="Create an App Runner service with a privileged IAM role to gain its permissions.",
+ description="Detect principals who can pass IAM roles and create App Runner services. This allows creating a service with a privileged role attached, gaining that role's permissions via StartCommand execution, a container web shell, or a malicious apprunner.yaml configuration.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - APPRUNNER-001 - iam:PassRole + apprunner:CreateService",
+ link="https://pathfinding.cloud/paths/apprunner-001",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find apprunner:CreateService permission
+ MATCH (principal)--(apprunner_policy:AWSPolicy)--(stmt_apprunner:AWSPolicyStatement)
+ WHERE stmt_apprunner.effect = 'Allow'
+ AND any(action IN stmt_apprunner.action WHERE
+ toLower(action) = 'apprunner:createservice'
+ OR toLower(action) = 'apprunner:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust App Runner tasks service (can be passed to App Runner)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'tasks.apprunner.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# APPRUNNER-002
+AWS_APPRUNNER_PRIVESC_UPDATE_SERVICE = AttackPathsQueryDefinition(
+ id="aws-apprunner-privesc-update-service",
+ name="App Runner Service Update for Role Access (APPRUNNER-002)",
+ short_description="Update an existing App Runner service to leverage its already-attached privileged role.",
+ description="Detect principals who can update existing App Runner services. This allows modifying a service's configuration to execute arbitrary code with the service's already-attached IAM role, without requiring iam:PassRole. Exploitation methods include injecting a malicious StartCommand, updating to a container image with a web shell, or pointing to a repository with a malicious apprunner.yaml file.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - APPRUNNER-002 - apprunner:UpdateService",
+ link="https://pathfinding.cloud/paths/apprunner-002",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with apprunner:UpdateService permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(update_policy:AWSPolicy)--(stmt_update:AWSPolicyStatement)
+ WHERE stmt_update.effect = 'Allow'
+ AND any(action IN stmt_update.action WHERE
+ toLower(action) = 'apprunner:updateservice'
+ OR toLower(action) = 'apprunner:*'
+ OR action = '*'
+ )
+
+ // Find existing App Runner services with roles attached (potential targets)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'tasks.apprunner.amazonaws.com'}})
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# BEDROCK-001
+AWS_BEDROCK_PRIVESC_PASSROLE_CODE_INTERPRETER = AttackPathsQueryDefinition(
+ id="aws-bedrock-privesc-passrole-code-interpreter",
+ name="Bedrock Code Interpreter with Privileged Role (BEDROCK-001)",
+ short_description="Create a Bedrock AgentCore Code Interpreter with a privileged role attached.",
+ description="Detect principals who can pass IAM roles and create Bedrock AgentCore Code Interpreters. This allows creating a code interpreter with a privileged role attached, gaining that role's permissions.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - BEDROCK-001 - iam:PassRole + bedrock-agentcore:CreateCodeInterpreter + bedrock-agentcore:StartCodeInterpreterSession + bedrock-agentcore:InvokeCodeInterpreter",
+ link="https://pathfinding.cloud/paths/bedrock-001",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find bedrock-agentcore:CreateCodeInterpreter permission
+ MATCH (principal)--(bedrock_policy:AWSPolicy)--(stmt_bedrock:AWSPolicyStatement)
+ WHERE stmt_bedrock.effect = 'Allow'
+ AND any(action IN stmt_bedrock.action WHERE
+ toLower(action) = 'bedrock-agentcore:createcodeinterpreter'
+ OR toLower(action) = 'bedrock-agentcore:*'
+ OR action = '*'
+ )
+
+ // Find bedrock-agentcore:StartCodeInterpreterSession permission
+ MATCH (principal)--(session_policy:AWSPolicy)--(stmt_session:AWSPolicyStatement)
+ WHERE stmt_session.effect = 'Allow'
+ AND any(action IN stmt_session.action WHERE
+ toLower(action) = 'bedrock-agentcore:startcodeinterpretersession'
+ OR toLower(action) = 'bedrock-agentcore:*'
+ OR action = '*'
+ )
+
+ // Find bedrock-agentcore:InvokeCodeInterpreter permission
+ MATCH (principal)--(invoke_policy:AWSPolicy)--(stmt_invoke:AWSPolicyStatement)
+ WHERE stmt_invoke.effect = 'Allow'
+ AND any(action IN stmt_invoke.action WHERE
+ toLower(action) = 'bedrock-agentcore:invokecodeinterpreter'
+ OR toLower(action) = 'bedrock-agentcore:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust the Bedrock AgentCore service (can be passed to a code interpreter)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'bedrock-agentcore.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# BEDROCK-002
+AWS_BEDROCK_PRIVESC_INVOKE_CODE_INTERPRETER = AttackPathsQueryDefinition(
+ id="aws-bedrock-privesc-invoke-code-interpreter",
+ name="Bedrock Code Interpreter Session Hijacking (BEDROCK-002)",
+ short_description="Start a session on an existing Bedrock code interpreter to exfiltrate its privileged role credentials.",
+ description="Detect principals who can start sessions and invoke code on existing Bedrock AgentCore code interpreters. This allows executing arbitrary Python code within an interpreter that has a privileged role attached, gaining that role's credentials via the MicroVM Metadata Service without requiring iam:PassRole.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - BEDROCK-002 - bedrock-agentcore:StartCodeInterpreterSession + bedrock-agentcore:InvokeCodeInterpreter",
+ link="https://pathfinding.cloud/paths/bedrock-002",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with bedrock-agentcore:StartCodeInterpreterSession permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(session_policy:AWSPolicy)--(stmt_session:AWSPolicyStatement)
+ WHERE stmt_session.effect = 'Allow'
+ AND any(action IN stmt_session.action WHERE
+ toLower(action) = 'bedrock-agentcore:startcodeinterpretersession'
+ OR toLower(action) = 'bedrock-agentcore:*'
+ OR action = '*'
+ )
+
+ // Find bedrock-agentcore:InvokeCodeInterpreter permission
+ MATCH (principal)--(invoke_policy:AWSPolicy)--(stmt_invoke:AWSPolicyStatement)
+ WHERE stmt_invoke.effect = 'Allow'
+ AND any(action IN stmt_invoke.action WHERE
+ toLower(action) = 'bedrock-agentcore:invokecodeinterpreter'
+ OR toLower(action) = 'bedrock-agentcore:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust the Bedrock AgentCore service (already attached to existing code interpreters)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'bedrock-agentcore.amazonaws.com'}})
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# CLOUDFORMATION-001
+AWS_CLOUDFORMATION_PRIVESC_PASSROLE_CREATE_STACK = AttackPathsQueryDefinition(
+ id="aws-cloudformation-privesc-passrole-create-stack",
+ name="CloudFormation Stack Creation with Privileged Role (CLOUDFORMATION-001)",
+ short_description="Create a CloudFormation stack with a privileged role to provision arbitrary AWS resources.",
+ description="Detect principals who can pass IAM roles and create CloudFormation stacks. This allows launching a stack with a malicious template that executes with the passed role's permissions, enabling creation of resources like IAM users, Lambda functions, or EC2 instances controlled by the attacker.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - CLOUDFORMATION-001 - iam:PassRole + cloudformation:CreateStack",
+ link="https://pathfinding.cloud/paths/cloudformation-001",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find cloudformation:CreateStack permission
+ MATCH (principal)--(cfn_policy:AWSPolicy)--(stmt_cfn:AWSPolicyStatement)
+ WHERE stmt_cfn.effect = 'Allow'
+ AND any(action IN stmt_cfn.action WHERE
+ toLower(action) = 'cloudformation:createstack'
+ OR toLower(action) = 'cloudformation:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust CloudFormation service (can be passed to CloudFormation)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'cloudformation.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# CLOUDFORMATION-002
+AWS_CLOUDFORMATION_PRIVESC_UPDATE_STACK = AttackPathsQueryDefinition(
+ id="aws-cloudformation-privesc-update-stack",
+ name="CloudFormation Stack Update for Role Access (CLOUDFORMATION-002)",
+ short_description="Update an existing CloudFormation stack to leverage its already-attached privileged service role.",
+ description="Detect principals who can update existing CloudFormation stacks. This allows modifying a stack's template to add new resources (such as IAM roles with admin access) that are created with the stack's already-attached service role permissions, without requiring iam:PassRole.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - CLOUDFORMATION-002 - cloudformation:UpdateStack",
+ link="https://pathfinding.cloud/paths/cloudformation-002",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with cloudformation:UpdateStack permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(update_policy:AWSPolicy)--(stmt_update:AWSPolicyStatement)
+ WHERE stmt_update.effect = 'Allow'
+ AND any(action IN stmt_update.action WHERE
+ toLower(action) = 'cloudformation:updatestack'
+ OR toLower(action) = 'cloudformation:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust CloudFormation service (already attached to existing stacks)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'cloudformation.amazonaws.com'}})
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# CLOUDFORMATION-003
+AWS_CLOUDFORMATION_PRIVESC_PASSROLE_CREATE_STACKSET = AttackPathsQueryDefinition(
+ id="aws-cloudformation-privesc-passrole-create-stackset",
+ name="CloudFormation StackSet Creation with Privileged Role (CLOUDFORMATION-003)",
+ short_description="Create a CloudFormation StackSet with a privileged execution role to provision arbitrary resources across accounts.",
+ description="Detect principals who can pass IAM roles, create CloudFormation StackSets, and deploy stack instances. This allows creating a StackSet with a malicious template and a privileged execution role, then deploying instances that create resources (such as IAM roles with admin access) using that role's permissions.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - CLOUDFORMATION-003 - iam:PassRole + cloudformation:CreateStackSet + cloudformation:CreateStackInstances",
+ link="https://pathfinding.cloud/paths/cloudformation-003",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find cloudformation:CreateStackSet permission
+ MATCH (principal)--(cfn_policy:AWSPolicy)--(stmt_cfn:AWSPolicyStatement)
+ WHERE stmt_cfn.effect = 'Allow'
+ AND any(action IN stmt_cfn.action WHERE
+ toLower(action) = 'cloudformation:createstackset'
+ OR toLower(action) = 'cloudformation:*'
+ OR action = '*'
+ )
+
+ // Find cloudformation:CreateStackInstances permission
+ MATCH (principal)--(cfn_instances_policy:AWSPolicy)--(stmt_cfn_instances:AWSPolicyStatement)
+ WHERE stmt_cfn_instances.effect = 'Allow'
+ AND any(action IN stmt_cfn_instances.action WHERE
+ toLower(action) = 'cloudformation:createstackinstances'
+ OR toLower(action) = 'cloudformation:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust CloudFormation service (can be passed as execution role)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'cloudformation.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# CLOUDFORMATION-004
+AWS_CLOUDFORMATION_PRIVESC_PASSROLE_UPDATE_STACKSET = AttackPathsQueryDefinition(
+ id="aws-cloudformation-privesc-passrole-update-stackset",
+ name="CloudFormation StackSet Update with Privileged Role (CLOUDFORMATION-004)",
+ short_description="Update an existing CloudFormation StackSet to inject malicious resources using a privileged execution role.",
+ description="Detect principals who can pass IAM roles and update CloudFormation StackSets. This allows modifying an existing StackSet's template to add resources (such as IAM roles with admin access) that are provisioned by the StackSet's privileged execution role across target accounts.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - CLOUDFORMATION-004 - iam:PassRole + cloudformation:UpdateStackSet",
+ link="https://pathfinding.cloud/paths/cloudformation-004",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find cloudformation:UpdateStackSet permission
+ MATCH (principal)--(cfn_policy:AWSPolicy)--(stmt_cfn:AWSPolicyStatement)
+ WHERE stmt_cfn.effect = 'Allow'
+ AND any(action IN stmt_cfn.action WHERE
+ toLower(action) = 'cloudformation:updatestackset'
+ OR toLower(action) = 'cloudformation:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust CloudFormation service (can be passed as execution role)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'cloudformation.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# CLOUDFORMATION-005
+AWS_CLOUDFORMATION_PRIVESC_CHANGESET = AttackPathsQueryDefinition(
+ id="aws-cloudformation-privesc-changeset",
+ name="CloudFormation Change Set Privilege Escalation (CLOUDFORMATION-005)",
+ short_description="Create and execute a change set on an existing stack to leverage its privileged service role.",
+ description="Detect principals who can create and execute CloudFormation change sets. This allows modifying an existing stack's template through a staged change set, inheriting the stack's already-attached service role permissions to provision arbitrary resources without requiring iam:PassRole.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - CLOUDFORMATION-005 - cloudformation:CreateChangeSet + cloudformation:ExecuteChangeSet",
+ link="https://pathfinding.cloud/paths/cloudformation-005",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with cloudformation:CreateChangeSet permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(create_policy:AWSPolicy)--(stmt_create:AWSPolicyStatement)
+ WHERE stmt_create.effect = 'Allow'
+ AND any(action IN stmt_create.action WHERE
+ toLower(action) = 'cloudformation:createchangeset'
+ OR toLower(action) = 'cloudformation:*'
+ OR action = '*'
+ )
+
+ // Find cloudformation:ExecuteChangeSet permission
+ MATCH (principal)--(exec_policy:AWSPolicy)--(stmt_exec:AWSPolicyStatement)
+ WHERE stmt_exec.effect = 'Allow'
+ AND any(action IN stmt_exec.action WHERE
+ toLower(action) = 'cloudformation:executechangeset'
+ OR toLower(action) = 'cloudformation:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust CloudFormation service (already attached to existing stacks)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'cloudformation.amazonaws.com'}})
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# CODEBUILD-001
+AWS_CODEBUILD_PRIVESC_PASSROLE_CREATE_PROJECT = AttackPathsQueryDefinition(
+ id="aws-codebuild-privesc-passrole-create-project",
+ name="CodeBuild Project Creation with Privileged Role (CODEBUILD-001)",
+ short_description="Create a CodeBuild project with a privileged role to execute arbitrary code via a malicious buildspec.",
+ description="Detect principals who can pass IAM roles, create CodeBuild projects, and start builds. This allows creating a project with a privileged role attached and executing arbitrary code through a malicious buildspec, gaining that role's permissions.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - CODEBUILD-001 - iam:PassRole + codebuild:CreateProject + codebuild:StartBuild",
+ link="https://pathfinding.cloud/paths/codebuild-001",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find codebuild:CreateProject permission
+ MATCH (principal)--(create_policy:AWSPolicy)--(stmt_create:AWSPolicyStatement)
+ WHERE stmt_create.effect = 'Allow'
+ AND any(action IN stmt_create.action WHERE
+ toLower(action) = 'codebuild:createproject'
+ OR toLower(action) = 'codebuild:*'
+ OR action = '*'
+ )
+
+ // Find codebuild:StartBuild permission
+ MATCH (principal)--(build_policy:AWSPolicy)--(stmt_build:AWSPolicyStatement)
+ WHERE stmt_build.effect = 'Allow'
+ AND any(action IN stmt_build.action WHERE
+ toLower(action) = 'codebuild:startbuild'
+ OR toLower(action) = 'codebuild:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust CodeBuild service (can be passed to CodeBuild)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'codebuild.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# CODEBUILD-002
+AWS_CODEBUILD_PRIVESC_START_BUILD = AttackPathsQueryDefinition(
+ id="aws-codebuild-privesc-start-build",
+ name="CodeBuild Buildspec Override for Role Access (CODEBUILD-002)",
+ short_description="Start a build on an existing CodeBuild project with a buildspec override to execute code with its privileged role.",
+ description="Detect principals who can start builds on existing CodeBuild projects. This allows overriding the buildspec with malicious commands that execute with the project's already-attached service role permissions, without requiring iam:PassRole or codebuild:CreateProject.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - CODEBUILD-002 - codebuild:StartBuild",
+ link="https://pathfinding.cloud/paths/codebuild-002",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with codebuild:StartBuild permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(build_policy:AWSPolicy)--(stmt_build:AWSPolicyStatement)
+ WHERE stmt_build.effect = 'Allow'
+ AND any(action IN stmt_build.action WHERE
+ toLower(action) = 'codebuild:startbuild'
+ OR toLower(action) = 'codebuild:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust CodeBuild service (already attached to existing projects)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'codebuild.amazonaws.com'}})
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# CODEBUILD-003
+AWS_CODEBUILD_PRIVESC_START_BUILD_BATCH = AttackPathsQueryDefinition(
+ id="aws-codebuild-privesc-start-build-batch",
+ name="CodeBuild Batch Buildspec Override for Role Access (CODEBUILD-003)",
+ short_description="Start a batch build on an existing CodeBuild project with a buildspec override to execute code with its privileged role.",
+ description="Detect principals who can start batch builds on existing CodeBuild projects. This allows overriding the buildspec with malicious commands that execute with the project's already-attached service role permissions, without requiring iam:PassRole or codebuild:CreateProject.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - CODEBUILD-003 - codebuild:StartBuildBatch",
+ link="https://pathfinding.cloud/paths/codebuild-003",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with codebuild:StartBuildBatch permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(build_policy:AWSPolicy)--(stmt_build:AWSPolicyStatement)
+ WHERE stmt_build.effect = 'Allow'
+ AND any(action IN stmt_build.action WHERE
+ toLower(action) = 'codebuild:startbuildbatch'
+ OR toLower(action) = 'codebuild:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust CodeBuild service (already attached to existing projects)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'codebuild.amazonaws.com'}})
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# CODEBUILD-004
+AWS_CODEBUILD_PRIVESC_PASSROLE_CREATE_PROJECT_BATCH = AttackPathsQueryDefinition(
+ id="aws-codebuild-privesc-passrole-create-project-batch",
+ name="CodeBuild Batch Project Creation with Privileged Role (CODEBUILD-004)",
+ short_description="Create a CodeBuild project configured for batch builds with a privileged role to execute arbitrary code via a malicious buildspec.",
+ description="Detect principals who can pass IAM roles, create CodeBuild projects, and start batch builds. This allows creating a project with a privileged role attached and executing arbitrary code through a malicious batch buildspec, gaining that role's permissions.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - CODEBUILD-004 - iam:PassRole + codebuild:CreateProject + codebuild:StartBuildBatch",
+ link="https://pathfinding.cloud/paths/codebuild-004",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find codebuild:CreateProject permission
+ MATCH (principal)--(create_policy:AWSPolicy)--(stmt_create:AWSPolicyStatement)
+ WHERE stmt_create.effect = 'Allow'
+ AND any(action IN stmt_create.action WHERE
+ toLower(action) = 'codebuild:createproject'
+ OR toLower(action) = 'codebuild:*'
+ OR action = '*'
+ )
+
+ // Find codebuild:StartBuildBatch permission
+ MATCH (principal)--(batch_policy:AWSPolicy)--(stmt_batch:AWSPolicyStatement)
+ WHERE stmt_batch.effect = 'Allow'
+ AND any(action IN stmt_batch.action WHERE
+ toLower(action) = 'codebuild:startbuildbatch'
+ OR toLower(action) = 'codebuild:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust CodeBuild service (can be passed to CodeBuild)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'codebuild.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# DATAPIPELINE-001
+AWS_DATAPIPELINE_PRIVESC_PASSROLE_CREATE_PIPELINE = AttackPathsQueryDefinition(
+ id="aws-datapipeline-privesc-passrole-create-pipeline",
+ name="Data Pipeline Creation with Privileged Role (DATAPIPELINE-001)",
+ short_description="Create a Data Pipeline with a privileged role to execute arbitrary commands on provisioned infrastructure.",
+ description="Detect principals who can pass IAM roles, create Data Pipelines, define pipeline objects, and activate them. This allows creating a pipeline with a privileged role attached and executing arbitrary commands on the provisioned EC2 instances or EMR clusters, gaining that role's permissions.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - DATAPIPELINE-001 - iam:PassRole + datapipeline:CreatePipeline + datapipeline:PutPipelineDefinition + datapipeline:ActivatePipeline",
+ link="https://pathfinding.cloud/paths/datapipeline-001",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find datapipeline:CreatePipeline permission
+ MATCH (principal)--(create_policy:AWSPolicy)--(stmt_create:AWSPolicyStatement)
+ WHERE stmt_create.effect = 'Allow'
+ AND any(action IN stmt_create.action WHERE
+ toLower(action) = 'datapipeline:createpipeline'
+ OR toLower(action) = 'datapipeline:*'
+ OR action = '*'
+ )
+
+ // Find datapipeline:PutPipelineDefinition permission
+ MATCH (principal)--(put_policy:AWSPolicy)--(stmt_put:AWSPolicyStatement)
+ WHERE stmt_put.effect = 'Allow'
+ AND any(action IN stmt_put.action WHERE
+ toLower(action) = 'datapipeline:putpipelinedefinition'
+ OR toLower(action) = 'datapipeline:*'
+ OR action = '*'
+ )
+
+ // Find datapipeline:ActivatePipeline permission
+ MATCH (principal)--(activate_policy:AWSPolicy)--(stmt_activate:AWSPolicyStatement)
+ WHERE stmt_activate.effect = 'Allow'
+ AND any(action IN stmt_activate.action WHERE
+ toLower(action) = 'datapipeline:activatepipeline'
+ OR toLower(action) = 'datapipeline:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust Data Pipeline or EMR service (can be passed to DataPipeline)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(trusted_principal:AWSPrincipal)
+ WHERE trusted_principal.arn IN ['datapipeline.amazonaws.com', 'elasticmapreduce.amazonaws.com']
+ AND any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# EC2-001
+AWS_EC2_PRIVESC_PASSROLE_IAM = AttackPathsQueryDefinition(
+ id="aws-ec2-privesc-passrole-iam",
+ name="EC2 Instance Launch with Privileged Role (EC2-001)",
+ short_description="Launch EC2 instances with privileged IAM roles to gain their permissions via IMDS.",
+ description="Detect principals who can launch EC2 instances with privileged IAM roles attached. This allows gaining the permissions of the passed role by accessing the EC2 instance metadata service.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - EC2-001 - iam:PassRole + ec2:RunInstances",
+ link="https://pathfinding.cloud/paths/ec2-001",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find ec2:RunInstances permission
+ MATCH (principal)--(ec2_policy:AWSPolicy)--(stmt_ec2:AWSPolicyStatement)
+ WHERE stmt_ec2.effect = 'Allow'
+ AND any(action IN stmt_ec2.action WHERE
+ toLower(action) = 'ec2:runinstances'
+ OR toLower(action) = 'ec2:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust EC2 service (can be passed to EC2)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'ec2.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# EC2-002
+AWS_EC2_PRIVESC_MODIFY_INSTANCE_ATTRIBUTE = AttackPathsQueryDefinition(
+ id="aws-ec2-privesc-modify-instance-attribute",
+ name="EC2 Role Hijacking via UserData Injection (EC2-002)",
+ short_description="Inject malicious scripts into EC2 instance userData to gain the attached role's permissions.",
+ description="Detect principals who can modify EC2 instance userData, stop, and start instances. This allows injecting malicious scripts that execute on instance restart, gaining the permissions of the instance's attached IAM role.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - EC2-002 - ec2:ModifyInstanceAttribute + ec2:StopInstances + ec2:StartInstances",
+ link="https://pathfinding.cloud/paths/ec2-002",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with ec2:ModifyInstanceAttribute permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(modify_policy:AWSPolicy)--(stmt_modify:AWSPolicyStatement)
+ WHERE stmt_modify.effect = 'Allow'
+ AND any(action IN stmt_modify.action WHERE
+ toLower(action) = 'ec2:modifyinstanceattribute'
+ OR toLower(action) = 'ec2:*'
+ OR action = '*'
+ )
+
+ // Find ec2:StopInstances permission (can be same or different policy)
+ MATCH (principal)--(stop_policy:AWSPolicy)--(stmt_stop:AWSPolicyStatement)
+ WHERE stmt_stop.effect = 'Allow'
+ AND any(action IN stmt_stop.action WHERE
+ toLower(action) = 'ec2:stopinstances'
+ OR toLower(action) = 'ec2:*'
+ OR action = '*'
+ )
+
+ // Find ec2:StartInstances permission (can be same or different policy)
+ MATCH (principal)--(start_policy:AWSPolicy)--(stmt_start:AWSPolicyStatement)
+ WHERE stmt_start.effect = 'Allow'
+ AND any(action IN stmt_start.action WHERE
+ toLower(action) = 'ec2:startinstances'
+ OR toLower(action) = 'ec2:*'
+ OR action = '*'
+ )
+
+ // Find EC2 instances with instance profiles (potential targets)
+ MATCH path_target = (aws)--(ec2:EC2Instance)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# EC2-003
+AWS_EC2_PRIVESC_PASSROLE_SPOT_INSTANCES = AttackPathsQueryDefinition(
+ id="aws-ec2-privesc-passrole-spot-instances",
+ name="Spot Instance Launch with Privileged Role (EC2-003)",
+ short_description="Launch EC2 Spot Instances with privileged IAM roles to gain their permissions via IMDS.",
+ description="Detect principals who can pass IAM roles and request EC2 Spot Instances. This allows launching a spot instance with a privileged role attached, gaining that role's permissions via the instance metadata service.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - EC2-003 - iam:PassRole + ec2:RequestSpotInstances",
+ link="https://pathfinding.cloud/paths/ec2-003",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find ec2:RequestSpotInstances permission
+ MATCH (principal)--(spot_policy:AWSPolicy)--(stmt_spot:AWSPolicyStatement)
+ WHERE stmt_spot.effect = 'Allow'
+ AND any(action IN stmt_spot.action WHERE
+ toLower(action) = 'ec2:requestspotinstances'
+ OR toLower(action) = 'ec2:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust EC2 service (can be passed to EC2 spot instances)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'ec2.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# EC2-004
+AWS_EC2_PRIVESC_LAUNCH_TEMPLATE = AttackPathsQueryDefinition(
+ id="aws-ec2-privesc-launch-template",
+ name="Launch Template Poisoning for Role Access (EC2-004)",
+ short_description="Inject malicious userData into launch templates that reference privileged roles, no PassRole needed.",
+ description="Detect principals who can create new launch template versions and modify launch templates. This allows injecting malicious user data into existing templates that already reference privileged IAM roles, without requiring iam:PassRole permissions.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - EC2-004 - ec2:CreateLaunchTemplateVersion + ec2:ModifyLaunchTemplate",
+ link="https://pathfinding.cloud/paths/ec2-004",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with ec2:CreateLaunchTemplateVersion permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(create_policy:AWSPolicy)--(stmt_create:AWSPolicyStatement)
+ WHERE stmt_create.effect = 'Allow'
+ AND any(action IN stmt_create.action WHERE
+ toLower(action) = 'ec2:createlaunchtemplateversion'
+ OR toLower(action) = 'ec2:*'
+ OR action = '*'
+ )
+
+ // Find ec2:ModifyLaunchTemplate permission
+ MATCH (principal)--(modify_policy:AWSPolicy)--(stmt_modify:AWSPolicyStatement)
+ WHERE stmt_modify.effect = 'Allow'
+ AND any(action IN stmt_modify.action WHERE
+ toLower(action) = 'ec2:modifylaunchtemplate'
+ OR toLower(action) = 'ec2:*'
+ OR action = '*'
+ )
+
+ // Find launch templates in the account (potential targets)
+ MATCH path_target = (aws)--(template:LaunchTemplate)
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# EC2INSTANCECONNECT-003
+AWS_EC2INSTANCECONNECT_PRIVESC_SEND_SSH_PUBLIC_KEY = AttackPathsQueryDefinition(
+ id="aws-ec2instanceconnect-privesc-send-ssh-public-key",
+ name="EC2 Instance Connect SSH Access for Role Credentials (EC2INSTANCECONNECT-003)",
+ short_description="Push a temporary SSH key to an EC2 instance via Instance Connect to access its attached role credentials through IMDS.",
+ description="Detect principals who can send SSH public keys via EC2 Instance Connect. This allows establishing an SSH session on a running EC2 instance and retrieving the attached IAM role's temporary credentials from the Instance Metadata Service (IMDS), gaining that role's permissions.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - EC2INSTANCECONNECT-003 - ec2-instance-connect:SendSSHPublicKey",
+ link="https://pathfinding.cloud/paths/ec2instanceconnect-003",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with ec2-instance-connect:SendSSHPublicKey permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(connect_policy:AWSPolicy)--(stmt_connect:AWSPolicyStatement)
+ WHERE stmt_connect.effect = 'Allow'
+ AND any(action IN stmt_connect.action WHERE
+ toLower(action) = 'ec2-instance-connect:sendsshpublickey'
+ OR toLower(action) = 'ec2-instance-connect:*'
+ OR action = '*'
+ )
+
+ // Find EC2 instances with attached roles (targets for credential theft via IMDS)
+ MATCH path_target = (aws)--(ec2:EC2Instance)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# ECS-001
+AWS_ECS_PRIVESC_PASSROLE_CREATE_SERVICE = AttackPathsQueryDefinition(
+ id="aws-ecs-privesc-passrole-create-service",
+ name="ECS Service Creation with Privileged Role (ECS-001 - New Cluster)",
+ short_description="Create an ECS cluster and service with a privileged Fargate task role to execute arbitrary code.",
+ description="Detect principals who can pass IAM roles, create ECS clusters, register task definitions, and create services. This allows creating a Fargate task with a privileged role attached, gaining that role's permissions to execute arbitrary code via the container.",
+ provider="aws",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - ECS-001 - iam:PassRole + ecs:CreateCluster + ecs:RegisterTaskDefinition + ecs:CreateService",
+ link="https://pathfinding.cloud/paths/ecs-001",
+ ),
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find ecs:CreateCluster permission
+ MATCH (principal)--(cluster_policy:AWSPolicy)--(stmt_cluster:AWSPolicyStatement)
+ WHERE stmt_cluster.effect = 'Allow'
+ AND any(action IN stmt_cluster.action WHERE
+ toLower(action) = 'ecs:createcluster'
+ OR toLower(action) = 'ecs:*'
+ OR action = '*'
+ )
+
+ // Find ecs:RegisterTaskDefinition permission
+ MATCH (principal)--(taskdef_policy:AWSPolicy)--(stmt_taskdef:AWSPolicyStatement)
+ WHERE stmt_taskdef.effect = 'Allow'
+ AND any(action IN stmt_taskdef.action WHERE
+ toLower(action) = 'ecs:registertaskdefinition'
+ OR toLower(action) = 'ecs:*'
+ OR action = '*'
+ )
+
+ // Find ecs:CreateService permission
+ MATCH (principal)--(service_policy:AWSPolicy)--(stmt_service:AWSPolicyStatement)
+ WHERE stmt_service.effect = 'Allow'
+ AND any(action IN stmt_service.action WHERE
+ toLower(action) = 'ecs:createservice'
+ OR toLower(action) = 'ecs:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust ECS tasks service (can be passed to ECS tasks)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'ecs-tasks.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# ECS-002
+AWS_ECS_PRIVESC_PASSROLE_RUN_TASK = AttackPathsQueryDefinition(
+ id="aws-ecs-privesc-passrole-run-task",
+ name="ECS Task Execution with Privileged Role (ECS-002 - New Cluster)",
+ short_description="Create an ECS cluster and run a one-off Fargate task with a privileged role to execute arbitrary code.",
+ description="Detect principals who can pass IAM roles, create ECS clusters, register task definitions, and run tasks. This allows creating a Fargate task with a privileged role attached, gaining that role's permissions to execute arbitrary code via the container. Unlike ecs:CreateService, ecs:RunTask executes the task once without creating a persistent service.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - ECS-002 - iam:PassRole + ecs:CreateCluster + ecs:RegisterTaskDefinition + ecs:RunTask",
+ link="https://pathfinding.cloud/paths/ecs-002",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find ecs:CreateCluster permission
+ MATCH (principal)--(cluster_policy:AWSPolicy)--(stmt_cluster:AWSPolicyStatement)
+ WHERE stmt_cluster.effect = 'Allow'
+ AND any(action IN stmt_cluster.action WHERE
+ toLower(action) = 'ecs:createcluster'
+ OR toLower(action) = 'ecs:*'
+ OR action = '*'
+ )
+
+ // Find ecs:RegisterTaskDefinition permission
+ MATCH (principal)--(taskdef_policy:AWSPolicy)--(stmt_taskdef:AWSPolicyStatement)
+ WHERE stmt_taskdef.effect = 'Allow'
+ AND any(action IN stmt_taskdef.action WHERE
+ toLower(action) = 'ecs:registertaskdefinition'
+ OR toLower(action) = 'ecs:*'
+ OR action = '*'
+ )
+
+ // Find ecs:RunTask permission
+ MATCH (principal)--(runtask_policy:AWSPolicy)--(stmt_runtask:AWSPolicyStatement)
+ WHERE stmt_runtask.effect = 'Allow'
+ AND any(action IN stmt_runtask.action WHERE
+ toLower(action) = 'ecs:runtask'
+ OR toLower(action) = 'ecs:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust ECS tasks service (can be passed to ECS tasks)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'ecs-tasks.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# ECS-003
+AWS_ECS_PRIVESC_PASSROLE_CREATE_SERVICE_EXISTING_CLUSTER = AttackPathsQueryDefinition(
+ id="aws-ecs-privesc-passrole-create-service-existing-cluster",
+ name="ECS Service Creation with Privileged Role (ECS-003 - Existing Cluster)",
+ short_description="Deploy a Fargate service with a privileged role on an existing ECS cluster.",
+ description="Detect principals who can pass IAM roles, register ECS task definitions, and create services on existing clusters. Unlike ECS-001, this does not require ecs:CreateCluster since it targets clusters that already exist. The attacker registers a task definition with a privileged role and launches it as a Fargate service, gaining that role's permissions.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - ECS-003 - iam:PassRole + ecs:RegisterTaskDefinition + ecs:CreateService",
+ link="https://pathfinding.cloud/paths/ecs-003",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find ecs:RegisterTaskDefinition permission
+ MATCH (principal)--(taskdef_policy:AWSPolicy)--(stmt_taskdef:AWSPolicyStatement)
+ WHERE stmt_taskdef.effect = 'Allow'
+ AND any(action IN stmt_taskdef.action WHERE
+ toLower(action) = 'ecs:registertaskdefinition'
+ OR toLower(action) = 'ecs:*'
+ OR action = '*'
+ )
+
+ // Find ecs:CreateService permission
+ MATCH (principal)--(service_policy:AWSPolicy)--(stmt_service:AWSPolicyStatement)
+ WHERE stmt_service.effect = 'Allow'
+ AND any(action IN stmt_service.action WHERE
+ toLower(action) = 'ecs:createservice'
+ OR toLower(action) = 'ecs:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust ECS tasks service (can be passed to ECS tasks)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'ecs-tasks.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# ECS-004
+AWS_ECS_PRIVESC_PASSROLE_RUN_TASK_EXISTING_CLUSTER = AttackPathsQueryDefinition(
+ id="aws-ecs-privesc-passrole-run-task-existing-cluster",
+ name="ECS Task Execution with Privileged Role (ECS-004 - Existing Cluster)",
+ short_description="Run a one-off Fargate task with a privileged role on an existing ECS cluster.",
+ description="Detect principals who can pass IAM roles, register ECS task definitions, and run tasks on existing clusters. Unlike ECS-002, this does not require ecs:CreateCluster since it targets clusters that already exist. The attacker registers a task definition with a privileged role and runs it as a one-off Fargate task, gaining that role's permissions.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - ECS-004 - iam:PassRole + ecs:RegisterTaskDefinition + ecs:RunTask",
+ link="https://pathfinding.cloud/paths/ecs-004",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find ecs:RegisterTaskDefinition permission
+ MATCH (principal)--(taskdef_policy:AWSPolicy)--(stmt_taskdef:AWSPolicyStatement)
+ WHERE stmt_taskdef.effect = 'Allow'
+ AND any(action IN stmt_taskdef.action WHERE
+ toLower(action) = 'ecs:registertaskdefinition'
+ OR toLower(action) = 'ecs:*'
+ OR action = '*'
+ )
+
+ // Find ecs:RunTask permission
+ MATCH (principal)--(runtask_policy:AWSPolicy)--(stmt_runtask:AWSPolicyStatement)
+ WHERE stmt_runtask.effect = 'Allow'
+ AND any(action IN stmt_runtask.action WHERE
+ toLower(action) = 'ecs:runtask'
+ OR toLower(action) = 'ecs:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust ECS tasks service (can be passed to ECS tasks)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'ecs-tasks.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# ECS-005
+AWS_ECS_PRIVESC_PASSROLE_START_TASK_EXISTING_CLUSTER = AttackPathsQueryDefinition(
+ id="aws-ecs-privesc-passrole-start-task-existing-cluster",
+ name="ECS Task Start with Privileged Role on EC2 (ECS-005 - Existing Cluster)",
+ short_description="Register a task definition with a privileged role and start it on an EC2 container instance to execute arbitrary code.",
+ description="Detect principals who can pass IAM roles, register ECS task definitions, and start tasks on existing EC2 container instances. Unlike ecs:RunTask which works with both EC2 and Fargate, ecs:StartTask is specific to EC2 launch types and requires specifying an existing container instance ARN. The attacker registers a task definition with a privileged role and starts it on a container instance, gaining that role's permissions.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - ECS-005 - iam:PassRole + ecs:RegisterTaskDefinition + ecs:StartTask",
+ link="https://pathfinding.cloud/paths/ecs-005",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find ecs:RegisterTaskDefinition permission
+ MATCH (principal)--(taskdef_policy:AWSPolicy)--(stmt_taskdef:AWSPolicyStatement)
+ WHERE stmt_taskdef.effect = 'Allow'
+ AND any(action IN stmt_taskdef.action WHERE
+ toLower(action) = 'ecs:registertaskdefinition'
+ OR toLower(action) = 'ecs:*'
+ OR action = '*'
+ )
+
+ // Find ecs:StartTask permission
+ MATCH (principal)--(starttask_policy:AWSPolicy)--(stmt_starttask:AWSPolicyStatement)
+ WHERE stmt_starttask.effect = 'Allow'
+ AND any(action IN stmt_starttask.action WHERE
+ toLower(action) = 'ecs:starttask'
+ OR toLower(action) = 'ecs:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust ECS tasks service (can be passed to ECS tasks)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'ecs-tasks.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# ECS-006
+AWS_ECS_PRIVESC_EXECUTE_COMMAND = AttackPathsQueryDefinition(
+ id="aws-ecs-privesc-execute-command",
+ name="ECS Exec Container Hijacking for Role Credentials (ECS-006)",
+ short_description="Shell into a running ECS container via ECS Exec to steal the attached task role's credentials.",
+ description="Detect principals who can execute commands in running ECS containers and describe tasks. This allows establishing an interactive shell session in a container where ECS Exec is enabled, then retrieving the task role's temporary credentials from the container metadata service, without requiring iam:PassRole.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - ECS-006 - ecs:ExecuteCommand + ecs:DescribeTasks",
+ link="https://pathfinding.cloud/paths/ecs-006",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with ecs:ExecuteCommand permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(exec_policy:AWSPolicy)--(stmt_exec:AWSPolicyStatement)
+ WHERE stmt_exec.effect = 'Allow'
+ AND any(action IN stmt_exec.action WHERE
+ toLower(action) = 'ecs:executecommand'
+ OR toLower(action) = 'ecs:*'
+ OR action = '*'
+ )
+
+ // Find ecs:DescribeTasks permission (required by AWS CLI to get container runtime ID)
+ MATCH (principal)--(describe_policy:AWSPolicy)--(stmt_describe:AWSPolicyStatement)
+ WHERE stmt_describe.effect = 'Allow'
+ AND any(action IN stmt_describe.action WHERE
+ toLower(action) = 'ecs:describetasks'
+ OR toLower(action) = 'ecs:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust ECS tasks service (already attached to running tasks)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'ecs-tasks.amazonaws.com'}})
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# GLUE-001
+AWS_GLUE_PRIVESC_PASSROLE_DEV_ENDPOINT = AttackPathsQueryDefinition(
+ id="aws-glue-privesc-passrole-dev-endpoint",
+ name="Glue Dev Endpoint with Privileged Role (GLUE-001)",
+ short_description="Create a Glue development endpoint with a privileged role attached to gain its permissions.",
+ description="Detect principals who can pass IAM roles and create Glue development endpoints. This allows creating a dev endpoint with a privileged role attached, gaining that role's permissions.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - GLUE-001 - iam:PassRole + glue:CreateDevEndpoint",
+ link="https://pathfinding.cloud/paths/glue-001",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find glue:CreateDevEndpoint permission
+ MATCH (principal)--(glue_policy:AWSPolicy)--(stmt_glue:AWSPolicyStatement)
+ WHERE stmt_glue.effect = 'Allow'
+ AND any(action IN stmt_glue.action WHERE
+ toLower(action) = 'glue:createdevendpoint'
+ OR toLower(action) = 'glue:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust Glue service (can be passed to Glue)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'glue.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# GLUE-002
+AWS_GLUE_PRIVESC_UPDATE_DEV_ENDPOINT = AttackPathsQueryDefinition(
+ id="aws-glue-privesc-update-dev-endpoint",
+ name="Glue Dev Endpoint SSH Hijacking via Update (GLUE-002)",
+ short_description="Update an existing Glue development endpoint to inject an SSH public key and access its attached role credentials.",
+ description="Detect principals who can update Glue development endpoints. This allows adding an attacker-controlled SSH public key to an existing dev endpoint that already has a privileged role attached, then SSHing into it to steal the role's temporary credentials without requiring iam:PassRole.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - GLUE-002 - glue:UpdateDevEndpoint",
+ link="https://pathfinding.cloud/paths/glue-002",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with glue:UpdateDevEndpoint permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'glue:updatedevendpoint'
+ OR toLower(action) = 'glue:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust Glue service (already attached to existing dev endpoints)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'glue.amazonaws.com'}})
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# GLUE-003
+AWS_GLUE_PRIVESC_PASSROLE_CREATE_JOB = AttackPathsQueryDefinition(
+ id="aws-glue-privesc-passrole-create-job",
+ name="Glue Job Creation with Privileged Role (GLUE-003)",
+ short_description="Create a Glue job with a privileged role and start it to execute arbitrary code with that role's permissions.",
+ description="Detect principals who can pass IAM roles, create Glue jobs, and start job runs. This allows creating a Python shell job with a privileged role attached and executing arbitrary code that modifies IAM permissions, a cost-effective alternative to Glue development endpoints.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - GLUE-003 - iam:PassRole + glue:CreateJob + glue:StartJobRun",
+ link="https://pathfinding.cloud/paths/glue-003",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find glue:CreateJob permission
+ MATCH (principal)--(createjob_policy:AWSPolicy)--(stmt_createjob:AWSPolicyStatement)
+ WHERE stmt_createjob.effect = 'Allow'
+ AND any(action IN stmt_createjob.action WHERE
+ toLower(action) = 'glue:createjob'
+ OR toLower(action) = 'glue:*'
+ OR action = '*'
+ )
+
+ // Find glue:StartJobRun permission
+ MATCH (principal)--(startjob_policy:AWSPolicy)--(stmt_startjob:AWSPolicyStatement)
+ WHERE stmt_startjob.effect = 'Allow'
+ AND any(action IN stmt_startjob.action WHERE
+ toLower(action) = 'glue:startjobrun'
+ OR toLower(action) = 'glue:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust Glue service (can be passed to Glue jobs)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'glue.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# GLUE-004
+AWS_GLUE_PRIVESC_PASSROLE_CREATE_JOB_TRIGGER = AttackPathsQueryDefinition(
+ id="aws-glue-privesc-passrole-create-job-trigger",
+ name="Glue Job Creation with Scheduled Trigger and Privileged Role (GLUE-004)",
+ short_description="Create a Glue job with a privileged role and a scheduled trigger to persistently execute arbitrary code.",
+ description="Detect principals who can pass IAM roles, create Glue jobs, and create triggers with automatic activation. Unlike manual execution via StartJobRun, this creates a persistent attack by scheduling the job to run repeatedly, making it harder to detect and remediate.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - GLUE-004 - iam:PassRole + glue:CreateJob + glue:CreateTrigger",
+ link="https://pathfinding.cloud/paths/glue-004",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find glue:CreateJob permission
+ MATCH (principal)--(createjob_policy:AWSPolicy)--(stmt_createjob:AWSPolicyStatement)
+ WHERE stmt_createjob.effect = 'Allow'
+ AND any(action IN stmt_createjob.action WHERE
+ toLower(action) = 'glue:createjob'
+ OR toLower(action) = 'glue:*'
+ OR action = '*'
+ )
+
+ // Find glue:CreateTrigger permission
+ MATCH (principal)--(trigger_policy:AWSPolicy)--(stmt_trigger:AWSPolicyStatement)
+ WHERE stmt_trigger.effect = 'Allow'
+ AND any(action IN stmt_trigger.action WHERE
+ toLower(action) = 'glue:createtrigger'
+ OR toLower(action) = 'glue:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust Glue service (can be passed to Glue jobs)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'glue.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# GLUE-005
+AWS_GLUE_PRIVESC_PASSROLE_UPDATE_JOB = AttackPathsQueryDefinition(
+ id="aws-glue-privesc-passrole-update-job",
+ name="Glue Job Hijacking via Update with Privileged Role (GLUE-005)",
+ short_description="Update an existing Glue job to attach a privileged role and inject malicious code, then start it to gain that role's permissions.",
+ description="Detect principals who can pass IAM roles, update existing Glue jobs, and start job runs. This allows modifying an existing job's role and script to execute arbitrary code with elevated privileges, a stealthier variant of job creation since it reuses existing infrastructure rather than creating new resources.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - GLUE-005 - iam:PassRole + glue:UpdateJob + glue:StartJobRun",
+ link="https://pathfinding.cloud/paths/glue-005",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find glue:UpdateJob permission
+ MATCH (principal)--(updatejob_policy:AWSPolicy)--(stmt_updatejob:AWSPolicyStatement)
+ WHERE stmt_updatejob.effect = 'Allow'
+ AND any(action IN stmt_updatejob.action WHERE
+ toLower(action) = 'glue:updatejob'
+ OR toLower(action) = 'glue:*'
+ OR action = '*'
+ )
+
+ // Find glue:StartJobRun permission
+ MATCH (principal)--(startjob_policy:AWSPolicy)--(stmt_startjob:AWSPolicyStatement)
+ WHERE stmt_startjob.effect = 'Allow'
+ AND any(action IN stmt_startjob.action WHERE
+ toLower(action) = 'glue:startjobrun'
+ OR toLower(action) = 'glue:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust Glue service (can be passed to Glue jobs)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'glue.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# GLUE-006
+AWS_GLUE_PRIVESC_PASSROLE_UPDATE_JOB_TRIGGER = AttackPathsQueryDefinition(
+ id="aws-glue-privesc-passrole-update-job-trigger",
+ name="Glue Job Hijacking with Scheduled Trigger and Privileged Role (GLUE-006)",
+ short_description="Update an existing Glue job to attach a privileged role and inject malicious code, then create a scheduled trigger for persistent automated execution.",
+ description="Detect principals who can pass IAM roles, update existing Glue jobs, and create triggers with automatic activation. This combines the stealth of modifying existing infrastructure with the persistence of scheduled automation, creating a recurring backdoor that re-executes even after remediation attempts.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - GLUE-006 - iam:PassRole + glue:UpdateJob + glue:CreateTrigger",
+ link="https://pathfinding.cloud/paths/glue-006",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find glue:UpdateJob permission
+ MATCH (principal)--(updatejob_policy:AWSPolicy)--(stmt_updatejob:AWSPolicyStatement)
+ WHERE stmt_updatejob.effect = 'Allow'
+ AND any(action IN stmt_updatejob.action WHERE
+ toLower(action) = 'glue:updatejob'
+ OR toLower(action) = 'glue:*'
+ OR action = '*'
+ )
+
+ // Find glue:CreateTrigger permission
+ MATCH (principal)--(trigger_policy:AWSPolicy)--(stmt_trigger:AWSPolicyStatement)
+ WHERE stmt_trigger.effect = 'Allow'
+ AND any(action IN stmt_trigger.action WHERE
+ toLower(action) = 'glue:createtrigger'
+ OR toLower(action) = 'glue:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust Glue service (can be passed to Glue jobs)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'glue.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-001
+AWS_IAM_PRIVESC_CREATE_POLICY_VERSION = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-create-policy-version",
+ name="Policy Version Override for Self-Escalation (IAM-001)",
+ short_description="Create a new version of an attached policy with administrative permissions, instantly escalating the principal's own privileges.",
+ description="Detect principals who can create new policy versions. If a customer-managed policy is already attached to a principal and that principal has iam:CreatePolicyVersion on that policy, they can replace its contents with a fully permissive policy and set it as the default, gaining immediate administrative access.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-001 - iam:CreatePolicyVersion",
+ link="https://pathfinding.cloud/paths/iam-001",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:CreatePolicyVersion permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:createpolicyversion'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find customer-managed policies attached to the same principal that can be overwritten
+ MATCH path_target = (aws)--(target_policy:AWSPolicy)--(principal)
+ WHERE target_policy.arn CONTAINS $provider_uid
+ AND any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_policy.arn CONTAINS resource
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-002
+AWS_IAM_PRIVESC_CREATE_ACCESS_KEY = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-create-access-key",
+ name="Access Key Creation for Lateral Movement (IAM-002)",
+ short_description="Create access keys for other IAM users to gain their permissions and move laterally across the account.",
+ description="Detect principals who can create access keys for other IAM users. This allows generating new credentials for any target user within the resource scope, immediately gaining that user's permissions without needing their password or existing keys.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-002 - iam:CreateAccessKey",
+ link="https://pathfinding.cloud/paths/iam-002",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:CreateAccessKey permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:createaccesskey'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find target users that the principal can create access keys for
+ MATCH path_target = (aws)--(target_user:AWSUser)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_user.arn CONTAINS resource
+ OR resource CONTAINS target_user.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-003
+AWS_IAM_PRIVESC_DELETE_CREATE_ACCESS_KEY = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-delete-create-access-key",
+ name="Access Key Rotation Attack for Lateral Movement (IAM-003)",
+ short_description="Delete and recreate access keys for other IAM users to bypass the two-key limit and gain their permissions.",
+ description="Detect principals who can both delete and create access keys for other IAM users. This variation of IAM-002 handles the scenario where a target user already has the maximum of two access keys by first deleting one, then creating a replacement under the attacker's control.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-003 - iam:CreateAccessKey + iam:DeleteAccessKey",
+ link="https://pathfinding.cloud/paths/iam-003",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:CreateAccessKey permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:createaccesskey'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find iam:DeleteAccessKey permission
+ MATCH (principal)--(delete_policy:AWSPolicy)--(stmt_delete:AWSPolicyStatement)
+ WHERE stmt_delete.effect = 'Allow'
+ AND any(action IN stmt_delete.action WHERE
+ toLower(action) = 'iam:deleteaccesskey'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find target users that the principal can rotate access keys for
+ MATCH path_target = (aws)--(target_user:AWSUser)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_user.arn CONTAINS resource
+ OR resource CONTAINS target_user.name
+ )
+ AND any(resource IN stmt_delete.resource WHERE
+ resource = '*'
+ OR target_user.arn CONTAINS resource
+ OR resource CONTAINS target_user.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-004
+AWS_IAM_PRIVESC_CREATE_LOGIN_PROFILE = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-create-login-profile",
+ name="Console Login Profile Creation for Lateral Movement (IAM-004)",
+ short_description="Create console login profiles for other IAM users to access the AWS Console with their permissions.",
+ description="Detect principals who can create console login profiles for other IAM users. By setting a known password on a target user that lacks a login profile, the attacker gains AWS Console access with that user's permissions without needing their existing credentials.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-004 - iam:CreateLoginProfile",
+ link="https://pathfinding.cloud/paths/iam-004",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:CreateLoginProfile permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:createloginprofile'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find target users that the principal can create login profiles for
+ MATCH path_target = (aws)--(target_user:AWSUser)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_user.arn CONTAINS resource
+ OR resource CONTAINS target_user.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-005
+AWS_IAM_PRIVESC_PUT_ROLE_POLICY = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-put-role-policy",
+ name="Inline Policy Injection for Self-Escalation (IAM-005)",
+ short_description="Attach an inline policy with administrative permissions to your own role, instantly escalating privileges.",
+ description="Detect roles that can use iam:PutRolePolicy on themselves. A role with this permission can attach an inline policy granting any permissions, including full administrative access, without needing to modify or assume any other resource.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-005 - iam:PutRolePolicy",
+ link="https://pathfinding.cloud/paths/iam-005",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find roles with iam:PutRolePolicy permission scoped to themselves
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(role:AWSRole)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:putrolepolicy'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+ AND any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR role.arn CONTAINS resource
+ OR resource CONTAINS role.name
+ )
+
+ WITH collect(path) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-006
+AWS_IAM_PRIVESC_UPDATE_LOGIN_PROFILE = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-update-login-profile",
+ name="Console Password Override for Lateral Movement (IAM-006)",
+ short_description="Change the console password of other IAM users to log in as them and gain their permissions.",
+ description="Detect principals who can update console login profiles for other IAM users. By resetting a target user's password, the attacker gains AWS Console access with that user's permissions. Unlike IAM-004, this targets users who already have a login profile configured.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-006 - iam:UpdateLoginProfile",
+ link="https://pathfinding.cloud/paths/iam-006",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:UpdateLoginProfile permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:updateloginprofile'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find target users that the principal can update login profiles for
+ MATCH path_target = (aws)--(target_user:AWSUser)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_user.arn CONTAINS resource
+ OR resource CONTAINS target_user.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-007
+AWS_IAM_PRIVESC_PUT_USER_POLICY = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-put-user-policy",
+ name="Inline Policy Injection on User for Self-Escalation (IAM-007)",
+ short_description="Attach an inline policy with administrative permissions to your own IAM user, instantly escalating privileges.",
+ description="Detect IAM users that can use iam:PutUserPolicy on themselves. A user with this permission can attach an inline policy granting any permissions, including full administrative access, without needing to modify or assume any other resource. This is the user equivalent of IAM-005 (PutRolePolicy).",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-007 - iam:PutUserPolicy",
+ link="https://pathfinding.cloud/paths/iam-007",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find users with iam:PutUserPolicy permission scoped to themselves
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(user:AWSUser)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:putuserpolicy'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+ AND any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR user.arn CONTAINS resource
+ OR resource CONTAINS user.name
+ )
+
+ WITH collect(path) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-008
+AWS_IAM_PRIVESC_ATTACH_USER_POLICY = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-attach-user-policy",
+ name="Managed Policy Attachment on User for Self-Escalation (IAM-008)",
+ short_description="Attach existing managed policies with administrative permissions to your own IAM user, instantly escalating privileges.",
+ description="Detect IAM users that can use iam:AttachUserPolicy on themselves. A user with this permission can attach any existing managed policy, including AdministratorAccess, to themselves without needing to modify or assume any other resource. Unlike IAM-007 (PutUserPolicy), this requires an existing managed policy with elevated permissions.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-008 - iam:AttachUserPolicy",
+ link="https://pathfinding.cloud/paths/iam-008",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find users with iam:AttachUserPolicy permission scoped to themselves
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(user:AWSUser)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:attachuserpolicy'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+ AND any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR user.arn CONTAINS resource
+ OR resource CONTAINS user.name
+ )
+
+ WITH collect(path) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-009
+AWS_IAM_PRIVESC_ATTACH_ROLE_POLICY = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-attach-role-policy",
+ name="Managed Policy Attachment on Role for Self-Escalation (IAM-009)",
+ short_description="Attach existing managed policies with administrative permissions to your own IAM role, instantly escalating privileges.",
+ description="Detect IAM roles that can use iam:AttachRolePolicy on themselves. A role with this permission can attach any existing managed policy, including AdministratorAccess, to itself without needing to modify or assume any other resource. Unlike IAM-005 (PutRolePolicy), this requires an existing managed policy with elevated permissions.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-009 - iam:AttachRolePolicy",
+ link="https://pathfinding.cloud/paths/iam-009",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find roles with iam:AttachRolePolicy permission scoped to themselves
+ MATCH path = (aws:AWSAccount {{id: $provider_uid}})--(role:AWSRole)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:attachrolepolicy'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+ AND any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR role.arn CONTAINS resource
+ OR resource CONTAINS role.name
+ )
+
+ WITH collect(path) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-010
+AWS_IAM_PRIVESC_ATTACH_GROUP_POLICY = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-attach-group-policy",
+ name="Managed Policy Attachment on Group for Self-Escalation (IAM-010)",
+ short_description="Attach existing managed policies with administrative permissions to a group you belong to, escalating privileges for all group members.",
+ description="Detect IAM users that can use iam:AttachGroupPolicy on a group they are a member of. A user with this permission can attach any existing managed policy, including AdministratorAccess, to a group they belong to, immediately escalating privileges for all group members.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-010 - iam:AttachGroupPolicy",
+ link="https://pathfinding.cloud/paths/iam-010",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find users with iam:AttachGroupPolicy permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(user:AWSUser)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:attachgrouppolicy'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find groups the user is a member of and can attach policies to
+ MATCH path_target = (aws)-[:RESOURCE]->(target_group:AWSGroup)<-[:MEMBER_AWS_GROUP]-(user)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_group.arn CONTAINS resource
+ OR resource CONTAINS target_group.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-011
+AWS_IAM_PRIVESC_PUT_GROUP_POLICY = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-put-group-policy",
+ name="Inline Policy Injection on Group for Self-Escalation (IAM-011)",
+ short_description="Attach an inline policy with administrative permissions to a group you belong to, escalating privileges for all group members.",
+ description="Detect IAM users that can use iam:PutGroupPolicy on a group they are a member of. A user with this permission can attach an inline policy granting any permissions to a group they belong to, immediately escalating privileges for all group members. Unlike IAM-010, this does not require an existing managed policy.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-011 - iam:PutGroupPolicy",
+ link="https://pathfinding.cloud/paths/iam-011",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find users with iam:PutGroupPolicy permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(user:AWSUser)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:putgrouppolicy'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find groups the user is a member of and can put policies on
+ MATCH path_target = (aws)-[:RESOURCE]->(target_group:AWSGroup)<-[:MEMBER_AWS_GROUP]-(user)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_group.arn CONTAINS resource
+ OR resource CONTAINS target_group.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-012
+AWS_IAM_PRIVESC_UPDATE_ASSUME_ROLE_POLICY = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-update-assume-role-policy",
+ name="Trust Policy Hijacking for Role Assumption (IAM-012)",
+ short_description="Modify a role's trust policy to allow yourself to assume it, gaining the role's permissions.",
+ description="Detect principals who can update the assume role policy (trust policy) of other IAM roles. By modifying a target role's trust policy to trust the attacker's principal, the attacker can then assume the role and gain all its permissions, including potential administrative access.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-012 - iam:UpdateAssumeRolePolicy",
+ link="https://pathfinding.cloud/paths/iam-012",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:UpdateAssumeRolePolicy permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:updateassumerolepolicy'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find target roles whose trust policy can be modified
+ MATCH path_target = (aws)--(target_role:AWSRole)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-013
+AWS_IAM_PRIVESC_ADD_USER_TO_GROUP = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-add-user-to-group",
+ name="Group Membership Hijacking for Privilege Escalation (IAM-013)",
+ short_description="Add yourself to a privileged IAM group to inherit its permissions, gaining access to all policies attached to the group.",
+ description="Detect principals who can add users to IAM groups. By adding themselves to a group with elevated permissions such as AdministratorAccess, the attacker immediately inherits all policies attached to that group. The level of access gained depends on the permissions of the target group.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-013 - iam:AddUserToGroup",
+ link="https://pathfinding.cloud/paths/iam-013",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:AddUserToGroup permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:addusertogroup'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find target groups the principal can add users to
+ MATCH path_target = (aws)-[:RESOURCE]->(target_group:AWSGroup)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_group.arn CONTAINS resource
+ OR resource CONTAINS target_group.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-014
+AWS_IAM_PRIVESC_ATTACH_ROLE_POLICY_ASSUME_ROLE = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-attach-role-policy-assume-role",
+ name="Managed Policy Attachment with Role Assumption for Lateral Movement (IAM-014)",
+ short_description="Attach administrative managed policies to another role you can assume, then assume it to gain elevated privileges.",
+ description="Detect principals who can attach managed policies to a different IAM role and also assume that role. By attaching AdministratorAccess to a target role and then assuming it, the attacker gains full administrative access. This is a variation of IAM-009 for lateral movement where the principal targets another assumable role instead of their own.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-014 - iam:AttachRolePolicy + sts:AssumeRole",
+ link="https://pathfinding.cloud/paths/iam-014",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:AttachRolePolicy permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:attachrolepolicy'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find target roles the principal can assume and attach policies to
+ MATCH path_target = (aws)--(target_role:AWSRole)<-[:STS_ASSUMEROLE_ALLOW]-(principal)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-015
+AWS_IAM_PRIVESC_ATTACH_USER_POLICY_CREATE_ACCESS_KEY = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-attach-user-policy-create-access-key",
+ name="Managed Policy Attachment with Access Key Creation for Lateral Movement (IAM-015)",
+ short_description="Attach administrative managed policies to another IAM user and create access keys for them to gain programmatic access with elevated privileges.",
+ description="Detect principals who can attach managed policies to another IAM user and also create access keys for that user. By attaching AdministratorAccess to a target user and creating access keys, the attacker gains programmatic access with the target user's elevated permissions. This combines IAM-008 (AttachUserPolicy) with IAM-002 (CreateAccessKey) for lateral movement.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-015 - iam:AttachUserPolicy + iam:CreateAccessKey",
+ link="https://pathfinding.cloud/paths/iam-015",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:AttachUserPolicy permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:attachuserpolicy'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find iam:CreateAccessKey permission
+ MATCH (principal)--(policy2:AWSPolicy)--(stmt2:AWSPolicyStatement)
+ WHERE stmt2.effect = 'Allow'
+ AND any(action IN stmt2.action WHERE
+ toLower(action) = 'iam:createaccesskey'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find target users the principal can attach policies to and create keys for
+ MATCH path_target = (aws)--(target_user:AWSUser)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_user.arn CONTAINS resource
+ OR resource CONTAINS target_user.name
+ )
+ AND any(resource IN stmt2.resource WHERE
+ resource = '*'
+ OR target_user.arn CONTAINS resource
+ OR resource CONTAINS target_user.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-016
+AWS_IAM_PRIVESC_CREATE_POLICY_VERSION_ASSUME_ROLE = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-create-policy-version-assume-role",
+ name="Policy Version Override with Role Assumption for Lateral Movement (IAM-016)",
+ short_description="Create a new version of a customer-managed policy attached to another role with administrative permissions, then assume that role to gain elevated access.",
+ description="Detect principals who can create new versions of customer-managed policies attached to other roles and also assume those roles. By creating a new policy version with administrative permissions on a policy attached to a target role, then assuming that role, the attacker gains full administrative access. This is a variation of IAM-001 for lateral movement where the modified policy is attached to an assumable role rather than the attacker's own principal.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-016 - iam:CreatePolicyVersion + sts:AssumeRole",
+ link="https://pathfinding.cloud/paths/iam-016",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:CreatePolicyVersion permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:createpolicyversion'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find target roles the principal can assume that have customer-managed policies the principal can modify
+ MATCH path_target = (aws)--(target_role:AWSRole)<-[:STS_ASSUMEROLE_ALLOW]-(principal)
+ MATCH (target_role)--(target_policy:AWSPolicy)
+ WHERE target_policy.arn CONTAINS $provider_uid
+ AND any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_policy.arn CONTAINS resource
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-017
+AWS_IAM_PRIVESC_PUT_ROLE_POLICY_ASSUME_ROLE = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-put-role-policy-assume-role",
+ name="Inline Policy Injection with Role Assumption for Lateral Movement (IAM-017)",
+ short_description="Attach an inline policy with administrative permissions to another role you can assume, then assume it to gain elevated privileges.",
+ description="Detect principals who can add inline policies to a different IAM role and also assume that role. By adding an inline policy granting administrative permissions to a target role and then assuming it, the attacker gains full administrative access. This is a variation of IAM-005 for lateral movement where the principal targets another assumable role instead of their own.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-017 - iam:PutRolePolicy + sts:AssumeRole",
+ link="https://pathfinding.cloud/paths/iam-017",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PutRolePolicy permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:putrolepolicy'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find target roles the principal can assume and put inline policies on
+ MATCH path_target = (aws)--(target_role:AWSRole)<-[:STS_ASSUMEROLE_ALLOW]-(principal)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-018
+AWS_IAM_PRIVESC_PUT_USER_POLICY_CREATE_ACCESS_KEY = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-put-user-policy-create-access-key",
+ name="Inline Policy Injection with Access Key Creation for Lateral Movement (IAM-018)",
+ short_description="Attach an inline policy with administrative permissions to another IAM user and create access keys for them to gain programmatic access with elevated privileges.",
+ description="Detect principals who can add inline policies to another IAM user and also create access keys for that user. By adding an administrative inline policy to a target user and creating access keys, the attacker gains programmatic access with the target user's elevated permissions. This combines IAM-007 (PutUserPolicy) with IAM-002 (CreateAccessKey) for lateral movement.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-018 - iam:PutUserPolicy + iam:CreateAccessKey",
+ link="https://pathfinding.cloud/paths/iam-018",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PutUserPolicy permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:putuserpolicy'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find iam:CreateAccessKey permission
+ MATCH (principal)--(policy2:AWSPolicy)--(stmt2:AWSPolicyStatement)
+ WHERE stmt2.effect = 'Allow'
+ AND any(action IN stmt2.action WHERE
+ toLower(action) = 'iam:createaccesskey'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find target users the principal can put policies on and create keys for
+ MATCH path_target = (aws)--(target_user:AWSUser)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_user.arn CONTAINS resource
+ OR resource CONTAINS target_user.name
+ )
+ AND any(resource IN stmt2.resource WHERE
+ resource = '*'
+ OR target_user.arn CONTAINS resource
+ OR resource CONTAINS target_user.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-019
+AWS_IAM_PRIVESC_ATTACH_ROLE_POLICY_UPDATE_ASSUME_ROLE = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-attach-role-policy-update-assume-role",
+ name="Managed Policy Attachment with Trust Policy Hijacking for Privilege Escalation (IAM-019)",
+ short_description="Attach administrative managed policies to a role and modify its trust policy to allow yourself to assume it, gaining elevated privileges without prior assume-role access.",
+ description="Detect principals who can attach managed policies to an IAM role and also update that role's trust policy. By attaching AdministratorAccess and modifying the trust policy to allow the attacker, the principal can then assume the role without needing pre-existing sts:AssumeRole permission. This combines IAM-009 (AttachRolePolicy) with IAM-012 (UpdateAssumeRolePolicy).",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-019 - iam:AttachRolePolicy + iam:UpdateAssumeRolePolicy",
+ link="https://pathfinding.cloud/paths/iam-019",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:AttachRolePolicy permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:attachrolepolicy'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find iam:UpdateAssumeRolePolicy permission
+ MATCH (principal)--(policy2:AWSPolicy)--(stmt2:AWSPolicyStatement)
+ WHERE stmt2.effect = 'Allow'
+ AND any(action IN stmt2.action WHERE
+ toLower(action) = 'iam:updateassumerolepolicy'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find target roles the principal can attach policies to and update trust policy for
+ MATCH path_target = (aws)--(target_role:AWSRole)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+ AND any(resource IN stmt2.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-020
+AWS_IAM_PRIVESC_CREATE_POLICY_VERSION_UPDATE_ASSUME_ROLE = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-create-policy-version-update-assume-role",
+ name="Policy Version Override with Trust Policy Hijacking for Privilege Escalation (IAM-020)",
+ short_description="Create a new version of a customer-managed policy attached to a role with administrative permissions and modify its trust policy to assume it, without prior assume-role access.",
+ description="Detect principals who can create new versions of customer-managed policies attached to roles and also update those roles' trust policies. By creating an administrative policy version and modifying the trust policy to allow the attacker, the principal can assume the role without needing pre-existing sts:AssumeRole permission. This combines IAM-001 (CreatePolicyVersion) with IAM-012 (UpdateAssumeRolePolicy).",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-020 - iam:CreatePolicyVersion + iam:UpdateAssumeRolePolicy",
+ link="https://pathfinding.cloud/paths/iam-020",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:CreatePolicyVersion permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:createpolicyversion'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find iam:UpdateAssumeRolePolicy permission
+ MATCH (principal)--(policy2:AWSPolicy)--(stmt2:AWSPolicyStatement)
+ WHERE stmt2.effect = 'Allow'
+ AND any(action IN stmt2.action WHERE
+ toLower(action) = 'iam:updateassumerolepolicy'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find target roles with customer-managed policies the principal can modify and update trust policy for
+ MATCH path_target = (aws)--(target_role:AWSRole)
+ WHERE any(resource IN stmt2.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+ MATCH (target_role)--(target_policy:AWSPolicy)
+ WHERE target_policy.arn CONTAINS $provider_uid
+ AND any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_policy.arn CONTAINS resource
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# IAM-021
+AWS_IAM_PRIVESC_PUT_ROLE_POLICY_UPDATE_ASSUME_ROLE = AttackPathsQueryDefinition(
+ id="aws-iam-privesc-put-role-policy-update-assume-role",
+ name="Inline Policy Injection with Trust Policy Hijacking for Privilege Escalation (IAM-021)",
+ short_description="Add an inline policy with administrative permissions to a role and modify its trust policy to allow yourself to assume it, gaining elevated privileges without prior assume-role access.",
+ description="Detect principals who can add inline policies to an IAM role and also update that role's trust policy. By adding an administrative inline policy and modifying the trust policy to allow the attacker, the principal can then assume the role without needing pre-existing sts:AssumeRole permission. This combines IAM-005 (PutRolePolicy) with IAM-012 (UpdateAssumeRolePolicy).",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - IAM-021 - iam:PutRolePolicy + iam:UpdateAssumeRolePolicy",
+ link="https://pathfinding.cloud/paths/iam-021",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PutRolePolicy permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'iam:putrolepolicy'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find iam:UpdateAssumeRolePolicy permission
+ MATCH (principal)--(policy2:AWSPolicy)--(stmt2:AWSPolicyStatement)
+ WHERE stmt2.effect = 'Allow'
+ AND any(action IN stmt2.action WHERE
+ toLower(action) = 'iam:updateassumerolepolicy'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find target roles the principal can put inline policies on and update trust policy for
+ MATCH path_target = (aws)--(target_role:AWSRole)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+ AND any(resource IN stmt2.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# LAMBDA-001
+AWS_LAMBDA_PRIVESC_PASSROLE_CREATE_FUNCTION = AttackPathsQueryDefinition(
+ id="aws-lambda-privesc-passrole-create-function",
+ name="Lambda Function Creation with Privileged Role (LAMBDA-001)",
+ short_description="Create a Lambda function with a privileged IAM role and invoke it to execute code with that role's permissions.",
+ description="Detect principals who can create Lambda functions with privileged IAM roles and invoke them. By passing a privileged role to a new Lambda function and invoking it, the attacker executes code with the role's permissions, gaining access to any resources the role can access.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - LAMBDA-001 - iam:PassRole + lambda:CreateFunction + lambda:InvokeFunction",
+ link="https://pathfinding.cloud/paths/lambda-001",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find lambda:CreateFunction permission
+ MATCH (principal)--(create_policy:AWSPolicy)--(stmt_create:AWSPolicyStatement)
+ WHERE stmt_create.effect = 'Allow'
+ AND any(action IN stmt_create.action WHERE
+ toLower(action) = 'lambda:createfunction'
+ OR toLower(action) = 'lambda:*'
+ OR action = '*'
+ )
+
+ // Find lambda:InvokeFunction permission
+ MATCH (principal)--(invoke_policy:AWSPolicy)--(stmt_invoke:AWSPolicyStatement)
+ WHERE stmt_invoke.effect = 'Allow'
+ AND any(action IN stmt_invoke.action WHERE
+ toLower(action) = 'lambda:invokefunction'
+ OR toLower(action) = 'lambda:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust Lambda service (can be passed to Lambda)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'lambda.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# LAMBDA-002
+AWS_LAMBDA_PRIVESC_PASSROLE_CREATE_FUNCTION_EVENT_SOURCE = AttackPathsQueryDefinition(
+ id="aws-lambda-privesc-passrole-create-function-event-source",
+ name="Lambda Function Creation with Event Source Trigger (LAMBDA-002)",
+ short_description="Create a Lambda function with a privileged IAM role and an event source mapping to trigger it automatically, executing code with the role's permissions.",
+ description="Detect principals who can create Lambda functions with privileged IAM roles and configure event source mappings to trigger them. By passing a privileged role to a new Lambda function and creating an event source mapping (DynamoDB stream, Kinesis, SQS), the attacker executes code with elevated privileges without needing to invoke the function directly.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - LAMBDA-002 - iam:PassRole + lambda:CreateFunction + lambda:CreateEventSourceMapping",
+ link="https://pathfinding.cloud/paths/lambda-002",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find lambda:CreateFunction permission
+ MATCH (principal)--(create_policy:AWSPolicy)--(stmt_create:AWSPolicyStatement)
+ WHERE stmt_create.effect = 'Allow'
+ AND any(action IN stmt_create.action WHERE
+ toLower(action) = 'lambda:createfunction'
+ OR toLower(action) = 'lambda:*'
+ OR action = '*'
+ )
+
+ // Find lambda:CreateEventSourceMapping permission
+ MATCH (principal)--(event_policy:AWSPolicy)--(stmt_event:AWSPolicyStatement)
+ WHERE stmt_event.effect = 'Allow'
+ AND any(action IN stmt_event.action WHERE
+ toLower(action) = 'lambda:createeventsourcemapping'
+ OR toLower(action) = 'lambda:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust Lambda service (can be passed to Lambda)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'lambda.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# LAMBDA-003
+AWS_LAMBDA_PRIVESC_UPDATE_FUNCTION_CODE = AttackPathsQueryDefinition(
+ id="aws-lambda-privesc-update-function-code",
+ name="Lambda Function Code Injection (LAMBDA-003)",
+ short_description="Modify the code of an existing Lambda function to execute arbitrary commands with the function's execution role permissions.",
+ description="Detect principals who can update the code of existing Lambda functions. By replacing a Lambda function's code with malicious code, the attacker executes arbitrary commands with the privileges of the function's execution role when it is next invoked, either manually or via automatic triggers.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - LAMBDA-003 - lambda:UpdateFunctionCode",
+ link="https://pathfinding.cloud/paths/lambda-003",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with lambda:UpdateFunctionCode permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'lambda:updatefunctioncode'
+ OR toLower(action) = 'lambda:*'
+ OR action = '*'
+ )
+
+ // Find existing Lambda functions with execution roles
+ MATCH path_target = (aws)-[:RESOURCE]->(lambda_fn:AWSLambda)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR lambda_fn.arn CONTAINS resource
+ OR resource CONTAINS lambda_fn.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# LAMBDA-004
+AWS_LAMBDA_PRIVESC_UPDATE_FUNCTION_CODE_INVOKE = AttackPathsQueryDefinition(
+ id="aws-lambda-privesc-update-function-code-invoke",
+ name="Lambda Function Code Injection with Direct Invocation (LAMBDA-004)",
+ short_description="Modify the code of an existing Lambda function and invoke it directly to execute arbitrary commands with the function's execution role permissions.",
+ description="Detect principals who can update the code of existing Lambda functions and invoke them. By replacing a Lambda function's code with malicious code and invoking it directly, the attacker executes arbitrary commands with the privileges of the function's execution role immediately, without waiting for automatic triggers.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - LAMBDA-004 - lambda:UpdateFunctionCode + lambda:InvokeFunction",
+ link="https://pathfinding.cloud/paths/lambda-004",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with lambda:UpdateFunctionCode permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'lambda:updatefunctioncode'
+ OR toLower(action) = 'lambda:*'
+ OR action = '*'
+ )
+
+ // Find lambda:InvokeFunction permission
+ MATCH (principal)--(policy2:AWSPolicy)--(stmt2:AWSPolicyStatement)
+ WHERE stmt2.effect = 'Allow'
+ AND any(action IN stmt2.action WHERE
+ toLower(action) = 'lambda:invokefunction'
+ OR toLower(action) = 'lambda:*'
+ OR action = '*'
+ )
+
+ // Find existing Lambda functions with execution roles
+ MATCH path_target = (aws)-[:RESOURCE]->(lambda_fn:AWSLambda)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR lambda_fn.arn CONTAINS resource
+ OR resource CONTAINS lambda_fn.name
+ )
+ AND any(resource IN stmt2.resource WHERE
+ resource = '*'
+ OR lambda_fn.arn CONTAINS resource
+ OR resource CONTAINS lambda_fn.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# LAMBDA-005
+AWS_LAMBDA_PRIVESC_UPDATE_FUNCTION_CODE_ADD_PERMISSION = AttackPathsQueryDefinition(
+ id="aws-lambda-privesc-update-function-code-add-permission",
+ name="Lambda Function Code Injection with Resource Policy Grant (LAMBDA-005)",
+ short_description="Modify the code of an existing Lambda function and grant yourself invocation permission via its resource-based policy to execute code with the function's execution role.",
+ description="Detect principals who can update the code of existing Lambda functions and add permissions to their resource-based policies. By replacing a Lambda function's code and granting themselves invoke access through the resource-based policy, the attacker executes malicious code with the function's execution role without needing lambda:InvokeFunction as an IAM permission.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - LAMBDA-005 - lambda:UpdateFunctionCode + lambda:AddPermission",
+ link="https://pathfinding.cloud/paths/lambda-005",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with lambda:UpdateFunctionCode permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'lambda:updatefunctioncode'
+ OR toLower(action) = 'lambda:*'
+ OR action = '*'
+ )
+
+ // Find lambda:AddPermission permission
+ MATCH (principal)--(policy2:AWSPolicy)--(stmt2:AWSPolicyStatement)
+ WHERE stmt2.effect = 'Allow'
+ AND any(action IN stmt2.action WHERE
+ toLower(action) = 'lambda:addpermission'
+ OR toLower(action) = 'lambda:*'
+ OR action = '*'
+ )
+
+ // Find existing Lambda functions with execution roles
+ MATCH path_target = (aws)-[:RESOURCE]->(lambda_fn:AWSLambda)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR lambda_fn.arn CONTAINS resource
+ OR resource CONTAINS lambda_fn.name
+ )
+ AND any(resource IN stmt2.resource WHERE
+ resource = '*'
+ OR lambda_fn.arn CONTAINS resource
+ OR resource CONTAINS lambda_fn.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# LAMBDA-006
+AWS_LAMBDA_PRIVESC_PASSROLE_CREATE_FUNCTION_ADD_PERMISSION = AttackPathsQueryDefinition(
+ id="aws-lambda-privesc-passrole-create-function-add-permission",
+ name="Lambda Function Creation with Resource Policy Invocation (LAMBDA-006)",
+ short_description="Create a Lambda function with a privileged IAM role and grant yourself invocation permission via its resource-based policy to execute code with the role's permissions.",
+ description="Detect principals who can create Lambda functions with privileged IAM roles and add permissions to their resource-based policies. By passing a privileged role to a new Lambda function and granting themselves invoke access through the resource-based policy, the attacker executes malicious code with elevated privileges without needing lambda:InvokeFunction as an IAM permission.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - LAMBDA-006 - iam:PassRole + lambda:CreateFunction + lambda:AddPermission",
+ link="https://pathfinding.cloud/paths/lambda-006",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find lambda:CreateFunction permission
+ MATCH (principal)--(create_policy:AWSPolicy)--(stmt_create:AWSPolicyStatement)
+ WHERE stmt_create.effect = 'Allow'
+ AND any(action IN stmt_create.action WHERE
+ toLower(action) = 'lambda:createfunction'
+ OR toLower(action) = 'lambda:*'
+ OR action = '*'
+ )
+
+ // Find lambda:AddPermission permission
+ MATCH (principal)--(perm_policy:AWSPolicy)--(stmt_perm:AWSPolicyStatement)
+ WHERE stmt_perm.effect = 'Allow'
+ AND any(action IN stmt_perm.action WHERE
+ toLower(action) = 'lambda:addpermission'
+ OR toLower(action) = 'lambda:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust Lambda service (can be passed to Lambda)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'lambda.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# SAGEMAKER-001
+AWS_SAGEMAKER_PRIVESC_PASSROLE_CREATE_NOTEBOOK = AttackPathsQueryDefinition(
+ id="aws-sagemaker-privesc-passrole-create-notebook",
+ name="SageMaker Notebook Creation with Privileged Role (SAGEMAKER-001)",
+ short_description="Create a SageMaker notebook instance with a privileged IAM role to execute arbitrary code with the role's permissions via the Jupyter environment.",
+ description="Detect principals who can create SageMaker notebook instances with privileged IAM roles. By passing a privileged role to a new notebook instance, the attacker gains shell access through the Jupyter environment and can execute arbitrary commands with the role's permissions.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - SAGEMAKER-001 - iam:PassRole + sagemaker:CreateNotebookInstance",
+ link="https://pathfinding.cloud/paths/sagemaker-001",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find sagemaker:CreateNotebookInstance permission
+ MATCH (principal)--(sm_policy:AWSPolicy)--(stmt_sm:AWSPolicyStatement)
+ WHERE stmt_sm.effect = 'Allow'
+ AND any(action IN stmt_sm.action WHERE
+ toLower(action) = 'sagemaker:createnotebookinstance'
+ OR toLower(action) = 'sagemaker:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust SageMaker service (can be passed to SageMaker)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'sagemaker.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# SAGEMAKER-002
+AWS_SAGEMAKER_PRIVESC_PASSROLE_CREATE_TRAINING_JOB = AttackPathsQueryDefinition(
+ id="aws-sagemaker-privesc-passrole-create-training-job",
+ name="SageMaker Training Job Creation with Privileged Role (SAGEMAKER-002)",
+ short_description="Create a SageMaker training job with a privileged IAM role to execute arbitrary container code with the role's permissions.",
+ description="Detect principals who can create SageMaker training jobs with privileged IAM roles. By passing a privileged role to a new training job with a malicious training script or container, the attacker executes code with elevated privileges and can exfiltrate credentials or modify AWS resources.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - SAGEMAKER-002 - iam:PassRole + sagemaker:CreateTrainingJob",
+ link="https://pathfinding.cloud/paths/sagemaker-002",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find sagemaker:CreateTrainingJob permission
+ MATCH (principal)--(sm_policy:AWSPolicy)--(stmt_sm:AWSPolicyStatement)
+ WHERE stmt_sm.effect = 'Allow'
+ AND any(action IN stmt_sm.action WHERE
+ toLower(action) = 'sagemaker:createtrainingjob'
+ OR toLower(action) = 'sagemaker:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust SageMaker service (can be passed to SageMaker)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'sagemaker.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# SAGEMAKER-003
+AWS_SAGEMAKER_PRIVESC_PASSROLE_CREATE_PROCESSING_JOB = AttackPathsQueryDefinition(
+ id="aws-sagemaker-privesc-passrole-create-processing-job",
+ name="SageMaker Processing Job Creation with Privileged Role (SAGEMAKER-003)",
+ short_description="Create a SageMaker processing job with a privileged IAM role to execute arbitrary container code with the role's permissions.",
+ description="Detect principals who can create SageMaker processing jobs with privileged IAM roles. By passing a privileged role to a new processing job with a malicious script or container, the attacker executes code with elevated privileges and can exfiltrate credentials or modify AWS resources.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - SAGEMAKER-003 - iam:PassRole + sagemaker:CreateProcessingJob",
+ link="https://pathfinding.cloud/paths/sagemaker-003",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with iam:PassRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(passrole_policy:AWSPolicy)--(stmt_passrole:AWSPolicyStatement)
+ WHERE stmt_passrole.effect = 'Allow'
+ AND any(action IN stmt_passrole.action WHERE
+ toLower(action) = 'iam:passrole'
+ OR toLower(action) = 'iam:*'
+ OR action = '*'
+ )
+
+ // Find sagemaker:CreateProcessingJob permission
+ MATCH (principal)--(sm_policy:AWSPolicy)--(stmt_sm:AWSPolicyStatement)
+ WHERE stmt_sm.effect = 'Allow'
+ AND any(action IN stmt_sm.action WHERE
+ toLower(action) = 'sagemaker:createprocessingjob'
+ OR toLower(action) = 'sagemaker:*'
+ OR action = '*'
+ )
+
+ // Find roles that trust SageMaker service (can be passed to SageMaker)
+ MATCH path_target = (aws)--(target_role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(:AWSPrincipal {{arn: 'sagemaker.amazonaws.com'}})
+ WHERE any(resource IN stmt_passrole.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# SAGEMAKER-004
+AWS_SAGEMAKER_PRIVESC_PRESIGNED_NOTEBOOK_URL = AttackPathsQueryDefinition(
+ id="aws-sagemaker-privesc-presigned-notebook-url",
+ name="SageMaker Presigned Notebook URL for Privilege Escalation (SAGEMAKER-004)",
+ short_description="Generate a presigned URL to access an existing SageMaker notebook instance and execute code with its execution role's permissions.",
+ description="Detect principals who can generate presigned URLs to access existing SageMaker notebook instances. By accessing the Jupyter environment via a presigned URL, the attacker can execute arbitrary code with the permissions of the notebook's execution role without creating any new resources.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - SAGEMAKER-004 - sagemaker:CreatePresignedNotebookInstanceUrl",
+ link="https://pathfinding.cloud/paths/sagemaker-004",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with sagemaker:CreatePresignedNotebookInstanceUrl permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'sagemaker:createpresignednotebookinstanceurl'
+ OR toLower(action) = 'sagemaker:*'
+ OR action = '*'
+ )
+
+ // Find existing SageMaker notebook instances with execution roles
+ MATCH path_target = (aws)-[:RESOURCE]->(notebook:AWSSageMakerNotebookInstance)-[:HAS_EXECUTION_ROLE]->(target_role:AWSRole)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR notebook.arn CONTAINS resource
+ OR resource CONTAINS notebook.notebook_instance_name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# SAGEMAKER-005
+AWS_SAGEMAKER_PRIVESC_LIFECYCLE_CONFIG_NOTEBOOK = AttackPathsQueryDefinition(
+ id="aws-sagemaker-privesc-lifecycle-config-notebook",
+ name="SageMaker Notebook Lifecycle Config Injection (SAGEMAKER-005)",
+ short_description="Inject a malicious lifecycle configuration into an existing SageMaker notebook to execute code with the notebook's execution role during startup.",
+ description="Detect principals who can inject malicious lifecycle configurations into existing SageMaker notebook instances. By stopping a notebook, attaching a malicious lifecycle config, and restarting it, the attacker executes arbitrary code with the notebook's execution role permissions during startup.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - SAGEMAKER-005 - sagemaker:CreateNotebookInstanceLifecycleConfig + sagemaker:StopNotebookInstance + sagemaker:UpdateNotebookInstance + sagemaker:StartNotebookInstance",
+ link="https://pathfinding.cloud/paths/sagemaker-005",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with sagemaker:CreateNotebookInstanceLifecycleConfig permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'sagemaker:createnotebookinstancelifecycleconfig'
+ OR toLower(action) = 'sagemaker:*'
+ OR action = '*'
+ )
+
+ // Find sagemaker:UpdateNotebookInstance permission
+ MATCH (principal)--(policy2:AWSPolicy)--(stmt2:AWSPolicyStatement)
+ WHERE stmt2.effect = 'Allow'
+ AND any(action IN stmt2.action WHERE
+ toLower(action) = 'sagemaker:updatenotebookinstance'
+ OR toLower(action) = 'sagemaker:*'
+ OR action = '*'
+ )
+
+ // Find sagemaker:StopNotebookInstance permission
+ MATCH (principal)--(policy3:AWSPolicy)--(stmt3:AWSPolicyStatement)
+ WHERE stmt3.effect = 'Allow'
+ AND any(action IN stmt3.action WHERE
+ toLower(action) = 'sagemaker:stopnotebookinstance'
+ OR toLower(action) = 'sagemaker:*'
+ OR action = '*'
+ )
+
+ // Find sagemaker:StartNotebookInstance permission
+ MATCH (principal)--(policy4:AWSPolicy)--(stmt4:AWSPolicyStatement)
+ WHERE stmt4.effect = 'Allow'
+ AND any(action IN stmt4.action WHERE
+ toLower(action) = 'sagemaker:startnotebookinstance'
+ OR toLower(action) = 'sagemaker:*'
+ OR action = '*'
+ )
+
+ // Find existing SageMaker notebook instances with execution roles
+ MATCH path_target = (aws)-[:RESOURCE]->(notebook:AWSSageMakerNotebookInstance)-[:HAS_EXECUTION_ROLE]->(target_role:AWSRole)
+ WHERE any(resource IN stmt2.resource WHERE
+ resource = '*'
+ OR notebook.arn CONTAINS resource
+ OR resource CONTAINS notebook.notebook_instance_name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# SSM-001
+AWS_SSM_PRIVESC_START_SESSION = AttackPathsQueryDefinition(
+ id="aws-ssm-privesc-start-session",
+ name="SSM Session Access for EC2 Role Credentials (SSM-001)",
+ short_description="Start an SSM session on an EC2 instance to access its attached role credentials through IMDS.",
+ description="Detect principals who can start SSM sessions on EC2 instances. This allows establishing a shell session on a running EC2 instance and retrieving the attached IAM role's temporary credentials from the Instance Metadata Service (IMDS), gaining that role's permissions.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - SSM-001 - ssm:StartSession",
+ link="https://pathfinding.cloud/paths/ssm-001",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with ssm:StartSession permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'ssm:startsession'
+ OR toLower(action) = 'ssm:*'
+ OR action = '*'
+ )
+
+ // Find EC2 instances with attached roles (targets for credential theft via IMDS)
+ MATCH path_target = (aws)--(ec2:EC2Instance)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# SSM-002
+AWS_SSM_PRIVESC_SEND_COMMAND = AttackPathsQueryDefinition(
+ id="aws-ssm-privesc-send-command",
+ name="SSM Send Command for EC2 Role Credentials (SSM-002)",
+ short_description="Execute commands on an EC2 instance via SSM Run Command to access its attached role credentials through IMDS.",
+ description="Detect principals who can send SSM commands to EC2 instances. This allows executing arbitrary commands on a running EC2 instance and retrieving the attached IAM role's temporary credentials from the Instance Metadata Service (IMDS), gaining that role's permissions.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - SSM-002 - ssm:SendCommand",
+ link="https://pathfinding.cloud/paths/ssm-002",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with ssm:SendCommand permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'ssm:sendcommand'
+ OR toLower(action) = 'ssm:*'
+ OR action = '*'
+ )
+
+ // Find EC2 instances with attached roles (targets for credential theft via IMDS)
+ MATCH path_target = (aws)--(ec2:EC2Instance)-[:STS_ASSUMEROLE_ALLOW]->(target_role:AWSRole)
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# STS-001
+AWS_STS_PRIVESC_ASSUME_ROLE = AttackPathsQueryDefinition(
+ id="aws-sts-privesc-assume-role",
+ name="Role Assumption for Privilege Escalation (STS-001)",
+ short_description="Assume IAM roles with elevated permissions by exploiting bidirectional trust between the starting principal and the target role.",
+ description="Detect principals who can assume other IAM roles via sts:AssumeRole. When a principal has sts:AssumeRole permission and the target role's trust policy allows the principal to assume it (bidirectional trust), the attacker gains all permissions of the target role. This enables privilege escalation when the target role has higher privileges than the starting principal.",
+ attribution=AttackPathsQueryAttribution(
+ text="pathfinding.cloud - STS-001 - sts:AssumeRole",
+ link="https://pathfinding.cloud/paths/sts-001",
+ ),
+ provider="aws",
+ cypher=f"""
+ // Find principals with sts:AssumeRole permission
+ MATCH path_principal = (aws:AWSAccount {{id: $provider_uid}})--(principal:AWSPrincipal)--(policy:AWSPolicy)--(stmt:AWSPolicyStatement)
+ WHERE stmt.effect = 'Allow'
+ AND any(action IN stmt.action WHERE
+ toLower(action) = 'sts:assumerole'
+ OR toLower(action) = 'sts:*'
+ OR action = '*'
+ )
+
+ // Find target roles the principal can assume (bidirectional trust via Cartography)
+ MATCH path_target = (aws)--(target_role:AWSRole)<-[:STS_ASSUMEROLE_ALLOW]-(principal)
+ WHERE any(resource IN stmt.resource WHERE
+ resource = '*'
+ OR target_role.arn CONTAINS resource
+ OR resource CONTAINS target_role.name
+ )
+
+ WITH collect(path_principal) + collect(path_target) AS paths
+ UNWIND paths AS p
+ UNWIND nodes(p) AS n
+
+ WITH paths, collect(DISTINCT n) AS unique_nodes
+ UNWIND unique_nodes AS n
+
+ OPTIONAL MATCH (n)-[pfr]-(pf:{PROWLER_FINDING_LABEL} {{status: 'FAIL'}})
+
+ RETURN paths, collect(DISTINCT pf) as dpf, collect(DISTINCT pfr) as dpfr
+ """,
+ parameters=[],
+)
+
+# AWS Queries List
+# ----------------
+
+AWS_DEPRECATED_QUERIES: list[AttackPathsQueryDefinition] = [
+ AWS_INTERNET_EXPOSED_EC2_SENSITIVE_S3_ACCESS,
+ AWS_RDS_INSTANCES,
+ AWS_RDS_UNENCRYPTED_STORAGE,
+ AWS_S3_ANONYMOUS_ACCESS_BUCKETS,
+ AWS_IAM_STATEMENTS_ALLOW_ALL_ACTIONS,
+ AWS_IAM_STATEMENTS_ALLOW_DELETE_POLICY,
+ AWS_IAM_STATEMENTS_ALLOW_CREATE_ACTIONS,
+ AWS_EC2_INSTANCES_INTERNET_EXPOSED,
+ AWS_SECURITY_GROUPS_OPEN_INTERNET_FACING,
+ AWS_CLASSIC_ELB_INTERNET_EXPOSED,
+ AWS_ELBV2_INTERNET_EXPOSED,
+ AWS_PUBLIC_IP_RESOURCE_LOOKUP,
+ AWS_APPRUNNER_PRIVESC_PASSROLE_CREATE_SERVICE,
+ AWS_APPRUNNER_PRIVESC_UPDATE_SERVICE,
+ AWS_BEDROCK_PRIVESC_PASSROLE_CODE_INTERPRETER,
+ AWS_BEDROCK_PRIVESC_INVOKE_CODE_INTERPRETER,
+ AWS_CLOUDFORMATION_PRIVESC_PASSROLE_CREATE_STACK,
+ AWS_CLOUDFORMATION_PRIVESC_UPDATE_STACK,
+ AWS_CLOUDFORMATION_PRIVESC_PASSROLE_CREATE_STACKSET,
+ AWS_CLOUDFORMATION_PRIVESC_PASSROLE_UPDATE_STACKSET,
+ AWS_CLOUDFORMATION_PRIVESC_CHANGESET,
+ AWS_CODEBUILD_PRIVESC_PASSROLE_CREATE_PROJECT,
+ AWS_CODEBUILD_PRIVESC_START_BUILD,
+ AWS_CODEBUILD_PRIVESC_START_BUILD_BATCH,
+ AWS_CODEBUILD_PRIVESC_PASSROLE_CREATE_PROJECT_BATCH,
+ AWS_DATAPIPELINE_PRIVESC_PASSROLE_CREATE_PIPELINE,
+ AWS_EC2_PRIVESC_PASSROLE_IAM,
+ AWS_EC2_PRIVESC_MODIFY_INSTANCE_ATTRIBUTE,
+ AWS_EC2_PRIVESC_PASSROLE_SPOT_INSTANCES,
+ AWS_EC2_PRIVESC_LAUNCH_TEMPLATE,
+ AWS_EC2INSTANCECONNECT_PRIVESC_SEND_SSH_PUBLIC_KEY,
+ AWS_ECS_PRIVESC_PASSROLE_CREATE_SERVICE,
+ AWS_ECS_PRIVESC_PASSROLE_RUN_TASK,
+ AWS_ECS_PRIVESC_PASSROLE_CREATE_SERVICE_EXISTING_CLUSTER,
+ AWS_ECS_PRIVESC_PASSROLE_RUN_TASK_EXISTING_CLUSTER,
+ AWS_ECS_PRIVESC_PASSROLE_START_TASK_EXISTING_CLUSTER,
+ AWS_ECS_PRIVESC_EXECUTE_COMMAND,
+ AWS_GLUE_PRIVESC_PASSROLE_DEV_ENDPOINT,
+ AWS_GLUE_PRIVESC_UPDATE_DEV_ENDPOINT,
+ AWS_GLUE_PRIVESC_PASSROLE_CREATE_JOB,
+ AWS_GLUE_PRIVESC_PASSROLE_CREATE_JOB_TRIGGER,
+ AWS_GLUE_PRIVESC_PASSROLE_UPDATE_JOB,
+ AWS_GLUE_PRIVESC_PASSROLE_UPDATE_JOB_TRIGGER,
+ AWS_IAM_PRIVESC_CREATE_POLICY_VERSION,
+ AWS_IAM_PRIVESC_CREATE_ACCESS_KEY,
+ AWS_IAM_PRIVESC_DELETE_CREATE_ACCESS_KEY,
+ AWS_IAM_PRIVESC_CREATE_LOGIN_PROFILE,
+ AWS_IAM_PRIVESC_PUT_ROLE_POLICY,
+ AWS_IAM_PRIVESC_UPDATE_LOGIN_PROFILE,
+ AWS_IAM_PRIVESC_PUT_USER_POLICY,
+ AWS_IAM_PRIVESC_ATTACH_USER_POLICY,
+ AWS_IAM_PRIVESC_ATTACH_ROLE_POLICY,
+ AWS_IAM_PRIVESC_ATTACH_GROUP_POLICY,
+ AWS_IAM_PRIVESC_PUT_GROUP_POLICY,
+ AWS_IAM_PRIVESC_UPDATE_ASSUME_ROLE_POLICY,
+ AWS_IAM_PRIVESC_ADD_USER_TO_GROUP,
+ AWS_IAM_PRIVESC_ATTACH_ROLE_POLICY_ASSUME_ROLE,
+ AWS_IAM_PRIVESC_ATTACH_USER_POLICY_CREATE_ACCESS_KEY,
+ AWS_IAM_PRIVESC_CREATE_POLICY_VERSION_ASSUME_ROLE,
+ AWS_IAM_PRIVESC_PUT_ROLE_POLICY_ASSUME_ROLE,
+ AWS_IAM_PRIVESC_PUT_USER_POLICY_CREATE_ACCESS_KEY,
+ AWS_IAM_PRIVESC_ATTACH_ROLE_POLICY_UPDATE_ASSUME_ROLE,
+ AWS_IAM_PRIVESC_CREATE_POLICY_VERSION_UPDATE_ASSUME_ROLE,
+ AWS_IAM_PRIVESC_PUT_ROLE_POLICY_UPDATE_ASSUME_ROLE,
+ AWS_LAMBDA_PRIVESC_PASSROLE_CREATE_FUNCTION,
+ AWS_LAMBDA_PRIVESC_PASSROLE_CREATE_FUNCTION_EVENT_SOURCE,
+ AWS_LAMBDA_PRIVESC_UPDATE_FUNCTION_CODE,
+ AWS_LAMBDA_PRIVESC_UPDATE_FUNCTION_CODE_INVOKE,
+ AWS_LAMBDA_PRIVESC_UPDATE_FUNCTION_CODE_ADD_PERMISSION,
+ AWS_LAMBDA_PRIVESC_PASSROLE_CREATE_FUNCTION_ADD_PERMISSION,
+ AWS_SAGEMAKER_PRIVESC_PASSROLE_CREATE_NOTEBOOK,
+ AWS_SAGEMAKER_PRIVESC_PASSROLE_CREATE_TRAINING_JOB,
+ AWS_SAGEMAKER_PRIVESC_PASSROLE_CREATE_PROCESSING_JOB,
+ AWS_SAGEMAKER_PRIVESC_PRESIGNED_NOTEBOOK_URL,
+ AWS_SAGEMAKER_PRIVESC_LIFECYCLE_CONFIG_NOTEBOOK,
+ AWS_SSM_PRIVESC_START_SESSION,
+ AWS_SSM_PRIVESC_SEND_COMMAND,
+ AWS_STS_PRIVESC_ASSUME_ROLE,
+]
diff --git a/api/src/backend/api/attack_paths/queries/registry.py b/api/src/backend/api/attack_paths/queries/registry.py
index d055b842fd..358b1d6aed 100644
--- a/api/src/backend/api/attack_paths/queries/registry.py
+++ b/api/src/backend/api/attack_paths/queries/registry.py
@@ -1,12 +1,14 @@
from api.attack_paths.queries.aws import AWS_QUERIES
+
+# TODO: drop after Neptune cutover
+from api.attack_paths.queries.aws_deprecated import AWS_DEPRECATED_QUERIES
from api.attack_paths.queries.types import AttackPathsQueryDefinition
-# Query definitions organized by provider
+# Query definitions for scans synced with the current schema.
_QUERY_DEFINITIONS: dict[str, list[AttackPathsQueryDefinition]] = {
"aws": AWS_QUERIES,
}
-# Flat lookup by query ID for O(1) access
_QUERIES_BY_ID: dict[str, AttackPathsQueryDefinition] = {
definition.id: definition
for definitions in _QUERY_DEFINITIONS.values()
@@ -14,11 +16,45 @@ _QUERIES_BY_ID: dict[str, AttackPathsQueryDefinition] = {
}
-def get_queries_for_provider(provider: str) -> list[AttackPathsQueryDefinition]:
- """Get all attack path queries for a specific provider."""
- return _QUERY_DEFINITIONS.get(provider, [])
+# TODO: drop after Neptune cutover
+#
+# Query definitions for pre-cutover scans (`AttackPathsScan.is_migrated=False`)
+# whose graph data was written under the previous schema. Both maps expose the
+# same query IDs so the API contract is identical regardless of which set is
+# routed to.
+_DEPRECATED_QUERY_DEFINITIONS: dict[str, list[AttackPathsQueryDefinition]] = {
+ "aws": AWS_DEPRECATED_QUERIES,
+}
+
+_DEPRECATED_QUERIES_BY_ID: dict[str, AttackPathsQueryDefinition] = {
+ definition.id: definition
+ for definitions in _DEPRECATED_QUERY_DEFINITIONS.values()
+ for definition in definitions
+}
-def get_query_by_id(query_id: str) -> AttackPathsQueryDefinition | None:
- """Get a specific attack path query by its ID."""
- return _QUERIES_BY_ID.get(query_id)
+def get_queries_for_provider(
+ provider: str,
+ is_migrated: bool = True,
+) -> list[AttackPathsQueryDefinition]:
+ """Get all attack path queries for a provider.
+
+ `is_migrated` selects the catalog: True for scans synced with the current
+ schema, False for pre-cutover scans still using the legacy graph shape.
+ # TODO: drop the `is_migrated` parameter after Neptune cutover
+ """
+ catalog = _QUERY_DEFINITIONS if is_migrated else _DEPRECATED_QUERY_DEFINITIONS
+ return catalog.get(provider, [])
+
+
+def get_query_by_id(
+ query_id: str,
+ is_migrated: bool = True,
+) -> AttackPathsQueryDefinition | None:
+ """Get a specific attack path query by ID.
+
+ `is_migrated` selects the catalog (see `get_queries_for_provider`).
+ # TODO: drop the `is_migrated` parameter after Neptune cutover
+ """
+ by_id = _QUERIES_BY_ID if is_migrated else _DEPRECATED_QUERIES_BY_ID
+ return by_id.get(query_id)
diff --git a/api/src/backend/api/attack_paths/retryable_session.py b/api/src/backend/api/attack_paths/retryable_session.py
index 16f0d9e31a..e7e78e9798 100644
--- a/api/src/backend/api/attack_paths/retryable_session.py
+++ b/api/src/backend/api/attack_paths/retryable_session.py
@@ -1,4 +1,6 @@
import logging
+import random
+import time
from collections.abc import Callable
from typing import Any
@@ -8,18 +10,44 @@ import neo4j.exceptions
logger = logging.getLogger(__name__)
+class RetryExhaustedError(Exception):
+ def __init__(
+ self,
+ *,
+ retry_context: str,
+ method_name: str,
+ attempts: int,
+ elapsed_seconds: float,
+ last_error: Exception,
+ ) -> None:
+ self.retry_context = retry_context
+ self.method_name = method_name
+ self.attempts = attempts
+ self.elapsed_seconds = elapsed_seconds
+ self.last_error = last_error
+ last_message = getattr(last_error, "message", None) or str(last_error)
+ super().__init__(
+ f"{retry_context} {method_name} failed after {attempts} attempts over "
+ f"{elapsed_seconds:.3f}s. Last error: {last_message}"
+ )
+
+
class RetryableSession:
- """
- Wrapper around `neo4j.Session` that retries `neo4j.exceptions.ServiceUnavailable` errors.
- """
+ """Wrapper around ``neo4j.Session`` with a refreshable retry policy."""
def __init__(
self,
session_factory: Callable[[], neo4j.Session],
max_retries: int,
+ retry_if: Callable[[Exception], bool] | None = None,
+ initial_retry_delay_seconds: float = 0,
+ retry_context: str | None = None,
) -> None:
self._session_factory = session_factory
self._max_retries = max(0, max_retries)
+ self._retry_if = retry_if
+ self._initial_retry_delay_seconds = max(0.0, initial_retry_delay_seconds)
+ self._retry_context = retry_context
self._session = self._session_factory()
def close(self) -> None:
@@ -50,30 +78,75 @@ class RetryableSession:
def _call_with_retry(self, method_name: str, *args: Any, **kwargs: Any) -> Any:
attempt = 0
last_exc: Exception | None = None
+ started_at = time.monotonic()
while attempt <= self._max_retries:
try:
method = getattr(self._session, method_name)
return method(*args, **kwargs)
- except (
- BrokenPipeError,
- ConnectionResetError,
- neo4j.exceptions.ServiceUnavailable,
- ) as exc: # pragma: no cover - depends on infra
+ except Exception as exc:
+ if not self._should_retry(exc):
+ raise
+
last_exc = exc
attempt += 1
if attempt > self._max_retries:
+ if self._retry_context is not None:
+ raise RetryExhaustedError(
+ retry_context=self._retry_context,
+ method_name=method_name,
+ attempts=attempt,
+ elapsed_seconds=time.monotonic() - started_at,
+ last_error=exc,
+ ) from exc
raise
- logger.warning(
- f"Neo4j session {method_name} failed with {type(exc).__name__} ({attempt}/{self._max_retries} attempts). Retrying..."
- )
+ delay = self._retry_delay(attempt)
+ if self._retry_context is not None:
+ error_message = getattr(exc, "message", None) or str(exc)
+ logger.warning(
+ "%s %s failed with %s: %s; retry %s/%s in %.3fs",
+ self._retry_context,
+ method_name,
+ type(exc).__name__,
+ error_message,
+ attempt,
+ self._max_retries,
+ delay,
+ )
+ else:
+ logger.warning(
+ "Graph session %s failed with %s; retry %s/%s in %.3fs",
+ method_name,
+ type(exc).__name__,
+ attempt,
+ self._max_retries,
+ delay,
+ )
self._refresh_session()
+ if delay:
+ time.sleep(delay)
raise last_exc if last_exc else RuntimeError("Unexpected retry loop exit")
+ def _should_retry(self, exc: Exception) -> bool:
+ if isinstance(
+ exc,
+ (
+ BrokenPipeError,
+ ConnectionResetError,
+ neo4j.exceptions.ServiceUnavailable,
+ ),
+ ):
+ return True
+ return self._retry_if(exc) if self._retry_if else False
+
+ def _retry_delay(self, attempt: int) -> float:
+ max_delay = self._initial_retry_delay_seconds * (2**attempt)
+ return random.uniform(max_delay / 2, max_delay) if max_delay else 0
+
def _refresh_session(self) -> None:
if self._session is not None:
try:
diff --git a/api/src/backend/api/attack_paths/sink/__init__.py b/api/src/backend/api/attack_paths/sink/__init__.py
new file mode 100644
index 0000000000..b90fd6e442
--- /dev/null
+++ b/api/src/backend/api/attack_paths/sink/__init__.py
@@ -0,0 +1,28 @@
+"""Attack-paths sink database layer.
+
+The sink is the persistent store where attack-paths graphs live after a scan
+finishes. Currently selectable between Neo4j (OSS / local dev default) and
+AWS Neptune (hosted dev/staging/prod). Backend is picked by the
+`ATTACK_PATHS_SINK_DATABASE` setting at process init.
+
+This package exposes the public factory API; the implementation lives in
+`api.attack_paths.sink.factory`.
+"""
+
+from api.attack_paths.sink.factory import (
+ SinkBackend,
+ close,
+ get_backend,
+ get_backend_for_name,
+ get_backend_for_scan,
+ init,
+)
+
+__all__ = [
+ "SinkBackend",
+ "close",
+ "get_backend",
+ "get_backend_for_name",
+ "get_backend_for_scan",
+ "init",
+]
diff --git a/api/src/backend/api/attack_paths/sink/base.py b/api/src/backend/api/attack_paths/sink/base.py
new file mode 100644
index 0000000000..0134e0a41f
--- /dev/null
+++ b/api/src/backend/api/attack_paths/sink/base.py
@@ -0,0 +1,94 @@
+"""Protocol every sink backend must implement."""
+
+from contextlib import AbstractContextManager
+from typing import Any, Protocol
+
+import neo4j
+
+
+class SinkDatabase(Protocol):
+ """Contract for the persistent attack-paths graph store.
+
+ The `database` argument is an opaque identifier passed through from the
+ legacy `database.py` API surface. On Neo4j it is the per-tenant database
+ name (e.g. `db-tenant-{uuid}`). On Neptune it is ignored (the cluster
+ has a single graph, and isolation is label-based).
+ """
+
+ sync_batch_size: int
+
+ def init(self) -> None: ...
+
+ def close(self) -> None: ...
+
+ def verify_connectivity(self) -> None:
+ """Raise if the backend the API read path uses is unreachable.
+
+ Neo4j verifies its single driver. Neptune verifies the reader
+ driver (the endpoint the API serves reads from); on single-endpoint
+ clusters the reader aliases the writer, so that path is covered too.
+ Used by the readiness probe; must not block longer than the caller's
+ probe budget.
+ """
+ ...
+
+ def get_session(
+ self,
+ database: str | None = None,
+ default_access_mode: str | None = None,
+ ) -> AbstractContextManager: ...
+
+ def execute_read_query(
+ self,
+ database: str,
+ cypher: str,
+ parameters: dict[str, Any] | None = None,
+ ) -> neo4j.graph.Graph: ...
+
+ def create_database(self, database: str) -> None: ...
+
+ def drop_database(self, database: str) -> None: ...
+
+ def drop_subgraph(self, database: str, provider_id: str) -> int: ...
+
+ def has_provider_data(self, database: str, provider_id: str) -> bool: ...
+
+ def clear_cache(self, database: str) -> None: ...
+
+ def ensure_sync_indexes(self, database: str) -> None:
+ """Create any index needed for the sync write path.
+
+ Called once at the start of each provider sync; must be idempotent.
+ Neo4j creates a `_provider_element_id` index on `_ProviderResource`;
+ Neptune is a no-op (its `~id` lookup needs no index).
+ """
+ ...
+
+ def write_nodes(
+ self,
+ database: str,
+ labels: str,
+ rows: list[dict[str, Any]],
+ ) -> None:
+ """Upsert a batch of nodes into the sink.
+
+ `labels` is a pre-rendered Cypher label string ready to drop after
+ the node variable (e.g. `` `AWSUser`:`_ProviderResource`:`_Tenant_x` ``).
+ Each row carries `provider_element_id` and `props`.
+ """
+ ...
+
+ def write_relationships(
+ self,
+ database: str,
+ rel_type: str,
+ provider_id: str,
+ rows: list[dict[str, Any]],
+ ) -> None:
+ """Upsert a batch of relationships into the sink.
+
+ Each row carries `start_element_id`, `end_element_id`,
+ `provider_element_id` and `props`. `rel_type` is the relationship
+ type (already a valid Cypher identifier).
+ """
+ ...
diff --git a/api/src/backend/api/attack_paths/sink/drop.py b/api/src/backend/api/attack_paths/sink/drop.py
new file mode 100644
index 0000000000..be13a394f5
--- /dev/null
+++ b/api/src/backend/api/attack_paths/sink/drop.py
@@ -0,0 +1,81 @@
+"""Shared batched deletion helpers for sink backends."""
+
+import logging
+import time
+from typing import Any
+
+RELATIONSHIP_DELETE_QUERY_TEMPLATES = {
+ "outgoing relationship": """
+ MATCH (n:`{provider_label}`)-[r]->()
+ WITH r LIMIT $batch_size
+ DELETE r
+ RETURN COUNT(r) AS deleted_rels_count
+ """,
+ "incoming relationship": """
+ MATCH (n:`{provider_label}`)<-[r]-()
+ WITH r LIMIT $batch_size
+ DELETE r
+ RETURN COUNT(r) AS deleted_rels_count
+ """,
+}
+
+NODE_DELETE_QUERY_TEMPLATE = """
+ MATCH (n:{provider_resource_label}:`{provider_label}`)
+ WITH n LIMIT $batch_size
+ DELETE n
+ RETURN COUNT(n) AS deleted_nodes_count
+ """
+
+
+def delete_batches(
+ *,
+ session: Any,
+ logger: logging.Logger,
+ log_target: str,
+ provider_id: str,
+ query: str,
+ phase: str,
+ count_key: str,
+ total_key: str,
+ deleted_key: str,
+ initial_total: int,
+ batch_size: int,
+ drop_t0: float,
+) -> tuple[int, int]:
+ def delete_batch(tx: Any) -> int:
+ record = tx.run(query, {"batch_size": batch_size}).single()
+ return (record[count_key] if record else 0) or 0
+
+ deleted_total = initial_total
+ batches = 0
+ while True:
+ logger.info(
+ "Deleting %s batch from %s "
+ "(provider=%s, batch=%s, total_%s=%s, elapsed=%.3fs)",
+ phase,
+ log_target,
+ provider_id,
+ batches + 1,
+ total_key,
+ deleted_total,
+ time.perf_counter() - drop_t0,
+ )
+ deleted = session.execute_write(delete_batch)
+ if deleted == 0:
+ return deleted_total, batches
+
+ batches += 1
+ deleted_total += deleted
+ logger.info(
+ "Deleted %s batch from %s "
+ "(provider=%s, batch=%s, %s=%s, total_%s=%s, elapsed=%.3fs)",
+ phase,
+ log_target,
+ provider_id,
+ batches,
+ deleted_key,
+ deleted,
+ total_key,
+ deleted_total,
+ time.perf_counter() - drop_t0,
+ )
diff --git a/api/src/backend/api/attack_paths/sink/factory.py b/api/src/backend/api/attack_paths/sink/factory.py
new file mode 100644
index 0000000000..ad2116fa40
--- /dev/null
+++ b/api/src/backend/api/attack_paths/sink/factory.py
@@ -0,0 +1,134 @@
+"""Sink backend factory and process-wide handle cache.
+
+Picks the active backend from `settings.ATTACK_PATHS_SINK_DATABASE` at first
+use, holds the active backend plus any secondary backends needed to serve
+scans written under the previous configuration, and tears them all down on
+process shutdown. Imported via `from api.attack_paths import sink as
+sink_module`.
+"""
+
+import threading
+from enum import StrEnum, auto
+
+from api.attack_paths.sink.base import SinkDatabase
+from api.models import AttackPathsScan
+from django.conf import settings
+
+# Backend names
+
+
+class SinkBackend(StrEnum):
+ NEO4J = auto()
+ NEPTUNE = auto()
+
+
+# Backend cache
+
+_backend: SinkDatabase | None = None
+_secondary_backends: dict[SinkBackend, SinkDatabase] = {}
+_lock = threading.Lock()
+
+
+def _resolve_setting() -> SinkBackend:
+ raw = settings.ATTACK_PATHS_SINK_DATABASE.lower()
+ try:
+ return SinkBackend(raw)
+
+ except ValueError:
+ valid = sorted(b.value for b in SinkBackend)
+ raise RuntimeError(
+ f"ATTACK_PATHS_SINK_DATABASE must be one of {valid}; got {raw!r}"
+ )
+
+
+def _build_backend(name: SinkBackend) -> SinkDatabase:
+ if name is SinkBackend.NEO4J:
+ from api.attack_paths.sink.neo4j import Neo4jSink
+
+ return Neo4jSink()
+
+ if name is SinkBackend.NEPTUNE:
+ from api.attack_paths.sink.neptune import NeptuneSink
+
+ return NeptuneSink()
+
+ raise RuntimeError(f"Unknown sink backend {name!r}")
+
+
+# Lifecycle
+
+
+def init(name: SinkBackend | str | None = None) -> SinkDatabase:
+ """Initialize the configured sink backend. Idempotent."""
+ global _backend
+ if _backend is not None:
+ return _backend
+
+ with _lock:
+ if _backend is None:
+ resolved = SinkBackend(name) if name else _resolve_setting()
+ backend = _build_backend(resolved)
+ backend.init()
+ _backend = backend
+
+ return _backend
+
+
+def close() -> None:
+ """Close the active backend and every cached secondary backend."""
+ global _backend
+ with _lock:
+ backends = [
+ b for b in (_backend, *_secondary_backends.values()) if b is not None
+ ]
+ _backend = None
+ _secondary_backends.clear()
+
+ for backend in backends:
+ try:
+ backend.close()
+
+ except Exception: # pragma: no cover - best-effort
+ pass
+
+
+def get_backend() -> SinkDatabase:
+ """Return the active sink. Initializes on first call."""
+ return init()
+
+
+# Per-scan routing
+
+
+def get_backend_for_scan(scan: AttackPathsScan) -> SinkDatabase:
+ """Route reads by the sink that stores this scan's graph."""
+ raw_backend = getattr(scan, "sink_backend", SinkBackend.NEO4J.value)
+ if not isinstance(raw_backend, str):
+ raw_backend = SinkBackend.NEO4J.value
+ return get_backend_for_name(raw_backend)
+
+
+def get_backend_for_name(name: SinkBackend | str) -> SinkDatabase:
+ """Return the backend named by persisted scan metadata."""
+ resolved = SinkBackend(name)
+ if resolved is _resolve_setting():
+ return get_backend()
+
+ return _build_backend_cached(resolved)
+
+
+def _build_backend_cached(name: SinkBackend) -> SinkDatabase:
+ # TODO: drop after Neptune cutover
+ # Needed only during cutover to serve Neo4j-written scans from a Neptune-
+ # configured API pod (and vice versa). Once every scan is on Neptune,
+ # `get_backend_for_scan` becomes a one-liner returning `get_backend()`.
+ if name in _secondary_backends:
+ return _secondary_backends[name]
+
+ with _lock:
+ if name not in _secondary_backends:
+ backend = _build_backend(name)
+ backend.init()
+ _secondary_backends[name] = backend
+
+ return _secondary_backends[name]
diff --git a/api/src/backend/api/attack_paths/sink/neo4j.py b/api/src/backend/api/attack_paths/sink/neo4j.py
new file mode 100644
index 0000000000..c820ed9d93
--- /dev/null
+++ b/api/src/backend/api/attack_paths/sink/neo4j.py
@@ -0,0 +1,419 @@
+"""Neo4j sink implementation.
+
+Owns a Neo4j driver independent from the staging driver. On OSS and local dev
+this is the only sink; on hosted deployments it runs only as a legacy read
+path while phase-1 drains tenant DBs.
+"""
+
+import atexit
+import logging
+import threading
+import time
+from collections.abc import Iterator
+from contextlib import AbstractContextManager, contextmanager
+from typing import Any
+
+import neo4j
+import neo4j.exceptions
+from api.attack_paths.retryable_session import RetryableSession
+from api.attack_paths.sink.base import SinkDatabase
+from api.attack_paths.sink.drop import (
+ NODE_DELETE_QUERY_TEMPLATE,
+ RELATIONSHIP_DELETE_QUERY_TEMPLATES,
+ delete_batches,
+)
+from config.env import env
+from django.conf import settings
+
+logging.getLogger("neo4j").setLevel(logging.ERROR)
+logging.getLogger("neo4j").propagate = False
+
+logger = logging.getLogger(__name__)
+
+SERVICE_UNAVAILABLE_MAX_RETRIES = env.int(
+ "ATTACK_PATHS_SERVICE_UNAVAILABLE_MAX_RETRIES", default=3
+)
+READ_QUERY_TIMEOUT_SECONDS = env.int(
+ "ATTACK_PATHS_READ_QUERY_TIMEOUT_SECONDS", default=30
+)
+CONN_ACQUISITION_TIMEOUT = env.int("NEO4J_CONN_ACQUISITION_TIMEOUT", default=15)
+# TCP connect timeout, ordered below the acquisition timeout so an unreachable
+# host can't pin a request or the readiness probe longer than this.
+CONNECTION_TIMEOUT = env.int("NEO4J_CONNECTION_TIMEOUT", default=5)
+MAX_CONNECTION_LIFETIME = env.int("NEO4J_MAX_CONNECTION_LIFETIME", default=7200)
+MAX_CONNECTION_POOL_SIZE = env.int("NEO4J_MAX_CONNECTION_POOL_SIZE", default=50)
+
+READ_EXCEPTION_CODES = [
+ "Neo.ClientError.Statement.AccessMode",
+ "Neo.ClientError.Procedure.ProcedureNotFound",
+]
+CLIENT_STATEMENT_EXCEPTION_PREFIX = "Neo.ClientError.Statement."
+DATABASE_NOT_FOUND_CODE = "Neo.ClientError.Database.DatabaseNotFound"
+
+
+class Neo4jSink(SinkDatabase):
+ """Neo4j-backed sink. Multi-database cluster; tenant isolation is physical."""
+
+ sync_batch_size = env.int("ATTACK_PATHS_NEO4J_SYNC_BATCH_SIZE", default=1000)
+
+ def __init__(self) -> None:
+ self._driver: neo4j.Driver | None = None
+ self._lock = threading.Lock()
+ self._atexit_registered = False
+
+ # Driver
+
+ def _config(self) -> dict:
+ return settings.DATABASES["neo4j"]
+
+ def _uri(self) -> str:
+ cfg = self._config()
+ host = cfg["HOST"]
+ port = cfg["PORT"]
+ if not host or not port:
+ raise RuntimeError(
+ "NEO4J_HOST / NEO4J_PORT must be set when ATTACK_PATHS_SINK_DATABASE=neo4j"
+ )
+ return f"bolt://{host}:{port}"
+
+ def init(self) -> neo4j.Driver:
+ if self._driver is not None:
+ return self._driver
+ with self._lock:
+ if self._driver is None:
+ cfg = self._config()
+ self._driver = neo4j.GraphDatabase.driver(
+ self._uri(),
+ auth=(cfg["USER"], cfg["PASSWORD"]),
+ keep_alive=True,
+ max_connection_lifetime=MAX_CONNECTION_LIFETIME,
+ connection_timeout=CONNECTION_TIMEOUT,
+ connection_acquisition_timeout=CONN_ACQUISITION_TIMEOUT,
+ max_connection_pool_size=MAX_CONNECTION_POOL_SIZE,
+ )
+ # Eager connectivity check is best-effort:
+ # A Neo4j that is down at boot must not crash the process, same degradation model as Postgres
+ # The driver reconnects lazily on first use
+ # /health/ready surfaces the outage until it recovers
+ try:
+ self._driver.verify_connectivity()
+
+ except Exception:
+ logger.warning(
+ "Neo4j sink unreachable at init; continuing with a lazily-reconnecting driver",
+ exc_info=True,
+ )
+
+ if not self._atexit_registered:
+ atexit.register(self.close)
+ self._atexit_registered = True
+ return self._driver
+
+ def _get_driver(self) -> neo4j.Driver:
+ return self.init()
+
+ def verify_connectivity(self) -> None:
+ self._get_driver().verify_connectivity()
+
+ def close(self) -> None:
+ with self._lock:
+ if self._driver is not None:
+ try:
+ self._driver.close()
+ finally:
+ self._driver = None
+
+ # Sessions
+
+ @contextmanager
+ def get_session(
+ self,
+ database: str | None = None,
+ default_access_mode: str | None = None,
+ ) -> Iterator[RetryableSession]:
+ from api.attack_paths.database import (
+ ClientStatementException,
+ GraphDatabaseQueryException,
+ WriteQueryNotAllowedException,
+ )
+
+ session_wrapper: RetryableSession | None = None
+ try:
+ session_wrapper = RetryableSession(
+ session_factory=lambda: self._get_driver().session(
+ database=database, default_access_mode=default_access_mode
+ ),
+ max_retries=SERVICE_UNAVAILABLE_MAX_RETRIES,
+ )
+ yield session_wrapper
+
+ except neo4j.exceptions.Neo4jError as exc:
+ if (
+ default_access_mode == neo4j.READ_ACCESS
+ and exc.code
+ and exc.code in READ_EXCEPTION_CODES
+ ):
+ raise WriteQueryNotAllowedException(
+ message="Read query not allowed", code=READ_EXCEPTION_CODES[0]
+ )
+
+ message = exc.message if exc.message is not None else str(exc)
+ if exc.code and exc.code.startswith(CLIENT_STATEMENT_EXCEPTION_PREFIX):
+ raise ClientStatementException(message=message, code=exc.code)
+ raise GraphDatabaseQueryException(message=message, code=exc.code)
+
+ finally:
+ if session_wrapper is not None:
+ session_wrapper.close()
+
+ # Operations
+
+ def execute_read_query(
+ self,
+ database: str,
+ cypher: str,
+ parameters: dict[str, Any] | None = None,
+ ) -> neo4j.graph.Graph:
+ with self.get_session(
+ database, default_access_mode=neo4j.READ_ACCESS
+ ) as session:
+
+ def _run(tx: neo4j.ManagedTransaction) -> neo4j.graph.Graph:
+ result = tx.run(
+ cypher, parameters or {}, timeout=READ_QUERY_TIMEOUT_SECONDS
+ )
+ return result.graph()
+
+ return session.execute_read(_run)
+
+ def create_database(self, database: str) -> None:
+ with self.get_session() as session:
+ session.run(
+ "CREATE DATABASE $database IF NOT EXISTS", {"database": database}
+ )
+
+ def drop_database(self, database: str) -> None:
+ with self.get_session() as session:
+ session.run(f"DROP DATABASE `{database}` IF EXISTS DESTROY DATA")
+
+ def drop_subgraph(self, database: str, provider_id: str) -> int:
+ """Delete all nodes for a provider from a tenant database, batched.
+
+ Deletes relationships then nodes in batches (not `DETACH DELETE`) so a
+ dense provider's graph cannot exceed Neo4j's transaction memory limit.
+ Silently returns 0 if the database doesn't exist.
+ """
+ from api.attack_paths.database import GraphDatabaseQueryException
+ from tasks.jobs.attack_paths.config import (
+ GRAPH_MUTATION_BATCH_SIZE,
+ PROVIDER_RESOURCE_LABEL,
+ get_provider_label,
+ )
+
+ provider_label = get_provider_label(provider_id)
+ deleted_nodes = deleted_relationships = 0
+ relationship_batches = node_batches = 0
+ drop_t0 = time.perf_counter()
+
+ logger.info(
+ "Dropping provider graph from Neo4j sink database %s "
+ "(provider=%s, provider_label=%s)",
+ database,
+ provider_id,
+ provider_label,
+ )
+
+ try:
+ logger.info(
+ "Opening Neo4j sink session for provider graph drop "
+ "(database=%s, provider=%s)",
+ database,
+ provider_id,
+ )
+ with self.get_session(database) as session:
+ logger.info(
+ "Opened Neo4j sink session for provider graph drop "
+ "(database=%s, provider=%s)",
+ database,
+ provider_id,
+ )
+ log_target = f"Neo4j sink database {database}"
+ for (
+ phase,
+ query_template,
+ ) in RELATIONSHIP_DELETE_QUERY_TEMPLATES.items():
+ deleted_relationships, phase_batches = delete_batches(
+ session=session,
+ logger=logger,
+ log_target=log_target,
+ provider_id=provider_id,
+ query=query_template.format(provider_label=provider_label),
+ phase=phase,
+ count_key="deleted_rels_count",
+ total_key="rels",
+ deleted_key="deleted_rels",
+ initial_total=deleted_relationships,
+ batch_size=GRAPH_MUTATION_BATCH_SIZE,
+ drop_t0=drop_t0,
+ )
+ relationship_batches += phase_batches
+
+ deleted_nodes, node_batches = delete_batches(
+ session=session,
+ logger=logger,
+ log_target=log_target,
+ provider_id=provider_id,
+ query=NODE_DELETE_QUERY_TEMPLATE.format(
+ provider_label=provider_label,
+ provider_resource_label=PROVIDER_RESOURCE_LABEL,
+ ),
+ phase="node",
+ count_key="deleted_nodes_count",
+ total_key="nodes",
+ deleted_key="deleted_nodes",
+ initial_total=0,
+ batch_size=GRAPH_MUTATION_BATCH_SIZE,
+ drop_t0=drop_t0,
+ )
+
+ except GraphDatabaseQueryException as exc:
+ if exc.code == DATABASE_NOT_FOUND_CODE:
+ logger.info(
+ "Skipped provider graph drop from Neo4j sink database %s "
+ "(provider=%s, reason=database_not_found, elapsed=%.3fs)",
+ database,
+ provider_id,
+ time.perf_counter() - drop_t0,
+ )
+ return 0
+ raise
+
+ logger.info(
+ "Finished dropping provider graph from Neo4j sink database %s "
+ "(provider=%s, relationship_batches=%s, deleted_rels=%s, "
+ "node_batches=%s, deleted_nodes=%s, elapsed=%.3fs)",
+ database,
+ provider_id,
+ relationship_batches,
+ deleted_relationships,
+ node_batches,
+ deleted_nodes,
+ time.perf_counter() - drop_t0,
+ )
+ return deleted_nodes
+
+ def has_provider_data(self, database: str, provider_id: str) -> bool:
+ from api.attack_paths.database import GraphDatabaseQueryException
+ from tasks.jobs.attack_paths.config import (
+ PROVIDER_RESOURCE_LABEL,
+ get_provider_label,
+ )
+
+ provider_label = get_provider_label(provider_id)
+ query = (
+ f"MATCH (n:{PROVIDER_RESOURCE_LABEL}:`{provider_label}`) RETURN 1 LIMIT 1"
+ )
+ try:
+ with self.get_session(
+ database, default_access_mode=neo4j.READ_ACCESS
+ ) as session:
+ result = session.run(query)
+ return result.single() is not None
+
+ except GraphDatabaseQueryException as exc:
+ if exc.code == DATABASE_NOT_FOUND_CODE:
+ return False
+ raise
+
+ def clear_cache(self, database: str) -> None:
+ from api.attack_paths.database import GraphDatabaseQueryException
+
+ try:
+ with self.get_session(database) as session:
+ session.run("CALL db.clearQueryCaches()")
+ except GraphDatabaseQueryException as exc:
+ logger.warning(
+ f"Failed to clear query cache for database `{database}`: {exc}"
+ )
+
+ # Sync write path
+
+ def ensure_sync_indexes(self, database: str) -> None:
+ """Create the `_provider_element_id` lookup index on `_ProviderResource`.
+
+ Every synced node carries the `_ProviderResource` label, so a single
+ index covers both node-upserts and relationship endpoint MATCHes.
+ Without this index the rel sync degrades to a label scan per row and
+ large provider syncs become unworkable.
+ """
+ from tasks.jobs.attack_paths.config import (
+ PROVIDER_ELEMENT_ID_PROPERTY,
+ PROVIDER_RESOURCE_LABEL,
+ )
+
+ query = (
+ f"CREATE INDEX provider_element_id_idx IF NOT EXISTS "
+ f"FOR (n:`{PROVIDER_RESOURCE_LABEL}`) "
+ f"ON (n.`{PROVIDER_ELEMENT_ID_PROPERTY}`)"
+ )
+ with self.get_session(database) as session:
+ session.execute_write(lambda tx: tx.run(query).consume())
+
+ def write_nodes(
+ self,
+ database: str,
+ labels: str,
+ rows: list[dict[str, Any]],
+ ) -> None:
+ if not rows:
+ return
+ from tasks.jobs.attack_paths.config import (
+ PROVIDER_ELEMENT_ID_PROPERTY,
+ PROVIDER_RESOURCE_LABEL,
+ )
+
+ query = f"""
+ UNWIND $rows AS row
+ MERGE (n:`{PROVIDER_RESOURCE_LABEL}` {{`{PROVIDER_ELEMENT_ID_PROPERTY}`: row.provider_element_id}})
+ SET n:{labels}
+ SET n += row.props
+ """
+ with self.get_session(database) as session:
+ session.execute_write(lambda tx: tx.run(query, {"rows": rows}).consume())
+
+ def write_relationships(
+ self,
+ database: str,
+ rel_type: str,
+ provider_id: str,
+ rows: list[dict[str, Any]],
+ ) -> None:
+ if not rows:
+ return
+ from tasks.jobs.attack_paths.config import (
+ PROVIDER_ELEMENT_ID_PROPERTY,
+ PROVIDER_RESOURCE_LABEL,
+ get_provider_label,
+ )
+
+ provider_label = get_provider_label(provider_id)
+ query = f"""
+ UNWIND $rows AS row
+ MATCH (s:`{PROVIDER_RESOURCE_LABEL}`:`{provider_label}` {{`{PROVIDER_ELEMENT_ID_PROPERTY}`: row.start_element_id}})
+ MATCH (t:`{PROVIDER_RESOURCE_LABEL}`:`{provider_label}` {{`{PROVIDER_ELEMENT_ID_PROPERTY}`: row.end_element_id}})
+ MERGE (s)-[r:`{rel_type}` {{`{PROVIDER_ELEMENT_ID_PROPERTY}`: row.provider_element_id}}]->(t)
+ SET r += row.props
+ """
+ with self.get_session(database) as session:
+ session.execute_write(lambda tx: tx.run(query, {"rows": rows}).consume())
+
+ # For compatibility with test harnesses that patch the concrete driver
+ def get_driver(self) -> neo4j.Driver:
+ return self._get_driver()
+
+
+# Helper for tests / external callers that want a writer session specifically
+def get_read_session(
+ sink: Neo4jSink, database: str
+) -> AbstractContextManager[RetryableSession]:
+ return sink.get_session(database, default_access_mode=neo4j.READ_ACCESS)
diff --git a/api/src/backend/api/attack_paths/sink/neptune.py b/api/src/backend/api/attack_paths/sink/neptune.py
new file mode 100644
index 0000000000..022e3c8669
--- /dev/null
+++ b/api/src/backend/api/attack_paths/sink/neptune.py
@@ -0,0 +1,519 @@
+"""AWS Neptune sink implementation.
+
+Dual Bolt drivers: one against the writer endpoint for workers, one against
+the reader endpoint for the API read path. If `NEPTUNE_READER_ENDPOINT` is
+unset the reader falls back to the writer driver so single-node clusters work.
+
+Neptune is single-database. The `database` argument on the SinkDatabase
+protocol is ignored; tenant / provider isolation is enforced by labels that
+the sync step already writes on every node (see tasks/jobs/attack_paths/sync.py).
+
+SigV4 auth lives at the bottom of this file as `neptune_auth_provider`. The
+neo4j driver invokes the returned callable on each token refresh.
+"""
+
+import atexit
+import datetime
+import json
+import logging
+import threading
+import time
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
+from typing import Any
+from urllib.parse import urlsplit
+
+import neo4j
+import neo4j.exceptions
+from api.attack_paths.retryable_session import RetryableSession, RetryExhaustedError
+from api.attack_paths.sink.base import SinkDatabase
+from api.attack_paths.sink.drop import (
+ NODE_DELETE_QUERY_TEMPLATE,
+ RELATIONSHIP_DELETE_QUERY_TEMPLATES,
+ delete_batches,
+)
+from botocore.auth import SigV4Auth
+from botocore.awsrequest import AWSRequest
+from botocore.session import Session as BotoSession
+from config.env import env
+from django.conf import settings
+from neo4j.auth_management import AuthManagers, ExpiringAuth
+
+logging.getLogger("neo4j").setLevel(logging.ERROR)
+logging.getLogger("neo4j").propagate = False
+
+logger = logging.getLogger(__name__)
+
+SERVICE_UNAVAILABLE_MAX_RETRIES = env.int(
+ "ATTACK_PATHS_SERVICE_UNAVAILABLE_MAX_RETRIES", default=3
+)
+READ_QUERY_TIMEOUT_SECONDS = env.int(
+ "ATTACK_PATHS_READ_QUERY_TIMEOUT_SECONDS", default=30
+)
+# Neptune serverless cold-start can be >30s; give the driver room
+CONN_ACQUISITION_TIMEOUT = env.int("NEPTUNE_CONN_ACQUISITION_TIMEOUT", default=60)
+# TCP connect timeout, ordered below the acquisition timeout so an unreachable
+# endpoint can't pin a request or the readiness probe longer than this. Kept
+# generous: cold-start delays query execution, not the socket connect.
+CONNECTION_TIMEOUT = env.int("NEPTUNE_CONNECTION_TIMEOUT", default=10)
+# Roll connections hourly so SigV4 rotations and cert refreshes don't strand long-lived pool entries
+MAX_CONNECTION_LIFETIME = env.int("NEPTUNE_MAX_CONNECTION_LIFETIME", default=3600)
+MAX_CONNECTION_POOL_SIZE = env.int("NEPTUNE_MAX_CONNECTION_POOL_SIZE", default=50)
+NEPTUNE_WRITE_RETRY_DELAY_SECONDS = 2
+
+READ_EXCEPTION_CODES = [
+ "Neo.ClientError.Statement.AccessMode",
+ "Neo.ClientError.Procedure.ProcedureNotFound",
+]
+CLIENT_STATEMENT_EXCEPTION_PREFIX = "Neo.ClientError.Statement."
+RETRYABLE_WRITE_ERROR_FRAGMENTS = (
+ "Operation failed due to conflicting concurrent operations",
+ "Operation terminated (deadline exceeded)",
+)
+
+# Refresh 60s before the 5-minute SigV4 window closes
+SIGV4_TOKEN_LIFETIME_MINUTES = 4
+
+
+def _is_retryable_write_error(exc: Exception) -> bool:
+ if not isinstance(exc, neo4j.exceptions.Neo4jError):
+ return False
+ message = exc.message or ""
+ return any(fragment in message for fragment in RETRYABLE_WRITE_ERROR_FRAGMENTS)
+
+
+class NeptuneSink(SinkDatabase):
+ """Neptune-backed sink. Single database; isolation is label-based."""
+
+ sync_batch_size = env.int("ATTACK_PATHS_NEPTUNE_SYNC_BATCH_SIZE", default=500)
+
+ def __init__(self) -> None:
+ self._writer: neo4j.Driver | None = None
+ self._reader: neo4j.Driver | None = None
+ self._lock = threading.Lock()
+ self._atexit_registered = False
+
+ # Config
+
+ def _config(self) -> dict:
+ return settings.DATABASES["neptune"]
+
+ def _bolt_uri(self, endpoint: str, port: str) -> str:
+ return f"bolt+s://{endpoint}:{port}"
+
+ def _https_url(self, endpoint: str, port: str) -> str:
+ return f"https://{endpoint}:{port}"
+
+ def _build_driver(self, endpoint: str) -> neo4j.Driver:
+ cfg = self._config()
+ port = cfg["PORT"]
+ region = cfg["REGION"]
+ if not endpoint or not region:
+ raise RuntimeError(
+ "NEPTUNE_WRITER_ENDPOINT and AWS_REGION must be set when "
+ "ATTACK_PATHS_SINK_DATABASE=neptune"
+ )
+ return neo4j.GraphDatabase.driver(
+ self._bolt_uri(endpoint, port),
+ auth=AuthManagers.bearer(
+ neptune_auth_provider(region, self._https_url(endpoint, port))
+ ),
+ keep_alive=True,
+ max_connection_lifetime=MAX_CONNECTION_LIFETIME,
+ connection_timeout=CONNECTION_TIMEOUT,
+ connection_acquisition_timeout=CONN_ACQUISITION_TIMEOUT,
+ max_connection_pool_size=MAX_CONNECTION_POOL_SIZE,
+ max_transaction_retry_time=0,
+ )
+
+ # Lifecycle
+
+ def init(self) -> None:
+ if self._writer is not None:
+ return
+ with self._lock:
+ if self._writer is None:
+ cfg = self._config()
+ writer_endpoint = cfg["WRITER_ENDPOINT"]
+ reader_endpoint = cfg["READER_ENDPOINT"] or writer_endpoint
+
+ # Eager connectivity checks are best-effort
+ # A Neptune that is down at boot must not crash the process, same degradation model as Postgres
+ # Drivers reconnect lazily on first use
+ # /health/ready surfaces the outage until it recovers
+ self._writer = self._build_driver(writer_endpoint)
+ self._verify_best_effort(self._writer, "writer")
+
+ if reader_endpoint == writer_endpoint:
+ self._reader = self._writer
+
+ else:
+ self._reader = self._build_driver(reader_endpoint)
+ self._verify_best_effort(self._reader, "reader")
+
+ if not self._atexit_registered:
+ atexit.register(self.close)
+ self._atexit_registered = True
+
+ def close(self) -> None:
+ with self._lock:
+ # `Driver.close()` is idempotent, so closing the same driver twice
+ # (when reader aliases writer on single-endpoint configs) is safe
+ for driver in (self._reader, self._writer):
+ if driver is None:
+ continue
+ try:
+ driver.close()
+ except Exception: # pragma: no cover - best-effort
+ pass
+ self._writer = None
+ self._reader = None
+
+ # Sessions
+
+ def _get_writer(self) -> neo4j.Driver:
+ self.init()
+ assert self._writer is not None
+ return self._writer
+
+ def _get_reader(self) -> neo4j.Driver:
+ self.init()
+ assert self._reader is not None
+ return self._reader
+
+ @staticmethod
+ def _verify_best_effort(driver: neo4j.Driver, role: str) -> None:
+ try:
+ driver.verify_connectivity()
+
+ except Exception:
+ logger.warning(
+ "Neptune %s endpoint unreachable at init; continuing with a lazily-reconnecting driver",
+ role,
+ exc_info=True,
+ )
+
+ def verify_connectivity(self) -> None:
+ # The API read path uses the reader driver
+ # On single-endpoint clusters it aliases the writer, so this also covers the writer
+ # A writer-only outage is a workers' concern (no HTTP probe there) and deliberately does not fail API readiness
+ self._get_reader().verify_connectivity()
+
+ @contextmanager
+ def get_session(
+ self,
+ database: str | None = None, # noqa: ARG002 - ignored on Neptune
+ default_access_mode: str | None = None,
+ ) -> Iterator[RetryableSession]:
+ from api.attack_paths.database import (
+ ClientStatementException,
+ GraphDatabaseQueryException,
+ NeptuneWriteRetryExhaustedException,
+ WriteQueryNotAllowedException,
+ )
+
+ driver = (
+ self._get_reader()
+ if default_access_mode == neo4j.READ_ACCESS
+ else self._get_writer()
+ )
+
+ session_wrapper: RetryableSession | None = None
+ try:
+ is_write_session = default_access_mode != neo4j.READ_ACCESS
+ session_wrapper = RetryableSession(
+ session_factory=lambda: driver.session(
+ default_access_mode=default_access_mode
+ ),
+ max_retries=SERVICE_UNAVAILABLE_MAX_RETRIES,
+ retry_if=_is_retryable_write_error if is_write_session else None,
+ initial_retry_delay_seconds=(
+ NEPTUNE_WRITE_RETRY_DELAY_SECONDS if is_write_session else 0
+ ),
+ retry_context="Neptune write" if is_write_session else None,
+ )
+ yield session_wrapper
+
+ except RetryExhaustedError as exc:
+ last_error = exc.last_error
+ raise NeptuneWriteRetryExhaustedException(
+ message=str(exc),
+ code=getattr(last_error, "code", None),
+ ) from last_error
+
+ except neo4j.exceptions.Neo4jError as exc:
+ if (
+ default_access_mode == neo4j.READ_ACCESS
+ and exc.code
+ and exc.code in READ_EXCEPTION_CODES
+ ):
+ raise WriteQueryNotAllowedException(
+ message="Read query not allowed", code=READ_EXCEPTION_CODES[0]
+ )
+
+ message = exc.message if exc.message is not None else str(exc)
+ if exc.code and exc.code.startswith(CLIENT_STATEMENT_EXCEPTION_PREFIX):
+ raise ClientStatementException(message=message, code=exc.code)
+ raise GraphDatabaseQueryException(message=message, code=exc.code)
+
+ finally:
+ if session_wrapper is not None:
+ session_wrapper.close()
+
+ # Operations
+
+ def execute_read_query(
+ self,
+ database: str, # noqa: ARG002 - ignored on Neptune
+ cypher: str,
+ parameters: dict[str, Any] | None = None,
+ ) -> neo4j.graph.Graph:
+ with self.get_session(default_access_mode=neo4j.READ_ACCESS) as session:
+
+ def _run(tx: neo4j.ManagedTransaction) -> neo4j.graph.Graph:
+ result = tx.run(
+ cypher, parameters or {}, timeout=READ_QUERY_TIMEOUT_SECONDS
+ )
+ return result.graph()
+
+ return session.execute_read(_run)
+
+ def create_database(self, database: str) -> None: # noqa: ARG002
+ # Neptune clusters are single-database; there is nothing to create.
+ return None
+
+ def drop_database(self, database: str) -> None: # noqa: ARG002
+ # Neptune clusters are single-database; there is nothing to drop.
+ return None
+
+ def drop_subgraph(self, database: str, provider_id: str) -> int: # noqa: ARG002
+ """Delete a provider's subgraph in two bounded phases.
+
+ Neptune write transactions are capped at ~2 minutes. A naive
+ `DETACH DELETE` on a label-scanned batch grows unbounded with graph
+ density (one node can drag thousands of relationships into the same
+ transaction). Instead:
+
+ 1. Delete relationships incident to provider nodes, one fixed-size
+ batch per transaction.
+ 2. Delete the now-orphaned nodes, one fixed-size batch per transaction.
+
+ Each transaction does work proportional to `batch_size`, never to the
+ graph's branching factor.
+ """
+ from tasks.jobs.attack_paths.config import (
+ GRAPH_MUTATION_BATCH_SIZE,
+ PROVIDER_RESOURCE_LABEL,
+ get_provider_label,
+ )
+
+ provider_label = get_provider_label(provider_id)
+ deleted_relationships = 0
+ relationship_batches = 0
+ node_batches = 0
+ drop_t0 = time.perf_counter()
+
+ logger.info(
+ "Dropping provider graph from Neptune sink "
+ "(provider=%s, provider_label=%s)",
+ provider_id,
+ provider_label,
+ )
+
+ logger.info(
+ "Opening Neptune writer session for provider graph drop (provider=%s)",
+ provider_id,
+ )
+ with self.get_session() as session:
+ logger.info(
+ "Opened Neptune writer session for provider graph drop (provider=%s)",
+ provider_id,
+ )
+ for phase, query_template in RELATIONSHIP_DELETE_QUERY_TEMPLATES.items():
+ deleted_relationships, phase_batches = delete_batches(
+ session=session,
+ logger=logger,
+ log_target="Neptune sink",
+ provider_id=provider_id,
+ query=query_template.format(provider_label=provider_label),
+ phase=phase,
+ count_key="deleted_rels_count",
+ total_key="rels",
+ deleted_key="deleted_rels",
+ initial_total=deleted_relationships,
+ batch_size=GRAPH_MUTATION_BATCH_SIZE,
+ drop_t0=drop_t0,
+ )
+ relationship_batches += phase_batches
+
+ deleted_nodes, node_batches = delete_batches(
+ session=session,
+ logger=logger,
+ log_target="Neptune sink",
+ provider_id=provider_id,
+ query=NODE_DELETE_QUERY_TEMPLATE.format(
+ provider_label=provider_label,
+ provider_resource_label=PROVIDER_RESOURCE_LABEL,
+ ),
+ phase="node",
+ count_key="deleted_nodes_count",
+ total_key="nodes",
+ deleted_key="deleted_nodes",
+ initial_total=0,
+ batch_size=GRAPH_MUTATION_BATCH_SIZE,
+ drop_t0=drop_t0,
+ )
+
+ logger.info(
+ "Finished dropping provider graph from Neptune sink "
+ "(provider=%s, relationship_batches=%s, deleted_rels=%s, "
+ "node_batches=%s, deleted_nodes=%s, elapsed=%.3fs)",
+ provider_id,
+ relationship_batches,
+ deleted_relationships,
+ node_batches,
+ deleted_nodes,
+ time.perf_counter() - drop_t0,
+ )
+ return deleted_nodes
+
+ def has_provider_data(self, database: str, provider_id: str) -> bool: # noqa: ARG002
+ from tasks.jobs.attack_paths.config import (
+ PROVIDER_RESOURCE_LABEL,
+ get_provider_label,
+ )
+
+ provider_label = get_provider_label(provider_id)
+ query = (
+ f"MATCH (n:{PROVIDER_RESOURCE_LABEL}:`{provider_label}`) RETURN 1 LIMIT 1"
+ )
+ with self.get_session(default_access_mode=neo4j.READ_ACCESS) as session:
+ result = session.run(query)
+ return result.single() is not None
+
+ def clear_cache(self, database: str) -> None: # noqa: ARG002
+ # Neptune has no user-facing cache-clear procedure; no-op.
+ return None
+
+ # Sync write path
+
+ def ensure_sync_indexes(self, database: str) -> None: # noqa: ARG002
+ # Neptune routes node and relationship lookups through `~id`, which is the cluster's primary key
+ # No additional index is needed or supported
+ return None
+
+ def write_nodes(
+ self,
+ database: str, # noqa: ARG002
+ labels: str,
+ rows: list[dict[str, Any]],
+ ) -> None:
+ if not rows:
+ return
+ from tasks.jobs.attack_paths.config import (
+ PROVIDER_ELEMENT_ID_PROPERTY,
+ PROVIDER_RESOURCE_LABEL,
+ )
+
+ # MERGE on `~id` is the documented and engine-optimized idempotent
+ # upsert pattern for Neptune openCypher. The label inside the MERGE
+ # matters: Neptune assigns a default `vertex` label to any node
+ # created without an explicit one, so we pin `_ProviderResource`
+ # (which every synced node carries anyway) at MERGE-time. Additional
+ # labels are added after
+ #
+ # We also write `_provider_element_id` as a regular property so
+ # non-sync code (drop_subgraph, query helpers) keeps a stable contract
+ # that doesn't know about `~id`
+ query = f"""
+ UNWIND $rows AS row
+ MERGE (n:`{PROVIDER_RESOURCE_LABEL}` {{`~id`: row.provider_element_id}})
+ SET n:{labels}
+ SET n += row.props
+ SET n.`{PROVIDER_ELEMENT_ID_PROPERTY}` = row.provider_element_id
+ """
+ with self.get_session() as session:
+ session.execute_write(lambda tx: tx.run(query, {"rows": rows}).consume())
+
+ def write_relationships(
+ self,
+ database: str, # noqa: ARG002
+ rel_type: str,
+ provider_id: str, # noqa: ARG002 - encoded in start/end `~id` already
+ rows: list[dict[str, Any]],
+ ) -> None:
+ if not rows:
+ return
+ from tasks.jobs.attack_paths.config import PROVIDER_ELEMENT_ID_PROPERTY
+
+ # `id(n) = $value` is Neptune's parameterized fast path; both endpoint
+ # MATCHes resolve in O(1) via the system `~id`, so per-row work stays
+ # bounded regardless of batch size
+ query = f"""
+ UNWIND $rows AS row
+ MATCH (s) WHERE id(s) = row.start_element_id
+ MATCH (e) WHERE id(e) = row.end_element_id
+ MERGE (s)-[r:`{rel_type}` {{`{PROVIDER_ELEMENT_ID_PROPERTY}`: row.provider_element_id}}]->(e)
+ SET r += row.props
+ """
+ with self.get_session() as session:
+ session.execute_write(lambda tx: tx.run(query, {"rows": rows}).consume())
+
+ # Test helpers
+
+ def get_writer(self) -> neo4j.Driver:
+ return self._get_writer()
+
+ def get_reader(self) -> neo4j.Driver:
+ return self._get_reader()
+
+
+# SigV4 auth provider
+
+
+class _NeptuneAuthToken(neo4j.Auth):
+ """Neo4j Auth backed by a SigV4-signed GET to `/opencypher`."""
+
+ def __init__(self, region: str, url: str) -> None:
+ session = BotoSession()
+ credentials = session.get_credentials()
+ if credentials is None:
+ raise RuntimeError(
+ "No AWS credentials available for Neptune SigV4 signing. "
+ "Ensure the boto3 credential chain can resolve."
+ )
+ credentials = credentials.get_frozen_credentials()
+
+ request = AWSRequest(method="GET", url=url + "/opencypher")
+ # SigV4 canonical Host must carry the real `host:port`
+ # Neptune runs on a non-default port (8182), so `.hostname` would drop it and break signing
+ request.headers.add_header("Host", urlsplit(url).netloc)
+ SigV4Auth(credentials, "neptune-db", region).add_auth(request)
+
+ auth_obj = {
+ header: request.headers[header]
+ for header in (
+ "Authorization",
+ "X-Amz-Date",
+ "X-Amz-Security-Token",
+ "Host",
+ )
+ if header in request.headers
+ }
+ auth_obj["HttpMethod"] = "GET"
+
+ super().__init__("basic", "username", json.dumps(auth_obj))
+
+
+def neptune_auth_provider(region: str, https_url: str) -> Callable[[], ExpiringAuth]:
+ """Return a callable the neo4j driver can invoke to refresh credentials."""
+
+ def _provider() -> ExpiringAuth:
+ token = _NeptuneAuthToken(region, https_url)
+ expires_at = (
+ datetime.datetime.now(datetime.UTC)
+ + datetime.timedelta(minutes=SIGV4_TOKEN_LIFETIME_MINUTES)
+ ).timestamp()
+ return ExpiringAuth(auth=token, expires_at=expires_at)
+
+ return _provider
diff --git a/api/src/backend/api/attack_paths/views_helpers.py b/api/src/backend/api/attack_paths/views_helpers.py
index bfb077abd0..1c1d3e7888 100644
--- a/api/src/backend/api/attack_paths/views_helpers.py
+++ b/api/src/backend/api/attack_paths/views_helpers.py
@@ -5,6 +5,7 @@ from typing import Any
import neo4j
from api.attack_paths import AttackPathsQueryDefinition
from api.attack_paths import database as graph_database
+from api.attack_paths import sink as sink_module
from api.attack_paths.cypher_sanitizer import (
inject_provider_label,
validate_custom_query,
@@ -14,7 +15,9 @@ from api.attack_paths.queries.schema import (
RAW_SCHEMA_URL,
get_cartography_schema_query,
)
+from api.models import AttackPathsScan
from config.custom_logging import BackendLogger
+from config.env import env
from rest_framework.exceptions import APIException, PermissionDenied, ValidationError
from tasks.jobs.attack_paths.config import (
INTERNAL_LABELS,
@@ -26,6 +29,10 @@ from tasks.jobs.attack_paths.config import (
logger = logging.getLogger(BackendLogger.API)
+def _custom_query_timeout_ms() -> int:
+ return env.int("ATTACK_PATHS_READ_QUERY_TIMEOUT_SECONDS", default=30) * 1000
+
+
# Predefined query helpers
@@ -102,13 +109,13 @@ def execute_query(
definition: AttackPathsQueryDefinition,
parameters: dict[str, Any],
provider_id: str,
+ scan: AttackPathsScan,
) -> dict[str, Any]:
try:
- graph = graph_database.execute_read_query(
- database=database_name,
- cypher=definition.cypher,
- parameters=parameters,
- )
+ # TODO: drop after Neptune cutover
+ # Route reads by the scan row's recorded sink, not by current settings.
+ backend = sink_module.get_backend_for_scan(scan)
+ graph = backend.execute_read_query(database_name, definition.cypher, parameters)
return _serialize_graph(graph, provider_id)
except graph_database.WriteQueryNotAllowedException:
@@ -142,22 +149,31 @@ def execute_custom_query(
database_name: str,
cypher: str,
provider_id: str,
+ scan: AttackPathsScan,
) -> dict[str, Any]:
# Defense-in-depth for custom queries:
- # 1. neo4j.READ_ACCESS — prevents mutations at the driver level
- # 2. inject_provider_label() — regex-based label injection scopes node patterns
- # 3. _serialize_graph() — post-query filter drops nodes without the provider label
+ # 1. `neo4j.READ_ACCESS` - prevents mutations at the driver level
+ # 2. `inject_provider_label()` - regex-based label injection scopes node patterns
+ # 3. `_serialize_graph()` - post-query filter drops nodes without the provider label
+ # 4. `USING QUERY:TIMEOUTMILLISECONDS` on Neptune - server-side runaway cutoff
#
# Layer 2 is best-effort (regex can't fully parse Cypher);
# layer 3 is the safety net that guarantees provider isolation.
validate_custom_query(cypher)
cypher = inject_provider_label(cypher, provider_id)
+ # TODO: drop after Neptune cutover
+ backend = sink_module.get_backend_for_scan(scan)
+
+ # Neptune enforces a cluster-level query timeout; prepending the hint
+ # makes the limit explicit and matches the client-side read timeout.
+ # Applies only when the scan's graph lives in Neptune.
+ if getattr(scan, "sink_backend", None) == "neptune":
+ timeout_ms = _custom_query_timeout_ms()
+ cypher = f"USING QUERY:TIMEOUTMILLISECONDS {timeout_ms}\n{cypher}"
+
try:
- graph = graph_database.execute_read_query(
- database=database_name,
- cypher=cypher,
- )
+ graph = backend.execute_read_query(database_name, cypher, None)
serialized = _serialize_graph(graph, provider_id)
return _truncate_graph(serialized)
@@ -180,10 +196,11 @@ def execute_custom_query(
def get_cartography_schema(
- database_name: str, provider_id: str
+ database_name: str, provider_id: str, scan: AttackPathsScan
) -> dict[str, str] | None:
try:
- with graph_database.get_session(
+ backend = sink_module.get_backend_for_scan(scan)
+ with backend.get_session(
database_name, default_access_mode=neo4j.READ_ACCESS
) as session:
result = session.run(get_cartography_schema_query(provider_id))
diff --git a/api/src/backend/api/db_utils.py b/api/src/backend/api/db_utils.py
index 2c378f2ea8..b6d3fdada1 100644
--- a/api/src/backend/api/db_utils.py
+++ b/api/src/backend/api/db_utils.py
@@ -2,7 +2,7 @@ import re
import secrets
import time
import uuid
-from contextlib import contextmanager
+from contextlib import ExitStack, contextmanager, nullcontext
from datetime import UTC, datetime, timedelta
from api.db_router import (
@@ -48,6 +48,140 @@ REPLICA_MAX_ATTEMPTS = env.int("POSTGRES_REPLICA_MAX_ATTEMPTS", default=3)
REPLICA_RETRY_BASE_DELAY = env.float("POSTGRES_REPLICA_RETRY_BASE_DELAY", default=0.5)
SET_CONFIG_QUERY = "SELECT set_config(%s, %s::text, TRUE);"
+SET_TRANSACTION_READ_ONLY_QUERY = "SET TRANSACTION READ ONLY;"
+
+REPLICA_CONNECTION_SQLSTATE_PREFIXES = ("08",)
+REPLICA_CONNECTION_SQLSTATES = {"57P01", "57P02", "57P03"}
+REPLICA_NON_FAILOVER_SQLSTATES = {"57014", "40001", "40P01"}
+REPLICA_CONNECTION_ERROR_MESSAGES = (
+ "ssl syscall",
+ "eof detected",
+ "server closed the connection",
+ "connection already closed",
+ "connection not open",
+ "could not connect to server",
+ "connection refused",
+ "connection reset",
+ "connection timed out",
+ "lost synchronization",
+ "terminating connection",
+ "database system is starting up",
+ "database system is shutting down",
+ "database system is in recovery mode",
+)
+REPLICA_NON_FAILOVER_ERROR_MESSAGES = (
+ "canceling statement due to user request",
+ "deadlock detected",
+ "could not serialize access",
+)
+
+
+def _iter_exception_chain(error: BaseException):
+ seen = set()
+ pending = [error]
+ while pending:
+ current = pending.pop(0)
+ if current is None or id(current) in seen:
+ continue
+ seen.add(id(current))
+ yield current
+
+ cause = getattr(current, "__cause__", None)
+ context = getattr(current, "__context__", None)
+ if cause is not None:
+ pending.append(cause)
+ if context is not None:
+ pending.append(context)
+ for arg in getattr(current, "args", ()):
+ if isinstance(arg, BaseException):
+ pending.append(arg)
+
+
+def _get_exception_sqlstate(error: BaseException) -> str | None:
+ for attr in ("pgcode", "sqlstate"):
+ sqlstate = getattr(error, attr, None)
+ if sqlstate:
+ return sqlstate
+
+ diag = getattr(error, "diag", None)
+ if diag is not None:
+ sqlstate = getattr(diag, "sqlstate", None)
+ if sqlstate:
+ return sqlstate
+ return None
+
+
+def _is_replica_connection_failure(error: BaseException) -> bool:
+ """
+ Return True only for replica failures where retrying on primary is safe.
+
+ Query cancellations, serialization failures, and deadlocks should surface to
+ callers because replaying them can hide real query or concurrency problems.
+ """
+ messages = []
+ sqlstates = set()
+
+ for chained_error in _iter_exception_chain(error):
+ sqlstate = _get_exception_sqlstate(chained_error)
+ if sqlstate:
+ sqlstates.add(sqlstate)
+ messages.append(str(chained_error).lower())
+
+ if sqlstates & REPLICA_NON_FAILOVER_SQLSTATES:
+ return False
+ if any(
+ sqlstate.startswith(REPLICA_CONNECTION_SQLSTATE_PREFIXES)
+ or sqlstate in REPLICA_CONNECTION_SQLSTATES
+ for sqlstate in sqlstates
+ ):
+ return True
+
+ message = " ".join(messages)
+ if any(marker in message for marker in REPLICA_NON_FAILOVER_ERROR_MESSAGES):
+ return False
+
+ return any(marker in message for marker in REPLICA_CONNECTION_ERROR_MESSAGES)
+
+
+def _strip_leading_sql_comments(sql: str) -> str:
+ if not isinstance(sql, str):
+ return ""
+
+ sql_text = sql.lstrip()
+ while True:
+ if sql_text.startswith("--"):
+ newline_index = sql_text.find("\n")
+ if newline_index == -1:
+ return ""
+ sql_text = sql_text[newline_index + 1 :].lstrip()
+ continue
+
+ if sql_text.startswith("/*"):
+ comment_end_index = sql_text.find("*/", 2)
+ if comment_end_index == -1:
+ return ""
+ sql_text = sql_text[comment_end_index + 2 :].lstrip()
+ continue
+
+ return sql_text
+
+
+def _is_safe_primary_replay(sql: str, many: bool) -> bool:
+ if many:
+ return False
+
+ sql_text = _strip_leading_sql_comments(sql)
+ if not re.match(r"(?is)^SELECT\b", sql_text):
+ return False
+
+ return not any(
+ re.search(pattern, sql_text, re.IGNORECASE | re.DOTALL)
+ for pattern in (
+ r"\bINTO\b",
+ r"\bFOR\s+(?:NO\s+KEY\s+)?UPDATE\b",
+ r"\bFOR\s+(?:KEY\s+)?SHARE\b",
+ )
+ )
@contextmanager
@@ -77,14 +211,36 @@ def rls_transaction(
retry_on_replica: bool = True,
):
"""
- Creates a new database transaction setting the given configuration value for Postgres RLS. It validates the
- if the value is a valid UUID.
+ Context manager that opens an RLS-scoped database transaction.
+
+ Sets a Postgres configuration variable (``set_config``) so that Row-Level
+ Security policies can filter by tenant. When *using* points to a read
+ replica and *retry_on_replica* is True, replica failures are handled in two
+ places:
+
+ 1. **Pre-yield** (connection-setup failures): the function retries
+ up to ``REPLICA_MAX_ATTEMPTS`` times on the replica, then falls
+ back to the primary DB.
+ 2. **Post-yield** (mid-query failures): an ``execute_wrapper``
+ intercepts connection-level ``OperationalError`` during
+ ``cursor.execute()`` calls and falls back directly to the primary DB
+ for single ``SELECT`` statements. The primary fallback transaction is
+ read-only, and unsafe statements keep raising the original error.
+ The wrapper swaps the inner cursor so ``fetchall()`` / ``fetchone()``
+ read from the new connection transparently.
+
+ Limitation: server-side cursors (``.iterator()``) fetch rows via
+ ``fetchmany()``, which the wrapper does not intercept. Call sites
+ that iterate large result sets with ``.iterator()`` on the replica
+ should add their own retry logic.
Args:
- value (str): Database configuration parameter value.
- parameter (str): Database configuration parameter name, by default is 'api.tenant_id'.
- using (str | None): Optional database alias to run the transaction against. Defaults to the
- active read alias (if any) or Django's default connection.
+ value: Database configuration parameter value (must be a valid UUID).
+ parameter: Database configuration parameter name.
+ using: Optional database alias. Defaults to the active read
+ alias or Django's default connection.
+ retry_on_replica: Whether replica setup failures can retry and
+ connection-level mid-query failures can fall back to primary.
"""
requested_alias = using or get_read_db_alias()
db_alias = requested_alias or DEFAULT_DB_ALIAS
@@ -92,54 +248,121 @@ def rls_transaction(
db_alias = DEFAULT_DB_ALIAS
alias = db_alias
- is_replica = READ_REPLICA_ALIAS and alias == READ_REPLICA_ALIAS
- max_attempts = REPLICA_MAX_ATTEMPTS if is_replica and retry_on_replica else 1
+ is_replica = bool(READ_REPLICA_ALIAS and alias == READ_REPLICA_ALIAS)
+ can_failover = is_replica and retry_on_replica
+ replica_alias = alias # captured before the loop mutates alias
+ max_attempts = (REPLICA_MAX_ATTEMPTS + 1) if can_failover else 1
- for attempt in range(1, max_attempts + 1):
- router_token = None
- yielded_cursor = False
+ # State shared between the generator and the _query_failover closure.
+ # The fallback transaction.atomic() is registered into fallback_stack
+ # via enter_context so its __exit__ runs when the outer with-ExitStack
+ # block exits, with the right exc_info. No manual __enter__/__exit__.
+ _fallback = {"succeeded": False, "token": None, "caller_exited_cleanly": False}
- # On final attempt, fallback to primary
- if attempt == max_attempts and is_replica:
- logger.warning(
- f"RLS transaction failed after {attempt - 1} attempts on replica, "
- f"falling back to primary DB"
- )
- alias = DEFAULT_DB_ALIAS
+ with ExitStack() as fallback_stack:
- conn = connections[alias]
- try:
- if alias != DEFAULT_DB_ALIAS:
- router_token = set_read_db_alias(alias)
+ def _query_failover(execute, sql, params, many, context):
+ """execute_wrapper: replay failed replica queries on the primary DB."""
+ try:
+ return execute(sql, params, many, context)
+ except OperationalError as err:
+ if not _is_replica_connection_failure(err):
+ raise
+ if not _is_safe_primary_replay(sql, many):
+ raise
- with transaction.atomic(using=alias):
- with conn.cursor() as cursor:
- try:
- # just in case the value is a UUID object
- uuid.UUID(str(value))
- except ValueError:
- raise ValidationError("Must be a valid UUID")
- cursor.execute(SET_CONFIG_QUERY, [parameter, value])
- yielded_cursor = True
- yield cursor
- return
- except OperationalError as e:
- if yielded_cursor:
- raise
- # If on primary or max attempts reached, raise
- if not is_replica or attempt == max_attempts:
- raise
+ try:
+ connections[replica_alias].close()
+ except Exception:
+ pass # Best-effort; connection may already be dead
- # Retry with exponential backoff
- delay = REPLICA_RETRY_BASE_DELAY * (2 ** (attempt - 1))
- logger.info(
- f"RLS transaction failed on replica (attempt {attempt}/{max_attempts}), "
- f"retrying in {delay}s. Error: {e}"
- )
- time.sleep(delay)
- finally:
- if router_token is not None:
- reset_read_db_alias(router_token)
+ logger.warning(
+ "Mid-query replica connection failure, falling back to primary DB"
+ )
+ primary = connections[DEFAULT_DB_ALIAS]
+ primary.ensure_connection()
+ fallback_stack.enter_context(transaction.atomic(using=DEFAULT_DB_ALIAS))
+
+ fallback_cursor = primary.cursor()
+ fallback_stack.callback(fallback_cursor.close)
+ fallback_cursor.execute(SET_TRANSACTION_READ_ONLY_QUERY)
+ fallback_cursor.execute(SET_CONFIG_QUERY, [parameter, value])
+ _fallback["token"] = set_read_db_alias(DEFAULT_DB_ALIAS)
+
+ fallback_cursor.execute(sql, params)
+
+ context["cursor"].db = primary
+ context["cursor"].cursor = fallback_cursor.cursor
+ _fallback["succeeded"] = True
+ return None
+
+ for attempt in range(1, max_attempts + 1):
+ router_token = None
+ yielded_cursor = False
+
+ # On final attempt, fall back to primary
+ if attempt == max_attempts and can_failover:
+ if attempt > 1:
+ logger.warning(
+ f"RLS transaction failed after {attempt - 1} attempts on replica, "
+ f"falling back to primary DB"
+ )
+ alias = DEFAULT_DB_ALIAS
+
+ conn = connections[alias]
+ try:
+ if alias != DEFAULT_DB_ALIAS:
+ router_token = set_read_db_alias(alias)
+
+ with transaction.atomic(using=alias):
+ with conn.cursor() as cursor:
+ try:
+ uuid.UUID(str(value))
+ except ValueError:
+ raise ValidationError("Must be a valid UUID")
+ cursor.execute(SET_CONFIG_QUERY, [parameter, value])
+
+ wrapper_cm = (
+ conn.execute_wrapper(_query_failover)
+ if can_failover and alias == replica_alias
+ else nullcontext()
+ )
+ with wrapper_cm:
+ yielded_cursor = True
+ yield cursor
+ _fallback["caller_exited_cleanly"] = True
+ return
+ except OperationalError as e:
+ if yielded_cursor:
+ if _fallback["succeeded"] and _fallback["caller_exited_cleanly"]:
+ # Caller's queries succeeded on primary via failover.
+ # This error is transaction.atomic() cleanup on the
+ # dead replica connection, suppress it.
+ return
+ raise
+
+ if not can_failover or attempt == max_attempts:
+ raise
+
+ try:
+ connections[alias].close()
+ except Exception:
+ pass # Best-effort; connection may already be dead
+
+ # Retry with exponential backoff
+ delay = REPLICA_RETRY_BASE_DELAY * (2 ** (attempt - 1))
+ logger.info(
+ f"RLS transaction failed on replica (attempt {attempt}/{max_attempts}), "
+ f"retrying in {delay}s. Error: {e}"
+ )
+ time.sleep(delay)
+ finally:
+ if _fallback["token"] is not None:
+ reset_read_db_alias(_fallback["token"])
+ _fallback["token"] = None
+
+ if router_token is not None:
+ reset_read_db_alias(router_token)
class CustomUserManager(BaseUserManager):
diff --git a/api/src/backend/api/decorators.py b/api/src/backend/api/decorators.py
index a055b2252f..2dd2d5fea4 100644
--- a/api/src/backend/api/decorators.py
+++ b/api/src/backend/api/decorators.py
@@ -1,12 +1,13 @@
import uuid
from functools import wraps
+from api.attack_paths.database import GraphDatabaseQueryException
from api.db_router import READ_REPLICA_ALIAS
from api.db_utils import POSTGRES_TENANT_VAR, SET_CONFIG_QUERY, rls_transaction
from api.exceptions import ProviderDeletedException
-from api.models import Provider, Scan
+from api.models import Membership, Provider, Scan, Tenant
from django.core.exceptions import ObjectDoesNotExist
-from django.db import DatabaseError, connection, transaction
+from django.db import DEFAULT_DB_ALIAS, DatabaseError, connection, transaction
from rest_framework_json_api.serializers import ValidationError
@@ -75,9 +76,11 @@ def handle_provider_deletion(func):
"""
Decorator that raises `ProviderDeletedException` if provider was deleted during execution.
- Catches `ObjectDoesNotExist` and `DatabaseError` (including `IntegrityError`), checks if
- provider still exists, and raises `ProviderDeletedException` if not. Otherwise,
- re-raises original exception.
+ Catches `ObjectDoesNotExist`, `DatabaseError` (including `IntegrityError`), and
+ `GraphDatabaseQueryException`, checks if provider still exists, and raises
+ `ProviderDeletedException` if not. Graph database errors also check whether the
+ tenant still exists and has memberships. Otherwise, re-raises the original
+ exception.
Requires `tenant_id` and `provider_id` in kwargs.
@@ -92,11 +95,16 @@ def handle_provider_deletion(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
- except (ObjectDoesNotExist, DatabaseError):
+ except (ObjectDoesNotExist, DatabaseError, GraphDatabaseQueryException) as exc:
tenant_id = kwargs.get("tenant_id")
provider_id = kwargs.get("provider_id")
+ database_alias = (
+ DEFAULT_DB_ALIAS
+ if isinstance(exc, GraphDatabaseQueryException)
+ else READ_REPLICA_ALIAS
+ )
- with rls_transaction(tenant_id, using=READ_REPLICA_ALIAS):
+ with rls_transaction(tenant_id, using=database_alias):
if provider_id is None:
scan_id = kwargs.get("scan_id")
if scan_id is None:
@@ -113,6 +121,13 @@ def handle_provider_deletion(func):
raise ProviderDeletedException(
f"Provider '{provider_id}' was deleted during the scan"
) from None
+ if isinstance(exc, GraphDatabaseQueryException) and (
+ not Tenant.objects.filter(pk=tenant_id).exists()
+ or not Membership.objects.filter(tenant_id=tenant_id).exists()
+ ):
+ raise ProviderDeletedException(
+ f"Tenant '{tenant_id}' was deleted during the scan"
+ ) from None
raise
return wrapper
diff --git a/api/src/backend/api/filters.py b/api/src/backend/api/filters.py
index 740556329c..a7f888b453 100644
--- a/api/src/backend/api/filters.py
+++ b/api/src/backend/api/filters.py
@@ -67,6 +67,7 @@ from django_filters.rest_framework import (
)
from rest_framework_json_api.django_filters.backends import DjangoFilterBackend
from rest_framework_json_api.serializers import ValidationError
+from uuid6 import UUID
class CustomDjangoFilterBackend(DjangoFilterBackend):
@@ -672,35 +673,32 @@ class LatestResourceFilter(ProviderRelationshipFilterSet):
return queryset.filter(tags__text_search=value)
-class FindingFilter(CommonFindingFilters):
+FINDING_BASE_FILTER_FIELDS = {
+ "id": ["exact", "in"],
+ "uid": ["exact", "in"],
+ "scan": ["exact", "in"],
+ "delta": ["exact", "in"],
+ "status": ["exact", "in"],
+ "severity": ["exact", "in"],
+ "impact": ["exact", "in"],
+ "check_id": ["exact", "in", "icontains"],
+}
+
+
+class BaseFindingFilter(CommonFindingFilters):
+ DATE_FILTER_FIELDS = ()
+ DATE_FILTER_NAMES = ()
+ DATE_RANGE_HELP_TEXT = (
+ f"Maximum date range is {settings.FINDINGS_MAX_DAYS_IN_RANGE} days."
+ )
+ DATE_FILTER_REQUIRED_DETAIL = "At least one date filter is required."
+
scan = UUIDFilter(method="filter_scan_id")
scan__in = UUIDInFilter(method="filter_scan_id_in")
- inserted_at = DateFilter(method="filter_inserted_at", lookup_expr="date")
- inserted_at__date = DateFilter(method="filter_inserted_at", lookup_expr="date")
- inserted_at__gte = DateFilter(
- method="filter_inserted_at_gte",
- help_text=f"Maximum date range is {settings.FINDINGS_MAX_DAYS_IN_RANGE} days.",
- )
- inserted_at__lte = DateFilter(
- method="filter_inserted_at_lte",
- help_text=f"Maximum date range is {settings.FINDINGS_MAX_DAYS_IN_RANGE} days.",
- )
-
class Meta:
model = Finding
- fields = {
- "id": ["exact", "in"],
- "uid": ["exact", "in"],
- "scan": ["exact", "in"],
- "delta": ["exact", "in"],
- "status": ["exact", "in"],
- "severity": ["exact", "in"],
- "impact": ["exact", "in"],
- "check_id": ["exact", "in", "icontains"],
- "inserted_at": ["date", "gte", "lte"],
- "updated_at": ["gte", "lte"],
- }
+ fields = FINDING_BASE_FILTER_FIELDS
filter_overrides = {
FindingDeltaEnumField: {
"filter_class": CharFilter,
@@ -723,17 +721,13 @@ class FindingFilter(CommonFindingFilters):
return queryset.filter(resource_services__contains=[value])
def filter_queryset(self, queryset):
- if not (self.data.get("scan") or self.data.get("scan__in")) and not (
- self.data.get("inserted_at")
- or self.data.get("inserted_at__date")
- or self.data.get("inserted_at__gte")
- or self.data.get("inserted_at__lte")
+ if not (self.data.get("scan") or self.data.get("scan__in")) and not any(
+ self.data.get(filter_name) for filter_name in self.DATE_FILTER_NAMES
):
raise ValidationError(
[
{
- "detail": "At least one date filter is required: filter[inserted_at], filter[inserted_at.gte], "
- "or filter[inserted_at.lte].",
+ "detail": self.DATE_FILTER_REQUIRED_DETAIL,
"status": 400,
"source": {"pointer": "/data/attributes/inserted_at"},
"code": "required",
@@ -742,31 +736,42 @@ class FindingFilter(CommonFindingFilters):
)
cleaned = self.form.cleaned_data
- exact_date = cleaned.get("inserted_at") or cleaned.get("inserted_at__date")
- gte_date = cleaned.get("inserted_at__gte") or exact_date
- lte_date = cleaned.get("inserted_at__lte") or exact_date
-
- if gte_date is None:
- gte_date = datetime.now(UTC).date()
- if lte_date is None:
- lte_date = datetime.now(UTC).date()
-
- if abs(lte_date - gte_date) > timedelta(
- days=settings.FINDINGS_MAX_DAYS_IN_RANGE
- ):
- raise ValidationError(
- [
- {
- "detail": f"The date range cannot exceed {settings.FINDINGS_MAX_DAYS_IN_RANGE} days.",
- "status": 400,
- "source": {"pointer": "/data/attributes/inserted_at"},
- "code": "invalid",
- }
- ]
- )
+ for field_name in self.DATE_FILTER_FIELDS:
+ self.validate_datetime_filter_range(cleaned, field_name)
return super().filter_queryset(queryset)
+ def validate_datetime_filter_range(self, cleaned, field_name):
+ exact_value = cleaned.get(field_name) or cleaned.get(f"{field_name}__date")
+ gte_value = cleaned.get(f"{field_name}__gte") or exact_value
+ lte_value = cleaned.get(f"{field_name}__lte") or exact_value
+
+ if not (exact_value or gte_value or lte_value):
+ return
+
+ default_value = datetime.now(UTC).date()
+ gte_value = gte_value or default_value
+ lte_value = lte_value or default_value
+
+ gte_datetime = self.filter_value_to_datetime(gte_value, field_name)
+ lte_datetime = self.filter_value_to_datetime(lte_value, field_name)
+
+ if abs(lte_datetime - gte_datetime) <= timedelta(
+ days=settings.FINDINGS_MAX_DAYS_IN_RANGE
+ ):
+ return
+
+ raise ValidationError(
+ [
+ {
+ "detail": f"The date range cannot exceed {settings.FINDINGS_MAX_DAYS_IN_RANGE} days.",
+ "status": 400,
+ "source": {"pointer": f"/data/attributes/{field_name}"},
+ "code": "invalid",
+ }
+ ]
+ )
+
# Convert filter values to UUIDv7 values for use with partitioning
def filter_scan_id(self, queryset, name, value):
try:
@@ -824,27 +829,169 @@ class FindingFilter(CommonFindingFilters):
datetime_value = self.maybe_date_to_datetime(value)
start = uuid7_start(datetime_to_uuid7(datetime_value))
end = uuid7_start(datetime_to_uuid7(datetime_value + timedelta(days=1)))
-
return queryset.filter(id__gte=start, id__lt=end)
def filter_inserted_at_gte(self, queryset, name, value):
datetime_value = self.maybe_date_to_datetime(value)
start = uuid7_start(datetime_to_uuid7(datetime_value))
-
return queryset.filter(id__gte=start)
def filter_inserted_at_lte(self, queryset, name, value):
datetime_value = self.maybe_date_to_datetime(value)
end = uuid7_start(datetime_to_uuid7(datetime_value + timedelta(days=1)))
-
return queryset.filter(id__lt=end)
@staticmethod
def maybe_date_to_datetime(value):
- dt = value
+ if isinstance(value, datetime):
+ return value
if isinstance(value, date):
- dt = datetime.combine(value, datetime.min.time(), tzinfo=UTC)
- return dt
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ if isinstance(value, str):
+ return parse(value)
+ return value
+
+ @classmethod
+ def filter_value_to_datetime(cls, value, field_name):
+ try:
+ datetime_value = cls.maybe_date_to_datetime(value)
+ except (TypeError, ValueError, OverflowError):
+ raise ValidationError(
+ [
+ {
+ "detail": "Enter a valid date or datetime.",
+ "status": 400,
+ "source": {"pointer": f"/data/attributes/{field_name}"},
+ "code": "invalid",
+ }
+ ]
+ )
+
+ if datetime_value.tzinfo is None:
+ return datetime_value.replace(tzinfo=UTC)
+ return datetime_value.astimezone(UTC)
+
+
+class FindingFilter(BaseFindingFilter):
+ DATE_FILTER_FIELDS = ("inserted_at", "updated_at")
+ DATE_FILTER_NAMES = (
+ "inserted_at",
+ "inserted_at__date",
+ "inserted_at__gte",
+ "inserted_at__lte",
+ "updated_at",
+ "updated_at__date",
+ "updated_at__gte",
+ "updated_at__lte",
+ )
+ DATE_FILTER_REQUIRED_DETAIL = (
+ "At least one date filter is required: filter[inserted_at], filter[updated_at], "
+ "filter[inserted_at.gte], filter[updated_at.gte], filter[inserted_at.lte], "
+ "or filter[updated_at.lte]."
+ )
+
+ inserted_at = CharFilter(method="filter_inserted_at")
+ inserted_at__date = DateFilter(method="filter_inserted_at", lookup_expr="date")
+ inserted_at__gte = CharFilter(
+ method="filter_inserted_at",
+ help_text=BaseFindingFilter.DATE_RANGE_HELP_TEXT,
+ )
+ inserted_at__lte = CharFilter(
+ method="filter_inserted_at",
+ help_text=BaseFindingFilter.DATE_RANGE_HELP_TEXT,
+ )
+ updated_at = CharFilter(method="filter_updated_at")
+ updated_at__date = DateFilter(method="filter_updated_at", lookup_expr="date")
+ updated_at__gte = CharFilter(
+ method="filter_updated_at",
+ help_text=BaseFindingFilter.DATE_RANGE_HELP_TEXT,
+ )
+ updated_at__lte = CharFilter(
+ method="filter_updated_at",
+ help_text=BaseFindingFilter.DATE_RANGE_HELP_TEXT,
+ )
+
+ class Meta(BaseFindingFilter.Meta):
+ fields = FINDING_BASE_FILTER_FIELDS | {
+ "inserted_at": ["date", "gte", "lte"],
+ "updated_at": ["date", "gte", "lte"],
+ }
+
+ def filter_inserted_at(self, queryset, name, value):
+ start, end = self.filter_value_to_datetime_bounds(value, "inserted_at")
+
+ if name.endswith("__gte"):
+ return queryset.filter(id__gte=self.datetime_to_uuid7_boundary(start))
+ if name.endswith("__lte"):
+ return queryset.filter(id__lt=self.datetime_to_uuid7_boundary(end))
+
+ return queryset.filter(
+ id__gte=self.datetime_to_uuid7_boundary(start),
+ id__lt=self.datetime_to_uuid7_boundary(end),
+ )
+
+ def filter_updated_at(self, queryset, name, value):
+ start, end = self.filter_value_to_datetime_bounds(value, "updated_at")
+
+ if name.endswith("__gte"):
+ return queryset.filter(updated_at__gte=start)
+ if name.endswith("__lte"):
+ return queryset.filter(updated_at__lt=end)
+
+ return queryset.filter(updated_at__gte=start, updated_at__lt=end)
+
+ @classmethod
+ def filter_value_to_datetime_bounds(cls, value, field_name):
+ start = cls.filter_value_to_datetime(value, field_name)
+ if cls.is_date_filter_value(value):
+ return start, start + timedelta(days=1)
+ return start, start + timedelta(milliseconds=1)
+
+ @staticmethod
+ def datetime_to_uuid7_boundary(datetime_value):
+ timestamp_ms = int(datetime_value.timestamp() * 1000) & 0xFFFFFFFFFFFF
+ uuid_int = timestamp_ms << 80
+ uuid_int |= 0x7 << 76
+ uuid_int |= 0x2 << 62
+ return UUID(int=uuid_int)
+
+ @staticmethod
+ def is_date_filter_value(value):
+ if isinstance(value, datetime):
+ return False
+ if isinstance(value, date):
+ return True
+ return isinstance(value, str) and len(value.strip()) == 10
+
+
+class FindingMetadataFilter(BaseFindingFilter):
+ DATE_FILTER_FIELDS = ("inserted_at",)
+ DATE_FILTER_NAMES = (
+ "inserted_at",
+ "inserted_at__date",
+ "inserted_at__gte",
+ "inserted_at__lte",
+ )
+ DATE_FILTER_REQUIRED_DETAIL = (
+ "At least one date filter is required: filter[inserted_at], filter[inserted_at.gte], "
+ "or filter[inserted_at.lte]."
+ )
+
+ inserted_at = DateFilter(method="filter_inserted_at", lookup_expr="date")
+ inserted_at__date = DateFilter(method="filter_inserted_at", lookup_expr="date")
+ inserted_at__gte = DateFilter(
+ method="filter_inserted_at_gte",
+ help_text=BaseFindingFilter.DATE_RANGE_HELP_TEXT,
+ )
+ inserted_at__lte = DateFilter(
+ method="filter_inserted_at_lte",
+ help_text=BaseFindingFilter.DATE_RANGE_HELP_TEXT,
+ )
+
+ class Meta(BaseFindingFilter.Meta):
+ fields = FINDING_BASE_FILTER_FIELDS | {
+ "inserted_at": ["date", "gte", "lte"],
+ }
class LatestFindingFilter(CommonFindingFilters):
diff --git a/api/src/backend/api/health.py b/api/src/backend/api/health.py
index 691640c0bd..cca3bcef72 100644
--- a/api/src/backend/api/health.py
+++ b/api/src/backend/api/health.py
@@ -2,8 +2,9 @@
Format (draft-inadarei-api-health-check-06).
Liveness reports only process status. Readiness verifies that PostgreSQL,
-Valkey and Neo4j are reachable and returns per-dependency detail when any
-of them is unreachable.
+Valkey and the attack-paths graph store (Neo4j or Neptune, per
+``ATTACK_PATHS_SINK_DATABASE``) are reachable and returns per-dependency
+detail when any of them is unreachable.
"""
from __future__ import annotations
@@ -11,6 +12,8 @@ from __future__ import annotations
import logging
import threading
import time
+from concurrent.futures import ThreadPoolExecutor
+from concurrent.futures import TimeoutError as FuturesTimeoutError
from contextlib import suppress
from datetime import UTC, datetime
from typing import Any
@@ -37,9 +40,28 @@ STATUS_FAIL = "fail"
STATUS_WARN = "warn"
# Short socket timeout so a stuck Valkey cannot stall the probe.
-# Neo4j inherits its driver-level ``connection_acquisition_timeout``.
VALKEY_PROBE_TIMEOUT_SECONDS = 2
+# Probe-scoped budget for the graph database.
+# ``Driver.verify_connectivity()`` takes no timeout; its only bound is the
+# driver-level ``connection_acquisition_timeout`` (60s on Neptune). The
+# probe needs its own budget, independent of the workload driver, so a
+# graph-database outage cannot pin a worker thread (and the readiness lock)
+# for a minute.
+GRAPH_DB_PROBE_TIMEOUT_SECONDS = 5
+
+# Bounded pool that enforces ``GRAPH_DB_PROBE_TIMEOUT_SECONDS``. If the
+# graph database is unreachable the probe call blocks until the driver's
+# own acquisition timeout fires; we abandon the future after the budget and
+# report ``fail``. Orphaned tasks are capped by ``max_workers`` plus the 3s
+# readiness cache plus the per-IP throttle, so they cannot pile up: worst
+# case during a graph-database outage is every readiness call failing fast
+# in ``GRAPH_DB_PROBE_TIMEOUT_SECONDS`` with at most 2 background threads
+# stuck for <= the driver acquisition timeout.
+_graph_db_probe_executor = ThreadPoolExecutor(
+ max_workers=2, thread_name_prefix="health-graph-db-probe"
+)
+
# Brief cache window so high-frequency probes (ALB target groups, scrapers)
# do not stampede the actual dependency checks.
CACHE_CONTROL_HEADER = "max-age=3, must-revalidate"
@@ -109,11 +131,24 @@ def _probe_valkey() -> None:
client.close()
-def _probe_neo4j() -> None:
- # Lazy import: avoids pulling attack_paths into the boot import graph.
- from api.attack_paths.database import get_driver
+def _graph_db_component_id() -> str:
+ """Return the active graph database name for the ``componentId`` field."""
+ return settings.ATTACK_PATHS_SINK_DATABASE.strip().lower()
- get_driver().verify_connectivity()
+
+def _probe_graph_db() -> None:
+ # Lazy import: avoids pulling attack_paths into the boot import graph
+ from api.attack_paths.database import verify_connectivity
+
+ future = _graph_db_probe_executor.submit(verify_connectivity)
+ try:
+ future.result(timeout=GRAPH_DB_PROBE_TIMEOUT_SECONDS)
+ except FuturesTimeoutError as exc:
+ # Do not wait for the abandoned task; it ends when the driver's own acquisition timeout fires
+ future.cancel()
+ raise TimeoutError(
+ f"graph-db probe exceeded {GRAPH_DB_PROBE_TIMEOUT_SECONDS}s"
+ ) from exc
def _build_check_entry(
@@ -176,14 +211,18 @@ def _readiness_payload() -> tuple[dict[str, Any], int]:
):
return snapshot[1], snapshot[2]
+ graph_db_component_id = _graph_db_component_id()
+
postgres_result, postgres_ms = _measure("postgres", _probe_postgres)
valkey_result, valkey_ms = _measure("valkey", _probe_valkey)
- neo4j_result, neo4j_ms = _measure("neo4j", _probe_neo4j)
+ graph_db_result, graph_db_ms = _measure(graph_db_component_id, _probe_graph_db)
entries = [
_build_check_entry("postgres", "datastore", postgres_result, postgres_ms),
_build_check_entry("valkey", "datastore", valkey_result, valkey_ms),
- _build_check_entry("neo4j", "datastore", neo4j_result, neo4j_ms),
+ _build_check_entry(
+ graph_db_component_id, "datastore", graph_db_result, graph_db_ms
+ ),
]
overall = _aggregate_status(entries)
@@ -191,7 +230,7 @@ def _readiness_payload() -> tuple[dict[str, Any], int]:
payload["checks"] = {
"postgres:responseTime": [entries[0]],
"valkey:responseTime": [entries[1]],
- "neo4j:responseTime": [entries[2]],
+ "graphdb:responseTime": [entries[2]],
}
http_status = (
@@ -233,10 +272,10 @@ class LivenessView(APIView):
class ReadinessView(APIView):
"""Readiness probe.
- Returns 200 when PostgreSQL, Valkey and Neo4j all respond, or 503 with
- per-dependency detail when any of them is unreachable. Per-IP throttle
- plus the short in-process result cache cap the real dependency hits
- regardless of inbound traffic shape.
+ Returns 200 when PostgreSQL, Valkey and the attack-paths graph store
+ all respond, or 503 with per-dependency detail when any of them is
+ unreachable. Per-IP throttle plus the short in-process result cache cap
+ the real dependency hits regardless of inbound traffic shape.
"""
authentication_classes: list = []
diff --git a/api/src/backend/api/migrations/0096_attack_paths_scan_is_migrated.py b/api/src/backend/api/migrations/0096_attack_paths_scan_is_migrated.py
new file mode 100644
index 0000000000..75b3e2cac7
--- /dev/null
+++ b/api/src/backend/api/migrations/0096_attack_paths_scan_is_migrated.py
@@ -0,0 +1,24 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("api", "0095_reconcile_orphan_tasks_periodic_task"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="attackpathsscan",
+ name="is_migrated",
+ field=models.BooleanField(default=False),
+ ),
+ migrations.AddField(
+ model_name="attackpathsscan",
+ name="sink_backend",
+ field=models.CharField(
+ choices=[("neo4j", "Neo4j"), ("neptune", "Neptune")],
+ default="neo4j",
+ max_length=16,
+ ),
+ ),
+ ]
diff --git a/api/src/backend/api/migrations/0097_attack_paths_scan_db_defaults.py b/api/src/backend/api/migrations/0097_attack_paths_scan_db_defaults.py
new file mode 100644
index 0000000000..8bcb43d50c
--- /dev/null
+++ b/api/src/backend/api/migrations/0097_attack_paths_scan_db_defaults.py
@@ -0,0 +1,25 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("api", "0096_attack_paths_scan_is_migrated"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="attackpathsscan",
+ name="is_migrated",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ migrations.AlterField(
+ model_name="attackpathsscan",
+ name="sink_backend",
+ field=models.CharField(
+ choices=[("neo4j", "Neo4j"), ("neptune", "Neptune")],
+ db_default="neo4j",
+ default="neo4j",
+ max_length=16,
+ ),
+ ),
+ ]
diff --git a/api/src/backend/api/models.py b/api/src/backend/api/models.py
index 47f9803b95..a280708d53 100644
--- a/api/src/backend/api/models.py
+++ b/api/src/backend/api/models.py
@@ -757,6 +757,10 @@ class Scan(RowLevelSecurityProtectedModel):
class AttackPathsScan(RowLevelSecurityProtectedModel):
+ class SinkBackendChoices(models.TextChoices):
+ NEO4J = "neo4j", "Neo4j"
+ NEPTUNE = "neptune", "Neptune"
+
objects = ActiveProviderManager()
all_objects = models.Manager()
@@ -805,6 +809,19 @@ class AttackPathsScan(RowLevelSecurityProtectedModel):
)
ingestion_exceptions = models.JSONField(default=dict, null=True, blank=True)
+ # True when the scan was synced with the current schema (list-typed
+ # properties materialised as child item nodes). False for pre-cutover scans
+ # still using the previous graph shape. Query catalog selection uses this
+ # flag; physical read routing uses sink_backend below.
+ # TODO: drop after Neptune cutover
+ is_migrated = models.BooleanField(default=False, db_default=False)
+ sink_backend = models.CharField(
+ choices=SinkBackendChoices.choices,
+ db_default=SinkBackendChoices.NEO4J,
+ default=SinkBackendChoices.NEO4J,
+ max_length=16,
+ )
+
class Meta(RowLevelSecurityProtectedModel.Meta):
db_table = "attack_paths_scans"
diff --git a/api/src/backend/api/rbac/permissions.py b/api/src/backend/api/rbac/permissions.py
index ef0475fefb..3458346a5f 100644
--- a/api/src/backend/api/rbac/permissions.py
+++ b/api/src/backend/api/rbac/permissions.py
@@ -34,7 +34,7 @@ class HasPermissions(BasePermission):
if not tenant_id:
return False
- user_roles = (
+ user_roles = list(
User.objects.using(MainRouter.admin_db)
.get(id=request.user.id)
.roles.using(MainRouter.admin_db)
@@ -43,11 +43,10 @@ class HasPermissions(BasePermission):
if not user_roles:
return False
- for perm in required_permissions:
- if not getattr(user_roles[0], perm.value, False):
- return False
-
- return True
+ return all(
+ any(getattr(role, permission.value, False) for role in user_roles)
+ for permission in required_permissions
+ )
def get_role(user: User, tenant_id: str) -> Role:
diff --git a/api/src/backend/api/specs/v1.yaml b/api/src/backend/api/specs/v1.yaml
index 767a3aaf78..420ebb27cf 100644
--- a/api/src/backend/api/specs/v1.yaml
+++ b/api/src/backend/api/specs/v1.yaml
@@ -1,7 +1,7 @@
openapi: 3.0.3
info:
title: Prowler API
- version: 1.33.0
+ version: 1.37.0
description: |-
Prowler API specification.
@@ -9,7 +9,7 @@ info:
paths:
/api/v1/api-keys:
get:
- operationId: api_keys_list
+ operationId: api_v1_api_keys_list
description: Retrieve a list of API keys for the tenant, with filtering support.
summary: List API keys
parameters:
@@ -141,7 +141,7 @@ paths:
$ref: '#/components/schemas/PaginatedTenantApiKeyList'
description: ''
post:
- operationId: api_keys_create
+ operationId: api_v1_api_keys_create
description: Create a new API key for the tenant.
summary: Create a new API key
tags:
@@ -169,7 +169,7 @@ paths:
description: ''
/api/v1/api-keys/{id}:
get:
- operationId: api_keys_retrieve
+ operationId: api_v1_api_keys_retrieve
description: Fetch detailed information about a specific API key by its ID.
summary: Retrieve API key details
parameters:
@@ -220,7 +220,7 @@ paths:
$ref: '#/components/schemas/TenantApiKeyResponse'
description: ''
patch:
- operationId: api_keys_partial_update
+ operationId: api_v1_api_keys_partial_update
description: Modify certain fields of an existing API key without affecting
other settings.
summary: Partially update an API key
@@ -257,7 +257,7 @@ paths:
description: ''
/api/v1/api-keys/{id}/revoke:
delete:
- operationId: api_keys_revoke_destroy
+ operationId: api_v1_api_keys_revoke_destroy
description: Revoke an API key by its ID. This action is irreversible and will
prevent the key from being used.
summary: Revoke an API key
@@ -282,7 +282,7 @@ paths:
description: API key was successfully revoked
/api/v1/attack-paths-scans:
get:
- operationId: attack_paths_scans_list
+ operationId: api_v1_attack_paths_scans_list
description: Retrieve Attack Paths scans for the tenant with support for filtering,
ordering, and pagination.
summary: List Attack Paths scans
@@ -352,11 +352,26 @@ paths:
description: Multiple values may be separated by commas.
explode: false
style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -370,10 +385,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -397,7 +412,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -411,10 +426,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -575,7 +590,7 @@ paths:
description: ''
/api/v1/attack-paths-scans/{id}:
get:
- operationId: attack_paths_scans_retrieve
+ operationId: api_v1_attack_paths_scans_retrieve
description: Fetch full details for a specific Attack Paths scan.
summary: Retrieve Attack Paths scan details
parameters:
@@ -635,7 +650,7 @@ paths:
description: ''
/api/v1/attack-paths-scans/{id}/queries:
get:
- operationId: attack_paths_scans_queries_retrieve
+ operationId: api_v1_attack_paths_scans_queries_retrieve
description: Retrieve the catalog of Attack Paths queries available for this
Attack Paths scan.
summary: List Attack Paths queries
@@ -698,7 +713,7 @@ paths:
description: No queries found for the selected provider
/api/v1/attack-paths-scans/{id}/queries/custom:
post:
- operationId: attack_paths_scans_queries_custom_create
+ operationId: api_v1_attack_paths_scans_queries_custom_create
description: Execute a raw openCypher query against the Attack Paths graph.
Results are filtered to the scan's provider and truncated to a maximum node
count.
@@ -745,7 +760,7 @@ paths:
description: Query execution failed due to a database error
/api/v1/attack-paths-scans/{id}/queries/run:
post:
- operationId: attack_paths_scans_queries_run_create
+ operationId: api_v1_attack_paths_scans_queries_run_create
description: Execute the selected Attack Paths query against the Attack Paths
graph and return the resulting subgraph.
summary: Execute an Attack Paths query
@@ -792,7 +807,7 @@ paths:
description: Attack Paths query execution failed due to a database error
/api/v1/attack-paths-scans/{id}/schema:
get:
- operationId: attack_paths_scans_schema_retrieve
+ operationId: api_v1_attack_paths_scans_schema_retrieve
description: Return the cartography provider, version, and links to the schema
documentation for the cloud provider associated with this Attack Paths scan.
summary: Retrieve cartography schema metadata
@@ -839,9 +854,11 @@ paths:
description: Unable to retrieve cartography schema due to a database error
/api/v1/compliance-overviews:
get:
- operationId: compliance_overviews_list
- description: Retrieve an overview of all the compliance in a given scan.
- summary: List compliance overviews for a scan
+ operationId: api_v1_compliance_overviews_list
+ description: Retrieve compliance overview data for a scan. When provider filters
+ are provided, the endpoint uses the latest completed scan for each matching
+ provider.
+ summary: List compliance overviews
parameters:
- in: query
name: fields[compliance-overviews]
@@ -900,6 +917,120 @@ paths:
schema:
type: string
format: date-time
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[provider_id]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_id__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[provider_type]
+ schema:
+ type: string
+ x-spec-enum-id: 203afc16daac9b64
+ enum:
+ - alibabacloud
+ - aws
+ - azure
+ - cloudflare
+ - gcp
+ - github
+ - googleworkspace
+ - iac
+ - image
+ - kubernetes
+ - m365
+ - mongodbatlas
+ - okta
+ - openstack
+ - oraclecloud
+ - vercel
+ description: |-
+ * `aws` - AWS
+ * `azure` - Azure
+ * `gcp` - GCP
+ * `kubernetes` - Kubernetes
+ * `m365` - M365
+ * `github` - GitHub
+ * `mongodbatlas` - MongoDB Atlas
+ * `iac` - IaC
+ * `oraclecloud` - Oracle Cloud Infrastructure
+ * `alibabacloud` - Alibaba Cloud
+ * `cloudflare` - Cloudflare
+ * `openstack` - OpenStack
+ * `image` - Image
+ * `googleworkspace` - Google Workspace
+ * `vercel` - Vercel
+ * `okta` - Okta
+ - in: query
+ name: filter[provider_type__in]
+ schema:
+ type: array
+ items:
+ type: string
+ x-spec-enum-id: 203afc16daac9b64
+ enum:
+ - alibabacloud
+ - aws
+ - azure
+ - cloudflare
+ - gcp
+ - github
+ - googleworkspace
+ - iac
+ - image
+ - kubernetes
+ - m365
+ - mongodbatlas
+ - okta
+ - openstack
+ - oraclecloud
+ - vercel
+ description: |-
+ Multiple values may be separated by commas.
+
+ * `aws` - AWS
+ * `azure` - Azure
+ * `gcp` - GCP
+ * `kubernetes` - Kubernetes
+ * `m365` - M365
+ * `github` - GitHub
+ * `mongodbatlas` - MongoDB Atlas
+ * `iac` - IaC
+ * `oraclecloud` - Oracle Cloud Infrastructure
+ * `alibabacloud` - Alibaba Cloud
+ * `cloudflare` - Cloudflare
+ * `openstack` - OpenStack
+ * `image` - Image
+ * `googleworkspace` - Google Workspace
+ * `vercel` - Vercel
+ * `okta` - Okta
+ explode: false
+ style: form
- in: query
name: filter[region]
schema:
@@ -922,8 +1053,7 @@ paths:
schema:
type: string
format: uuid
- description: Related scan ID.
- required: true
+ description: Related scan ID. Required unless a provider filter is provided.
- name: filter[search]
required: false
in: query
@@ -998,7 +1128,7 @@ paths:
description: Compliance overviews generation task failed
/api/v1/compliance-overviews/attributes:
get:
- operationId: compliance_overviews_attributes_retrieve
+ operationId: api_v1_compliance_overviews_attributes_retrieve
description: Retrieve detailed attribute information for all requirements in
a specific compliance framework along with the associated check IDs for each
requirement.
@@ -1028,6 +1158,14 @@ paths:
type: string
description: Compliance framework ID to get attributes for.
required: true
+ - in: query
+ name: filter[scan_id]
+ schema:
+ type: string
+ format: uuid
+ description: Scan ID used to resolve the provider for multi-provider universal
+ frameworks (e.g. CSA CCM), so the returned check IDs match the scan's provider.
+ When omitted, the first provider that declares the framework is used.
tags:
- Compliance Overview
security:
@@ -1041,9 +1179,10 @@ paths:
description: Compliance attributes obtained successfully
/api/v1/compliance-overviews/metadata:
get:
- operationId: compliance_overviews_metadata_retrieve
- description: Fetch unique metadata values from a set of compliance overviews.
- This is useful for dynamic filtering.
+ operationId: api_v1_compliance_overviews_metadata_retrieve
+ description: Fetch unique metadata values from compliance overviews. This is
+ useful for dynamic filtering. When provider filters are provided, metadata
+ is computed from the latest completed scan for each matching provider.
summary: Retrieve metadata values from compliance overviews
parameters:
- in: query
@@ -1057,13 +1196,209 @@ paths:
description: endpoint return only specific fields in the response on a per-type
basis by including a fields[TYPE] query parameter.
explode: false
+ - in: query
+ name: filter[compliance_id]
+ schema:
+ type: string
+ - in: query
+ name: filter[compliance_id__icontains]
+ schema:
+ type: string
+ - in: query
+ name: filter[framework]
+ schema:
+ type: string
+ - in: query
+ name: filter[framework__icontains]
+ schema:
+ type: string
+ - in: query
+ name: filter[framework__iexact]
+ schema:
+ type: string
+ - in: query
+ name: filter[inserted_at]
+ schema:
+ type: string
+ format: date
+ - in: query
+ name: filter[inserted_at__date]
+ schema:
+ type: string
+ format: date
+ - in: query
+ name: filter[inserted_at__gte]
+ schema:
+ type: string
+ format: date-time
+ - in: query
+ name: filter[inserted_at__lte]
+ schema:
+ type: string
+ format: date-time
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[provider_id]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_id__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[provider_type]
+ schema:
+ type: string
+ x-spec-enum-id: 203afc16daac9b64
+ enum:
+ - alibabacloud
+ - aws
+ - azure
+ - cloudflare
+ - gcp
+ - github
+ - googleworkspace
+ - iac
+ - image
+ - kubernetes
+ - m365
+ - mongodbatlas
+ - okta
+ - openstack
+ - oraclecloud
+ - vercel
+ description: |-
+ * `aws` - AWS
+ * `azure` - Azure
+ * `gcp` - GCP
+ * `kubernetes` - Kubernetes
+ * `m365` - M365
+ * `github` - GitHub
+ * `mongodbatlas` - MongoDB Atlas
+ * `iac` - IaC
+ * `oraclecloud` - Oracle Cloud Infrastructure
+ * `alibabacloud` - Alibaba Cloud
+ * `cloudflare` - Cloudflare
+ * `openstack` - OpenStack
+ * `image` - Image
+ * `googleworkspace` - Google Workspace
+ * `vercel` - Vercel
+ * `okta` - Okta
+ - in: query
+ name: filter[provider_type__in]
+ schema:
+ type: array
+ items:
+ type: string
+ x-spec-enum-id: 203afc16daac9b64
+ enum:
+ - alibabacloud
+ - aws
+ - azure
+ - cloudflare
+ - gcp
+ - github
+ - googleworkspace
+ - iac
+ - image
+ - kubernetes
+ - m365
+ - mongodbatlas
+ - okta
+ - openstack
+ - oraclecloud
+ - vercel
+ description: |-
+ Multiple values may be separated by commas.
+
+ * `aws` - AWS
+ * `azure` - Azure
+ * `gcp` - GCP
+ * `kubernetes` - Kubernetes
+ * `m365` - M365
+ * `github` - GitHub
+ * `mongodbatlas` - MongoDB Atlas
+ * `iac` - IaC
+ * `oraclecloud` - Oracle Cloud Infrastructure
+ * `alibabacloud` - Alibaba Cloud
+ * `cloudflare` - Cloudflare
+ * `openstack` - OpenStack
+ * `image` - Image
+ * `googleworkspace` - Google Workspace
+ * `vercel` - Vercel
+ * `okta` - Okta
+ explode: false
+ style: form
+ - in: query
+ name: filter[region]
+ schema:
+ type: string
+ - in: query
+ name: filter[region__icontains]
+ schema:
+ type: string
+ - in: query
+ name: filter[region__in]
+ schema:
+ type: array
+ items:
+ type: string
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[scan_id]
schema:
type: string
format: uuid
- description: Related scan ID.
- required: true
+ description: Related scan ID. Required unless a provider filter is provided.
+ - name: filter[search]
+ required: false
+ in: query
+ description: A search term.
+ schema:
+ type: string
+ - in: query
+ name: filter[version]
+ schema:
+ type: string
+ - in: query
+ name: filter[version__icontains]
+ schema:
+ type: string
+ - name: sort
+ required: false
+ in: query
+ description: '[list of fields to sort by](https://jsonapi.org/format/#fetching-sorting)'
+ schema:
+ type: array
+ items:
+ type: string
+ enum:
+ - compliance_id
+ - -compliance_id
+ explode: false
tags:
- Compliance Overview
security:
@@ -1100,11 +1435,12 @@ paths:
description: Compliance overviews generation task failed
/api/v1/compliance-overviews/requirements:
get:
- operationId: compliance_overviews_requirements_retrieve
- description: Retrieve a detailed overview of compliance requirements in a given
- scan, grouped by compliance framework. This endpoint provides requirement-level
- details and aggregates status across regions.
- summary: List compliance requirements overview for a scan
+ operationId: api_v1_compliance_overviews_requirements_retrieve
+ description: Retrieve a detailed overview of compliance requirements, grouped
+ by compliance framework. This endpoint provides requirement-level details
+ and aggregates status across regions. When provider filters are provided,
+ the endpoint uses the latest completed scan for each matching provider.
+ summary: List compliance requirements overview
parameters:
- in: query
name: fields[compliance-requirements-details]
@@ -1163,6 +1499,120 @@ paths:
schema:
type: string
format: date-time
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[provider_id]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_id__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[provider_type]
+ schema:
+ type: string
+ x-spec-enum-id: 203afc16daac9b64
+ enum:
+ - alibabacloud
+ - aws
+ - azure
+ - cloudflare
+ - gcp
+ - github
+ - googleworkspace
+ - iac
+ - image
+ - kubernetes
+ - m365
+ - mongodbatlas
+ - okta
+ - openstack
+ - oraclecloud
+ - vercel
+ description: |-
+ * `aws` - AWS
+ * `azure` - Azure
+ * `gcp` - GCP
+ * `kubernetes` - Kubernetes
+ * `m365` - M365
+ * `github` - GitHub
+ * `mongodbatlas` - MongoDB Atlas
+ * `iac` - IaC
+ * `oraclecloud` - Oracle Cloud Infrastructure
+ * `alibabacloud` - Alibaba Cloud
+ * `cloudflare` - Cloudflare
+ * `openstack` - OpenStack
+ * `image` - Image
+ * `googleworkspace` - Google Workspace
+ * `vercel` - Vercel
+ * `okta` - Okta
+ - in: query
+ name: filter[provider_type__in]
+ schema:
+ type: array
+ items:
+ type: string
+ x-spec-enum-id: 203afc16daac9b64
+ enum:
+ - alibabacloud
+ - aws
+ - azure
+ - cloudflare
+ - gcp
+ - github
+ - googleworkspace
+ - iac
+ - image
+ - kubernetes
+ - m365
+ - mongodbatlas
+ - okta
+ - openstack
+ - oraclecloud
+ - vercel
+ description: |-
+ Multiple values may be separated by commas.
+
+ * `aws` - AWS
+ * `azure` - Azure
+ * `gcp` - GCP
+ * `kubernetes` - Kubernetes
+ * `m365` - M365
+ * `github` - GitHub
+ * `mongodbatlas` - MongoDB Atlas
+ * `iac` - IaC
+ * `oraclecloud` - Oracle Cloud Infrastructure
+ * `alibabacloud` - Alibaba Cloud
+ * `cloudflare` - Cloudflare
+ * `openstack` - OpenStack
+ * `image` - Image
+ * `googleworkspace` - Google Workspace
+ * `vercel` - Vercel
+ * `okta` - Okta
+ explode: false
+ style: form
- in: query
name: filter[region]
schema:
@@ -1185,8 +1635,7 @@ paths:
schema:
type: string
format: uuid
- description: Related scan ID.
- required: true
+ description: Related scan ID. Required unless a provider filter is provided.
- name: filter[search]
required: false
in: query
@@ -1249,7 +1698,7 @@ paths:
description: Compliance overviews generation task failed
/api/v1/finding-groups:
get:
- operationId: finding_groups_list
+ operationId: api_v1_finding_groups_list
description: "\n Retrieve aggregated findings grouped by check_id.\n\n\
\ Each group shows:\n - Aggregated status (FAIL if any non-muted\
\ failure)\n - Maximum severity across all findings\n - Resource\
@@ -1422,6 +1871,21 @@ paths:
description: Multiple values may be separated by commas.
explode: false
style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -1454,10 +1918,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -1494,10 +1958,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -1799,7 +2263,7 @@ paths:
description: ''
/api/v1/finding-groups/{id}/resources:
get:
- operationId: finding_groups_resources_retrieve
+ operationId: api_v1_finding_groups_resources_retrieve
description: "\n Retrieve resources affected by a specific check (finding\
\ group).\n\n Returns individual resources with their current status,\
\ severity,\n and timing information including how long they have been\
@@ -1970,6 +2434,21 @@ paths:
description: Multiple values may be separated by commas.
explode: false
style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -2002,10 +2481,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -2042,10 +2521,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -2342,12 +2821,12 @@ paths:
description: ''
/api/v1/finding-groups/latest:
get:
- operationId: finding_groups_latest_retrieve
+ operationId: api_v1_finding_groups_latest_retrieve
description: "\n Retrieve the latest available state for each finding\
\ group (check_id).\n\n This endpoint returns finding groups without\
\ requiring date filters,\n automatically using the latest available\
- \ data per check_id.\n All other filters (provider_id, provider_type,\
- \ check_id) are still supported.\n "
+ \ data per check_id.\n Provider, provider group, check, and computed\
+ \ filters are still supported.\n "
summary: List latest finding groups
parameters:
- in: query
@@ -2394,6 +2873,471 @@ paths:
description: endpoint return only specific fields in the response on a per-type
basis by including a fields[TYPE] query parameter.
explode: false
+ - in: query
+ name: filter[category]
+ schema:
+ type: string
+ - in: query
+ name: filter[category__in]
+ schema:
+ type: array
+ items:
+ type: string
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[check_id]
+ schema:
+ type: string
+ - in: query
+ name: filter[check_id__icontains]
+ schema:
+ type: string
+ - in: query
+ name: filter[check_id__in]
+ schema:
+ type: array
+ items:
+ type: string
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[check_title__icontains]
+ schema:
+ type: string
+ - in: query
+ name: filter[delta]
+ schema:
+ type: string
+ enum:
+ - changed
+ - new
+ description: |-
+ * `new` - New
+ * `changed` - Changed
+ - in: query
+ name: filter[impact]
+ schema:
+ type: string
+ enum:
+ - critical
+ - high
+ - informational
+ - low
+ - medium
+ description: |-
+ * `critical` - Critical
+ * `high` - High
+ * `medium` - Medium
+ * `low` - Low
+ * `informational` - Informational
+ - in: query
+ name: filter[muted]
+ schema:
+ type: boolean
+ description: If this filter is not provided, muted and non-muted findings
+ will be returned.
+ - in: query
+ name: filter[provider]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[provider_alias]
+ schema:
+ type: string
+ - in: query
+ name: filter[provider_alias__icontains]
+ schema:
+ type: string
+ - in: query
+ name: filter[provider_alias__in]
+ schema:
+ type: array
+ items:
+ type: string
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[provider_id]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_id__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[provider_type]
+ schema:
+ type: string
+ enum:
+ - alibabacloud
+ - aws
+ - azure
+ - cloudflare
+ - gcp
+ - github
+ - googleworkspace
+ - iac
+ - image
+ - kubernetes
+ - m365
+ - mongodbatlas
+ - okta
+ - openstack
+ - oraclecloud
+ - vercel
+ description: |-
+ * `aws` - AWS
+ * `azure` - Azure
+ * `gcp` - GCP
+ * `kubernetes` - Kubernetes
+ * `m365` - M365
+ * `github` - GitHub
+ * `mongodbatlas` - MongoDB Atlas
+ * `iac` - IaC
+ * `oraclecloud` - Oracle Cloud Infrastructure
+ * `alibabacloud` - Alibaba Cloud
+ * `cloudflare` - Cloudflare
+ * `openstack` - OpenStack
+ * `image` - Image
+ * `googleworkspace` - Google Workspace
+ * `vercel` - Vercel
+ * `okta` - Okta
+ - in: query
+ name: filter[provider_type__in]
+ schema:
+ type: array
+ items:
+ type: string
+ enum:
+ - alibabacloud
+ - aws
+ - azure
+ - cloudflare
+ - gcp
+ - github
+ - googleworkspace
+ - iac
+ - image
+ - kubernetes
+ - m365
+ - mongodbatlas
+ - okta
+ - openstack
+ - oraclecloud
+ - vercel
+ description: |-
+ Multiple values may be separated by commas.
+
+ * `aws` - AWS
+ * `azure` - Azure
+ * `gcp` - GCP
+ * `kubernetes` - Kubernetes
+ * `m365` - M365
+ * `github` - GitHub
+ * `mongodbatlas` - MongoDB Atlas
+ * `iac` - IaC
+ * `oraclecloud` - Oracle Cloud Infrastructure
+ * `alibabacloud` - Alibaba Cloud
+ * `cloudflare` - Cloudflare
+ * `openstack` - OpenStack
+ * `image` - Image
+ * `googleworkspace` - Google Workspace
+ * `vercel` - Vercel
+ * `okta` - Okta
+ explode: false
+ style: form
+ - in: query
+ name: filter[provider_uid]
+ schema:
+ type: string
+ - in: query
+ name: filter[provider_uid__icontains]
+ schema:
+ type: string
+ - in: query
+ name: filter[provider_uid__in]
+ schema:
+ type: array
+ items:
+ type: string
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[region]
+ schema:
+ type: string
+ - in: query
+ name: filter[region__icontains]
+ schema:
+ type: string
+ - in: query
+ name: filter[region__in]
+ schema:
+ type: array
+ items:
+ type: string
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[resource_groups]
+ schema:
+ type: string
+ - in: query
+ name: filter[resource_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[resource_name]
+ schema:
+ type: string
+ - in: query
+ name: filter[resource_name__icontains]
+ schema:
+ type: string
+ - in: query
+ name: filter[resource_name__in]
+ schema:
+ type: array
+ items:
+ type: string
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[resource_type]
+ schema:
+ type: string
+ - in: query
+ name: filter[resource_type__icontains]
+ schema:
+ type: string
+ - in: query
+ name: filter[resource_type__in]
+ schema:
+ type: array
+ items:
+ type: string
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[resource_uid]
+ schema:
+ type: string
+ - in: query
+ name: filter[resource_uid__icontains]
+ schema:
+ type: string
+ - in: query
+ name: filter[resource_uid__in]
+ schema:
+ type: array
+ items:
+ type: string
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[resources]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[scan]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[scan__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[service]
+ schema:
+ type: string
+ - in: query
+ name: filter[service__icontains]
+ schema:
+ type: string
+ - in: query
+ name: filter[service__in]
+ schema:
+ type: array
+ items:
+ type: string
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
+ - in: query
+ name: filter[severity]
+ schema:
+ type: string
+ enum:
+ - critical
+ - high
+ - informational
+ - low
+ - medium
+ description: |-
+ * `critical` - Critical
+ * `high` - High
+ * `medium` - Medium
+ * `low` - Low
+ * `informational` - Informational
+ - in: query
+ name: filter[status]
+ schema:
+ type: string
+ enum:
+ - FAIL
+ - MANUAL
+ - PASS
+ description: |-
+ * `FAIL` - Fail
+ * `PASS` - Pass
+ * `MANUAL` - Manual
+ - in: query
+ name: filter[uid]
+ schema:
+ type: string
+ - in: query
+ name: filter[updated_at]
+ schema:
+ type: string
+ format: date
+ - name: sort
+ required: false
+ in: query
+ description: '[list of fields to sort by](https://jsonapi.org/format/#fetching-sorting)'
+ schema:
+ type: array
+ items:
+ type: string
+ enum:
+ - id
+ - -id
+ - check_id
+ - -check_id
+ - check_title
+ - -check_title
+ - check_description
+ - -check_description
+ - severity
+ - -severity
+ - status
+ - -status
+ - muted
+ - -muted
+ - impacted_providers
+ - -impacted_providers
+ - resources_fail
+ - -resources_fail
+ - resources_total
+ - -resources_total
+ - pass_count
+ - -pass_count
+ - fail_count
+ - -fail_count
+ - manual_count
+ - -manual_count
+ - pass_muted_count
+ - -pass_muted_count
+ - fail_muted_count
+ - -fail_muted_count
+ - manual_muted_count
+ - -manual_muted_count
+ - muted_count
+ - -muted_count
+ - new_count
+ - -new_count
+ - changed_count
+ - -changed_count
+ - new_fail_count
+ - -new_fail_count
+ - new_fail_muted_count
+ - -new_fail_muted_count
+ - new_pass_count
+ - -new_pass_count
+ - new_pass_muted_count
+ - -new_pass_muted_count
+ - new_manual_count
+ - -new_manual_count
+ - new_manual_muted_count
+ - -new_manual_muted_count
+ - changed_fail_count
+ - -changed_fail_count
+ - changed_fail_muted_count
+ - -changed_fail_muted_count
+ - changed_pass_count
+ - -changed_pass_count
+ - changed_pass_muted_count
+ - -changed_pass_muted_count
+ - changed_manual_count
+ - -changed_manual_count
+ - changed_manual_muted_count
+ - -changed_manual_muted_count
+ - first_seen_at
+ - -first_seen_at
+ - last_seen_at
+ - -last_seen_at
+ - failing_since
+ - -failing_since
+ explode: false
tags:
- Finding Groups
security:
@@ -2407,7 +3351,7 @@ paths:
description: ''
/api/v1/finding-groups/latest/{check_id}/resources:
get:
- operationId: finding_groups_latest_resources_retrieve
+ operationId: api_v1_finding_groups_latest_resources_retrieve
description: "\n Retrieve resources affected by a specific check (finding\
\ group) from the\n latest completed scan for each provider.\n\n \
\ Returns individual resources with their current status, severity,\n\
@@ -2561,6 +3505,21 @@ paths:
description: Multiple values may be separated by commas.
explode: false
style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -2593,10 +3552,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -2633,10 +3592,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -2926,7 +3885,7 @@ paths:
description: ''
/api/v1/findings:
get:
- operationId: findings_list
+ operationId: api_v1_findings_list
description: Retrieve a list of all findings with options for filtering by various
criteria.
summary: List all findings
@@ -3068,13 +4027,11 @@ paths:
name: filter[inserted_at__gte]
schema:
type: string
- format: date
description: Maximum date range is 7 days.
- in: query
name: filter[inserted_at__lte]
schema:
type: string
- format: date
description: Maximum date range is 7 days.
- in: query
name: filter[muted]
@@ -3114,6 +4071,21 @@ paths:
description: Multiple values may be separated by commas.
explode: false
style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -3133,7 +4105,7 @@ paths:
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -3147,10 +4119,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -3174,7 +4146,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -3188,10 +4160,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -3422,6 +4394,10 @@ paths:
style: form
- in: query
name: filter[updated_at]
+ schema:
+ type: string
+ - in: query
+ name: filter[updated_at__date]
schema:
type: string
format: date
@@ -3429,12 +4405,12 @@ paths:
name: filter[updated_at__gte]
schema:
type: string
- format: date-time
+ description: Maximum date range is 7 days.
- in: query
name: filter[updated_at__lte]
schema:
type: string
- format: date-time
+ description: Maximum date range is 7 days.
- in: query
name: include
schema:
@@ -3492,7 +4468,7 @@ paths:
description: ''
/api/v1/findings/{id}:
get:
- operationId: findings_retrieve
+ operationId: api_v1_findings_retrieve
description: Fetch detailed information about a specific finding by its ID.
summary: Retrieve data from a specific finding
parameters:
@@ -3556,7 +4532,7 @@ paths:
description: ''
/api/v1/findings/findings_services_regions:
get:
- operationId: findings_findings_services_regions_retrieve
+ operationId: api_v1_findings_findings_services_regions_retrieve
description: Fetch services and regions affected in findings.
summary: Retrieve the services and regions that are impacted by findings
parameters:
@@ -3668,7 +4644,6 @@ paths:
name: filter[inserted_at]
schema:
type: string
- format: date
- in: query
name: filter[inserted_at__date]
schema:
@@ -3678,13 +4653,11 @@ paths:
name: filter[inserted_at__gte]
schema:
type: string
- format: date
description: Maximum date range is 7 days.
- in: query
name: filter[inserted_at__lte]
schema:
type: string
- format: date
description: Maximum date range is 7 days.
- in: query
name: filter[muted]
@@ -3724,6 +4697,21 @@ paths:
description: Multiple values may be separated by commas.
explode: false
style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -3743,7 +4731,7 @@ paths:
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -3757,10 +4745,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -3784,7 +4772,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -3798,10 +4786,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -4032,6 +5020,10 @@ paths:
style: form
- in: query
name: filter[updated_at]
+ schema:
+ type: string
+ - in: query
+ name: filter[updated_at__date]
schema:
type: string
format: date
@@ -4039,12 +5031,12 @@ paths:
name: filter[updated_at__gte]
schema:
type: string
- format: date-time
+ description: Maximum date range is 7 days.
- in: query
name: filter[updated_at__lte]
schema:
type: string
- format: date-time
+ description: Maximum date range is 7 days.
- name: sort
required: false
in: query
@@ -4079,7 +5071,7 @@ paths:
description: ''
/api/v1/findings/latest:
get:
- operationId: findings_latest_retrieve
+ operationId: api_v1_findings_latest_retrieve
description: Retrieve a list of the latest findings from the latest scans for
each provider with options for filtering by various criteria.
summary: List the latest findings
@@ -4242,6 +5234,21 @@ paths:
description: Multiple values may be separated by commas.
explode: false
style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -4261,7 +5268,7 @@ paths:
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -4275,10 +5282,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -4302,7 +5309,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -4316,10 +5323,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -4583,7 +5590,7 @@ paths:
description: ''
/api/v1/findings/metadata:
get:
- operationId: findings_metadata_retrieve
+ operationId: api_v1_findings_metadata_retrieve
description: Fetch unique metadata values from a set of findings. This is useful
for dynamic filtering.
summary: Retrieve metadata values from findings
@@ -4758,6 +5765,21 @@ paths:
description: Multiple values may be separated by commas.
explode: false
style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -4777,7 +5799,7 @@ paths:
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -4791,10 +5813,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -4818,7 +5840,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -4832,10 +5854,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -5112,7 +6134,7 @@ paths:
description: ''
/api/v1/findings/metadata/latest:
get:
- operationId: findings_metadata_latest_retrieve
+ operationId: api_v1_findings_metadata_latest_retrieve
description: Fetch unique metadata values from a set of findings from the latest
scans for each provider. This is useful for dynamic filtering.
summary: Retrieve metadata values from the latest findings
@@ -5262,6 +6284,21 @@ paths:
description: Multiple values may be separated by commas.
explode: false
style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -5281,7 +6318,7 @@ paths:
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -5295,10 +6332,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -5322,7 +6359,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -5336,10 +6373,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -5591,7 +6628,7 @@ paths:
description: ''
/api/v1/integrations:
get:
- operationId: integrations_list
+ operationId: api_v1_integrations_list
description: Retrieve a list of all configured integrations with options for
filtering by various criteria.
summary: List all integrations
@@ -5742,7 +6779,7 @@ paths:
$ref: '#/components/schemas/PaginatedIntegrationList'
description: ''
post:
- operationId: integrations_create
+ operationId: api_v1_integrations_create
description: Register a new integration with the system, providing necessary
configuration details.
summary: Create a new integration
@@ -5771,7 +6808,7 @@ paths:
description: ''
/api/v1/integrations/{integration_pk}/jira/dispatches:
post:
- operationId: integrations_jira_dispatches_create
+ operationId: api_v1_integrations_jira_dispatches_create
description: |-
Send a set of filtered findings to the given integration. At least one finding filter must be provided.
@@ -5844,7 +6881,7 @@ paths:
description: ''
/api/v1/integrations/{integration_pk}/jira/issue_types:
get:
- operationId: integrations_jira_issue_types_retrieve
+ operationId: api_v1_integrations_jira_issue_types_retrieve
description: Fetch the available issue types from Jira for a given project key
and update the integration configuration.
summary: Get available issue types for a Jira project
@@ -5885,7 +6922,7 @@ paths:
description: ''
/api/v1/integrations/{id}:
get:
- operationId: integrations_retrieve
+ operationId: api_v1_integrations_retrieve
description: Fetch detailed information about a specific integration by its
ID.
summary: Retrieve integration details
@@ -5939,7 +6976,7 @@ paths:
$ref: '#/components/schemas/IntegrationResponse'
description: ''
patch:
- operationId: integrations_partial_update
+ operationId: api_v1_integrations_partial_update
description: Modify certain fields of an existing integration without affecting
other settings.
summary: Partially update an integration
@@ -5975,7 +7012,7 @@ paths:
$ref: '#/components/schemas/IntegrationUpdateResponse'
description: ''
delete:
- operationId: integrations_destroy
+ operationId: api_v1_integrations_destroy
description: Remove an integration from the system by its ID.
summary: Delete an integration
parameters:
@@ -5995,7 +7032,7 @@ paths:
description: No response body
/api/v1/integrations/{id}/connection:
post:
- operationId: integrations_connection_create
+ operationId: api_v1_integrations_connection_create
description: Try to verify integration connection
summary: Check integration connection
parameters:
@@ -6034,7 +7071,7 @@ paths:
description: ''
/api/v1/invitations/accept:
post:
- operationId: invitations_accept_create
+ operationId: api_v1_invitations_accept_create
description: Accept an invitation to an existing tenant. This invitation cannot
be expired and the emails must match.
summary: Accept an invitation
@@ -6063,7 +7100,7 @@ paths:
description: ''
/api/v1/lighthouse-configurations:
get:
- operationId: lighthouse_configurations_list
+ operationId: api_v1_lighthouse_configurations_list
description: Retrieve a list of all Lighthouse AI configurations.
summary: List all Lighthouse AI configurations
parameters:
@@ -6136,7 +7173,7 @@ paths:
$ref: '#/components/schemas/PaginatedLighthouseConfigList'
description: ''
post:
- operationId: lighthouse_configurations_create
+ operationId: api_v1_lighthouse_configurations_create
description: Create a new Lighthouse AI configuration with the specified details.
summary: Create a new Lighthouse AI configuration
tags:
@@ -6165,7 +7202,7 @@ paths:
description: ''
/api/v1/lighthouse-configurations/{id}:
patch:
- operationId: lighthouse_configurations_partial_update
+ operationId: api_v1_lighthouse_configurations_partial_update
description: Update certain fields of an existing Lighthouse AI configuration.
summary: Partially update a Lighthouse AI configuration
parameters:
@@ -6199,7 +7236,7 @@ paths:
$ref: '#/components/schemas/LighthouseConfigUpdateResponse'
description: ''
delete:
- operationId: lighthouse_configurations_destroy
+ operationId: api_v1_lighthouse_configurations_destroy
description: Remove a Lighthouse AI configuration by its ID.
summary: Delete a Lighthouse AI configuration
parameters:
@@ -6218,7 +7255,7 @@ paths:
description: No response body
/api/v1/lighthouse-configurations/{id}/connection:
post:
- operationId: lighthouse_configurations_connection_create
+ operationId: api_v1_lighthouse_configurations_connection_create
description: Verify the connection to the OpenAI API for a specific Lighthouse
AI configuration.
summary: Check the connection to the OpenAI API
@@ -6257,7 +7294,7 @@ paths:
description: ''
/api/v1/lighthouse/configuration:
get:
- operationId: lighthouse_configuration_list
+ operationId: api_v1_lighthouse_configuration_list
description: Retrieve current tenant-level Lighthouse AI settings. Returns a
single configuration object.
summary: Get Lighthouse AI Tenant config
@@ -6332,7 +7369,7 @@ paths:
$ref: '#/components/schemas/PaginatedLighthouseTenantConfigList'
description: ''
patch:
- operationId: lighthouse_configuration_partial_update
+ operationId: api_v1_lighthouse_configuration_partial_update
description: Update tenant-level settings. Validates that the default provider
is configured and active and that default model IDs exist for the chosen providers.
Auto-creates configuration if it doesn't exist.
@@ -6362,7 +7399,7 @@ paths:
description: ''
/api/v1/lighthouse/models:
get:
- operationId: lighthouse_models_list
+ operationId: api_v1_lighthouse_models_list
description: List available LLM models per configured provider for the current
tenant.
summary: List all LLM models
@@ -6492,7 +7529,7 @@ paths:
description: ''
/api/v1/lighthouse/models/{id}:
get:
- operationId: lighthouse_models_retrieve
+ operationId: api_v1_lighthouse_models_retrieve
description: Get details for a specific LLM model.
summary: Retrieve LLM model details
parameters:
@@ -6533,7 +7570,7 @@ paths:
description: ''
/api/v1/lighthouse/providers:
get:
- operationId: lighthouse_providers_list
+ operationId: api_v1_lighthouse_providers_list
description: Retrieve all LLM provider configurations for the current tenant
summary: List all LLM provider configurations
parameters:
@@ -6648,7 +7685,7 @@ paths:
$ref: '#/components/schemas/PaginatedLighthouseProviderConfigList'
description: ''
post:
- operationId: lighthouse_providers_create
+ operationId: api_v1_lighthouse_providers_create
description: Create a per-tenant configuration for an LLM provider. Only one
configuration per provider type is allowed per tenant.
summary: Create LLM provider configuration
@@ -6677,7 +7714,7 @@ paths:
description: ''
/api/v1/lighthouse/providers/{id}:
get:
- operationId: lighthouse_providers_retrieve
+ operationId: api_v1_lighthouse_providers_retrieve
description: Get details for a specific provider configuration in the current
tenant.
summary: Retrieve LLM provider configuration
@@ -6718,7 +7755,7 @@ paths:
$ref: '#/components/schemas/LighthouseProviderConfigResponse'
description: ''
patch:
- operationId: lighthouse_providers_partial_update
+ operationId: api_v1_lighthouse_providers_partial_update
description: Partially update a provider configuration (e.g., base_url, is_active).
summary: Update LLM provider configuration
parameters:
@@ -6753,7 +7790,7 @@ paths:
$ref: '#/components/schemas/LighthouseProviderConfigUpdateResponse'
description: ''
delete:
- operationId: lighthouse_providers_destroy
+ operationId: api_v1_lighthouse_providers_destroy
description: Delete a provider configuration. Any tenant defaults that reference
this provider are cleared during deletion.
summary: Delete LLM provider configuration
@@ -6774,7 +7811,7 @@ paths:
description: No response body
/api/v1/lighthouse/providers/{id}/connection:
post:
- operationId: lighthouse_providers_connection_create
+ operationId: api_v1_lighthouse_providers_connection_create
description: Validate provider credentials asynchronously and toggle is_active.
summary: Check LLM provider connection
parameters:
@@ -6813,7 +7850,7 @@ paths:
description: ''
/api/v1/lighthouse/providers/{id}/refresh-models:
post:
- operationId: lighthouse_providers_refresh_models_create
+ operationId: api_v1_lighthouse_providers_refresh_models_create
description: Fetch available models for this provider configuration and upsert
into catalog. Supports OpenAI, OpenAI-compatible, and AWS Bedrock providers.
summary: Refresh LLM models catalog
@@ -6853,7 +7890,7 @@ paths:
description: ''
/api/v1/mute-rules:
get:
- operationId: mute_rules_list
+ operationId: api_v1_mute_rules_list
description: Retrieve a list of all mute rules with filtering options.
summary: List all mute rules
parameters:
@@ -6999,7 +8036,7 @@ paths:
$ref: '#/components/schemas/PaginatedMuteRuleList'
description: ''
post:
- operationId: mute_rules_create
+ operationId: api_v1_mute_rules_create
description: Create a new mute rule by providing finding IDs, name, and reason.
The rule will immediately mute the selected findings and launch a background
task to mute all historical findings with matching UIDs.
@@ -7029,7 +8066,7 @@ paths:
description: ''
/api/v1/mute-rules/{id}:
get:
- operationId: mute_rules_retrieve
+ operationId: api_v1_mute_rules_retrieve
description: Fetch detailed information about a specific mute rule by ID.
summary: Retrieve a mute rule
parameters:
@@ -7080,7 +8117,7 @@ paths:
$ref: '#/components/schemas/MuteRuleResponse'
description: ''
patch:
- operationId: mute_rules_partial_update
+ operationId: api_v1_mute_rules_partial_update
description: Update certain fields of an existing mute rule (e.g., name, reason,
enabled).
summary: Partially update a mute rule
@@ -7116,7 +8153,7 @@ paths:
$ref: '#/components/schemas/SerializerMetaclassResponse'
description: ''
delete:
- operationId: mute_rules_destroy
+ operationId: api_v1_mute_rules_destroy
description: 'Remove a mute rule from the system. Note: Previously muted findings
remain muted.'
summary: Delete a mute rule
@@ -7137,7 +8174,7 @@ paths:
description: No response body
/api/v1/overviews/attack-surfaces:
get:
- operationId: overviews_attack_surfaces_list
+ operationId: api_v1_overviews_attack_surfaces_list
description: Retrieve aggregated attack surface metrics from latest completed
scans per provider.
summary: Get attack surface overview
@@ -7156,6 +8193,21 @@ paths:
description: endpoint return only specific fields in the response on a per-type
basis by including a fields[TYPE] query parameter.
explode: false
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -7175,7 +8227,7 @@ paths:
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -7189,10 +8241,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -7216,7 +8268,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -7230,10 +8282,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -7304,7 +8356,7 @@ paths:
description: ''
/api/v1/overviews/categories:
get:
- operationId: overviews_categories_list
+ operationId: api_v1_overviews_categories_list
description: 'Retrieve aggregated category metrics from latest completed scans
per provider. Returns one row per category with total, failed, and new failed
findings counts, plus a severity breakdown showing failed findings per severity
@@ -7339,6 +8391,21 @@ paths:
description: Multiple values may be separated by commas.
explode: false
style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -7358,7 +8425,7 @@ paths:
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -7372,10 +8439,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -7399,7 +8466,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -7413,10 +8480,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -7489,7 +8556,7 @@ paths:
description: ''
/api/v1/overviews/compliance-watchlist:
get:
- operationId: overviews_compliance_watchlist_list
+ operationId: api_v1_overviews_compliance_watchlist_list
description: 'Retrieve compliance metrics with FAIL-dominant aggregation. Without
filters: uses pre-aggregated TenantComplianceSummary. With provider filters:
queries ProviderComplianceScore with FAIL-dominant logic where any FAIL in
@@ -7512,6 +8579,21 @@ paths:
description: endpoint return only specific fields in the response on a per-type
basis by including a fields[TYPE] query parameter.
explode: false
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -7544,10 +8626,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -7584,10 +8666,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -7662,7 +8744,7 @@ paths:
description: ''
/api/v1/overviews/findings:
get:
- operationId: overviews_findings_retrieve
+ operationId: api_v1_overviews_findings_retrieve
description: Fetch aggregated findings data across all providers, grouped by
various metrics such as passed, failed, muted, and total findings. This endpoint
calculates summary statistics based on the latest scans for each provider
@@ -7714,6 +8796,21 @@ paths:
schema:
type: string
format: date-time
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -7733,7 +8830,7 @@ paths:
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -7747,10 +8844,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -7774,7 +8871,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -7788,10 +8885,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -7887,7 +8984,7 @@ paths:
description: ''
/api/v1/overviews/findings_severity:
get:
- operationId: overviews_findings_severity_retrieve
+ operationId: api_v1_overviews_findings_severity_retrieve
description: Retrieve an aggregated summary of findings grouped by severity
levels, such as low, medium, high, and critical. The response includes the
total count of findings for each severity, considering only the latest scans
@@ -7931,6 +9028,21 @@ paths:
schema:
type: string
format: date-time
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -7950,7 +9062,7 @@ paths:
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -7964,10 +9076,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -7991,7 +9103,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -8005,10 +9117,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -8107,7 +9219,7 @@ paths:
description: ''
/api/v1/overviews/findings_severity/timeseries:
get:
- operationId: overviews_findings_severity_timeseries_retrieve
+ operationId: api_v1_overviews_findings_severity_timeseries_retrieve
description: Retrieve daily aggregated findings data grouped by severity levels
over a date range. Returns one data point per day with counts of failed findings
by severity (critical, high, medium, low, informational) and muted findings.
@@ -8143,6 +9255,21 @@ paths:
schema:
type: string
format: date
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -8175,10 +9302,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -8215,10 +9342,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -8285,7 +9412,7 @@ paths:
description: ''
/api/v1/overviews/providers:
get:
- operationId: overviews_providers_retrieve
+ operationId: api_v1_overviews_providers_retrieve
description: Retrieve an aggregated overview of findings and resources grouped
by providers. The response includes the count of passed, failed, and manual
findings, along with the total number of resources managed by each provider.
@@ -8319,7 +9446,7 @@ paths:
description: ''
/api/v1/overviews/providers/count:
get:
- operationId: overviews_providers_count_retrieve
+ operationId: api_v1_overviews_providers_count_retrieve
description: Retrieve the number of providers grouped by provider type. This
endpoint counts every provider in the tenant, including those without completed
scans.
@@ -8350,7 +9477,7 @@ paths:
description: ''
/api/v1/overviews/regions:
get:
- operationId: overviews_regions_retrieve
+ operationId: api_v1_overviews_regions_retrieve
description: Retrieve an aggregated summary of findings grouped by region. The
response includes the total, passed, failed, and muted findings for each region
based on the latest completed scans per provider. Standard overview filters
@@ -8394,6 +9521,21 @@ paths:
schema:
type: string
format: date-time
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -8413,7 +9555,7 @@ paths:
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -8427,10 +9569,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -8454,7 +9596,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -8468,10 +9610,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -8553,7 +9695,7 @@ paths:
description: ''
/api/v1/overviews/resource-groups:
get:
- operationId: overviews_resource_groups_list
+ operationId: api_v1_overviews_resource_groups_list
description: Retrieve aggregated resource group metrics from latest completed
scans per provider. Returns one row per resource group with total, failed,
and new failed findings counts, plus a severity breakdown showing failed findings
@@ -8576,6 +9718,21 @@ paths:
description: endpoint return only specific fields in the response on a per-type
basis by including a fields[TYPE] query parameter.
explode: false
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -8595,7 +9752,7 @@ paths:
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -8609,10 +9766,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -8636,7 +9793,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -8650,10 +9807,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -8741,7 +9898,7 @@ paths:
description: ''
/api/v1/overviews/services:
get:
- operationId: overviews_services_retrieve
+ operationId: api_v1_overviews_services_retrieve
description: Retrieve an aggregated summary of findings grouped by service.
The response includes the total count of findings for each service, as long
as there are at least one finding for that service.
@@ -8782,6 +9939,21 @@ paths:
schema:
type: string
format: date-time
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -8801,7 +9973,7 @@ paths:
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -8815,10 +9987,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -8842,7 +10014,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -8856,10 +10028,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -8937,7 +10109,7 @@ paths:
description: ''
/api/v1/overviews/threatscore:
get:
- operationId: overviews_threatscore_retrieve
+ operationId: api_v1_overviews_threatscore_retrieve
description: Retrieve ThreatScore metrics. By default, returns the latest snapshot
for each provider. Use snapshot_id to retrieve a specific historical snapshot.
summary: Get ThreatScore snapshots
@@ -8968,6 +10140,38 @@ paths:
description: endpoint return only specific fields in the response on a per-type
basis by including a fields[TYPE] query parameter.
explode: false
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ description: Filter by provider group ID
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: string
+ description: Filter by multiple provider group IDs (comma-separated UUIDs)
+ - in: query
+ name: filter[provider_id]
+ schema:
+ type: string
+ format: uuid
+ description: Filter by specific provider ID
+ - in: query
+ name: filter[provider_id__in]
+ schema:
+ type: string
+ description: Filter by multiple provider IDs (comma-separated UUIDs)
+ - in: query
+ name: filter[provider_type]
+ schema:
+ type: string
+ description: Filter by provider type (aws, azure, gcp, etc.)
+ - in: query
+ name: filter[provider_type__in]
+ schema:
+ type: string
+ description: Filter by multiple provider types (comma-separated)
- in: query
name: include
schema:
@@ -8980,27 +10184,6 @@ paths:
description: include query parameter to allow the client to customize which
related resources should be returned.
explode: false
- - in: query
- name: provider_id
- schema:
- type: string
- format: uuid
- description: Filter by specific provider ID
- - in: query
- name: provider_id__in
- schema:
- type: string
- description: Filter by multiple provider IDs (comma-separated UUIDs)
- - in: query
- name: provider_type
- schema:
- type: string
- description: Filter by provider type (aws, azure, gcp, etc.)
- - in: query
- name: provider_type__in
- schema:
- type: string
- description: Filter by multiple provider types (comma-separated)
- in: query
name: snapshot_id
schema:
@@ -9021,7 +10204,7 @@ paths:
description: ''
/api/v1/processors:
get:
- operationId: processors_list
+ operationId: api_v1_processors_list
description: Retrieve a list of all configured processors with options for filtering
by various criteria.
summary: List all processors
@@ -9116,7 +10299,7 @@ paths:
$ref: '#/components/schemas/PaginatedProcessorList'
description: ''
post:
- operationId: processors_create
+ operationId: api_v1_processors_create
description: Register a new processor with the system, providing necessary configuration
details. There can only be one processor of each type per tenant.
summary: Create a new processor
@@ -9145,7 +10328,7 @@ paths:
description: ''
/api/v1/processors/{id}:
get:
- operationId: processors_retrieve
+ operationId: api_v1_processors_retrieve
description: Fetch detailed information about a specific processor by its ID.
summary: Retrieve processor details
parameters:
@@ -9183,7 +10366,7 @@ paths:
$ref: '#/components/schemas/ProcessorResponse'
description: ''
patch:
- operationId: processors_partial_update
+ operationId: api_v1_processors_partial_update
description: Modify certain fields of an existing processor without affecting
other settings.
summary: Partially update a processor
@@ -9219,7 +10402,7 @@ paths:
$ref: '#/components/schemas/ProcessorUpdateResponse'
description: ''
delete:
- operationId: processors_destroy
+ operationId: api_v1_processors_destroy
description: Remove a processor from the system by its ID.
summary: Delete a processor
parameters:
@@ -9239,7 +10422,7 @@ paths:
description: No response body
/api/v1/provider-groups:
get:
- operationId: provider_groups_list
+ operationId: api_v1_provider_groups_list
description: Retrieve a list of all provider groups with options for filtering
by various criteria.
summary: List all provider groups
@@ -9372,7 +10555,7 @@ paths:
$ref: '#/components/schemas/PaginatedProviderGroupList'
description: ''
post:
- operationId: provider_groups_create
+ operationId: api_v1_provider_groups_create
description: Add a new provider group to the system by providing the required
provider group details.
summary: Create a new provider group
@@ -9401,7 +10584,7 @@ paths:
description: ''
/api/v1/provider-groups/{id}:
get:
- operationId: provider_groups_retrieve
+ operationId: api_v1_provider_groups_retrieve
description: Fetch detailed information about a specific provider group by their
ID.
summary: Retrieve data from a provider group
@@ -9441,7 +10624,7 @@ paths:
$ref: '#/components/schemas/ProviderGroupResponse'
description: ''
patch:
- operationId: provider_groups_partial_update
+ operationId: api_v1_provider_groups_partial_update
description: Update certain fields of an existing provider group's information
without affecting other fields.
summary: Partially update a provider group
@@ -9477,7 +10660,7 @@ paths:
$ref: '#/components/schemas/SerializerMetaclassResponse'
description: ''
delete:
- operationId: provider_groups_destroy
+ operationId: api_v1_provider_groups_destroy
description: Remove a provider group from the system by their ID.
summary: Delete a provider group
parameters:
@@ -9497,7 +10680,7 @@ paths:
description: No response body
/api/v1/provider-groups/{id}/relationships/providers:
post:
- operationId: provider_groups_relationships_providers_create
+ operationId: api_v1_provider_groups_relationships_providers_create
description: Add a new provider_group-providers relationship to the system by
providing the required provider_group-providers details.
summary: Create a new provider_group-providers relationship
@@ -9523,7 +10706,7 @@ paths:
'400':
description: Bad request (e.g., relationship already exists)
patch:
- operationId: provider_groups_relationships_providers_partial_update
+ operationId: api_v1_provider_groups_relationships_providers_partial_update
description: Update the provider_group-providers relationship information without
affecting other fields.
summary: Partially update a provider_group-providers relationship
@@ -9547,7 +10730,7 @@ paths:
'204':
description: Relationship updated successfully
delete:
- operationId: provider_groups_relationships_providers_destroy
+ operationId: api_v1_provider_groups_relationships_providers_destroy
description: Remove the provider_group-providers relationship from the system
by their ID.
summary: Delete a provider_group-providers relationship
@@ -9560,7 +10743,7 @@ paths:
description: Relationship deleted successfully
/api/v1/providers:
get:
- operationId: providers_list
+ operationId: api_v1_providers_list
description: Retrieve a list of all providers with options for filtering by
various criteria.
summary: List all providers
@@ -9648,7 +10831,7 @@ paths:
name: filter[provider]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -9662,10 +10845,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -9689,7 +10872,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -9703,10 +10886,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -9728,11 +10911,26 @@ paths:
* `okta` - Okta
explode: false
style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -9746,10 +10944,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -9773,7 +10971,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -9787,10 +10985,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -9910,7 +11108,7 @@ paths:
$ref: '#/components/schemas/PaginatedProviderList'
description: ''
post:
- operationId: providers_create
+ operationId: api_v1_providers_create
description: Add a new provider to the system by providing the required provider
details.
summary: Create a new provider
@@ -9939,7 +11137,7 @@ paths:
description: ''
/api/v1/providers/{id}:
get:
- operationId: providers_retrieve
+ operationId: api_v1_providers_retrieve
description: Fetch detailed information about a specific provider by their ID.
summary: Retrieve data from a provider
parameters:
@@ -9992,7 +11190,7 @@ paths:
$ref: '#/components/schemas/ProviderResponse'
description: ''
patch:
- operationId: providers_partial_update
+ operationId: api_v1_providers_partial_update
description: Update certain fields of an existing provider's information without
affecting other fields.
summary: Partially update a provider
@@ -10028,7 +11226,7 @@ paths:
$ref: '#/components/schemas/SerializerMetaclassResponse'
description: ''
delete:
- operationId: providers_destroy
+ operationId: api_v1_providers_destroy
description: Remove a provider from the system by their ID.
summary: Delete a provider
parameters:
@@ -10067,7 +11265,7 @@ paths:
description: ''
/api/v1/providers/{id}/connection:
post:
- operationId: providers_connection_create
+ operationId: api_v1_providers_connection_create
description: Try to verify connection. For instance, Role & Credentials are
set correctly
summary: Check connection
@@ -10107,7 +11305,7 @@ paths:
description: ''
/api/v1/providers/secrets:
get:
- operationId: providers_secrets_list
+ operationId: api_v1_providers_secrets_list
description: Retrieve a list of all secrets with options for filtering by various
criteria.
summary: List all secrets
@@ -10199,7 +11397,7 @@ paths:
$ref: '#/components/schemas/PaginatedProviderSecretList'
description: ''
post:
- operationId: providers_secrets_create
+ operationId: api_v1_providers_secrets_create
description: Add a new secret to the system by providing the required secret
details.
summary: Create a new secret
@@ -10228,7 +11426,7 @@ paths:
description: ''
/api/v1/providers/secrets/{id}:
get:
- operationId: providers_secrets_retrieve
+ operationId: api_v1_providers_secrets_retrieve
description: Fetch detailed information about a specific secret by their ID.
summary: Retrieve data from a secret
parameters:
@@ -10266,7 +11464,7 @@ paths:
$ref: '#/components/schemas/ProviderSecretResponse'
description: ''
patch:
- operationId: providers_secrets_partial_update
+ operationId: api_v1_providers_secrets_partial_update
description: Update certain fields of an existing secret's information without
affecting other fields.
summary: Partially update a secret
@@ -10301,7 +11499,7 @@ paths:
$ref: '#/components/schemas/ProviderSecretUpdateResponse'
description: ''
delete:
- operationId: providers_secrets_destroy
+ operationId: api_v1_providers_secrets_destroy
description: Remove a secret from the system by their ID.
summary: Delete a secret
parameters:
@@ -10320,7 +11518,7 @@ paths:
description: No response body
/api/v1/resources:
get:
- operationId: resources_list
+ operationId: api_v1_resources_list
description: Retrieve a list of all resources with options for filtering by
various criteria. Resources are objects that are discovered by Prowler. They
can be anything from a single host to a whole VPC.
@@ -10444,6 +11642,21 @@ paths:
description: Multiple values may be separated by commas.
explode: false
style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -10463,7 +11676,7 @@ paths:
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -10477,10 +11690,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -10504,7 +11717,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -10518,10 +11731,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -10746,7 +11959,7 @@ paths:
description: ''
/api/v1/resources/{id}:
get:
- operationId: resources_retrieve
+ operationId: api_v1_resources_retrieve
description: Fetch detailed information about a specific resource by their ID.
A Resource is an object that is discovered by Prowler. It can be anything
from a single host to a whole VPC.
@@ -10810,7 +12023,7 @@ paths:
description: ''
/api/v1/resources/{id}/events:
get:
- operationId: resources_events_list
+ operationId: api_v1_resources_events_list
description: |-
Retrieve events showing modification history for a resource. Returns who modified the resource and when. Currently only available for AWS resources.
@@ -10891,7 +12104,7 @@ paths:
description: Provider service unavailable
/api/v1/resources/latest:
get:
- operationId: resources_latest_retrieve
+ operationId: api_v1_resources_latest_retrieve
description: Retrieve a list of the latest resources from the latest scans for
each provider with options for filtering by various criteria.
summary: List the latest resources
@@ -10999,6 +12212,21 @@ paths:
description: Multiple values may be separated by commas.
explode: false
style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -11018,7 +12246,7 @@ paths:
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -11032,10 +12260,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -11059,7 +12287,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -11073,10 +12301,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -11256,7 +12484,7 @@ paths:
description: ''
/api/v1/resources/metadata:
get:
- operationId: resources_metadata_retrieve
+ operationId: api_v1_resources_metadata_retrieve
description: Fetch unique metadata values from a set of resources. This is useful
for dynamic filtering.
summary: Retrieve metadata values from resources
@@ -11367,6 +12595,21 @@ paths:
description: Multiple values may be separated by commas.
explode: false
style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -11386,7 +12629,7 @@ paths:
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -11400,10 +12643,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -11427,7 +12670,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -11441,10 +12684,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -11645,7 +12888,7 @@ paths:
description: ''
/api/v1/resources/metadata/latest:
get:
- operationId: resources_metadata_latest_retrieve
+ operationId: api_v1_resources_metadata_latest_retrieve
description: Fetch unique metadata values from a set of resources from the latest
scans for each provider. This is useful for dynamic filtering.
summary: Retrieve metadata values from the latest resources
@@ -11741,6 +12984,21 @@ paths:
description: Multiple values may be separated by commas.
explode: false
style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_id]
schema:
@@ -11760,7 +13018,7 @@ paths:
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -11774,10 +13032,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -11801,7 +13059,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -11815,10 +13073,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -11986,7 +13244,7 @@ paths:
description: ''
/api/v1/roles:
get:
- operationId: roles_list
+ operationId: api_v1_roles_list
description: Retrieve a list of all roles with options for filtering by various
criteria.
summary: List all roles
@@ -12155,7 +13413,7 @@ paths:
$ref: '#/components/schemas/PaginatedRoleList'
description: ''
post:
- operationId: roles_create
+ operationId: api_v1_roles_create
description: Add a new role to the system by providing the required role details.
summary: Create a new role
tags:
@@ -12183,7 +13441,7 @@ paths:
description: ''
/api/v1/roles/{id}:
get:
- operationId: roles_retrieve
+ operationId: api_v1_roles_retrieve
description: Fetch detailed information about a specific role by their ID.
summary: Retrieve data from a role
parameters:
@@ -12230,7 +13488,7 @@ paths:
$ref: '#/components/schemas/RoleResponse'
description: ''
patch:
- operationId: roles_partial_update
+ operationId: api_v1_roles_partial_update
description: Update selected fields on an existing role. When changing the `users`
relationship of a role that grants MANAGE_ACCOUNT, the API blocks attempts
that would leave the tenant without any MANAGE_ACCOUNT assignees and prevents
@@ -12268,7 +13526,7 @@ paths:
$ref: '#/components/schemas/SerializerMetaclassResponse'
description: ''
delete:
- operationId: roles_destroy
+ operationId: api_v1_roles_destroy
description: Delete the specified role. The API rejects deletion of the last
role in the tenant that grants MANAGE_ACCOUNT.
summary: Delete a role
@@ -12289,7 +13547,7 @@ paths:
description: No response body
/api/v1/roles/{id}/relationships/provider_groups:
post:
- operationId: roles_relationships_provider_groups_create
+ operationId: api_v1_roles_relationships_provider_groups_create
description: Add a new role-provider_groups relationship to the system by providing
the required role-provider_groups details.
summary: Create a new role-provider_groups relationship
@@ -12315,7 +13573,7 @@ paths:
'400':
description: Bad request (e.g., relationship already exists)
patch:
- operationId: roles_relationships_provider_groups_partial_update
+ operationId: api_v1_roles_relationships_provider_groups_partial_update
description: Update the role-provider_groups relationship information without
affecting other fields.
summary: Partially update a role-provider_groups relationship
@@ -12339,7 +13597,7 @@ paths:
'204':
description: Relationship updated successfully
delete:
- operationId: roles_relationships_provider_groups_destroy
+ operationId: api_v1_roles_relationships_provider_groups_destroy
description: Remove the role-provider_groups relationship from the system by
their ID.
summary: Delete a role-provider_groups relationship
@@ -12352,7 +13610,7 @@ paths:
description: Relationship deleted successfully
/api/v1/saml-config:
get:
- operationId: saml_config_list
+ operationId: api_v1_saml_config_list
description: Returns all the SAML-based SSO configurations associated with the
current tenant.
summary: List all SSO configurations
@@ -12421,7 +13679,7 @@ paths:
$ref: '#/components/schemas/PaginatedSAMLConfigurationList'
description: ''
post:
- operationId: saml_config_create
+ operationId: api_v1_saml_config_create
description: Creates a new SAML SSO configuration for the current tenant, including
email domain and metadata XML.
summary: Create the SSO configuration
@@ -12450,7 +13708,7 @@ paths:
description: ''
/api/v1/saml-config/{id}:
get:
- operationId: saml_config_retrieve
+ operationId: api_v1_saml_config_retrieve
description: Returns the details of a specific SAML configuration belonging
to the current tenant.
summary: Retrieve SSO configuration details
@@ -12488,7 +13746,7 @@ paths:
$ref: '#/components/schemas/SAMLConfigurationResponse'
description: ''
patch:
- operationId: saml_config_partial_update
+ operationId: api_v1_saml_config_partial_update
description: Partially updates an existing SAML SSO configuration. Supports
changes to email domain and metadata XML.
summary: Update the SSO configuration
@@ -12524,7 +13782,7 @@ paths:
$ref: '#/components/schemas/SAMLConfigurationResponse'
description: ''
delete:
- operationId: saml_config_destroy
+ operationId: api_v1_saml_config_destroy
description: Deletes an existing SAML SSO configuration associated with the
current tenant.
summary: Delete the SSO configuration
@@ -12545,7 +13803,7 @@ paths:
description: No response body
/api/v1/scans:
get:
- operationId: scans_list
+ operationId: api_v1_scans_list
description: Retrieve a list of all scans with options for filtering by various
criteria.
summary: List all scans
@@ -12655,11 +13913,26 @@ paths:
description: Multiple values may be separated by commas.
explode: false
style: form
+ - in: query
+ name: filter[provider_groups]
+ schema:
+ type: string
+ format: uuid
+ - in: query
+ name: filter[provider_groups__in]
+ schema:
+ type: array
+ items:
+ type: string
+ format: uuid
+ description: Multiple values may be separated by commas.
+ explode: false
+ style: form
- in: query
name: filter[provider_type]
schema:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -12673,10 +13946,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
* `aws` - AWS
* `azure` - Azure
@@ -12700,7 +13973,7 @@ paths:
type: array
items:
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
enum:
- alibabacloud
- aws
@@ -12714,10 +13987,10 @@ paths:
- kubernetes
- m365
- mongodbatlas
+ - okta
- openstack
- oraclecloud
- vercel
- - okta
description: |-
Multiple values may be separated by commas.
@@ -12889,7 +14162,7 @@ paths:
$ref: '#/components/schemas/PaginatedScanList'
description: ''
post:
- operationId: scans_create
+ operationId: api_v1_scans_create
description: Trigger a manual scan by providing the required scan details. If
`scanner_args` are not provided, the system will automatically use the default
settings from the associated provider. If you do provide `scanner_args`, these
@@ -12937,7 +14210,7 @@ paths:
description: ''
/api/v1/scans/{id}:
get:
- operationId: scans_retrieve
+ operationId: api_v1_scans_retrieve
description: Fetch detailed information about a specific scan by its ID.
summary: Retrieve data from a specific scan
parameters:
@@ -12996,7 +14269,7 @@ paths:
$ref: '#/components/schemas/ScanResponse'
description: ''
patch:
- operationId: scans_partial_update
+ operationId: api_v1_scans_partial_update
description: Update certain fields of an existing scan without affecting other
fields.
summary: Partially update a scan
@@ -13033,7 +14306,7 @@ paths:
description: ''
/api/v1/scans/{id}/cis:
get:
- operationId: scans_cis_retrieve
+ operationId: api_v1_scans_cis_retrieve
description: Download the CIS Benchmark compliance report as a PDF file. When
a provider ships multiple CIS versions, the report is generated for the highest
available version.
@@ -13100,7 +14373,7 @@ paths:
has not started yet
/api/v1/scans/{id}/compliance/{name}:
get:
- operationId: scans_compliance_retrieve
+ operationId: api_v1_scans_compliance_retrieve
description: Download a specific compliance report (e.g., 'cis_1.4_aws') as
a CSV file.
summary: Retrieve compliance report as CSV
@@ -13145,10 +14418,11 @@ paths:
description: Compliance report not found, or the scan has no reports yet
/api/v1/scans/{id}/compliance/{name}/ocsf:
get:
- operationId: scans_compliance_ocsf_retrieve
+ operationId: api_v1_scans_compliance_ocsf_retrieve
description: Download a specific compliance report as an OCSF JSON file. Only
universal frameworks that declare an output configuration produce this artifact
- (currently 'dora' and 'csa_ccm_4.0'); any other framework returns 404.
+ (currently 'dora_2022_2554', 'csa_ccm_4.0' and 'cis_controls_8.1'); any other
+ framework returns 404.
summary: Retrieve compliance report as OCSF JSON
parameters:
- in: query
@@ -13174,7 +14448,7 @@ paths:
name: name
schema:
type: string
- description: The compliance report name, like 'dora'
+ description: The compliance report name, like 'dora_2022_2554'
required: true
tags:
- Scan
@@ -13192,7 +14466,7 @@ paths:
an OCSF export, or the scan has no reports yet
/api/v1/scans/{id}/csa:
get:
- operationId: scans_csa_retrieve
+ operationId: api_v1_scans_csa_retrieve
description: Download CSA Cloud Controls Matrix (CCM) v4.0 compliance report
as a PDF file.
summary: Retrieve CSA CCM compliance report
@@ -13258,7 +14532,7 @@ paths:
task has not started yet
/api/v1/scans/{id}/ens:
get:
- operationId: scans_ens_retrieve
+ operationId: api_v1_scans_ens_retrieve
description: Download ENS RD2022 compliance report (e.g., 'ens_rd2022_aws')
as a PDF file.
summary: Retrieve ENS RD2022 compliance report
@@ -13324,7 +14598,7 @@ paths:
has not started yet
/api/v1/scans/{id}/nis2:
get:
- operationId: scans_nis2_retrieve
+ operationId: api_v1_scans_nis2_retrieve
description: Download NIS2 compliance report (Directive (EU) 2022/2555) as a
PDF file.
summary: Retrieve NIS2 compliance report
@@ -13390,7 +14664,7 @@ paths:
task has not started yet
/api/v1/scans/{id}/report:
get:
- operationId: scans_report_retrieve
+ operationId: api_v1_scans_report_retrieve
description: Returns a ZIP file containing the requested report
summary: Download ZIP report
parameters:
@@ -13428,7 +14702,7 @@ paths:
not started yet
/api/v1/scans/{id}/threatscore:
get:
- operationId: scans_threatscore_retrieve
+ operationId: api_v1_scans_threatscore_retrieve
description: Download a specific threatscore report (e.g., 'prowler_threatscore_aws')
as a PDF file.
summary: Retrieve threatscore report
@@ -13494,7 +14768,7 @@ paths:
generation task has not started yet
/api/v1/schedules/daily:
post:
- operationId: schedules_daily_create
+ operationId: api_v1_schedules_daily_create
description: Schedules a daily scan for the specified provider. This endpoint
creates a periodic task that will execute a scan every 24 hours.
summary: Create a daily schedule scan for a given provider
@@ -13538,7 +14812,7 @@ paths:
description: ''
/api/v1/tasks:
get:
- operationId: tasks_list
+ operationId: api_v1_tasks_list
description: Retrieve a list of all tasks with options for filtering by name,
state, and other criteria.
summary: List all tasks
@@ -13638,7 +14912,7 @@ paths:
description: ''
/api/v1/tasks/{id}:
get:
- operationId: tasks_retrieve
+ operationId: api_v1_tasks_retrieve
description: Fetch detailed information about a specific task by its ID.
summary: Retrieve data from a specific task
parameters:
@@ -13678,7 +14952,7 @@ paths:
$ref: '#/components/schemas/TaskResponse'
description: ''
delete:
- operationId: tasks_destroy
+ operationId: api_v1_tasks_destroy
description: Try to revoke a task using its ID. Only tasks that are not yet
in progress can be revoked.
summary: Revoke a task
@@ -13718,7 +14992,7 @@ paths:
description: ''
/api/v1/tenants:
get:
- operationId: tenants_list
+ operationId: api_v1_tenants_list
description: Retrieve a list of all tenants with options for filtering by various
criteria.
summary: List all tenants
@@ -13824,7 +15098,7 @@ paths:
$ref: '#/components/schemas/PaginatedTenantList'
description: ''
post:
- operationId: tenants_create
+ operationId: api_v1_tenants_create
description: Add a new tenant to the system by providing the required tenant
details.
summary: Create a new tenant
@@ -13853,7 +15127,7 @@ paths:
description: ''
/api/v1/tenants/{id}:
get:
- operationId: tenants_retrieve
+ operationId: api_v1_tenants_retrieve
description: Fetch detailed information about a specific tenant by their ID.
summary: Retrieve data from a tenant
parameters:
@@ -13888,7 +15162,7 @@ paths:
$ref: '#/components/schemas/TenantResponse'
description: ''
patch:
- operationId: tenants_partial_update
+ operationId: api_v1_tenants_partial_update
description: Update certain fields of an existing tenant's information without
affecting other fields.
summary: Partially update a tenant
@@ -13924,7 +15198,7 @@ paths:
$ref: '#/components/schemas/TenantResponse'
description: ''
delete:
- operationId: tenants_destroy
+ operationId: api_v1_tenants_destroy
description: Remove a tenant from the system by their ID.
summary: Delete a tenant
parameters:
@@ -13944,7 +15218,7 @@ paths:
description: No response body
/api/v1/tenants/{tenant_pk}/memberships:
get:
- operationId: tenants_memberships_list
+ operationId: api_v1_tenants_memberships_list
description: List the membership details of users in a tenant you are a part
of.
summary: List tenant memberships
@@ -14062,7 +15336,7 @@ paths:
description: ''
/api/v1/tenants/{tenant_pk}/memberships/{id}:
delete:
- operationId: tenants_memberships_destroy
+ operationId: api_v1_tenants_memberships_destroy
description: 'Delete a user''s membership from a tenant. This action: (1) removes
the membership, (2) revokes all refresh tokens for the expelled user, (3)
removes their role grants for this tenant, (4) cleans up orphaned roles, and
@@ -14093,7 +15367,7 @@ paths:
description: No response body
/api/v1/tenants/invitations:
get:
- operationId: tenants_invitations_list
+ operationId: api_v1_tenants_invitations_list
description: Retrieve a list of all tenant invitations with options for filtering
by various criteria.
summary: List all invitations
@@ -14275,7 +15549,7 @@ paths:
$ref: '#/components/schemas/PaginatedInvitationList'
description: ''
post:
- operationId: tenants_invitations_create
+ operationId: api_v1_tenants_invitations_create
description: Add a new tenant invitation to the system by providing the required
invitation details. The invited user will have to accept the invitations or
create an account using the given code.
@@ -14305,7 +15579,7 @@ paths:
description: ''
/api/v1/tenants/invitations/{id}:
get:
- operationId: tenants_invitations_retrieve
+ operationId: api_v1_tenants_invitations_retrieve
description: Fetch detailed information about a specific invitation by its ID.
summary: Retrieve data from a tenant invitation
parameters:
@@ -14346,7 +15620,7 @@ paths:
$ref: '#/components/schemas/InvitationResponse'
description: ''
patch:
- operationId: tenants_invitations_partial_update
+ operationId: api_v1_tenants_invitations_partial_update
description: Update certain fields of an existing tenant invitation's information
without affecting other fields.
summary: Partially update a tenant invitation
@@ -14381,7 +15655,7 @@ paths:
$ref: '#/components/schemas/InvitationUpdateResponse'
description: ''
delete:
- operationId: tenants_invitations_destroy
+ operationId: api_v1_tenants_invitations_destroy
description: Revoke a tenant invitation from the system by their ID.
summary: Revoke a tenant invitation
parameters:
@@ -14400,7 +15674,7 @@ paths:
description: No response body
/api/v1/tokens:
post:
- operationId: tokens_create
+ operationId: api_v1_tokens_create
description: Obtain a token by providing valid credentials and an optional tenant
ID.
summary: Obtain a token
@@ -14430,7 +15704,7 @@ paths:
description: ''
/api/v1/tokens/refresh:
post:
- operationId: tokens_refresh_create
+ operationId: api_v1_tokens_refresh_create
description: Refresh an access token by providing a valid refresh token. Former
refresh tokens are invalidated when a new one is issued.
summary: Refresh a token
@@ -14460,7 +15734,7 @@ paths:
description: ''
/api/v1/tokens/switch:
post:
- operationId: tokens_switch_create
+ operationId: api_v1_tokens_switch_create
description: Switch tenant by providing a valid tenant ID. The authenticated
user must belong to the tenant.
summary: Switch tenant using a valid tenant ID
@@ -14489,7 +15763,7 @@ paths:
description: ''
/api/v1/users:
get:
- operationId: users_list
+ operationId: api_v1_users_list
description: Retrieve a list of all users with options for filtering by various
criteria.
summary: List all users
@@ -14620,7 +15894,7 @@ paths:
$ref: '#/components/schemas/PaginatedUserList'
description: ''
post:
- operationId: users_create
+ operationId: api_v1_users_create
description: Create a new user account by providing the necessary registration
details.
summary: Register a new user
@@ -14657,7 +15931,7 @@ paths:
description: ''
/api/v1/users/{id}:
get:
- operationId: users_retrieve
+ operationId: api_v1_users_retrieve
description: Fetch detailed information about an authenticated user.
summary: Retrieve a user's information
parameters:
@@ -14708,7 +15982,7 @@ paths:
$ref: '#/components/schemas/UserResponse'
description: ''
patch:
- operationId: users_partial_update
+ operationId: api_v1_users_partial_update
description: Partially update information about a user.
summary: Update user information
parameters:
@@ -14743,7 +16017,7 @@ paths:
$ref: '#/components/schemas/UserUpdateResponse'
description: ''
delete:
- operationId: users_destroy
+ operationId: api_v1_users_destroy
description: Remove the current user account from the system.
summary: Delete the user account
parameters:
@@ -14763,7 +16037,7 @@ paths:
description: No response body
/api/v1/users/{id}/relationships/roles:
post:
- operationId: users_relationships_roles_create
+ operationId: api_v1_users_relationships_roles_create
description: Add a new user-roles relationship to the system by providing the
required user-roles details.
summary: Create a new user-roles relationship
@@ -14789,7 +16063,7 @@ paths:
'400':
description: Bad request (e.g., relationship already exists)
patch:
- operationId: users_relationships_roles_partial_update
+ operationId: api_v1_users_relationships_roles_partial_update
description: Update the user-roles relationship information without affecting
other fields. If the update would remove MANAGE_ACCOUNT from the last remaining
user in the tenant, the API rejects the request with a 400 response.
@@ -14814,7 +16088,7 @@ paths:
'204':
description: Relationship updated successfully
delete:
- operationId: users_relationships_roles_destroy
+ operationId: api_v1_users_relationships_roles_destroy
description: Remove the user-roles relationship from the system by their ID.
If removing MANAGE_ACCOUNT would take it away from the last remaining user
in the tenant, the API rejects the request with a 400 response. Users also
@@ -14830,7 +16104,7 @@ paths:
description: Relationship deleted successfully
/api/v1/users/{user_pk}/memberships:
get:
- operationId: users_memberships_list
+ operationId: api_v1_users_memberships_list
description: Retrieve a list of all user memberships with options for filtering
by various criteria.
summary: List user memberships
@@ -14943,7 +16217,7 @@ paths:
description: ''
/api/v1/users/{user_pk}/memberships/{id}:
get:
- operationId: users_memberships_retrieve
+ operationId: api_v1_users_memberships_retrieve
description: Fetch detailed information about a specific user membership by
their ID.
summary: Retrieve membership data from the user
@@ -14988,7 +16262,7 @@ paths:
description: ''
/api/v1/users/me:
get:
- operationId: users_me_retrieve
+ operationId: api_v1_users_me_retrieve
description: Fetch detailed information about the authenticated user.
summary: Retrieve the current user's information
parameters:
@@ -20271,18 +21545,22 @@ components:
properties:
okta_client_id:
type: string
- description: Client ID of the Okta API Services app used for OAuth 2.0 private-key JWT authentication.
+ description: Client ID of the Okta API Services app used for
+ OAuth 2.0 private-key JWT authentication.
okta_private_key:
type: string
- description: PEM-encoded private key whose matching public key (JWK) is registered on the Okta service app.
+ description: PEM-encoded private key whose matching public
+ key (JWK) is registered on the Okta service app.
okta_scopes:
type: array
items:
type: string
- description: OAuth scopes to request. Optional; defaults to the minimum set required to run the currently enabled Okta checks.
+ description: OAuth scopes to request. Optional; defaults to
+ the minimum set required to run the currently enabled Okta
+ checks.
required:
- - okta_client_id
- - okta_private_key
+ - okta_client_id
+ - okta_private_key
- type: object
title: Vercel API Token
properties:
@@ -21314,7 +22592,7 @@ components:
* `googleworkspace` - Google Workspace
* `vercel` - Vercel
* `okta` - Okta
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
uid:
type: string
title: Unique identifier for the provider, set by the provider
@@ -21437,7 +22715,7 @@ components:
- vercel
- okta
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
description: |-
Type of provider to create.
@@ -21511,7 +22789,7 @@ components:
- vercel
- okta
type: string
- x-spec-enum-id: 91f917e0c3ab97e8
+ x-spec-enum-id: 203afc16daac9b64
description: |-
Type of provider to create.
@@ -22385,18 +23663,21 @@ components:
properties:
okta_client_id:
type: string
- description: Client ID of the Okta API Services app used for OAuth 2.0 private-key JWT authentication.
+ description: Client ID of the Okta API Services app used for OAuth
+ 2.0 private-key JWT authentication.
okta_private_key:
type: string
- description: PEM-encoded private key whose matching public key (JWK) is registered on the Okta service app.
+ description: PEM-encoded private key whose matching public key
+ (JWK) is registered on the Okta service app.
okta_scopes:
type: array
items:
type: string
- description: OAuth scopes to request. Optional; defaults to the minimum set required to run the currently enabled Okta checks.
+ description: OAuth scopes to request. Optional; defaults to the
+ minimum set required to run the currently enabled Okta checks.
required:
- - okta_client_id
- - okta_private_key
+ - okta_client_id
+ - okta_private_key
- type: object
title: Vercel API Token
properties:
@@ -22827,18 +24108,22 @@ components:
properties:
okta_client_id:
type: string
- description: Client ID of the Okta API Services app used for OAuth 2.0 private-key JWT authentication.
+ description: Client ID of the Okta API Services app used for
+ OAuth 2.0 private-key JWT authentication.
okta_private_key:
type: string
- description: PEM-encoded private key whose matching public key (JWK) is registered on the Okta service app.
+ description: PEM-encoded private key whose matching public
+ key (JWK) is registered on the Okta service app.
okta_scopes:
type: array
items:
type: string
- description: OAuth scopes to request. Optional; defaults to the minimum set required to run the currently enabled Okta checks.
+ description: OAuth scopes to request. Optional; defaults to
+ the minimum set required to run the currently enabled Okta
+ checks.
required:
- - okta_client_id
- - okta_private_key
+ - okta_client_id
+ - okta_private_key
- type: object
title: Vercel API Token
properties:
@@ -23279,18 +24564,21 @@ components:
properties:
okta_client_id:
type: string
- description: Client ID of the Okta API Services app used for OAuth 2.0 private-key JWT authentication.
+ description: Client ID of the Okta API Services app used for OAuth
+ 2.0 private-key JWT authentication.
okta_private_key:
type: string
- description: PEM-encoded private key whose matching public key (JWK) is registered on the Okta service app.
+ description: PEM-encoded private key whose matching public key
+ (JWK) is registered on the Okta service app.
okta_scopes:
type: array
items:
type: string
- description: OAuth scopes to request. Optional; defaults to the minimum set required to run the currently enabled Okta checks.
+ description: OAuth scopes to request. Optional; defaults to the
+ minimum set required to run the currently enabled Okta checks.
required:
- - okta_client_id
- - okta_private_key
+ - okta_client_id
+ - okta_private_key
- type: object
title: Vercel API Token
properties:
diff --git a/api/src/backend/api/sse/channelmanager.py b/api/src/backend/api/sse/channelmanager.py
index 9190d4ab16..84a9362a19 100644
--- a/api/src/backend/api/sse/channelmanager.py
+++ b/api/src/backend/api/sse/channelmanager.py
@@ -16,7 +16,7 @@ if TYPE_CHECKING:
class SSEChannelManager(DefaultChannelManager):
"""Connect `django-eventstream` to the platform's SSE viewsets."""
- def get_channels_for_request(self, request: Request, view_kwargs: dict) -> set[str]: # noqa: vulture
+ def get_channels_for_request(self, request: Request, view_kwargs: dict) -> set[str]:
"""Return the request's channels scoped to the active JWT tenant.
Args:
@@ -30,6 +30,7 @@ class SSEChannelManager(DefaultChannelManager):
The subset of `request.sse_channels` whose embedded tenant
matches the active request tenant.
"""
+ _ = view_kwargs
try:
request_tenant_id = UUID(str(getattr(request, "tenant_id", None)))
except (TypeError, ValueError):
diff --git a/api/src/backend/api/tests/integration/test_authentication.py b/api/src/backend/api/tests/integration/test_authentication.py
index 4d1c40fe23..67f498b238 100644
--- a/api/src/backend/api/tests/integration/test_authentication.py
+++ b/api/src/backend/api/tests/integration/test_authentication.py
@@ -1,3 +1,4 @@
+import json
import time
from datetime import UTC, datetime, timedelta
from uuid import uuid4
@@ -8,6 +9,23 @@ from conftest import TEST_PASSWORD, get_api_tokens, get_authorization_header
from django.urls import reverse
from drf_simple_apikey.crypto import get_crypto
from rest_framework.test import APIClient
+from rest_framework_simplejwt.token_blacklist.models import (
+ BlacklistedToken,
+ OutstandingToken,
+)
+
+PASSWORD_CHANGE_PASSWORD = "InitialSecret123@"
+
+
+@pytest.fixture
+def password_change_user(tenants_fixture):
+ user = User.objects.create_user(
+ name="password_change_user",
+ email=f"password-change-{uuid4()}@prowler.com",
+ password=PASSWORD_CHANGE_PASSWORD,
+ )
+ Membership.objects.create(user=user, tenant=tenants_fixture[0])
+ return user
@pytest.mark.django_db
@@ -103,6 +121,120 @@ def test_refresh_token(create_test_user, tenants_fixture):
assert new_refresh_response.status_code == 200
+@pytest.mark.django_db
+def test_password_change_invalidates_existing_tokens(password_change_user):
+ client = APIClient()
+ new_password = "ChangedSecret123@"
+
+ access_token, refresh_token = get_api_tokens(
+ client, password_change_user.email, PASSWORD_CHANGE_PASSWORD
+ )
+ auth_headers = get_authorization_header(access_token)
+ outstanding_token_ids = list(
+ OutstandingToken.objects.filter(user=password_change_user).values_list(
+ "id", flat=True
+ )
+ )
+ assert outstanding_token_ids
+ assert not BlacklistedToken.objects.filter(
+ token_id__in=outstanding_token_ids
+ ).exists()
+
+ password_change_payload = {
+ "data": {
+ "type": "users",
+ "id": str(password_change_user.id),
+ "attributes": {"password": new_password},
+ }
+ }
+ password_change_response = client.patch(
+ reverse("user-detail", kwargs={"pk": password_change_user.id}),
+ data=json.dumps(password_change_payload),
+ headers=auth_headers,
+ content_type="application/vnd.api+json",
+ )
+ assert password_change_response.status_code == 200, password_change_response.json()
+ assert BlacklistedToken.objects.filter(
+ token_id__in=outstanding_token_ids
+ ).count() == len(outstanding_token_ids)
+
+ old_access_response = client.get(reverse("user-me"), headers=auth_headers)
+ assert old_access_response.status_code == 401
+
+ old_refresh_response = client.post(
+ reverse("token-refresh"),
+ data={
+ "data": {
+ "type": "tokens-refresh",
+ "attributes": {"refresh": refresh_token},
+ }
+ },
+ format="vnd.api+json",
+ )
+ assert old_refresh_response.status_code == 400
+
+ new_access_token, _ = get_api_tokens(
+ client, password_change_user.email, new_password
+ )
+ new_access_response = client.get(
+ reverse("user-me"), headers=get_authorization_header(new_access_token)
+ )
+ assert new_access_response.status_code == 200
+
+
+@pytest.mark.django_db
+def test_password_change_invalidates_rotated_refresh_token(
+ password_change_user,
+):
+ client = APIClient()
+ new_password = "ChangedSecret123@"
+
+ access_token, refresh_token = get_api_tokens(
+ client, password_change_user.email, PASSWORD_CHANGE_PASSWORD
+ )
+ rotated_refresh_response = client.post(
+ reverse("token-refresh"),
+ data={
+ "data": {
+ "type": "tokens-refresh",
+ "attributes": {"refresh": refresh_token},
+ }
+ },
+ format="vnd.api+json",
+ )
+ assert rotated_refresh_response.status_code == 200
+ rotated_refresh_token = rotated_refresh_response.json()["data"]["attributes"][
+ "refresh"
+ ]
+
+ password_change_payload = {
+ "data": {
+ "type": "users",
+ "id": str(password_change_user.id),
+ "attributes": {"password": new_password},
+ }
+ }
+ password_change_response = client.patch(
+ reverse("user-detail", kwargs={"pk": password_change_user.id}),
+ data=json.dumps(password_change_payload),
+ headers=get_authorization_header(access_token),
+ content_type="application/vnd.api+json",
+ )
+ assert password_change_response.status_code == 200, password_change_response.json()
+
+ old_rotated_refresh_response = client.post(
+ reverse("token-refresh"),
+ data={
+ "data": {
+ "type": "tokens-refresh",
+ "attributes": {"refresh": rotated_refresh_token},
+ }
+ },
+ format="vnd.api+json",
+ )
+ assert old_rotated_refresh_response.status_code == 400
+
+
@pytest.mark.django_db
def test_user_me_when_inviting_users(create_test_user, tenants_fixture, roles_fixture):
client = APIClient()
@@ -187,8 +319,9 @@ def test_user_me_when_inviting_users(create_test_user, tenants_fixture, roles_fi
@pytest.mark.django_db
class TestTokenSwitchTenant:
- def test_switch_tenant_with_valid_token(self, tenants_fixture, providers_fixture):
+ def test_switch_tenant_with_valid_token(self, tenants_fixture, aws_provider):
client = APIClient()
+ assert aws_provider
test_user = "test_email@prowler.com"
test_password = "Test_password1@"
@@ -1396,13 +1529,14 @@ class TestAPIKeyMultiTenantWorkflows:
assert me_response2.json()["data"]["id"] == str(user.id)
def test_api_key_cannot_access_different_tenant_resources(
- self, tenants_fixture, providers_fixture
+ self, tenants_fixture, aws_provider
):
"""API key from one tenant cannot access resources from another tenant.
Verifies RLS enforcement after authentication ensures tenant isolation.
"""
client = APIClient()
+ assert aws_provider
user1 = User.objects.create_user(
name="tenant1_user",
diff --git a/api/src/backend/api/tests/integration/test_rls_transaction.py b/api/src/backend/api/tests/integration/test_rls_transaction.py
index bd46871586..ce026d4f58 100644
--- a/api/src/backend/api/tests/integration/test_rls_transaction.py
+++ b/api/src/backend/api/tests/integration/test_rls_transaction.py
@@ -1,8 +1,12 @@
"""Tests for rls_transaction retry and fallback logic."""
+from unittest.mock import patch
+
import pytest
-from api.db_utils import rls_transaction
-from django.db import DEFAULT_DB_ALIAS
+from api.db_utils import POSTGRES_TENANT_VAR, rls_transaction
+from conftest import TEST_REPLICA_ALIAS
+from django.db import DEFAULT_DB_ALIAS, OperationalError, connections
+from psycopg2 import OperationalError as Psycopg2OperationalError
from rest_framework_json_api.serializers import ValidationError
@@ -36,3 +40,35 @@ class TestRLSTransaction:
cursor.execute("SELECT current_setting(%s, true)", [custom_param])
result = cursor.fetchone()
assert result == (str(tenant.id),)
+
+ @pytest.mark.requires_test_replica_alias
+ @pytest.mark.django_db(
+ transaction=True, databases=[DEFAULT_DB_ALIAS, TEST_REPLICA_ALIAS]
+ )
+ def test_mid_query_replica_connection_loss_falls_back_to_primary(self, tenant):
+ """Real Django connection state: closed replica atomic falls back to primary."""
+ replica = connections[TEST_REPLICA_ALIAS]
+ sql = "SELECT current_setting(%s, true), %s"
+ params = [POSTGRES_TENANT_VAR, 42]
+ failed_once = {"value": False}
+
+ def close_replica_and_raise(execute, sql_arg, params_arg, many, context):
+ if not failed_once["value"] and sql_arg == sql:
+ failed_once["value"] = True
+ replica.close()
+ try:
+ raise Psycopg2OperationalError("SSL SYSCALL error: EOF detected")
+ except Psycopg2OperationalError as psycopg_error:
+ raise OperationalError(
+ "SSL SYSCALL error: EOF detected"
+ ) from psycopg_error
+ return execute(sql_arg, params_arg, many, context)
+
+ with patch("api.db_utils.READ_REPLICA_ALIAS", TEST_REPLICA_ALIAS):
+ with rls_transaction(str(tenant.id), using=TEST_REPLICA_ALIAS) as cursor:
+ with replica.execute_wrapper(close_replica_and_raise):
+ cursor.execute(sql, params)
+ result = cursor.fetchone()
+
+ assert failed_once["value"]
+ assert result == (str(tenant.id), 42)
diff --git a/api/src/backend/api/tests/test_adapters.py b/api/src/backend/api/tests/test_adapters.py
index 91d3bb054a..c86d3f5620 100644
--- a/api/src/backend/api/tests/test_adapters.py
+++ b/api/src/backend/api/tests/test_adapters.py
@@ -2,11 +2,18 @@ from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
-from allauth.socialaccount.models import SocialLogin
+from allauth.account import app_settings as account_app_settings
+from allauth.account.models import EmailAddress
+from allauth.core import context
+from allauth.core.exceptions import ImmediateHttpResponse
+from allauth.socialaccount import app_settings as socialaccount_app_settings
+from allauth.socialaccount.internal.flows.login import complete_login
+from allauth.socialaccount.models import SocialAccount, SocialLogin
from api.adapters import ProwlerSocialAccountAdapter
from api.db_router import MainRouter
-from api.models import SAMLConfiguration
+from api.models import Invitation, Membership, SAMLConfiguration, Tenant
from django.contrib.auth import get_user_model
+from django.core import mail
User = get_user_model()
@@ -40,6 +47,7 @@ def _saml_request(rf, organization_slug):
def _saml_sociallogin(user):
sociallogin = MagicMock(spec=SocialLogin)
sociallogin.account = MagicMock()
+ sociallogin.account.pk = None
sociallogin.provider = MagicMock()
sociallogin.provider.id = "saml"
sociallogin.account.extra_data = {}
@@ -48,6 +56,59 @@ def _saml_sociallogin(user):
return sociallogin
+def _oauth_sociallogin(
+ user,
+ *,
+ provider="google",
+ provider_email_verified=True,
+ include_extra_email=True,
+):
+ sociallogin = MagicMock(spec=SocialLogin)
+ sociallogin.account = MagicMock()
+ sociallogin.account.pk = None
+ sociallogin.provider = MagicMock()
+ sociallogin.provider.id = provider
+ sociallogin.account.extra_data = (
+ {"email": user.email} if include_extra_email else {}
+ )
+ sociallogin.email_addresses = [
+ EmailAddress(
+ email=user.email,
+ verified=provider_email_verified,
+ primary=True,
+ )
+ ]
+ sociallogin.user = user
+ sociallogin.connect = MagicMock()
+ return sociallogin
+
+
+def _real_oauth_sociallogin(user, uid):
+ provider = MagicMock()
+ provider.id = "google"
+ provider.app = None
+ provider.get_settings.return_value = {}
+ return SocialLogin(
+ user=user,
+ account=SocialAccount(
+ provider="google",
+ uid=uid,
+ extra_data={"email": user.email},
+ ),
+ email_addresses=[EmailAddress(email=user.email, verified=True, primary=True)],
+ provider=provider,
+ )
+
+
+def _verify_local_email(user):
+ return EmailAddress.objects.create(
+ user=user,
+ email=user.email,
+ verified=True,
+ primary=True,
+ )
+
+
@pytest.mark.django_db
class TestProwlerSocialAccountAdapter:
def test_get_user_by_email_returns_user(self, create_test_user):
@@ -157,6 +218,7 @@ class TestProwlerSocialAccountAdapter:
sociallogin = MagicMock(spec=SocialLogin)
sociallogin.account = MagicMock()
+ sociallogin.account.pk = None
sociallogin.provider = MagicMock()
sociallogin.user = MagicMock()
sociallogin.user.email = ""
@@ -168,25 +230,157 @@ class TestProwlerSocialAccountAdapter:
sociallogin.connect.assert_not_called()
- def test_pre_social_login_non_saml_links_by_email(self, create_test_user, rf):
- """Non-SAML providers (e.g. Google/GitHub) still link to an existing
- local account by email; the tenant binding only applies to SAML."""
+ def test_pre_social_login_blocks_unverified_local_email(self, create_test_user, rf):
+ """A verified OAuth email must not claim an unverified local account."""
adapter = ProwlerSocialAccountAdapter()
+ sociallogin = _oauth_sociallogin(create_test_user)
- sociallogin = MagicMock(spec=SocialLogin)
- sociallogin.account = MagicMock()
- sociallogin.provider = MagicMock()
- sociallogin.provider.id = "google"
- sociallogin.account.extra_data = {"email": create_test_user.email}
- sociallogin.user = create_test_user
- sociallogin.connect = MagicMock()
+ with pytest.raises(ImmediateHttpResponse) as exc_info:
+ adapter.pre_social_login(rf.get("/"), sociallogin)
+
+ assert exc_info.value.response.status_code == 403
+ sociallogin.connect.assert_not_called()
+
+ def test_complete_oauth_login_does_not_link_unverified_local_email(
+ self, create_test_user, rf
+ ):
+ """Regression test for the complete pre-hijack account-linking flow."""
+ incoming_user = User(email=create_test_user.email)
+ incoming_user.set_unusable_password()
+ sociallogin = _real_oauth_sociallogin(
+ incoming_user,
+ uid="victim-google-account",
+ )
+ request = rf.get("/")
+ request.session = {}
+
+ with pytest.raises(ImmediateHttpResponse) as exc_info:
+ complete_login(request, sociallogin, raises=True)
+
+ assert exc_info.value.response.status_code == 403
+ assert not SocialAccount.objects.filter(
+ provider="google", uid="victim-google-account"
+ ).exists()
+
+ def test_pre_social_login_allows_already_connected_account(
+ self, create_test_user, rf
+ ):
+ """Existing provider bindings do not need to relink on every login."""
+ adapter = ProwlerSocialAccountAdapter()
+ sociallogin = _oauth_sociallogin(create_test_user)
+ sociallogin.account.pk = "existing-social-account"
adapter.pre_social_login(rf.get("/"), sociallogin)
- call_args = sociallogin.connect.call_args
- assert call_args is not None
- _, called_user = call_args[0]
- assert called_user.email == create_test_user.email
+ sociallogin.connect.assert_not_called()
+
+ def test_pre_social_login_blocks_unverified_provider_email(
+ self, create_test_user, rf
+ ):
+ """An OAuth provider must prove ownership of the matching email."""
+ _verify_local_email(create_test_user)
+ adapter = ProwlerSocialAccountAdapter()
+ sociallogin = _oauth_sociallogin(
+ create_test_user,
+ provider="github",
+ provider_email_verified=False,
+ )
+
+ with pytest.raises(ImmediateHttpResponse) as exc_info:
+ adapter.pre_social_login(rf.get("/"), sociallogin)
+
+ assert exc_info.value.response.status_code == 403
+ sociallogin.connect.assert_not_called()
+
+ def test_pre_social_login_links_verified_emails(self, create_test_user, rf):
+ _verify_local_email(create_test_user)
+ adapter = ProwlerSocialAccountAdapter()
+ sociallogin = _oauth_sociallogin(create_test_user)
+ request = rf.get("/")
+
+ adapter.pre_social_login(request, sociallogin)
+
+ sociallogin.connect.assert_called_once_with(request, create_test_user)
+
+ def test_verified_social_account_link_does_not_send_notification(
+ self, create_test_user, rf
+ ):
+ _verify_local_email(create_test_user)
+ sociallogin = _real_oauth_sociallogin(
+ create_test_user,
+ uid="verified-google-account",
+ )
+
+ request = rf.get("/")
+ with context.request_context(request):
+ ProwlerSocialAccountAdapter().pre_social_login(request, sociallogin)
+
+ assert SocialAccount.objects.filter(
+ provider="google",
+ uid="verified-google-account",
+ user=create_test_user,
+ ).exists()
+ assert mail.outbox == []
+
+ def test_pre_social_login_uses_verified_email_missing_from_extra_data(
+ self, create_test_user, rf
+ ):
+ """GitHub can return its verified primary email outside extra_data."""
+ _verify_local_email(create_test_user)
+ adapter = ProwlerSocialAccountAdapter()
+ sociallogin = _oauth_sociallogin(
+ create_test_user,
+ provider="github",
+ include_extra_email=False,
+ )
+ request = rf.get("/")
+
+ adapter.pre_social_login(request, sociallogin)
+
+ sociallogin.connect.assert_called_once_with(request, create_test_user)
+
+ def test_social_account_linking_settings_are_fail_closed(self):
+ assert not socialaccount_app_settings.EMAIL_AUTHENTICATION
+ assert not socialaccount_app_settings.EMAIL_AUTHENTICATION_AUTO_CONNECT
+ assert not account_app_settings.EMAIL_NOTIFICATIONS
+
+ def test_save_user_social_with_invitation_joins_invited_tenant(
+ self, rf, create_test_user, tenants_fixture
+ ):
+ adapter = ProwlerSocialAccountAdapter()
+ invited_tenant = tenants_fixture[2]
+ invited_email = "frank-invited@example.com"
+ invitation = Invitation.objects.create(
+ tenant=invited_tenant,
+ email=invited_email,
+ inviter=create_test_user,
+ )
+ request = rf.post("/", data={"invitation_token": invitation.token})
+ request.session = {}
+
+ sociallogin = MagicMock(spec=SocialLogin)
+ sociallogin.provider = MagicMock()
+ sociallogin.provider.id = "google"
+ sociallogin.account = MagicMock()
+ sociallogin.account.extra_data = {"name": "Frank"}
+
+ real_user = User.objects.create_user(
+ name="Frank", email=invited_email, password="Secret123!"
+ )
+ tenants_before = Tenant.objects.count()
+
+ with patch("api.adapters.super") as mock_super:
+ mock_super.return_value.save_user.return_value = real_user
+ adapter.save_user(request, sociallogin)
+
+ invitation.refresh_from_db()
+ assert invitation.state == Invitation.State.ACCEPTED
+ assert Tenant.objects.count() == tenants_before
+ assert Membership.objects.filter(
+ user=real_user,
+ tenant=invited_tenant,
+ role=Membership.RoleChoices.MEMBER,
+ ).exists()
def test_save_user_saml_sets_session_flag(self, rf):
adapter = ProwlerSocialAccountAdapter()
diff --git a/api/src/backend/api/tests/test_attack_paths.py b/api/src/backend/api/tests/test_attack_paths.py
index 30104a5a63..77bc01d255 100644
--- a/api/src/backend/api/tests/test_attack_paths.py
+++ b/api/src/backend/api/tests/test_attack_paths.py
@@ -92,7 +92,9 @@ def test_prepare_parameters_validates_cast(
def test_execute_query_serializes_graph(
- attack_paths_query_definition_factory, attack_paths_graph_stub_classes
+ attack_paths_query_definition_factory,
+ attack_paths_graph_stub_classes,
+ sink_backend_stub,
):
definition = attack_paths_query_definition_factory(
id="aws-rds",
@@ -135,18 +137,17 @@ def test_execute_query_serializes_graph(
database_name = "db-tenant-test-tenant-id"
- with patch(
- "api.attack_paths.views_helpers.graph_database.execute_read_query",
- return_value=graph_result,
- ) as mock_execute_read_query:
- result = views_helpers.execute_query(
- database_name, definition, parameters, provider_id=provider_id
- )
+ sink_backend_stub.execute_read_query.return_value = graph_result
+ result = views_helpers.execute_query(
+ database_name,
+ definition,
+ parameters,
+ provider_id=provider_id,
+ scan=MagicMock(is_migrated=False, sink_backend="neo4j"),
+ )
- mock_execute_read_query.assert_called_once_with(
- database=database_name,
- cypher=definition.cypher,
- parameters=parameters,
+ sink_backend_stub.execute_read_query.assert_called_once_with(
+ database_name, definition.cypher, parameters
)
assert result["nodes"][0]["id"] == "node-1"
assert result["nodes"][0]["properties"]["complex"]["items"][0] == "value"
@@ -155,6 +156,7 @@ def test_execute_query_serializes_graph(
def test_execute_query_wraps_graph_errors(
attack_paths_query_definition_factory,
+ sink_backend_stub,
):
definition = attack_paths_query_definition_factory(
id="aws-rds",
@@ -167,16 +169,17 @@ def test_execute_query_wraps_graph_errors(
database_name = "db-tenant-test-tenant-id"
parameters = {"provider_uid": "123"}
- with (
- patch(
- "api.attack_paths.views_helpers.graph_database.execute_read_query",
- side_effect=graph_database.GraphDatabaseQueryException("boom"),
- ),
- patch("api.attack_paths.views_helpers.logger") as mock_logger,
- ):
+ sink_backend_stub.execute_read_query.side_effect = (
+ graph_database.GraphDatabaseQueryException("boom")
+ )
+ with patch("api.attack_paths.views_helpers.logger") as mock_logger:
with pytest.raises(APIException):
views_helpers.execute_query(
- database_name, definition, parameters, provider_id="test-provider-123"
+ database_name,
+ definition,
+ parameters,
+ provider_id="test-provider-123",
+ scan=MagicMock(is_migrated=False, sink_backend="neo4j"),
)
mock_logger.error.assert_called_once()
@@ -184,6 +187,7 @@ def test_execute_query_wraps_graph_errors(
def test_execute_query_raises_permission_denied_on_read_only(
attack_paths_query_definition_factory,
+ sink_backend_stub,
):
definition = attack_paths_query_definition_factory(
id="aws-rds",
@@ -196,17 +200,20 @@ def test_execute_query_raises_permission_denied_on_read_only(
database_name = "db-tenant-test-tenant-id"
parameters = {"provider_uid": "123"}
- with patch(
- "api.attack_paths.views_helpers.graph_database.execute_read_query",
- side_effect=graph_database.WriteQueryNotAllowedException(
+ sink_backend_stub.execute_read_query.side_effect = (
+ graph_database.WriteQueryNotAllowedException(
message="Read query not allowed",
code="Neo.ClientError.Statement.AccessMode",
- ),
- ):
- with pytest.raises(PermissionDenied):
- views_helpers.execute_query(
- database_name, definition, parameters, provider_id="test-provider-123"
- )
+ )
+ )
+ with pytest.raises(PermissionDenied):
+ views_helpers.execute_query(
+ database_name,
+ definition,
+ parameters,
+ provider_id="test-provider-123",
+ scan=MagicMock(is_migrated=False, sink_backend="neo4j"),
+ )
def test_serialize_graph_filters_by_provider_label(attack_paths_graph_stub_classes):
@@ -440,6 +447,7 @@ def test_normalize_custom_query_payload_passthrough_for_flat_dict():
def test_execute_custom_query_serializes_graph(
attack_paths_graph_stub_classes,
+ sink_backend_stub,
):
provider_id = "test-provider-123"
plabel = get_provider_label(provider_id)
@@ -453,50 +461,73 @@ def test_execute_custom_query_serializes_graph(
graph_result.nodes = [node_1, node_2]
graph_result.relationships = [relationship]
- with patch(
- "api.attack_paths.views_helpers.graph_database.execute_read_query",
- return_value=graph_result,
- ) as mock_execute:
- result = views_helpers.execute_custom_query(
- "db-tenant-test", "MATCH (n) RETURN n", provider_id
- )
+ sink_backend_stub.execute_read_query.return_value = graph_result
+ result = views_helpers.execute_custom_query(
+ "db-tenant-test",
+ "MATCH (n) RETURN n",
+ provider_id,
+ scan=MagicMock(is_migrated=False, sink_backend="neo4j"),
+ )
- mock_execute.assert_called_once()
- call_kwargs = mock_execute.call_args[1]
- assert call_kwargs["database"] == "db-tenant-test"
+ sink_backend_stub.execute_read_query.assert_called_once()
+ call_args = sink_backend_stub.execute_read_query.call_args[0]
+ assert call_args[0] == "db-tenant-test"
# The cypher is rewritten with the provider label injection
- assert plabel in call_kwargs["cypher"]
+ assert plabel in call_args[1]
assert len(result["nodes"]) == 2
assert result["relationships"][0]["label"] == "OWNS"
assert result["truncated"] is False
assert result["total_nodes"] == 2
-def test_execute_custom_query_raises_permission_denied_on_write():
+def test_execute_custom_query_adds_timeout_for_neptune_scan(sink_backend_stub):
+ graph_result = MagicMock()
+ graph_result.nodes = []
+ graph_result.relationships = []
+ sink_backend_stub.execute_read_query.return_value = graph_result
+
with patch(
- "api.attack_paths.views_helpers.graph_database.execute_read_query",
- side_effect=graph_database.WriteQueryNotAllowedException(
+ "api.attack_paths.views_helpers.sink_module.get_backend_for_scan",
+ return_value=sink_backend_stub,
+ ):
+ views_helpers.execute_custom_query(
+ "db-tenant-test",
+ "MATCH (n) RETURN n",
+ "provider-1",
+ scan=MagicMock(is_migrated=True, sink_backend="neptune"),
+ )
+
+ cypher = sink_backend_stub.execute_read_query.call_args[0][1]
+ assert cypher.startswith("USING QUERY:TIMEOUTMILLISECONDS")
+
+
+def test_execute_custom_query_raises_permission_denied_on_write(sink_backend_stub):
+ sink_backend_stub.execute_read_query.side_effect = (
+ graph_database.WriteQueryNotAllowedException(
message="Read query not allowed",
code="Neo.ClientError.Statement.AccessMode",
- ),
- ):
- with pytest.raises(PermissionDenied):
- views_helpers.execute_custom_query(
- "db-tenant-test", "CREATE (n) RETURN n", "provider-1"
- )
+ )
+ )
+ with pytest.raises(PermissionDenied):
+ views_helpers.execute_custom_query(
+ "db-tenant-test",
+ "CREATE (n) RETURN n",
+ "provider-1",
+ scan=MagicMock(is_migrated=False, sink_backend="neo4j"),
+ )
-def test_execute_custom_query_wraps_graph_errors():
- with (
- patch(
- "api.attack_paths.views_helpers.graph_database.execute_read_query",
- side_effect=graph_database.GraphDatabaseQueryException("boom"),
- ),
- patch("api.attack_paths.views_helpers.logger") as mock_logger,
- ):
+def test_execute_custom_query_wraps_graph_errors(sink_backend_stub):
+ sink_backend_stub.execute_read_query.side_effect = (
+ graph_database.GraphDatabaseQueryException("boom")
+ )
+ with patch("api.attack_paths.views_helpers.logger") as mock_logger:
with pytest.raises(APIException):
views_helpers.execute_custom_query(
- "db-tenant-test", "MATCH (n) RETURN n", "provider-1"
+ "db-tenant-test",
+ "MATCH (n) RETURN n",
+ "provider-1",
+ scan=MagicMock(is_migrated=False, sink_backend="neo4j"),
)
mock_logger.error.assert_called_once()
@@ -561,13 +592,33 @@ def test_truncate_graph_empty_graph():
@pytest.fixture
def mock_neo4j_session():
- """Mock the Neo4j driver so execute_read_query uses a fake session."""
+ """Install a Neo4jSink with a mocked Bolt driver into the sink factory.
+
+ The yielded mock is the `neo4j.Session` that the Neo4jSink will obtain via
+ `driver.session(...)`. Tests configure `mock_neo4j_session.execute_read`
+ return values / side effects to exercise the read-mode error translation
+ path on the real `Neo4jSink.execute_read_query` and `get_session` code.
+ """
+ from api.attack_paths.sink import factory
+ from api.attack_paths.sink.neo4j import Neo4jSink
+
mock_session = MagicMock(spec=neo4j.Session)
mock_driver = MagicMock(spec=neo4j.Driver)
mock_driver.session.return_value = mock_session
- with patch("api.attack_paths.database.get_driver", return_value=mock_driver):
+ sink = Neo4jSink()
+ sink._driver = mock_driver
+
+ previous_backend = factory._backend
+ previous_secondary = dict(factory._secondary_backends)
+ factory._backend = sink
+ factory._secondary_backends.clear()
+ try:
yield mock_session
+ finally:
+ factory._backend = previous_backend
+ factory._secondary_backends.clear()
+ factory._secondary_backends.update(previous_secondary)
def test_execute_read_query_succeeds_with_select(mock_neo4j_session):
@@ -663,16 +714,20 @@ def test_execute_read_query_rejects_apoc_real_create(mock_neo4j_session, cypher)
@pytest.fixture
def mock_schema_session():
- """Mock get_session for cartography schema tests."""
+ """Mock the routed sink backend session for cartography schema tests."""
mock_result = MagicMock()
mock_session = MagicMock()
mock_session.run.return_value = mock_result
+ mock_backend = MagicMock()
with patch(
- "api.attack_paths.views_helpers.graph_database.get_session"
- ) as mock_get_session:
- mock_get_session.return_value.__enter__ = MagicMock(return_value=mock_session)
- mock_get_session.return_value.__exit__ = MagicMock(return_value=False)
+ "api.attack_paths.views_helpers.sink_module.get_backend_for_scan",
+ return_value=mock_backend,
+ ):
+ mock_backend.get_session.return_value.__enter__ = MagicMock(
+ return_value=mock_session
+ )
+ mock_backend.get_session.return_value.__exit__ = MagicMock(return_value=False)
yield mock_session, mock_result
@@ -683,7 +738,9 @@ def test_get_cartography_schema_returns_urls(mock_schema_session):
"module_version": "0.129.0",
}
- result = views_helpers.get_cartography_schema("db-tenant-test", "provider-123")
+ result = views_helpers.get_cartography_schema(
+ "db-tenant-test", "provider-123", MagicMock(sink_backend="neo4j")
+ )
mock_session.run.assert_called_once()
assert result["id"] == "aws-0.129.0"
@@ -699,7 +756,9 @@ def test_get_cartography_schema_returns_none_when_no_data(mock_schema_session):
_, mock_result = mock_schema_session
mock_result.single.return_value = None
- result = views_helpers.get_cartography_schema("db-tenant-test", "provider-123")
+ result = views_helpers.get_cartography_schema(
+ "db-tenant-test", "provider-123", MagicMock(sink_backend="neo4j")
+ )
assert result is None
@@ -721,21 +780,29 @@ def test_get_cartography_schema_extracts_provider(
"module_version": "1.0.0",
}
- result = views_helpers.get_cartography_schema("db-tenant-test", "provider-123")
+ result = views_helpers.get_cartography_schema(
+ "db-tenant-test", "provider-123", MagicMock(sink_backend="neo4j")
+ )
assert result["id"] == f"{expected_provider}-1.0.0"
assert result["provider"] == expected_provider
def test_get_cartography_schema_wraps_database_error():
+ mock_backend = MagicMock()
+ mock_backend.get_session.side_effect = graph_database.GraphDatabaseQueryException(
+ "boom"
+ )
with (
patch(
- "api.attack_paths.views_helpers.graph_database.get_session",
- side_effect=graph_database.GraphDatabaseQueryException("boom"),
+ "api.attack_paths.views_helpers.sink_module.get_backend_for_scan",
+ return_value=mock_backend,
),
patch("api.attack_paths.views_helpers.logger") as mock_logger,
):
with pytest.raises(APIException):
- views_helpers.get_cartography_schema("db-tenant-test", "provider-123")
+ views_helpers.get_cartography_schema(
+ "db-tenant-test", "provider-123", MagicMock(sink_backend="neo4j")
+ )
mock_logger.error.assert_called_once()
diff --git a/api/src/backend/api/tests/test_attack_paths_database.py b/api/src/backend/api/tests/test_attack_paths_database.py
index bf37daf5ee..c4aca45928 100644
--- a/api/src/backend/api/tests/test_attack_paths_database.py
+++ b/api/src/backend/api/tests/test_attack_paths_database.py
@@ -1,623 +1,240 @@
-"""
-Tests for Neo4j database lazy initialization.
+"""Tests for the attack-paths database facade.
-The Neo4j driver is created on first use for every process type; app startup
-never contacts Neo4j. These tests validate the database module behavior itself.
+After the Neptune port, `api.attack_paths.database` is a thin routing shim
+over `api.attack_paths.ingest` (cartography temp DB, always Neo4j) and
+`api.attack_paths.sink` (configurable Neo4j or Neptune). The facade's
+contract is routing by database-name prefix and the public exception
+hierarchy; sink-internal behavior is exercised in `test_sink.py`.
"""
-import threading
from unittest.mock import MagicMock, patch
import api.attack_paths.database as db_module
-import neo4j
-import neo4j.exceptions
import pytest
-class TestLazyInitialization:
- """Test that Neo4j driver is initialized lazily on first use."""
-
- @pytest.fixture(autouse=True)
- def reset_module_state(self):
- """Reset module-level singleton state before each test."""
- original_driver = db_module._driver
-
- db_module._driver = None
-
- yield
-
- db_module._driver = original_driver
-
- def test_driver_not_initialized_at_import(self):
- """Driver should be None after module import (no eager connection)."""
- assert db_module._driver is None
-
- @patch("api.attack_paths.database.settings")
- @patch("api.attack_paths.database.neo4j.GraphDatabase.driver")
- def test_init_driver_creates_connection_on_first_call(
- self, mock_driver_factory, mock_settings
- ):
- """init_driver() should create connection only when called."""
- mock_driver = MagicMock()
- mock_driver_factory.return_value = mock_driver
- mock_settings.DATABASES = {
- "neo4j": {
- "HOST": "localhost",
- "PORT": 7687,
- "USER": "neo4j",
- "PASSWORD": "password",
- }
- }
-
- assert db_module._driver is None
-
- result = db_module.init_driver()
-
- mock_driver_factory.assert_called_once()
- mock_driver.verify_connectivity.assert_called_once()
- assert result is mock_driver
- assert db_module._driver is mock_driver
-
- @patch("api.attack_paths.database.settings")
- @patch("api.attack_paths.database.neo4j.GraphDatabase.driver")
- def test_init_driver_leaves_driver_none_when_verify_fails(
- self, mock_driver_factory, mock_settings
- ):
- """A failed verify_connectivity() must not publish or leak the driver."""
- mock_driver = MagicMock()
- mock_driver.verify_connectivity.side_effect = (
- neo4j.exceptions.ServiceUnavailable("down")
+class TestDatabaseNameHelper:
+ def test_tenant_name_lowercases_uuid(self):
+ assert (
+ db_module.get_database_name("ABC-123", temporary=False)
+ == "db-tenant-abc-123"
)
- mock_driver_factory.return_value = mock_driver
- mock_settings.DATABASES = {
- "neo4j": {
- "HOST": "localhost",
- "PORT": 7687,
- "USER": "neo4j",
- "PASSWORD": "password",
- }
- }
- with pytest.raises(neo4j.exceptions.ServiceUnavailable):
- db_module.init_driver()
-
- assert db_module._driver is None
- mock_driver.close.assert_called_once()
-
- @patch("api.attack_paths.database.settings")
- @patch("api.attack_paths.database.neo4j.GraphDatabase.driver")
- def test_init_driver_returns_cached_driver_on_subsequent_calls(
- self, mock_driver_factory, mock_settings
- ):
- """Subsequent calls should return cached driver without reconnecting."""
- mock_driver = MagicMock()
- mock_driver_factory.return_value = mock_driver
- mock_settings.DATABASES = {
- "neo4j": {
- "HOST": "localhost",
- "PORT": 7687,
- "USER": "neo4j",
- "PASSWORD": "password",
- }
- }
-
- first_result = db_module.init_driver()
- second_result = db_module.init_driver()
- third_result = db_module.init_driver()
-
- # Only one connection attempt
- assert mock_driver_factory.call_count == 1
- assert mock_driver.verify_connectivity.call_count == 1
-
- # All calls return same instance
- assert first_result is second_result is third_result
-
- @patch("api.attack_paths.database.settings")
- @patch("api.attack_paths.database.neo4j.GraphDatabase.driver")
- def test_get_driver_delegates_to_init_driver(
- self, mock_driver_factory, mock_settings
- ):
- """get_driver() should use init_driver() for lazy initialization."""
- mock_driver = MagicMock()
- mock_driver_factory.return_value = mock_driver
- mock_settings.DATABASES = {
- "neo4j": {
- "HOST": "localhost",
- "PORT": 7687,
- "USER": "neo4j",
- "PASSWORD": "password",
- }
- }
-
- result = db_module.get_driver()
-
- assert result is mock_driver
- mock_driver_factory.assert_called_once()
+ def test_temporary_name_uses_tmp_scan_prefix(self):
+ assert (
+ db_module.get_database_name("XYZ-789", temporary=True)
+ == "db-tmp-scan-xyz-789"
+ )
-class TestConnectionAcquisitionTimeout:
- """Test that the connection acquisition timeout is configurable."""
+class TestExceptionHierarchy:
+ """`tasks/` and `api/v1/views.py` import these from the facade."""
- @pytest.fixture(autouse=True)
- def reset_module_state(self):
- original_driver = db_module._driver
- original_acq_timeout = db_module.CONN_ACQUISITION_TIMEOUT
- original_conn_timeout = db_module.CONNECTION_TIMEOUT
+ def test_write_query_is_graph_database_exception(self):
+ assert issubclass(
+ db_module.WriteQueryNotAllowedException,
+ db_module.GraphDatabaseQueryException,
+ )
- db_module._driver = None
+ def test_client_statement_is_graph_database_exception(self):
+ assert issubclass(
+ db_module.ClientStatementException, db_module.GraphDatabaseQueryException
+ )
- yield
+ def test_exception_str_includes_code_when_set(self):
+ exc = db_module.GraphDatabaseQueryException(
+ message="boom", code="Neo.ClientError.X.Y"
+ )
+ assert str(exc) == "Neo.ClientError.X.Y: boom"
- db_module._driver = original_driver
- db_module.CONN_ACQUISITION_TIMEOUT = original_acq_timeout
- db_module.CONNECTION_TIMEOUT = original_conn_timeout
-
- @patch("api.attack_paths.database.settings")
- @patch("api.attack_paths.database.neo4j.GraphDatabase.driver")
- def test_driver_receives_configured_timeout(
- self, mock_driver_factory, mock_settings
- ):
- """init_driver() should pass the configured timeouts to the neo4j driver."""
- mock_driver_factory.return_value = MagicMock()
- mock_settings.DATABASES = {
- "neo4j": {
- "HOST": "localhost",
- "PORT": 7687,
- "USER": "neo4j",
- "PASSWORD": "password",
- }
- }
- db_module.CONN_ACQUISITION_TIMEOUT = 42
- db_module.CONNECTION_TIMEOUT = 7
-
- db_module.init_driver()
-
- _, kwargs = mock_driver_factory.call_args
- assert kwargs["connection_acquisition_timeout"] == 42
- assert kwargs["connection_timeout"] == 7
+ def test_exception_str_falls_back_to_message_without_code(self):
+ exc = db_module.GraphDatabaseQueryException(message="boom")
+ assert str(exc) == "boom"
-class TestAtexitRegistration:
- """Test that atexit cleanup handler is registered correctly."""
+class TestExecuteReadQueryRoutes:
+ def test_execute_read_query_delegates_to_sink(self, sink_backend_stub):
+ sink_backend_stub.execute_read_query.return_value = "graph"
- @pytest.fixture(autouse=True)
- def reset_module_state(self):
- """Reset module-level singleton state before each test."""
- original_driver = db_module._driver
+ result = db_module.execute_read_query(
+ "db-tenant-abc", "MATCH (n) RETURN n", {"provider_uid": "123"}
+ )
- db_module._driver = None
+ sink_backend_stub.execute_read_query.assert_called_once_with(
+ "db-tenant-abc", "MATCH (n) RETURN n", {"provider_uid": "123"}
+ )
+ assert result == "graph"
- yield
+ def test_execute_read_query_defaults_parameters_to_none(self, sink_backend_stub):
+ db_module.execute_read_query("db-tenant-abc", "MATCH (n) RETURN n")
- db_module._driver = original_driver
-
- @patch("api.attack_paths.database.settings")
- @patch("api.attack_paths.database.atexit.register")
- @patch("api.attack_paths.database.neo4j.GraphDatabase.driver")
- def test_atexit_registered_on_first_init(
- self, mock_driver_factory, mock_atexit_register, mock_settings
- ):
- """atexit.register should be called on first initialization."""
- mock_driver_factory.return_value = MagicMock()
- mock_settings.DATABASES = {
- "neo4j": {
- "HOST": "localhost",
- "PORT": 7687,
- "USER": "neo4j",
- "PASSWORD": "password",
- }
- }
-
- db_module.init_driver()
-
- mock_atexit_register.assert_called_once_with(db_module.close_driver)
-
- @patch("api.attack_paths.database.settings")
- @patch("api.attack_paths.database.atexit.register")
- @patch("api.attack_paths.database.neo4j.GraphDatabase.driver")
- def test_atexit_registered_only_once(
- self, mock_driver_factory, mock_atexit_register, mock_settings
- ):
- """atexit.register should only be called once across multiple inits.
-
- The double-checked locking on _driver ensures the atexit registration
- block only executes once (when _driver is first created).
- """
- mock_driver_factory.return_value = MagicMock()
- mock_settings.DATABASES = {
- "neo4j": {
- "HOST": "localhost",
- "PORT": 7687,
- "USER": "neo4j",
- "PASSWORD": "password",
- }
- }
-
- db_module.init_driver()
- db_module.init_driver()
- db_module.init_driver()
-
- # Only registered once because subsequent calls hit the fast path
- assert mock_atexit_register.call_count == 1
+ sink_backend_stub.execute_read_query.assert_called_once_with(
+ "db-tenant-abc", "MATCH (n) RETURN n", None
+ )
-class TestCloseDriver:
- """Test driver cleanup functionality."""
+class TestScanDatabaseAvailability:
+ def test_verify_scan_databases_available_checks_ingest_and_sink(self):
+ with (
+ patch("api.attack_paths.database.ingest") as mock_ingest,
+ patch("api.attack_paths.database.get_driver") as mock_get_driver,
+ ):
+ db_module.verify_scan_databases_available()
- @pytest.fixture(autouse=True)
- def reset_module_state(self):
- """Reset module-level singleton state before each test."""
- original_driver = db_module._driver
+ mock_ingest.get_driver.return_value.verify_connectivity.assert_called_once_with()
+ mock_get_driver.return_value.verify_connectivity.assert_called_once_with()
- db_module._driver = None
-
- yield
-
- db_module._driver = original_driver
-
- def test_close_driver_closes_and_clears_driver(self):
- """close_driver() should close the driver and set it to None."""
- mock_driver = MagicMock()
- db_module._driver = mock_driver
-
- db_module.close_driver()
-
- mock_driver.close.assert_called_once()
- assert db_module._driver is None
-
- def test_close_driver_handles_none_driver(self):
- """close_driver() should handle case where driver is None."""
- db_module._driver = None
-
- # Should not raise
- db_module.close_driver()
-
- assert db_module._driver is None
-
- def test_close_driver_clears_driver_even_on_close_error(self):
- """Driver should be cleared even if close() raises an exception."""
- mock_driver = MagicMock()
- mock_driver.close.side_effect = Exception("Connection error")
- db_module._driver = mock_driver
-
- with pytest.raises(Exception, match="Connection error"):
- db_module.close_driver()
-
- # Driver should still be cleared
- assert db_module._driver is None
-
-
-class TestExecuteReadQuery:
- """Test read query execution helper."""
-
- def test_execute_read_query_calls_read_session_and_returns_result(self):
- tx = MagicMock()
- expected_graph = MagicMock()
- run_result = MagicMock()
- run_result.graph.return_value = expected_graph
- tx.run.return_value = run_result
-
- session = MagicMock()
-
- def execute_read_side_effect(fn):
- return fn(tx)
-
- session.execute_read.side_effect = execute_read_side_effect
-
- session_ctx = MagicMock()
- session_ctx.__enter__.return_value = session
- session_ctx.__exit__.return_value = False
-
- with patch(
- "api.attack_paths.database.get_session",
- return_value=session_ctx,
- ) as mock_get_session:
- result = db_module.execute_read_query(
- "db-tenant-test-tenant-id",
- "MATCH (n) RETURN n",
- {"provider_uid": "123"},
+ def test_verify_scan_databases_available_raises_when_ingest_is_down(self):
+ with (
+ patch("api.attack_paths.database.ingest") as mock_ingest,
+ patch("api.attack_paths.database.get_driver"),
+ ):
+ mock_ingest.get_driver.return_value.verify_connectivity.side_effect = (
+ RuntimeError("ingest down")
)
- mock_get_session.assert_called_once_with(
- "db-tenant-test-tenant-id",
- default_access_mode=neo4j.READ_ACCESS,
+ with pytest.raises(RuntimeError) as exc:
+ db_module.verify_scan_databases_available()
+
+ assert "Attack Paths graph database unavailable before scan start" in str(
+ exc.value
)
- session.execute_read.assert_called_once()
- tx.run.assert_called_once_with(
- "MATCH (n) RETURN n",
- {"provider_uid": "123"},
- timeout=db_module.READ_QUERY_TIMEOUT_SECONDS,
- )
- run_result.graph.assert_called_once_with()
- assert result is expected_graph
+ assert "ingest Neo4j: ingest down" in str(exc.value)
- def test_execute_read_query_defaults_parameters_to_empty_dict(self):
- tx = MagicMock()
- run_result = MagicMock()
- run_result.graph.return_value = MagicMock()
- tx.run.return_value = run_result
+ def test_verify_scan_databases_available_raises_when_sink_is_down(self, settings):
+ settings.ATTACK_PATHS_SINK_DATABASE = "neptune"
- session = MagicMock()
- session.execute_read.side_effect = lambda fn: fn(tx)
-
- session_ctx = MagicMock()
- session_ctx.__enter__.return_value = session
- session_ctx.__exit__.return_value = False
-
- with patch(
- "api.attack_paths.database.get_session",
- return_value=session_ctx,
+ with (
+ patch("api.attack_paths.database.ingest"),
+ patch("api.attack_paths.database.get_driver") as mock_get_driver,
):
- db_module.execute_read_query(
- "db-tenant-test-tenant-id",
- "MATCH (n) RETURN n",
+ mock_get_driver.return_value.verify_connectivity.side_effect = RuntimeError(
+ "writer down"
)
- tx.run.assert_called_once_with(
- "MATCH (n) RETURN n",
- {},
- timeout=db_module.READ_QUERY_TIMEOUT_SECONDS,
- )
- run_result.graph.assert_called_once_with()
+ with pytest.raises(RuntimeError) as exc:
+ db_module.verify_scan_databases_available()
+ assert "sink neptune: writer down" in str(exc.value)
-class TestGetSessionReadOnly:
- """Test that get_session translates Neo4j read-mode errors."""
+ def test_verify_scan_databases_available_reports_both_failures(self, settings):
+ settings.ATTACK_PATHS_SINK_DATABASE = "neo4j"
- @pytest.fixture(autouse=True)
- def reset_module_state(self):
- original_driver = db_module._driver
- db_module._driver = None
- yield
- db_module._driver = original_driver
-
- @pytest.mark.parametrize(
- "neo4j_code",
- [
- "Neo.ClientError.Statement.AccessMode",
- "Neo.ClientError.Procedure.ProcedureNotFound",
- ],
- )
- def test_get_session_raises_write_query_not_allowed(self, neo4j_code):
- """Read-mode Neo4j errors should raise `WriteQueryNotAllowedException`."""
- mock_session = MagicMock()
- neo4j_error = neo4j.exceptions.Neo4jError._hydrate_neo4j(
- code=neo4j_code,
- message="Write operations are not allowed",
- )
- mock_session.run.side_effect = neo4j_error
-
- mock_driver = MagicMock()
- mock_driver.session.return_value = mock_session
- db_module._driver = mock_driver
-
- with pytest.raises(db_module.WriteQueryNotAllowedException):
- with db_module.get_session(
- default_access_mode=neo4j.READ_ACCESS
- ) as session:
- session.run("CREATE (n) RETURN n")
-
- def test_get_session_raises_generic_exception_for_other_errors(self):
- """Non-read-mode Neo4j errors should raise GraphDatabaseQueryException."""
- mock_session = MagicMock()
- neo4j_error = neo4j.exceptions.Neo4jError._hydrate_neo4j(
- code="Neo.ClientError.Statement.SyntaxError",
- message="Invalid syntax",
- )
- mock_session.run.side_effect = neo4j_error
-
- mock_driver = MagicMock()
- mock_driver.session.return_value = mock_session
- db_module._driver = mock_driver
-
- with pytest.raises(db_module.GraphDatabaseQueryException):
- with db_module.get_session(
- default_access_mode=neo4j.READ_ACCESS
- ) as session:
- session.run("INVALID CYPHER")
-
-
-class TestThreadSafety:
- """Test thread-safe initialization."""
-
- @pytest.fixture(autouse=True)
- def reset_module_state(self):
- """Reset module-level singleton state before each test."""
- original_driver = db_module._driver
-
- db_module._driver = None
-
- yield
-
- db_module._driver = original_driver
-
- @patch("api.attack_paths.database.settings")
- @patch("api.attack_paths.database.neo4j.GraphDatabase.driver")
- def test_concurrent_init_creates_single_driver(
- self, mock_driver_factory, mock_settings
- ):
- """Multiple threads calling init_driver() should create only one driver."""
- mock_driver = MagicMock()
- mock_driver_factory.return_value = mock_driver
- mock_settings.DATABASES = {
- "neo4j": {
- "HOST": "localhost",
- "PORT": 7687,
- "USER": "neo4j",
- "PASSWORD": "password",
- }
- }
-
- results = []
- errors = []
-
- def call_init():
- try:
- result = db_module.init_driver()
- results.append(result)
- except Exception as e:
- errors.append(e)
-
- threads = [threading.Thread(target=call_init) for _ in range(10)]
-
- for t in threads:
- t.start()
- for t in threads:
- t.join()
-
- assert not errors, f"Threads raised errors: {errors}"
-
- # Only one driver created
- assert mock_driver_factory.call_count == 1
-
- # All threads got the same driver instance
- assert all(r is mock_driver for r in results)
- assert len(results) == 10
-
-
-class TestHasProviderData:
- """Test has_provider_data helper for checking provider nodes in Neo4j."""
-
- def test_returns_true_when_nodes_exist(self):
- mock_session = MagicMock()
- mock_result = MagicMock()
- mock_result.single.return_value = MagicMock() # non-None record
- mock_session.run.return_value = mock_result
-
- session_ctx = MagicMock()
- session_ctx.__enter__.return_value = mock_session
- session_ctx.__exit__.return_value = False
-
- with patch(
- "api.attack_paths.database.get_session",
- return_value=session_ctx,
+ with (
+ patch("api.attack_paths.database.ingest") as mock_ingest,
+ patch("api.attack_paths.database.get_driver") as mock_get_driver,
):
- assert db_module.has_provider_data("db-tenant-abc", "provider-123") is True
-
- mock_session.run.assert_called_once()
-
- def test_returns_false_when_no_nodes(self):
- mock_session = MagicMock()
- mock_result = MagicMock()
- mock_result.single.return_value = None
- mock_session.run.return_value = mock_result
-
- session_ctx = MagicMock()
- session_ctx.__enter__.return_value = mock_session
- session_ctx.__exit__.return_value = False
-
- with patch(
- "api.attack_paths.database.get_session",
- return_value=session_ctx,
- ):
- assert db_module.has_provider_data("db-tenant-abc", "provider-123") is False
-
- def test_returns_false_when_database_not_found(self):
- session_ctx = MagicMock()
- session_ctx.__enter__.side_effect = db_module.GraphDatabaseQueryException(
- message="Database does not exist",
- code="Neo.ClientError.Database.DatabaseNotFound",
- )
-
- with patch(
- "api.attack_paths.database.get_session",
- return_value=session_ctx,
- ):
- assert (
- db_module.has_provider_data("db-tenant-gone", "provider-123") is False
+ mock_ingest.get_driver.return_value.verify_connectivity.side_effect = (
+ RuntimeError("ingest down")
+ )
+ mock_get_driver.return_value.verify_connectivity.side_effect = RuntimeError(
+ "sink down"
)
- def test_raises_on_other_errors(self):
- session_ctx = MagicMock()
- session_ctx.__enter__.side_effect = db_module.GraphDatabaseQueryException(
- message="Connection refused",
- code="Neo.TransientError.General.UnknownError",
+ with pytest.raises(RuntimeError) as exc:
+ db_module.verify_scan_databases_available()
+
+ assert "ingest Neo4j: ingest down" in str(exc.value)
+ assert "sink neo4j: sink down" in str(exc.value)
+
+
+class TestSinkOperationsDelegation:
+ def test_has_provider_data_delegates_to_sink(self, sink_backend_stub):
+ sink_backend_stub.has_provider_data.return_value = True
+
+ assert db_module.has_provider_data("db-tenant-abc", "provider-123") is True
+ sink_backend_stub.has_provider_data.assert_called_once_with(
+ "db-tenant-abc", "provider-123"
)
- with patch(
- "api.attack_paths.database.get_session",
- return_value=session_ctx,
- ):
- with pytest.raises(db_module.GraphDatabaseQueryException):
- db_module.has_provider_data("db-tenant-abc", "provider-123")
+ def test_drop_subgraph_delegates_to_sink(self, sink_backend_stub):
+ sink_backend_stub.drop_subgraph.return_value = 42
-
-class TestDropSubgraph:
- """Test drop_subgraph two-phase batched deletion of a provider's graph."""
-
- @staticmethod
- def _result(count):
- result = MagicMock()
- result.single.return_value.get.return_value = count
- return result
-
- @staticmethod
- def _session_ctx(session):
- ctx = MagicMock()
- ctx.__enter__.return_value = session
- ctx.__exit__.return_value = False
- return ctx
-
- def test_deletes_relationships_then_nodes_in_batches(self):
- session = MagicMock()
- # Phase 1 (relationships): one full batch then empty.
- # Phase 2 (nodes): one full batch then empty.
- session.run.side_effect = [
- self._result(1000),
- self._result(0),
- self._result(1000),
- self._result(0),
- ]
-
- with patch(
- "api.attack_paths.database.get_session",
- return_value=self._session_ctx(session),
- ):
- deleted = db_module.drop_subgraph("db-tenant-abc", "provider-123")
-
- # Only phase-2 node counts contribute to the return value.
- assert deleted == 1000
- assert session.run.call_count == 4
-
- queries = [call.args[0] for call in session.run.call_args_list]
-
- # Regression guard: the memory blow-up was caused by DETACH DELETE.
- assert all("DETACH DELETE" not in query for query in queries)
-
- rel_queries = [query for query in queries if "DELETE r" in query]
- node_queries = [query for query in queries if "DELETE n" in query]
- assert rel_queries and node_queries
- # DISTINCT avoids double-counting relationships matched from both ends.
- assert all("DISTINCT r" in query for query in rel_queries)
-
- # Relationships must be fully drained before nodes are deleted.
- first_node = next(i for i, q in enumerate(queries) if "DELETE n" in q)
- last_rel = max(i for i, q in enumerate(queries) if "DELETE r" in q)
- assert last_rel < first_node
-
- def test_returns_zero_when_database_not_found(self):
- session_ctx = MagicMock()
- session_ctx.__enter__.side_effect = db_module.GraphDatabaseQueryException(
- message="Database does not exist",
- code="Neo.ClientError.Database.DatabaseNotFound",
+ assert db_module.drop_subgraph("db-tenant-abc", "provider-123") == 42
+ sink_backend_stub.drop_subgraph.assert_called_once_with(
+ "db-tenant-abc", "provider-123"
)
- with patch(
- "api.attack_paths.database.get_session",
- return_value=session_ctx,
- ):
- assert db_module.drop_subgraph("db-tenant-gone", "provider-123") == 0
- def test_raises_on_other_errors(self):
- session_ctx = MagicMock()
- session_ctx.__enter__.side_effect = db_module.GraphDatabaseQueryException(
- message="Connection refused",
- code="Neo.TransientError.General.UnknownError",
- )
+class TestRoutingByDatabasePrefix:
+ """`db-tmp-scan-*` and `None` route to ingest; everything else to sink."""
- with patch(
- "api.attack_paths.database.get_session",
- return_value=session_ctx,
- ):
- with pytest.raises(db_module.GraphDatabaseQueryException):
- db_module.drop_subgraph("db-tenant-abc", "provider-123")
+ def test_create_database_routes_temp_to_ingest(self, sink_backend_stub):
+ with patch("api.attack_paths.database.ingest") as mock_ingest:
+ db_module.create_database("db-tmp-scan-uuid-1")
+
+ mock_ingest.create_database.assert_called_once_with("db-tmp-scan-uuid-1")
+ sink_backend_stub.create_database.assert_not_called()
+
+ def test_create_database_routes_tenant_to_sink(self, sink_backend_stub):
+ with patch("api.attack_paths.database.ingest") as mock_ingest:
+ db_module.create_database("db-tenant-abc")
+
+ sink_backend_stub.create_database.assert_called_once_with("db-tenant-abc")
+ mock_ingest.create_database.assert_not_called()
+
+ def test_drop_database_routes_temp_to_ingest(self, sink_backend_stub):
+ with patch("api.attack_paths.database.ingest") as mock_ingest:
+ db_module.drop_database("db-tmp-scan-uuid-1")
+
+ mock_ingest.drop_database.assert_called_once_with("db-tmp-scan-uuid-1")
+ sink_backend_stub.drop_database.assert_not_called()
+
+ def test_drop_database_routes_tenant_to_sink(self, sink_backend_stub):
+ with patch("api.attack_paths.database.ingest") as mock_ingest:
+ db_module.drop_database("db-tenant-abc")
+
+ sink_backend_stub.drop_database.assert_called_once_with("db-tenant-abc")
+ mock_ingest.drop_database.assert_not_called()
+
+ def test_clear_cache_routes_temp_to_ingest(self, sink_backend_stub):
+ with patch("api.attack_paths.database.ingest") as mock_ingest:
+ db_module.clear_cache("db-tmp-scan-uuid-1")
+
+ mock_ingest.clear_cache.assert_called_once_with("db-tmp-scan-uuid-1")
+ sink_backend_stub.clear_cache.assert_not_called()
+
+ def test_clear_cache_routes_tenant_to_sink(self, sink_backend_stub):
+ with patch("api.attack_paths.database.ingest") as mock_ingest:
+ db_module.clear_cache("db-tenant-abc")
+
+ sink_backend_stub.clear_cache.assert_called_once_with("db-tenant-abc")
+ mock_ingest.clear_cache.assert_not_called()
+
+ def test_get_session_routes_temp_to_ingest(self, sink_backend_stub):
+ sentinel = MagicMock()
+ with patch("api.attack_paths.database.ingest") as mock_ingest:
+ mock_ingest.get_session.return_value = sentinel
+
+ result = db_module.get_session("db-tmp-scan-uuid-1")
+
+ assert result is sentinel
+ mock_ingest.get_session.assert_called_once()
+ sink_backend_stub.get_session.assert_not_called()
+
+ def test_get_session_routes_none_to_ingest(self, sink_backend_stub):
+ sentinel = MagicMock()
+ with patch("api.attack_paths.database.ingest") as mock_ingest:
+ mock_ingest.get_session.return_value = sentinel
+
+ result = db_module.get_session(None)
+
+ assert result is sentinel
+ sink_backend_stub.get_session.assert_not_called()
+
+ def test_get_ingest_uri_delegates_to_ingest(self, sink_backend_stub):
+ with patch("api.attack_paths.database.ingest") as mock_ingest:
+ mock_ingest.get_uri.return_value = "bolt://neo4j:7687"
+
+ assert db_module.get_ingest_uri() == "bolt://neo4j:7687"
+
+ mock_ingest.get_uri.assert_called_once_with()
+
+ def test_get_session_routes_tenant_to_sink(self, sink_backend_stub):
+ sentinel = MagicMock()
+ sink_backend_stub.get_session.return_value = sentinel
+ with patch("api.attack_paths.database.ingest") as mock_ingest:
+ result = db_module.get_session("db-tenant-abc")
+
+ assert result is sentinel
+ mock_ingest.get_session.assert_not_called()
diff --git a/api/src/backend/api/tests/test_cypher_sanitizer.py b/api/src/backend/api/tests/test_cypher_sanitizer.py
index 6caca47a56..c0d4f9b7ff 100644
--- a/api/src/backend/api/tests/test_cypher_sanitizer.py
+++ b/api/src/backend/api/tests/test_cypher_sanitizer.py
@@ -4,6 +4,7 @@ from unittest.mock import patch
import pytest
from api.attack_paths.cypher_sanitizer import (
+ inject_label,
inject_provider_label,
validate_custom_query,
)
@@ -21,6 +22,13 @@ def _inject(cypher: str) -> str:
return inject_provider_label(cypher, PROVIDER_ID)
+def test_generic_inject_label_reuses_provider_injection_pipeline():
+ result = inject_label("MATCH (n:AWSRole)--(m) RETURN n, m", "_Tenant_test")
+
+ assert "(n:AWSRole:_Tenant_test)" in result
+ assert "(m:_Tenant_test)" in result
+
+
# ---------------------------------------------------------------------------
# Pass A - Labeled node patterns (all clauses)
# ---------------------------------------------------------------------------
diff --git a/api/src/backend/api/tests/test_db_utils.py b/api/src/backend/api/tests/test_db_utils.py
index 06b528b44a..347be2b64d 100644
--- a/api/src/backend/api/tests/test_db_utils.py
+++ b/api/src/backend/api/tests/test_db_utils.py
@@ -1,11 +1,16 @@
+from contextlib import contextmanager
from datetime import UTC, datetime
from enum import Enum
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, call, patch
import pytest
from api.db_utils import (
POSTGRES_TENANT_VAR,
+ SET_CONFIG_QUERY,
+ SET_TRANSACTION_READ_ONLY_QUERY,
PostgresEnumMigration,
+ _is_replica_connection_failure,
+ _is_safe_primary_replay,
_should_create_index_on_partition,
batch_delete,
create_objects_in_batches,
@@ -392,10 +397,23 @@ class TestRlsTransaction:
with patch("api.db_utils.get_read_db_alias", return_value=None):
with patch("api.db_utils.connections") as mock_connections:
- mock_conn = MagicMock()
- mock_cursor = MagicMock()
- mock_conn.cursor.return_value.__enter__.return_value = mock_cursor
- mock_connections.__getitem__.return_value = mock_conn
+ mock_replica_conn = MagicMock()
+ mock_replica_cursor = MagicMock()
+ mock_replica_conn.cursor.return_value.__enter__.return_value = (
+ mock_replica_cursor
+ )
+ mock_primary_conn = MagicMock()
+ mock_primary_cursor = MagicMock()
+ mock_primary_conn.cursor.return_value.__enter__.return_value = (
+ mock_primary_cursor
+ )
+
+ def connections_getitem(alias):
+ if alias == "replica":
+ return mock_replica_conn
+ return mock_primary_conn
+
+ mock_connections.__getitem__.side_effect = connections_getitem
mock_connections.__contains__.return_value = True
with patch("api.db_utils.transaction.atomic"):
@@ -525,7 +543,7 @@ class TestRlsTransaction:
def atomic_side_effect(*args, **kwargs):
nonlocal call_count
call_count += 1
- if call_count < 3:
+ if call_count < 4:
raise OperationalError("Connection error")
return MagicMock(
__enter__=MagicMock(return_value=None),
@@ -544,10 +562,11 @@ class TestRlsTransaction:
with rls_transaction(tenant_id):
pass
- assert mock_sleep.call_count == 2
+ assert mock_sleep.call_count == 3
mock_sleep.assert_any_call(0.5)
mock_sleep.assert_any_call(1.0)
- assert mock_logger.info.call_count == 2
+ mock_sleep.assert_any_call(2.0)
+ assert mock_logger.info.call_count == 3
def test_rls_transaction_operational_error_inside_context_no_retry(
self, tenants_fixture, enable_read_replica
@@ -578,11 +597,12 @@ class TestRlsTransaction:
raise OperationalError("Conflict with recovery")
mock_sleep.assert_not_called()
+ mock_conn.close.assert_not_called()
- def test_rls_transaction_max_three_attempts_for_replica(
+ def test_rls_transaction_max_attempts_for_replica(
self, tenants_fixture, enable_read_replica
):
- """Test maximum 3 attempts for replica database."""
+ """Test REPLICA_MAX_ATTEMPTS replica tries + 1 primary fallback."""
tenant = tenants_fixture[0]
tenant_id = str(tenant.id)
@@ -606,7 +626,11 @@ class TestRlsTransaction:
with rls_transaction(tenant_id):
pass
- assert mock_atomic.call_count == 3
+ assert mock_atomic.call_args_list[-1] == call(
+ using=DEFAULT_DB_ALIAS
+ )
+ # 3 replica + 1 primary = 4 total
+ assert mock_atomic.call_count == 4
def test_rls_transaction_replica_no_retry_when_disabled(
self, tenants_fixture, enable_read_replica
@@ -617,10 +641,23 @@ class TestRlsTransaction:
with patch("api.db_utils.get_read_db_alias", return_value=enable_read_replica):
with patch("api.db_utils.connections") as mock_connections:
- mock_conn = MagicMock()
- mock_cursor = MagicMock()
- mock_conn.cursor.return_value.__enter__.return_value = mock_cursor
- mock_connections.__getitem__.return_value = mock_conn
+ mock_replica_conn = MagicMock()
+ mock_replica_cursor = MagicMock()
+ mock_replica_conn.cursor.return_value.__enter__.return_value = (
+ mock_replica_cursor
+ )
+ mock_primary_conn = MagicMock()
+ mock_primary_cursor = MagicMock()
+ mock_primary_conn.cursor.return_value.__enter__.return_value = (
+ mock_primary_cursor
+ )
+
+ def connections_getitem(alias):
+ if alias == "replica":
+ return mock_replica_conn
+ return mock_primary_conn
+
+ mock_connections.__getitem__.side_effect = connections_getitem
mock_connections.__contains__.return_value = True
with patch("api.db_utils.transaction.atomic") as mock_atomic:
@@ -682,7 +719,7 @@ class TestRlsTransaction:
def atomic_side_effect(*args, **kwargs):
nonlocal call_count
call_count += 1
- if call_count < 3:
+ if call_count < 4:
raise OperationalError("Replica error")
return MagicMock(
__enter__=MagicMock(return_value=None),
@@ -691,7 +728,7 @@ class TestRlsTransaction:
with patch(
"api.db_utils.transaction.atomic", side_effect=atomic_side_effect
- ):
+ ) as mock_atomic:
with patch("api.db_utils.time.sleep"):
with patch(
"api.db_utils.set_read_db_alias", return_value="token"
@@ -701,6 +738,9 @@ class TestRlsTransaction:
with rls_transaction(tenant_id):
pass
+ assert mock_atomic.call_args_list[-1] == call(
+ using=DEFAULT_DB_ALIAS
+ )
mock_logger.warning.assert_called_once()
warning_msg = mock_logger.warning.call_args[0][0]
assert "falling back to primary DB" in warning_msg
@@ -725,7 +765,7 @@ class TestRlsTransaction:
def atomic_side_effect(*args, **kwargs):
nonlocal call_count
call_count += 1
- if call_count < 3:
+ if call_count < 4:
raise OperationalError("Replica error")
return MagicMock(
__enter__=MagicMock(return_value=None),
@@ -744,7 +784,7 @@ class TestRlsTransaction:
with rls_transaction(tenant_id):
pass
- assert mock_logger.info.call_count == 2
+ assert mock_logger.info.call_count == 3
assert mock_logger.warning.call_count == 1
def test_rls_transaction_operational_error_raised_immediately_on_primary(
@@ -910,6 +950,520 @@ class TestRlsTransaction:
result = cursor.fetchone()
assert result[0] == 1
+ # --- Mid-query failover tests ---
+
+ class _FakeDatabaseError(Exception):
+ def __init__(self, message, pgcode=None):
+ super().__init__(message)
+ self.pgcode = pgcode
+
+ def _install_execute_wrapper(self, connection):
+ connection.execute_wrappers = []
+
+ @contextmanager
+ def _execute_wrapper(fn):
+ connection.execute_wrappers.append(fn)
+ try:
+ yield
+ finally:
+ connection.execute_wrappers.remove(fn)
+
+ connection.execute_wrapper = _execute_wrapper
+
+ def _mock_replica_and_primary_connections(self, mock_connections):
+ mock_replica_conn = MagicMock()
+ self._install_execute_wrapper(mock_replica_conn)
+ mock_replica_cursor = MagicMock()
+ mock_replica_conn.cursor.return_value.__enter__.return_value = (
+ mock_replica_cursor
+ )
+
+ mock_primary_conn = MagicMock()
+ mock_primary_cursor = MagicMock()
+ mock_primary_raw_cursor = MagicMock()
+ mock_primary_cursor.cursor = mock_primary_raw_cursor
+ mock_primary_conn.cursor.return_value = mock_primary_cursor
+
+ def connections_getitem(alias):
+ if alias == "replica":
+ return mock_replica_conn
+ return mock_primary_conn
+
+ mock_connections.__getitem__.side_effect = connections_getitem
+ mock_connections.__contains__.return_value = True
+
+ return mock_replica_conn, mock_primary_conn, mock_primary_cursor
+
+ @pytest.mark.parametrize(
+ "error",
+ [
+ _FakeDatabaseError("connection lost", pgcode="08006"),
+ _FakeDatabaseError("terminating connection", pgcode="57P01"),
+ OperationalError("SSL SYSCALL error: EOF detected"),
+ OperationalError("server closed the connection unexpectedly"),
+ OperationalError("database system is starting up"),
+ ],
+ )
+ def test_replica_connection_failure_detection_allows_failover(self, error):
+ assert _is_replica_connection_failure(error)
+
+ @pytest.mark.parametrize(
+ "error",
+ [
+ _FakeDatabaseError("canceling statement", pgcode="57014"),
+ _FakeDatabaseError("could not serialize access", pgcode="40001"),
+ _FakeDatabaseError("deadlock detected", pgcode="40P01"),
+ OperationalError("deadlock detected"),
+ ],
+ )
+ def test_replica_connection_failure_detection_rejects_query_errors(self, error):
+ assert not _is_replica_connection_failure(error)
+
+ @pytest.mark.parametrize(
+ ("sql", "many", "expected"),
+ [
+ ("SELECT 1", False, True),
+ (" -- leading comment\nSELECT 1", False, True),
+ ("/* leading comment */ SELECT 1", False, True),
+ ("SELECT 1", True, False),
+ ("SELECTING 1", False, False),
+ ("INSERT INTO fake_table (name) VALUES (%s)", False, False),
+ ("WITH rows AS (SELECT 1) SELECT * FROM rows", False, False),
+ ("SELECT * INTO fake_table_copy FROM fake_table", False, False),
+ ("SELECT * FROM fake_table FOR UPDATE", False, False),
+ ("SELECT * FROM fake_table FOR SHARE", False, False),
+ ],
+ )
+ def test_primary_replay_safety_detection(self, sql, many, expected):
+ assert _is_safe_primary_replay(sql, many) is expected
+
+ def test_mid_query_failure_falls_directly_back_to_primary(
+ self, tenants_fixture, enable_read_replica
+ ):
+ """Mid-query replica connection loss is replayed once on primary."""
+ tenant = tenants_fixture[0]
+ tenant_id = str(tenant.id)
+
+ with patch("api.db_utils.get_read_db_alias", return_value=enable_read_replica):
+ with patch("api.db_utils.connections") as mock_connections:
+ (
+ mock_replica_conn,
+ mock_primary_conn,
+ mock_primary_cursor,
+ ) = self._mock_replica_and_primary_connections(mock_connections)
+
+ outer_atomic = MagicMock()
+ outer_atomic.__enter__ = MagicMock(return_value=None)
+ outer_atomic.__exit__ = MagicMock(return_value=False)
+ fallback_atomic = MagicMock()
+ fallback_atomic.__enter__ = MagicMock(return_value=None)
+ fallback_atomic.__exit__ = MagicMock(return_value=False)
+
+ with patch(
+ "api.db_utils.transaction.atomic",
+ side_effect=[outer_atomic, fallback_atomic],
+ ) as mock_atomic:
+ with patch("api.db_utils.time.sleep") as mock_sleep:
+ with patch(
+ "api.db_utils.set_read_db_alias",
+ side_effect=["replica-token", "primary-token"],
+ ) as mock_set_alias:
+ with patch(
+ "api.db_utils.reset_read_db_alias"
+ ) as mock_reset_alias:
+ with rls_transaction(tenant_id):
+ wrapper = mock_replica_conn.execute_wrappers[0]
+ context_cursor = MagicMock()
+ mock_execute = MagicMock(
+ side_effect=OperationalError(
+ "SSL SYSCALL error: EOF detected"
+ )
+ )
+
+ wrapper(
+ mock_execute,
+ "SELECT %s",
+ ["value"],
+ False,
+ {"cursor": context_cursor},
+ )
+
+ mock_sleep.assert_not_called()
+ (
+ mock_replica_conn.ensure_connection.assert_not_called()
+ )
+ mock_replica_conn.close.assert_called_once()
+ (
+ mock_primary_conn.ensure_connection.assert_called_once()
+ )
+ mock_primary_conn.cursor.assert_called_once_with()
+ mock_primary_cursor.execute.assert_has_calls(
+ [
+ call(SET_TRANSACTION_READ_ONLY_QUERY),
+ call(
+ SET_CONFIG_QUERY,
+ [POSTGRES_TENANT_VAR, tenant_id],
+ ),
+ call("SELECT %s", ["value"]),
+ ]
+ )
+ assert context_cursor.db == mock_primary_conn
+ assert (
+ context_cursor.cursor
+ == mock_primary_cursor.cursor
+ )
+
+ mock_set_alias.assert_has_calls(
+ [
+ call(enable_read_replica),
+ call(DEFAULT_DB_ALIAS),
+ ]
+ )
+ mock_reset_alias.assert_has_calls(
+ [call("primary-token"), call("replica-token")]
+ )
+ assert mock_atomic.call_args_list == [
+ call(using=enable_read_replica),
+ call(using=DEFAULT_DB_ALIAS),
+ ]
+ assert mock_replica_conn.execute_wrappers == []
+
+ @pytest.mark.parametrize(
+ ("sql", "params", "many"),
+ [
+ ("INSERT INTO fake_table (name) VALUES (%s)", [("one",), ("two",)], True),
+ ("INSERT INTO fake_table (name) VALUES (%s)", ["one"], False),
+ ("UPDATE fake_table SET name = %s", ["one"], False),
+ ("DELETE FROM fake_table WHERE id = %s", [1], False),
+ (
+ "WITH deleted AS (DELETE FROM fake_table RETURNING *) "
+ "SELECT * FROM deleted",
+ None,
+ False,
+ ),
+ ("SELECT * INTO fake_table_copy FROM fake_table", None, False),
+ ],
+ )
+ def test_mid_query_fallback_rejects_unsafe_replay(
+ self, tenants_fixture, enable_read_replica, sql, params, many
+ ):
+ """Only single SELECT statements are replayed on primary."""
+ tenant = tenants_fixture[0]
+ tenant_id = str(tenant.id)
+
+ with patch("api.db_utils.get_read_db_alias", return_value=enable_read_replica):
+ with patch("api.db_utils.connections") as mock_connections:
+ (
+ mock_replica_conn,
+ mock_primary_conn,
+ mock_primary_cursor,
+ ) = self._mock_replica_and_primary_connections(mock_connections)
+
+ with patch("api.db_utils.transaction.atomic") as mock_atomic:
+ mock_atomic.return_value.__enter__ = MagicMock(return_value=None)
+ mock_atomic.return_value.__exit__ = MagicMock(return_value=False)
+ with patch(
+ "api.db_utils.set_read_db_alias",
+ side_effect=["replica-token", "primary-token"],
+ ):
+ with patch("api.db_utils.reset_read_db_alias"):
+ with rls_transaction(tenant_id):
+ wrapper = mock_replica_conn.execute_wrappers[0]
+ mock_execute = MagicMock(
+ side_effect=OperationalError(
+ "server closed the connection"
+ )
+ )
+
+ with pytest.raises(OperationalError):
+ wrapper(
+ mock_execute,
+ sql,
+ params,
+ many,
+ {"cursor": MagicMock()},
+ )
+
+ mock_primary_conn.ensure_connection.assert_not_called()
+ mock_primary_conn.cursor.assert_not_called()
+ mock_primary_cursor.execute.assert_not_called()
+ mock_primary_cursor.executemany.assert_not_called()
+
+ def test_mid_query_non_connection_error_does_not_fall_back(
+ self, tenants_fixture, enable_read_replica
+ ):
+ """Query/concurrency errors are not replayed on primary."""
+ tenant = tenants_fixture[0]
+ tenant_id = str(tenant.id)
+
+ with patch("api.db_utils.get_read_db_alias", return_value=enable_read_replica):
+ with patch("api.db_utils.connections") as mock_connections:
+ (
+ mock_replica_conn,
+ mock_primary_conn,
+ _mock_primary_cursor,
+ ) = self._mock_replica_and_primary_connections(mock_connections)
+
+ with patch("api.db_utils.transaction.atomic") as mock_atomic:
+ mock_atomic.return_value.__enter__ = MagicMock(return_value=None)
+ mock_atomic.return_value.__exit__ = MagicMock(return_value=False)
+ with patch(
+ "api.db_utils.set_read_db_alias", return_value="replica-token"
+ ):
+ with patch("api.db_utils.reset_read_db_alias"):
+ with rls_transaction(tenant_id):
+ wrapper = mock_replica_conn.execute_wrappers[0]
+ mock_execute = MagicMock(
+ side_effect=OperationalError("deadlock detected")
+ )
+
+ with pytest.raises(OperationalError):
+ wrapper(
+ mock_execute,
+ "SELECT 1",
+ None,
+ False,
+ {"cursor": MagicMock()},
+ )
+
+ mock_replica_conn.close.assert_not_called()
+ (
+ mock_primary_conn.ensure_connection.assert_not_called()
+ )
+
+ def test_mid_query_primary_replay_failure_propagates(
+ self, tenants_fixture, enable_read_replica
+ ):
+ """Primary fallback errors propagate as Django OperationalError."""
+ tenant = tenants_fixture[0]
+ tenant_id = str(tenant.id)
+
+ with patch("api.db_utils.get_read_db_alias", return_value=enable_read_replica):
+ with patch("api.db_utils.connections") as mock_connections:
+ (
+ mock_replica_conn,
+ _mock_primary_conn,
+ mock_primary_cursor,
+ ) = self._mock_replica_and_primary_connections(mock_connections)
+ mock_primary_cursor.execute.side_effect = [
+ None,
+ None,
+ OperationalError("primary down"),
+ ]
+
+ with patch("api.db_utils.transaction.atomic") as mock_atomic:
+ mock_atomic.return_value.__enter__ = MagicMock(return_value=None)
+ mock_atomic.return_value.__exit__ = MagicMock(return_value=False)
+ with patch(
+ "api.db_utils.set_read_db_alias",
+ side_effect=["replica-token", "primary-token"],
+ ):
+ with patch("api.db_utils.reset_read_db_alias"):
+ with pytest.raises(OperationalError, match="primary down"):
+ with rls_transaction(tenant_id):
+ wrapper = mock_replica_conn.execute_wrappers[0]
+ mock_execute = MagicMock(
+ side_effect=OperationalError(
+ "server closed the connection"
+ )
+ )
+ wrapper(
+ mock_execute,
+ "SELECT 1",
+ None,
+ False,
+ {"cursor": MagicMock()},
+ )
+
+ mock_primary_cursor.close.assert_called_once()
+
+ def test_mid_query_fallback_suppresses_cleanup_error(
+ self, tenants_fixture, enable_read_replica
+ ):
+ """After successful primary fallback, replica cleanup error is suppressed."""
+ tenant = tenants_fixture[0]
+ tenant_id = str(tenant.id)
+
+ with patch("api.db_utils.get_read_db_alias", return_value=enable_read_replica):
+ with patch("api.db_utils.connections") as mock_connections:
+ (
+ mock_replica_conn,
+ _mock_primary_conn,
+ mock_primary_cursor,
+ ) = self._mock_replica_and_primary_connections(mock_connections)
+
+ # Replica's atomic.__exit__ raises on dead replica cleanup;
+ # primary's atomic.__exit__ returns False (healthy commit).
+ mock_outer_atomic = MagicMock()
+ mock_outer_atomic.__enter__ = MagicMock(return_value=None)
+ mock_outer_atomic.__exit__ = MagicMock(
+ side_effect=OperationalError("cleanup failed on dead replica")
+ )
+
+ mock_fallback_atomic = MagicMock()
+ mock_fallback_atomic.__enter__ = MagicMock(return_value=None)
+ mock_fallback_atomic.__exit__ = MagicMock(return_value=False)
+
+ atomic_call_count = 0
+
+ def atomic_side_effect(*args, **kwargs):
+ nonlocal atomic_call_count
+ atomic_call_count += 1
+ if atomic_call_count == 1:
+ return mock_outer_atomic
+ return mock_fallback_atomic
+
+ with patch(
+ "api.db_utils.transaction.atomic",
+ side_effect=atomic_side_effect,
+ ):
+ with patch(
+ "api.db_utils.set_read_db_alias",
+ side_effect=["replica-token", "primary-token"],
+ ):
+ with patch("api.db_utils.reset_read_db_alias"):
+ with rls_transaction(tenant_id):
+ wrapper = mock_replica_conn.execute_wrappers[0]
+ mock_execute = MagicMock(
+ side_effect=OperationalError(
+ "server closed the connection"
+ )
+ )
+ mock_context = {"cursor": MagicMock()}
+ wrapper(
+ mock_execute,
+ "SELECT 1",
+ None,
+ False,
+ mock_context,
+ )
+
+ mock_primary_cursor.execute.assert_has_calls(
+ [
+ call(SET_TRANSACTION_READ_ONLY_QUERY),
+ call(
+ SET_CONFIG_QUERY,
+ [POSTGRES_TENANT_VAR, tenant_id],
+ ),
+ call("SELECT 1", None),
+ ]
+ )
+
+ def test_wrapper_not_installed_on_primary(self, tenants_fixture):
+ """execute_wrapper is not installed when targeting primary DB."""
+ tenant = tenants_fixture[0]
+ tenant_id = str(tenant.id)
+
+ with patch("api.db_utils.get_read_db_alias", return_value=None):
+ with patch("api.db_utils.connections") as mock_connections:
+ mock_conn = MagicMock()
+ mock_conn.execute_wrappers = []
+ mock_cursor = MagicMock()
+ mock_conn.cursor.return_value.__enter__.return_value = mock_cursor
+ mock_connections.__getitem__.return_value = mock_conn
+ mock_connections.__contains__.return_value = True
+
+ with patch("api.db_utils.transaction.atomic") as mock_atomic:
+ mock_atomic.return_value.__enter__ = MagicMock(return_value=None)
+ mock_atomic.return_value.__exit__ = MagicMock(return_value=False)
+
+ with rls_transaction(tenant_id):
+ # No wrapper installed on primary
+ assert len(mock_conn.execute_wrappers) == 0
+
+ def test_stale_connection_closed_on_pre_yield_retry(
+ self, tenants_fixture, enable_read_replica
+ ):
+ """Stale connection is closed before each pre-yield retry."""
+ tenant = tenants_fixture[0]
+ tenant_id = str(tenant.id)
+
+ with patch("api.db_utils.get_read_db_alias", return_value=enable_read_replica):
+ with patch("api.db_utils.connections") as mock_connections:
+ mock_conn = MagicMock()
+ mock_conn.execute_wrappers = []
+ mock_cursor = MagicMock()
+ mock_conn.cursor.return_value.__enter__.return_value = mock_cursor
+ mock_connections.__getitem__.return_value = mock_conn
+ mock_connections.__contains__.return_value = True
+
+ call_count = 0
+
+ def atomic_side_effect(*args, **kwargs):
+ nonlocal call_count
+ call_count += 1
+ if call_count < 3:
+ raise OperationalError("Connection error")
+ return MagicMock(
+ __enter__=MagicMock(return_value=None),
+ __exit__=MagicMock(return_value=False),
+ )
+
+ with patch(
+ "api.db_utils.transaction.atomic", side_effect=atomic_side_effect
+ ):
+ with patch("api.db_utils.time.sleep"):
+ with patch(
+ "api.db_utils.set_read_db_alias", return_value="token"
+ ):
+ with patch("api.db_utils.reset_read_db_alias"):
+ with rls_transaction(tenant_id):
+ pass
+
+ # close() called for each failed pre-yield attempt
+ assert mock_conn.close.call_count == 2
+
+ def test_caller_error_propagates_after_successful_failover(
+ self, tenants_fixture, enable_read_replica
+ ):
+ """OperationalError raised by caller after failover is NOT suppressed."""
+ tenant = tenants_fixture[0]
+ tenant_id = str(tenant.id)
+
+ with patch("api.db_utils.get_read_db_alias", return_value=enable_read_replica):
+ with patch("api.db_utils.connections") as mock_connections:
+ (
+ mock_replica_conn,
+ _mock_primary_conn,
+ _mock_primary_cursor,
+ ) = self._mock_replica_and_primary_connections(mock_connections)
+
+ # Transaction cleanup succeeds so the caller error should surface.
+ mock_atomic_cm = MagicMock()
+ mock_atomic_cm.__enter__ = MagicMock(return_value=None)
+ mock_atomic_cm.__exit__ = MagicMock(return_value=False)
+
+ with patch(
+ "api.db_utils.transaction.atomic", return_value=mock_atomic_cm
+ ):
+ with patch("api.db_utils.time.sleep"):
+ with patch(
+ "api.db_utils.set_read_db_alias", return_value="token"
+ ):
+ with patch("api.db_utils.reset_read_db_alias"):
+ with pytest.raises(
+ OperationalError, match="caller error"
+ ):
+ with rls_transaction(tenant_id):
+ # Trigger failover (succeeds on primary)
+ wrapper = mock_replica_conn.execute_wrappers[0]
+ mock_execute = MagicMock(
+ side_effect=OperationalError(
+ "server closed the connection"
+ )
+ )
+ mock_context = {"cursor": MagicMock()}
+ wrapper(
+ mock_execute,
+ "SELECT 1",
+ None,
+ False,
+ mock_context,
+ )
+ # Caller errors after successful failover
+ # should still propagate.
+ raise OperationalError("caller error")
+
class TestPostgresEnumMigration:
"""
diff --git a/api/src/backend/api/tests/test_decorators.py b/api/src/backend/api/tests/test_decorators.py
index 25053a2258..0bf58340a1 100644
--- a/api/src/backend/api/tests/test_decorators.py
+++ b/api/src/backend/api/tests/test_decorators.py
@@ -2,11 +2,12 @@ import uuid
from unittest.mock import call, patch
import pytest
+from api.attack_paths.database import GraphDatabaseQueryException
from api.db_utils import POSTGRES_TENANT_VAR, SET_CONFIG_QUERY
from api.decorators import handle_provider_deletion, set_tenant
from api.exceptions import ProviderDeletedException
from django.core.exceptions import ObjectDoesNotExist
-from django.db import DatabaseError, IntegrityError
+from django.db import DEFAULT_DB_ALIAS, DatabaseError, IntegrityError
@pytest.mark.django_db
@@ -40,10 +41,10 @@ class TestSetTenantDecorator:
@pytest.mark.django_db
class TestHandleProviderDeletionDecorator:
- def test_success_no_exception(self, tenants_fixture, providers_fixture):
+ def test_success_no_exception(self, tenants_fixture, aws_provider):
"""Decorated function runs normally when no exception is raised."""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
@handle_provider_deletion
def task_func(**kwargs):
@@ -127,11 +128,11 @@ class TestHandleProviderDeletionDecorator:
@patch("api.decorators.rls_transaction")
@patch("api.decorators.Provider.objects.filter")
def test_provider_exists_reraises_original(
- self, mock_filter, mock_rls, tenants_fixture, providers_fixture
+ self, mock_filter, mock_rls, tenants_fixture, aws_provider
):
"""Re-raises original exception when provider still exists."""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
mock_rls.return_value.__enter__ = lambda s: None
mock_rls.return_value.__exit__ = lambda s, *args: None
@@ -187,11 +188,11 @@ class TestHandleProviderDeletionDecorator:
@patch("api.decorators.rls_transaction")
@patch("api.decorators.Provider.objects.filter")
def test_database_error_provider_exists_reraises(
- self, mock_filter, mock_rls, tenants_fixture, providers_fixture
+ self, mock_filter, mock_rls, tenants_fixture, aws_provider
):
"""Re-raises original DatabaseError when provider still exists."""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
mock_rls.return_value.__enter__ = lambda s: None
mock_rls.return_value.__exit__ = lambda s, *args: None
@@ -204,6 +205,106 @@ class TestHandleProviderDeletionDecorator:
with pytest.raises(DatabaseError):
task_func(tenant_id=str(tenant.id), provider_id=str(provider.id))
+ @patch("api.decorators.rls_transaction")
+ @patch("api.decorators.Provider.objects.filter")
+ def test_graph_database_error_provider_missing_or_soft_deleted(
+ self, mock_provider_filter, mock_rls, tenants_fixture
+ ):
+ tenant = tenants_fixture[0]
+ provider_id = str(uuid.uuid4())
+
+ mock_rls.return_value.__enter__ = lambda s: None
+ mock_rls.return_value.__exit__ = lambda s, *args: None
+ mock_provider_filter.return_value.exists.return_value = False
+
+ @handle_provider_deletion
+ def task_func(**kwargs):
+ raise GraphDatabaseQueryException("Temporary database not found")
+
+ with pytest.raises(ProviderDeletedException):
+ task_func(tenant_id=str(tenant.id), provider_id=provider_id)
+
+ @patch("api.decorators.rls_transaction")
+ @patch("api.decorators.Tenant.objects.filter")
+ @patch("api.decorators.Provider.objects.filter")
+ def test_graph_database_error_tenant_missing(
+ self, mock_provider_filter, mock_tenant_filter, mock_rls, tenants_fixture
+ ):
+ tenant = tenants_fixture[0]
+ provider_id = str(uuid.uuid4())
+
+ mock_rls.return_value.__enter__ = lambda s: None
+ mock_rls.return_value.__exit__ = lambda s, *args: None
+ mock_provider_filter.return_value.exists.return_value = True
+ mock_tenant_filter.return_value.exists.return_value = False
+
+ @handle_provider_deletion
+ def task_func(**kwargs):
+ raise GraphDatabaseQueryException("Temporary database not found")
+
+ with pytest.raises(ProviderDeletedException):
+ task_func(tenant_id=str(tenant.id), provider_id=provider_id)
+
+ @patch("api.decorators.rls_transaction")
+ @patch("api.decorators.Membership.objects.filter")
+ @patch("api.decorators.Tenant.objects.filter")
+ @patch("api.decorators.Provider.objects.filter")
+ def test_graph_database_error_tenant_without_memberships(
+ self,
+ mock_provider_filter,
+ mock_tenant_filter,
+ mock_membership_filter,
+ mock_rls,
+ tenants_fixture,
+ ):
+ tenant = tenants_fixture[0]
+ provider_id = str(uuid.uuid4())
+
+ mock_rls.return_value.__enter__ = lambda s: None
+ mock_rls.return_value.__exit__ = lambda s, *args: None
+ mock_provider_filter.return_value.exists.return_value = True
+ mock_tenant_filter.return_value.exists.return_value = True
+ mock_membership_filter.return_value.exists.return_value = False
+
+ @handle_provider_deletion
+ def task_func(**kwargs):
+ raise GraphDatabaseQueryException("Temporary database not found")
+
+ with pytest.raises(ProviderDeletedException):
+ task_func(tenant_id=str(tenant.id), provider_id=provider_id)
+
+ @patch("api.decorators.rls_transaction")
+ @patch("api.decorators.Membership.objects.filter")
+ @patch("api.decorators.Tenant.objects.filter")
+ @patch("api.decorators.Provider.objects.filter")
+ def test_graph_database_error_active_provider_and_tenant_reraises(
+ self,
+ mock_provider_filter,
+ mock_tenant_filter,
+ mock_membership_filter,
+ mock_rls,
+ tenants_fixture,
+ ):
+ tenant = tenants_fixture[0]
+ provider_id = str(uuid.uuid4())
+ graph_error = GraphDatabaseQueryException("Temporary database not found")
+
+ mock_rls.return_value.__enter__ = lambda s: None
+ mock_rls.return_value.__exit__ = lambda s, *args: None
+ mock_provider_filter.return_value.exists.return_value = True
+ mock_tenant_filter.return_value.exists.return_value = True
+ mock_membership_filter.return_value.exists.return_value = True
+
+ @handle_provider_deletion
+ def task_func(**kwargs):
+ raise graph_error
+
+ with pytest.raises(GraphDatabaseQueryException) as exc_info:
+ task_func(tenant_id=str(tenant.id), provider_id=provider_id)
+
+ assert exc_info.value is graph_error
+ mock_rls.assert_called_once_with(str(tenant.id), using=DEFAULT_DB_ALIAS)
+
def test_missing_provider_and_scan_raises_assertion(self, tenants_fixture):
"""Raises AssertionError when neither provider_id nor scan_id in kwargs."""
diff --git a/api/src/backend/api/tests/test_health.py b/api/src/backend/api/tests/test_health.py
index f3a7bb34a4..b7cd20f697 100644
--- a/api/src/backend/api/tests/test_health.py
+++ b/api/src/backend/api/tests/test_health.py
@@ -67,7 +67,7 @@ class TestLivenessEndpoint:
with (
patch("api.health._probe_postgres") as mock_pg,
patch("api.health._probe_valkey") as mock_vk,
- patch("api.health._probe_neo4j") as mock_neo,
+ patch("api.health._probe_graph_db") as mock_neo,
):
response = api_client.get(reverse("health-live"))
@@ -83,14 +83,14 @@ class TestReadinessEndpoint:
return (
patch("api.health._probe_postgres", return_value=None),
patch("api.health._probe_valkey", return_value=None),
- patch("api.health._probe_neo4j", return_value=None),
+ patch("api.health._probe_graph_db", return_value=None),
)
def test_returns_200_and_pass_when_all_dependencies_healthy(self, api_client):
with (
patch("api.health._probe_postgres"),
patch("api.health._probe_valkey"),
- patch("api.health._probe_neo4j"),
+ patch("api.health._probe_graph_db"),
):
response = api_client.get(reverse("health-ready"))
@@ -107,7 +107,7 @@ class TestReadinessEndpoint:
assert set(body["checks"].keys()) == {
"postgres:responseTime",
"valkey:responseTime",
- "neo4j:responseTime",
+ "graphdb:responseTime",
}
for key in body["checks"]:
entries = body["checks"][key]
@@ -122,6 +122,23 @@ class TestReadinessEndpoint:
# `output` must not leak when the check passed.
assert "output" not in entry
+ @pytest.mark.parametrize("sink", ["neo4j", "neptune"])
+ def test_graphdb_component_id_reflects_active_sink(self, api_client, sink):
+ from django.test import override_settings
+
+ with (
+ override_settings(ATTACK_PATHS_SINK_DATABASE=sink),
+ patch("api.health._probe_postgres"),
+ patch("api.health._probe_valkey"),
+ patch("api.health._probe_graph_db"),
+ ):
+ response = api_client.get(reverse("health-ready"))
+
+ assert response.status_code == status.HTTP_200_OK
+ entry = response.json()["checks"]["graphdb:responseTime"][0]
+ # Stable key, but the concrete store is named in componentId.
+ assert entry["componentId"] == sink
+
def test_returns_503_and_fail_when_postgres_is_down(self, api_client):
with (
patch(
@@ -129,7 +146,7 @@ class TestReadinessEndpoint:
side_effect=RuntimeError("connection refused"),
),
patch("api.health._probe_valkey"),
- patch("api.health._probe_neo4j"),
+ patch("api.health._probe_graph_db"),
):
response = api_client.get(reverse("health-ready"))
@@ -141,13 +158,13 @@ class TestReadinessEndpoint:
# Exception detail is never echoed in the response, only logged.
assert "output" not in pg_entry
assert body["checks"]["valkey:responseTime"][0]["status"] == "pass"
- assert body["checks"]["neo4j:responseTime"][0]["status"] == "pass"
+ assert body["checks"]["graphdb:responseTime"][0]["status"] == "pass"
def test_returns_503_and_fail_when_valkey_is_down(self, api_client):
with (
patch("api.health._probe_postgres"),
patch("api.health._probe_valkey", side_effect=ConnectionError("timeout")),
- patch("api.health._probe_neo4j"),
+ patch("api.health._probe_graph_db"),
):
response = api_client.get(reverse("health-ready"))
@@ -158,12 +175,12 @@ class TestReadinessEndpoint:
assert vk_entry["status"] == "fail"
assert "output" not in vk_entry
- def test_returns_503_and_fail_when_neo4j_is_down(self, api_client):
+ def test_returns_503_and_fail_when_graph_db_is_down(self, api_client):
with (
patch("api.health._probe_postgres"),
patch("api.health._probe_valkey"),
patch(
- "api.health._probe_neo4j",
+ "api.health._probe_graph_db",
side_effect=RuntimeError("ServiceUnavailable"),
),
):
@@ -172,15 +189,15 @@ class TestReadinessEndpoint:
assert response.status_code == status.HTTP_503_SERVICE_UNAVAILABLE
body = response.json()
assert body["status"] == "fail"
- neo_entry = body["checks"]["neo4j:responseTime"][0]
- assert neo_entry["status"] == "fail"
- assert "output" not in neo_entry
+ graph_db_entry = body["checks"]["graphdb:responseTime"][0]
+ assert graph_db_entry["status"] == "fail"
+ assert "output" not in graph_db_entry
def test_reports_all_failures_simultaneously(self, api_client):
with (
patch("api.health._probe_postgres", side_effect=RuntimeError("pg down")),
patch("api.health._probe_valkey", side_effect=RuntimeError("vk down")),
- patch("api.health._probe_neo4j", side_effect=RuntimeError("neo down")),
+ patch("api.health._probe_graph_db", side_effect=RuntimeError("neo down")),
):
response = api_client.get(reverse("health-ready"))
@@ -190,7 +207,7 @@ class TestReadinessEndpoint:
for key in (
"postgres:responseTime",
"valkey:responseTime",
- "neo4j:responseTime",
+ "graphdb:responseTime",
):
entry = body["checks"][key][0]
assert entry["status"] == "fail"
@@ -209,7 +226,7 @@ class TestReadinessEndpoint:
with (
patch("api.health._probe_postgres", side_effect=RuntimeError(sensitive)),
patch("api.health._probe_valkey"),
- patch("api.health._probe_neo4j"),
+ patch("api.health._probe_graph_db"),
):
response = api_client.get(reverse("health-ready"))
@@ -229,7 +246,7 @@ class TestReadinessEndpoint:
with (
patch("api.health._probe_postgres"),
patch("api.health._probe_valkey"),
- patch("api.health._probe_neo4j"),
+ patch("api.health._probe_graph_db"),
):
api_client.credentials()
response = api_client.get(reverse("health-ready"))
@@ -244,7 +261,7 @@ class TestReadinessCache:
with (
patch("api.health._probe_postgres") as pg,
patch("api.health._probe_valkey") as vk,
- patch("api.health._probe_neo4j") as neo,
+ patch("api.health._probe_graph_db") as neo,
):
r1 = api_client.get(reverse("health-ready"))
r2 = api_client.get(reverse("health-ready"))
@@ -262,7 +279,7 @@ class TestReadinessCache:
with (
patch("api.health._probe_postgres") as pg,
patch("api.health._probe_valkey"),
- patch("api.health._probe_neo4j"),
+ patch("api.health._probe_graph_db"),
):
api_client.get(reverse("health-ready"))
assert pg.call_count == 1
@@ -286,7 +303,7 @@ class TestReadinessCache:
with (
patch("api.health._probe_postgres", side_effect=RuntimeError("down")) as pg,
patch("api.health._probe_valkey"),
- patch("api.health._probe_neo4j"),
+ patch("api.health._probe_graph_db"),
):
r1 = api_client.get(reverse("health-ready"))
r2 = api_client.get(reverse("health-ready"))
@@ -320,7 +337,7 @@ class TestRateLimiting:
with (
patch("api.health._probe_postgres"),
patch("api.health._probe_valkey"),
- patch("api.health._probe_neo4j"),
+ patch("api.health._probe_graph_db"),
patch.object(ScopedRateThrottle, "parse_rate", return_value=(2, 60)),
):
statuses = [
@@ -414,19 +431,42 @@ class TestProbeImplementations:
with pytest.raises(RuntimeError, match="bug"):
health._probe_valkey()
- def test_neo4j_probe_calls_verify_connectivity(self):
- with patch("api.attack_paths.database.get_driver") as mock_get_driver:
- mock_get_driver.return_value.verify_connectivity.return_value = None
- assert health._probe_neo4j() is None
- mock_get_driver.return_value.verify_connectivity.assert_called_once_with()
+ def test_graph_db_probe_calls_verify_connectivity(self):
+ with patch("api.attack_paths.database.verify_connectivity") as mock_verify:
+ mock_verify.return_value = None
+ assert health._probe_graph_db() is None
+ mock_verify.assert_called_once_with()
- def test_neo4j_probe_propagates_driver_errors(self):
- with patch("api.attack_paths.database.get_driver") as mock_get_driver:
- mock_get_driver.return_value.verify_connectivity.side_effect = RuntimeError(
- "unreachable"
- )
+ def test_graph_db_probe_propagates_errors(self):
+ with patch(
+ "api.attack_paths.database.verify_connectivity",
+ side_effect=RuntimeError("unreachable"),
+ ):
with pytest.raises(RuntimeError, match="unreachable"):
- health._probe_neo4j()
+ health._probe_graph_db()
+
+ def test_graph_db_probe_times_out_when_check_exceeds_budget(self):
+ # A sink whose connectivity check blocks past the probe budget must
+ # surface as a failure fast, not pin the request thread for the
+ # driver's full acquisition timeout.
+ import time as _time
+
+ def _hang() -> None:
+ _time.sleep(2)
+
+ with (
+ patch("api.health.GRAPH_DB_PROBE_TIMEOUT_SECONDS", 0.2),
+ patch(
+ "api.attack_paths.database.verify_connectivity",
+ side_effect=_hang,
+ ),
+ ):
+ started = _time.perf_counter()
+ with pytest.raises(TimeoutError):
+ health._probe_graph_db()
+ elapsed = _time.perf_counter() - started
+
+ assert elapsed < health.GRAPH_DB_PROBE_TIMEOUT_SECONDS + 1
class TestStatusAggregation:
diff --git a/api/src/backend/api/tests/test_models.py b/api/src/backend/api/tests/test_models.py
index 3ec823b89a..5095da3a0e 100644
--- a/api/src/backend/api/tests/test_models.py
+++ b/api/src/backend/api/tests/test_models.py
@@ -19,8 +19,8 @@ from django.db import IntegrityError
@pytest.mark.django_db
class TestResourceModel:
- def test_setting_tags(self, providers_fixture):
- provider, *_ = providers_fixture
+ def test_setting_tags(self, aws_provider):
+ provider = aws_provider
tenant_id = provider.tenant_id
resource = Resource.objects.create(
@@ -111,9 +111,9 @@ class TestResourceModel:
# @pytest.mark.django_db
# class TestFindingModel:
# def test_add_finding_with_long_uid(
-# self, providers_fixture, scans_fixture, resources_fixture
+# self, aws_provider, scans_fixture, resources_fixture
# ):
-# provider, *_ = providers_fixture
+# provider = aws_provider
# tenant_id = provider.tenant_id
# long_uid = "1" * 500
@@ -372,8 +372,8 @@ class TestSAMLConfigurationModel:
@pytest.mark.django_db
class TestProviderComplianceScoreModel:
- def test_create_provider_compliance_score(self, providers_fixture, scans_fixture):
- provider = providers_fixture[0]
+ def test_create_provider_compliance_score(self, aws_provider, scans_fixture):
+ provider = aws_provider
scan = scans_fixture[0]
scan.completed_at = datetime.now(UTC)
scan.save()
@@ -393,9 +393,9 @@ class TestProviderComplianceScoreModel:
assert score.requirement_status == StatusChoices.PASS
def test_unique_constraint_per_provider_compliance_requirement(
- self, providers_fixture, scans_fixture
+ self, aws_provider, scans_fixture
):
- provider = providers_fixture[0]
+ provider = aws_provider
scan = scans_fixture[0]
scan.completed_at = datetime.now(UTC)
scan.save()
@@ -422,9 +422,9 @@ class TestProviderComplianceScoreModel:
)
def test_different_providers_same_requirement_allowed(
- self, providers_fixture, scans_fixture
+ self, aws_provider_pair, scans_fixture
):
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
scan1 = scans_fixture[0]
scan1.completed_at = datetime.now(UTC)
scan1.save()
diff --git a/api/src/backend/api/tests/test_rbac.py b/api/src/backend/api/tests/test_rbac.py
index 4f787b1f5a..ed177138b2 100644
--- a/api/src/backend/api/tests/test_rbac.py
+++ b/api/src/backend/api/tests/test_rbac.py
@@ -11,6 +11,7 @@ from api.models import (
User,
UserRoleRelationship,
)
+from api.rbac.permissions import HasPermissions, Permissions
from api.v1.serializers import TokenSerializer
from conftest import TEST_PASSWORD, TODAY
from django.urls import reverse
@@ -103,20 +104,84 @@ class TestUserViewSet:
assert response.json()["data"]["attributes"]["name"] == "Updated Name"
def test_partial_update_user_with_no_permissions(
- self, authenticated_client_no_permissions_rbac, create_test_user
+ self, authenticated_client_no_permissions_rbac, create_test_user_rbac_limited
):
updated_data = {
"data": {
"type": "users",
+ "id": str(create_test_user_rbac_limited.id),
"attributes": {"name": "Updated Name"},
}
}
response = authenticated_client_no_permissions_rbac.patch(
- reverse("user-detail", kwargs={"pk": create_test_user.id}),
+ reverse("user-detail", kwargs={"pk": create_test_user_rbac_limited.id}),
data=updated_data,
- format="vnd.api+json",
+ content_type="application/vnd.api+json",
)
- assert response.status_code == status.HTTP_403_FORBIDDEN
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["data"]["attributes"]["name"] == "Updated Name"
+
+ def test_partial_update_other_user_with_no_permissions_denied(
+ self, authenticated_client_no_permissions_rbac, tenants_fixture
+ ):
+ original_email = "target-rbac-update@example.com"
+ original_password = "OriginalPassword123@"
+ target_user = User.objects.create_user(
+ name="target_rbac_update",
+ email=original_email,
+ password=original_password,
+ )
+ Membership.objects.create(user=target_user, tenant=tenants_fixture[0])
+ updated_data = {
+ "data": {
+ "type": "users",
+ "id": str(target_user.id),
+ "attributes": {
+ "email": "updated-target-rbac@example.com",
+ "password": "UpdatedPassword123@",
+ },
+ }
+ }
+
+ response = authenticated_client_no_permissions_rbac.patch(
+ reverse("user-detail", kwargs={"pk": target_user.id}),
+ data=updated_data,
+ content_type="application/vnd.api+json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ target_user.refresh_from_db()
+ assert target_user.email == original_email
+ assert target_user.check_password(original_password)
+
+ def test_partial_update_other_user_with_manage_users_allowed(
+ self, authenticated_client_rbac_manage_users_only
+ ):
+ user = authenticated_client_rbac_manage_users_only.user
+ tenant = Membership.objects.filter(user=user).first().tenant
+ target_user = User.objects.create_user(
+ name="target_manage_users_update",
+ email="target-manage-users-update@example.com",
+ password="Password123@",
+ )
+ Membership.objects.create(user=target_user, tenant=tenant)
+ updated_data = {
+ "data": {
+ "type": "users",
+ "id": str(target_user.id),
+ "attributes": {"name": "Updated Target Name"},
+ }
+ }
+
+ response = authenticated_client_rbac_manage_users_only.patch(
+ reverse("user-detail", kwargs={"pk": target_user.id}),
+ data=updated_data,
+ content_type="application/vnd.api+json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ target_user.refresh_from_db()
+ assert target_user.name == "Updated Target Name"
def test_delete_user_with_all_permissions(
self, authenticated_client_rbac, create_test_user_rbac
@@ -370,11 +435,11 @@ class TestUserViewSet:
@pytest.mark.django_db
class TestProviderViewSet:
def test_list_providers_with_all_permissions(
- self, authenticated_client_rbac, providers_fixture
+ self, authenticated_client_rbac, aws_provider
):
response = authenticated_client_rbac.get(reverse("provider-list"))
assert response.status_code == status.HTTP_200_OK
- assert len(response.json()["data"]) == len(providers_fixture)
+ assert len(response.json()["data"]) == 1
def test_list_providers_with_no_permissions(
self, authenticated_client_no_permissions_rbac
@@ -386,9 +451,9 @@ class TestProviderViewSet:
assert len(response.json()["data"]) == 0
def test_retrieve_provider_with_all_permissions(
- self, authenticated_client_rbac, providers_fixture
+ self, authenticated_client_rbac, aws_provider
):
- provider = providers_fixture[0]
+ provider = aws_provider
response = authenticated_client_rbac.get(
reverse("provider-detail", kwargs={"pk": provider.id})
)
@@ -396,9 +461,9 @@ class TestProviderViewSet:
assert response.json()["data"]["attributes"]["alias"] == provider.alias
def test_retrieve_provider_with_no_permissions(
- self, authenticated_client_no_permissions_rbac, providers_fixture
+ self, authenticated_client_no_permissions_rbac, aws_provider
):
- provider = providers_fixture[0]
+ provider = aws_provider
response = authenticated_client_no_permissions_rbac.get(
reverse("provider-detail", kwargs={"pk": provider.id})
)
@@ -422,9 +487,9 @@ class TestProviderViewSet:
assert response.status_code == status.HTTP_403_FORBIDDEN
def test_partial_update_provider_with_all_permissions(
- self, authenticated_client_rbac, providers_fixture
+ self, authenticated_client_rbac, aws_provider
):
- provider = providers_fixture[0]
+ provider = aws_provider
payload = {
"data": {
"type": "providers",
@@ -441,9 +506,9 @@ class TestProviderViewSet:
assert response.json()["data"]["attributes"]["alias"] == "updated_alias"
def test_partial_update_provider_with_no_permissions(
- self, authenticated_client_no_permissions_rbac, providers_fixture
+ self, authenticated_client_no_permissions_rbac, aws_provider
):
- provider = providers_fixture[0]
+ provider = aws_provider
update_payload = {
"data": {
"type": "providers",
@@ -464,7 +529,7 @@ class TestProviderViewSet:
mock_delete_task,
mock_task_get,
authenticated_client_rbac,
- providers_fixture,
+ aws_provider,
tasks_fixture,
):
prowler_task = tasks_fixture[0]
@@ -473,7 +538,7 @@ class TestProviderViewSet:
mock_delete_task.return_value = task_mock
mock_task_get.return_value = prowler_task
- provider1, *_ = providers_fixture
+ provider1 = aws_provider
response = authenticated_client_rbac.delete(
reverse("provider-detail", kwargs={"pk": provider1.id})
)
@@ -485,9 +550,9 @@ class TestProviderViewSet:
assert response.headers["Content-Location"] == f"/api/v1/tasks/{task_mock.id}"
def test_delete_provider_with_no_permissions(
- self, authenticated_client_no_permissions_rbac, providers_fixture
+ self, authenticated_client_no_permissions_rbac, aws_provider
):
- provider = providers_fixture[0]
+ provider = aws_provider
response = authenticated_client_no_permissions_rbac.delete(
reverse("provider-detail", kwargs={"pk": provider.id})
)
@@ -500,7 +565,7 @@ class TestProviderViewSet:
mock_provider_connection,
mock_task_get,
authenticated_client_rbac,
- providers_fixture,
+ aws_provider,
tasks_fixture,
):
prowler_task = tasks_fixture[0]
@@ -510,7 +575,7 @@ class TestProviderViewSet:
mock_provider_connection.return_value = task_mock
mock_task_get.return_value = prowler_task
- provider1, *_ = providers_fixture
+ provider1 = aws_provider
assert provider1.connected is None
assert provider1.connection_last_checked_at is None
@@ -525,9 +590,9 @@ class TestProviderViewSet:
assert response.headers["Content-Location"] == f"/api/v1/tasks/{task_mock.id}"
def test_connection_with_no_permissions(
- self, authenticated_client_no_permissions_rbac, providers_fixture
+ self, authenticated_client_no_permissions_rbac, aws_provider
):
- provider = providers_fixture[0]
+ provider = aws_provider
response = authenticated_client_no_permissions_rbac.post(
reverse("provider-connection", kwargs={"pk": provider.id})
)
@@ -540,12 +605,10 @@ class TestLimitedVisibility:
TEST_PASSWORD = "Thisisapassword123@"
@pytest.fixture
- def limited_admin_user(
- self, django_db_setup, django_db_blocker, tenants_fixture, providers_fixture
- ):
+ def limited_admin_user(self, django_db_blocker, tenants_fixture, aws_provider):
with django_db_blocker.unblock():
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
user = User.objects.create_user(
name="testing",
email=self.TEST_EMAIL,
@@ -592,25 +655,17 @@ class TestLimitedVisibility:
@pytest.fixture
def authenticated_client_rbac_limited(
- self, limited_admin_user, tenants_fixture, client
+ self,
+ limited_admin_user,
+ tenants_fixture,
+ authenticated_client_for_tenant_factory,
):
- client.user = limited_admin_user
- tenant_id = tenants_fixture[0].id
- serializer = TokenSerializer(
- data={
- "type": "tokens",
- "email": self.TEST_EMAIL,
- "password": self.TEST_PASSWORD,
- "tenant_id": tenant_id,
- }
+ return authenticated_client_for_tenant_factory(
+ limited_admin_user, tenants_fixture[0]
)
- serializer.is_valid(raise_exception=True)
- access_token = serializer.validated_data["access"]
- client.defaults["HTTP_AUTHORIZATION"] = f"Bearer {access_token}"
- return client
def test_integrations(
- self, authenticated_client_rbac_limited, integrations_fixture, providers_fixture
+ self, authenticated_client_rbac_limited, integrations_fixture
):
# Integration 2 is related to provider1 and provider 2
# This user cannot see provider 2
@@ -626,11 +681,11 @@ class TestLimitedVisibility:
response.json()["data"]["relationships"]["providers"]["meta"]["count"] == 1
)
+ @pytest.mark.usefixtures("scan_summaries_fixture")
def test_overviews_providers(
self,
authenticated_client_rbac_limited,
- scan_summaries_fixture,
- providers_fixture,
+ provider_factory,
):
# By default, the associated provider is the one which has the overview data
response = authenticated_client_rbac_limited.get(reverse("overview-providers"))
@@ -640,7 +695,7 @@ class TestLimitedVisibility:
# Changing the provider visibility, no data should be returned
# Only the associated provider to that group is changed
- new_provider = providers_fixture[1]
+ new_provider = provider_factory()
ProviderGroupMembership.objects.all().update(provider=new_provider)
response = authenticated_client_rbac_limited.get(reverse("overview-providers"))
@@ -648,6 +703,7 @@ class TestLimitedVisibility:
assert response.status_code == status.HTTP_200_OK
assert len(response.json()["data"]) == 0
+ @pytest.mark.usefixtures("scan_summaries_fixture")
@pytest.mark.parametrize(
"endpoint_name",
[
@@ -659,8 +715,7 @@ class TestLimitedVisibility:
self,
endpoint_name,
authenticated_client_rbac_limited,
- scan_summaries_fixture,
- providers_fixture,
+ provider_factory,
):
# By default, the associated provider is the one which has the overview data
response = authenticated_client_rbac_limited.get(
@@ -673,7 +728,7 @@ class TestLimitedVisibility:
# Changing the provider visibility, no data should be returned
# Only the associated provider to that group is changed
- new_provider = providers_fixture[1]
+ new_provider = provider_factory()
ProviderGroupMembership.objects.all().update(provider=new_provider)
response = authenticated_client_rbac_limited.get(
@@ -684,11 +739,11 @@ class TestLimitedVisibility:
data = response.json()["data"]["attributes"].values()
assert all(value == 0 for value in data)
+ @pytest.mark.usefixtures("scan_summaries_fixture")
def test_overviews_services(
self,
authenticated_client_rbac_limited,
- scan_summaries_fixture,
- providers_fixture,
+ provider_factory,
):
# By default, the associated provider is the one which has the overview data
response = authenticated_client_rbac_limited.get(
@@ -700,7 +755,7 @@ class TestLimitedVisibility:
# Changing the provider visibility, no data should be returned
# Only the associated provider to that group is changed
- new_provider = providers_fixture[1]
+ new_provider = provider_factory()
ProviderGroupMembership.objects.all().update(provider=new_provider)
response = authenticated_client_rbac_limited.get(
@@ -762,6 +817,48 @@ class TestRolePermissions:
assert response.status_code == status.HTTP_403_FORBIDDEN
+@pytest.mark.django_db
+class TestHasPermissions:
+ def test_permissions_are_combined_across_roles(
+ self, create_test_user_rbac_no_roles
+ ):
+ user = create_test_user_rbac_no_roles
+ tenant = Membership.objects.get(user=user).tenant
+ manage_users_role = Role.objects.create(
+ name="manage_users_only",
+ tenant=tenant,
+ manage_users=True,
+ )
+ UserRoleRelationship.objects.create(
+ user=user,
+ role=manage_users_role,
+ tenant=tenant,
+ )
+ request = Mock(user=user, tenant_id=tenant.id)
+ view = Mock(
+ required_permissions=[
+ Permissions.MANAGE_USERS,
+ Permissions.MANAGE_ACCOUNT,
+ ]
+ )
+ permission = HasPermissions()
+
+ assert not permission.has_permission(request, view)
+
+ manage_account_role = Role.objects.create(
+ name="manage_account_only",
+ tenant=tenant,
+ manage_account=True,
+ )
+ UserRoleRelationship.objects.create(
+ user=user,
+ role=manage_account_role,
+ tenant=tenant,
+ )
+
+ assert permission.has_permission(request, view)
+
+
@pytest.mark.django_db
class TestUserRoleLinkPermissions:
def test_link_user_roles_with_manage_account_only_allowed(
diff --git a/api/src/backend/api/tests/test_retryable_session.py b/api/src/backend/api/tests/test_retryable_session.py
new file mode 100644
index 0000000000..09b184c223
--- /dev/null
+++ b/api/src/backend/api/tests/test_retryable_session.py
@@ -0,0 +1,165 @@
+from unittest.mock import MagicMock, patch
+
+import pytest
+from api.attack_paths.retryable_session import RetryableSession, RetryExhaustedError
+from neo4j.exceptions import ServiceUnavailable
+
+
+class TestRetryableSession:
+ @patch("api.attack_paths.retryable_session.time.sleep")
+ @patch("api.attack_paths.retryable_session.random.uniform", return_value=3.0)
+ def test_custom_retry_uses_backoff_and_a_fresh_session(
+ self, mock_uniform, mock_sleep
+ ):
+ retryable_error = RuntimeError("retryable")
+ first_session = MagicMock()
+ first_session.execute_write.side_effect = retryable_error
+ second_session = MagicMock()
+ second_session.execute_write.return_value = "success"
+ session_factory = MagicMock(side_effect=[first_session, second_session])
+ work = MagicMock()
+
+ session = RetryableSession(
+ session_factory=session_factory,
+ max_retries=3,
+ retry_if=lambda exc: exc is retryable_error,
+ initial_retry_delay_seconds=2,
+ retry_context="Neptune write",
+ )
+
+ assert session.execute_write(work) == "success"
+ assert session_factory.call_count == 2
+ first_session.close.assert_called_once_with()
+ mock_uniform.assert_called_once_with(2.0, 4.0)
+ mock_sleep.assert_called_once_with(3.0)
+
+ def test_connection_errors_remain_retryable(self):
+ first_session = MagicMock()
+ first_session.run.side_effect = ServiceUnavailable("unavailable")
+ second_session = MagicMock()
+ second_session.run.return_value = "success"
+ session_factory = MagicMock(side_effect=[first_session, second_session])
+
+ session = RetryableSession(session_factory=session_factory, max_retries=1)
+
+ assert session.run("RETURN 1") == "success"
+ first_session.close.assert_called_once_with()
+
+ def test_non_retryable_error_is_raised_without_refreshing_session(self):
+ error = RuntimeError("do not retry")
+ driver_session = MagicMock()
+ driver_session.execute_write.side_effect = error
+ session_factory = MagicMock(return_value=driver_session)
+ session = RetryableSession(
+ session_factory=session_factory,
+ max_retries=3,
+ retry_if=lambda _: False,
+ initial_retry_delay_seconds=2,
+ retry_context="Neptune write",
+ )
+
+ with pytest.raises(RuntimeError) as exc_info:
+ session.execute_write(MagicMock())
+
+ assert exc_info.value is error
+ session_factory.assert_called_once_with()
+ driver_session.close.assert_not_called()
+
+ def test_retry_exhaustion_raises_the_last_error(self):
+ error = RuntimeError("still retryable")
+ driver_sessions = [MagicMock() for _ in range(3)]
+ for driver_session in driver_sessions:
+ driver_session.execute_write.side_effect = error
+ session_factory = MagicMock(side_effect=driver_sessions)
+ session = RetryableSession(
+ session_factory=session_factory,
+ max_retries=2,
+ retry_if=lambda _: True,
+ )
+
+ with pytest.raises(RuntimeError) as exc_info:
+ session.execute_write(MagicMock())
+
+ assert exc_info.value is error
+ assert session_factory.call_count == 3
+ driver_sessions[0].close.assert_called_once_with()
+ driver_sessions[1].close.assert_called_once_with()
+ driver_sessions[2].close.assert_not_called()
+
+ def test_retry_exhaustion_with_context_reports_attempts_and_elapsed_time(self):
+ error = RuntimeError("still retryable")
+ driver_sessions = [MagicMock() for _ in range(3)]
+ for driver_session in driver_sessions:
+ driver_session.execute_write.side_effect = error
+ session = RetryableSession(
+ session_factory=MagicMock(side_effect=driver_sessions),
+ max_retries=2,
+ retry_if=lambda _: True,
+ retry_context="Neptune write",
+ )
+
+ with (
+ patch(
+ "api.attack_paths.retryable_session.time.monotonic",
+ side_effect=[100.0, 127.1234],
+ ),
+ pytest.raises(RetryExhaustedError) as exc_info,
+ ):
+ session.execute_write(MagicMock())
+
+ assert exc_info.value.method_name == "execute_write"
+ assert exc_info.value.attempts == 3
+ assert exc_info.value.elapsed_seconds == pytest.approx(27.1234)
+ assert exc_info.value.last_error is error
+ assert exc_info.value.__cause__ is error
+ assert str(exc_info.value) == (
+ "Neptune write execute_write failed after 3 attempts over 27.123s. "
+ "Last error: still retryable"
+ )
+
+ def test_retry_exhaustion_with_zero_retries_reports_one_attempt(self):
+ error = ServiceUnavailable("still unavailable")
+ driver_session = MagicMock()
+ driver_session.execute_write.side_effect = error
+ session = RetryableSession(
+ session_factory=MagicMock(return_value=driver_session),
+ max_retries=0,
+ retry_context="Neptune write",
+ )
+
+ with pytest.raises(RetryExhaustedError) as exc_info:
+ session.execute_write(MagicMock())
+
+ assert exc_info.value.attempts == 1
+
+ @patch("api.attack_paths.retryable_session.time.sleep")
+ @patch("api.attack_paths.retryable_session.random.uniform", return_value=3.0)
+ def test_contextual_retry_warning_includes_original_error(
+ self, _mock_uniform, _mock_sleep
+ ):
+ error = RuntimeError("retryable detail")
+ first_session = MagicMock()
+ first_session.execute_write.side_effect = error
+ second_session = MagicMock()
+ second_session.execute_write.return_value = "success"
+ session = RetryableSession(
+ session_factory=MagicMock(side_effect=[first_session, second_session]),
+ max_retries=1,
+ retry_if=lambda _: True,
+ initial_retry_delay_seconds=2,
+ retry_context="Neptune write",
+ )
+
+ with patch("api.attack_paths.retryable_session.logger.warning") as mock_warning:
+ assert session.execute_write(MagicMock()) == "success"
+
+ mock_warning.assert_called_once_with(
+ "%s %s failed with %s: %s; retry %s/%s in %.3fs",
+ "Neptune write",
+ "execute_write",
+ "RuntimeError",
+ "retryable detail",
+ 1,
+ 1,
+ 3.0,
+ )
diff --git a/api/src/backend/api/tests/test_sentry.py b/api/src/backend/api/tests/test_sentry.py
index fb7abaffb4..67ba1ee01e 100644
--- a/api/src/backend/api/tests/test_sentry.py
+++ b/api/src/backend/api/tests/test_sentry.py
@@ -1,9 +1,34 @@
import logging
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, patch
+import pytest
+from config.settings import sentry as sentry_settings
from config.settings.sentry import before_send
+def test_initialize_sentry_skips_without_dsn():
+ with (
+ patch.object(sentry_settings.env, "str", return_value=""),
+ patch.object(sentry_settings.sentry_sdk, "init") as mock_init,
+ ):
+ sentry_settings.initialize_sentry()
+
+ mock_init.assert_not_called()
+
+
+def test_initialize_sentry_uses_configured_dsn():
+ sentry_dsn = "https://fake-public-key@sentry.example.invalid/1"
+
+ with (
+ patch.object(sentry_settings.env, "str", return_value=sentry_dsn),
+ patch.object(sentry_settings.sentry_sdk, "init") as mock_init,
+ ):
+ sentry_settings.initialize_sentry()
+
+ assert mock_init.call_args.kwargs["dsn"] == sentry_dsn
+ assert mock_init.call_args.kwargs["before_send"] is sentry_settings.before_send
+
+
def _make_log_record(msg, level=logging.ERROR, name="test", args=None):
"""Build a real LogRecord so getMessage() works like in production."""
record = logging.LogRecord(
@@ -58,6 +83,45 @@ def test_before_send_passes_through_non_ignored_log():
assert result == event
+def test_before_send_ignores_cartography_missing_temporary_database_log():
+ log_record = _make_log_record(
+ msg="Cartography job failed with %s for database %s",
+ name="cartography.graph.job",
+ args=(
+ "Neo.ClientError.Database.DatabaseNotFound",
+ "db-tmp-scan-12345678",
+ ),
+ )
+
+ event = MagicMock()
+
+ assert before_send(event, {"log_record": log_record}) is None
+
+
+@pytest.mark.parametrize(
+ ("logger_name", "message"),
+ [
+ (
+ "cartography.graph.job.worker",
+ "Neo.ClientError.Database.DatabaseNotFound for db-tmp-scan-12345678",
+ ),
+ (
+ "cartography.graph.job",
+ "DatabaseNotFound for db-tmp-scan-12345678",
+ ),
+ (
+ "cartography.graph.job",
+ "Neo.ClientError.Database.DatabaseNotFound for db-tenant-12345678",
+ ),
+ ],
+)
+def test_before_send_passes_through_similar_cartography_logs(logger_name, message):
+ log_record = _make_log_record(msg=message, name=logger_name)
+ event = MagicMock()
+
+ assert before_send(event, {"log_record": log_record}) is event
+
+
def test_before_send_passes_through_non_ignored_exception():
"""Test that before_send passes through exceptions that don't contain ignored exceptions."""
exc_info = (Exception, Exception("Some other error message"), None)
diff --git a/api/src/backend/api/tests/test_serializers.py b/api/src/backend/api/tests/test_serializers.py
index ea01075934..8e77d63604 100644
--- a/api/src/backend/api/tests/test_serializers.py
+++ b/api/src/backend/api/tests/test_serializers.py
@@ -1,6 +1,14 @@
import pytest
-from api.v1.serializer_utils.integrations import S3ConfigSerializer
-from api.v1.serializers import ImageProviderSecret
+from api.v1.serializer_utils.integrations import (
+ JiraCredentialSerializer,
+ S3ConfigSerializer,
+)
+from api.v1.serializer_utils.providers import ProviderSecretField
+from api.v1.serializers import (
+ ImageProviderSecret,
+ KubernetesProviderSecret,
+ OracleCloudProviderSecret,
+)
from rest_framework.exceptions import ValidationError
@@ -100,6 +108,59 @@ class TestS3ConfigSerializer:
assert "output_directory" in serializer.errors
+class TestJiraCredentialSerializer:
+ @pytest.mark.parametrize(
+ "domain",
+ (
+ "a",
+ "prowler",
+ "prowler-domain",
+ "A1-b2-C3",
+ "a" * 63,
+ ),
+ )
+ def test_valid_site_name(self, domain):
+ serializer = JiraCredentialSerializer(
+ data={
+ "user_mail": "testing@prowler.com",
+ "api_token": "fake-api-token",
+ "domain": domain,
+ }
+ )
+
+ assert serializer.is_valid(), serializer.errors
+
+ @pytest.mark.parametrize(
+ "domain",
+ (
+ "169.254.169.254#",
+ "internal/service",
+ "internal?target",
+ "internal\\target",
+ "internal:8000",
+ "user@internal",
+ "example.atlassian.net",
+ "-prowler",
+ "prowler-",
+ "a" * 64,
+ " prowler",
+ "prowler ",
+ "prowler\n",
+ ),
+ )
+ def test_invalid_site_name(self, domain):
+ serializer = JiraCredentialSerializer(
+ data={
+ "user_mail": "testing@prowler.com",
+ "api_token": "fake-api-token",
+ "domain": domain,
+ }
+ )
+
+ assert not serializer.is_valid()
+ assert "domain" in serializer.errors
+
+
class TestImageProviderSecret:
"""Test cases for ImageProviderSecret validation."""
@@ -132,3 +193,132 @@ class TestImageProviderSecret:
serializer = ImageProviderSecret(data={"registry_password": "pass"})
assert not serializer.is_valid()
assert "non_field_errors" in serializer.errors
+
+
+class TestOracleCloudProviderSecret:
+ def valid_secret(self, **overrides):
+ secret = {
+ "user": "ocid1.user.oc1..aaaaaaaexample",
+ "fingerprint": "aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99",
+ "key_content": "fake-base64-key-content",
+ "tenancy": "ocid1.tenancy.oc1..aaaaaaaexample",
+ }
+ secret.update(overrides)
+ return secret
+
+ def test_accepts_regionless_secret(self):
+ serializer = OracleCloudProviderSecret(data=self.valid_secret())
+
+ assert serializer.is_valid(), serializer.errors
+ assert "region" not in serializer.validated_data
+
+ def test_accepts_and_ignores_region_field(self):
+ secret = self.valid_secret(region="us-phoenix-1")
+ serializer = OracleCloudProviderSecret(data=secret)
+
+ assert serializer.is_valid(), serializer.errors
+
+ assert "region" not in serializer.validated_data
+
+ @pytest.mark.parametrize(
+ "legacy_field, legacy_value",
+ [
+ ("region", None),
+ ("region", ""),
+ ("region", {"name": "us-ashburn-1"}),
+ ],
+ )
+ def test_accepts_and_ignores_any_legacy_region_value(
+ self, legacy_field, legacy_value
+ ):
+ serializer = OracleCloudProviderSecret(
+ data=self.valid_secret(**{legacy_field: legacy_value})
+ )
+
+ assert serializer.is_valid(), serializer.errors
+
+ assert legacy_field not in serializer.validated_data
+
+
+class TestProviderSecretFieldSchema:
+ def test_oraclecloud_schema_includes_legacy_region_field(self):
+ schema = ProviderSecretField._spectacular_annotation["field"]
+ oraclecloud_schema = next(
+ credential_schema
+ for credential_schema in schema["oneOf"]
+ if credential_schema["title"]
+ == "Oracle Cloud Infrastructure (OCI) API Key Credentials"
+ )
+
+ assert oraclecloud_schema["properties"]["region"]["deprecated"] is True
+
+
+class TestKubernetesProviderSecret:
+ def test_valid_static_kubeconfig_is_accepted(self):
+ kubeconfig_content = """
+apiVersion: v1
+kind: Config
+clusters:
+ - name: test-cluster
+ cluster:
+ server: https://kubernetes.example.test
+users:
+ - name: test-user
+ user:
+ token: test-token
+contexts:
+ - name: test-context
+ context:
+ cluster: test-cluster
+ user: test-user
+current-context: test-context
+"""
+
+ serializer = KubernetesProviderSecret(
+ data={"kubeconfig_content": kubeconfig_content}
+ )
+
+ assert serializer.is_valid()
+
+ def test_kubeconfig_with_exec_authentication_is_rejected(self):
+ kubeconfig_content = """
+apiVersion: v1
+kind: Config
+clusters:
+ - name: test-cluster
+ cluster:
+ server: https://kubernetes.example.test
+users:
+ - name: test-user
+ user:
+ exec:
+ apiVersion: client.authentication.k8s.io/v1
+ command: kubectl
+contexts:
+ - name: test-context
+ context:
+ cluster: test-cluster
+ user: test-user
+current-context: test-context
+"""
+
+ serializer = KubernetesProviderSecret(
+ data={"kubeconfig_content": kubeconfig_content}
+ )
+
+ assert not serializer.is_valid()
+ assert "kubeconfig_content" in serializer.errors
+
+ def test_malformed_kubeconfig_is_rejected(self):
+ serializer = KubernetesProviderSecret(
+ data={"kubeconfig_content": "apiVersion: ["}
+ )
+
+ assert not serializer.is_valid()
+ assert "kubeconfig_content" in serializer.errors
+
+ def test_non_mapping_kubeconfig_is_rejected(self):
+ serializer = KubernetesProviderSecret(data={"kubeconfig_content": "[]"})
+
+ assert not serializer.is_valid()
+ assert "kubeconfig_content" in serializer.errors
diff --git a/api/src/backend/api/tests/test_sink.py b/api/src/backend/api/tests/test_sink.py
new file mode 100644
index 0000000000..c778626b62
--- /dev/null
+++ b/api/src/backend/api/tests/test_sink.py
@@ -0,0 +1,716 @@
+"""Tests for the attack-paths sink factory and Neo4j sink.
+
+The sink module picks a backend per ``settings.ATTACK_PATHS_SINK_DATABASE``.
+Neo4j is the default and preserves today's behavior; Neptune is opt-in and
+builds dual writer/reader Bolt drivers.
+"""
+
+import json
+from unittest.mock import MagicMock, patch
+
+import neo4j
+import pytest
+from api.attack_paths import sink as sink_module
+from api.attack_paths.database import (
+ GraphDatabaseQueryException,
+ NeptuneWriteRetryExhaustedException,
+)
+from api.attack_paths.retryable_session import RetryExhaustedError
+from api.attack_paths.sink import factory
+from api.attack_paths.sink.neo4j import DATABASE_NOT_FOUND_CODE, Neo4jSink
+from api.attack_paths.sink.neptune import (
+ NEPTUNE_WRITE_RETRY_DELAY_SECONDS,
+ NeptuneSink,
+ _is_retryable_write_error,
+ _NeptuneAuthToken,
+)
+
+
+@pytest.fixture(autouse=True)
+def reset_sink_state():
+ """Reset the module-level backend singletons around each test.
+
+ The cache lives in `api.attack_paths.sink.factory`, not on the package.
+ """
+ original_backend = factory._backend
+ original_secondary = dict(factory._secondary_backends)
+ factory._backend = None
+ factory._secondary_backends.clear()
+ yield
+ factory._backend = original_backend
+ factory._secondary_backends.clear()
+ factory._secondary_backends.update(original_secondary)
+
+
+class TestSinkFactory:
+ def test_default_resolves_to_neo4j(self, settings):
+ settings.ATTACK_PATHS_SINK_DATABASE = "neo4j"
+ assert factory._resolve_setting() == "neo4j"
+
+ def test_neptune_resolves_correctly(self, settings):
+ settings.ATTACK_PATHS_SINK_DATABASE = "neptune"
+ assert factory._resolve_setting() == "neptune"
+
+ def test_invalid_value_raises(self, settings):
+ settings.ATTACK_PATHS_SINK_DATABASE = "foo"
+ with pytest.raises(RuntimeError, match="ATTACK_PATHS_SINK_DATABASE"):
+ factory._resolve_setting()
+
+ @patch("api.attack_paths.sink.neo4j.neo4j.GraphDatabase.driver")
+ def test_init_builds_neo4j_backend_by_default(self, mock_driver, settings):
+ settings.ATTACK_PATHS_SINK_DATABASE = "neo4j"
+ settings.DATABASES = {
+ **settings.DATABASES,
+ "neo4j": {
+ "HOST": "localhost",
+ "PORT": "7687",
+ "USER": "neo4j",
+ "PASSWORD": "pw",
+ },
+ }
+ mock_driver.return_value = MagicMock()
+
+ backend = sink_module.init()
+
+ assert isinstance(backend, Neo4jSink)
+ mock_driver.assert_called_once()
+
+ @patch("api.attack_paths.sink.neptune.neptune_auth_provider")
+ @patch("api.attack_paths.sink.neptune.neo4j.GraphDatabase.driver")
+ def test_init_builds_neptune_backend(
+ self, mock_driver, mock_auth_provider, settings
+ ):
+ settings.ATTACK_PATHS_SINK_DATABASE = "neptune"
+ settings.DATABASES = {
+ **settings.DATABASES,
+ "neptune": {
+ "WRITER_ENDPOINT": "writer.example",
+ "READER_ENDPOINT": "reader.example",
+ "PORT": "8182",
+ "REGION": "eu-west-1",
+ },
+ }
+ mock_driver.return_value = MagicMock()
+ mock_auth_provider.return_value = lambda: None
+
+ backend = sink_module.init()
+
+ assert isinstance(backend, NeptuneSink)
+ # Writer + reader endpoints both trigger driver construction
+ assert mock_driver.call_count == 2
+ writer_uri = mock_driver.call_args_list[0][0][0]
+ reader_uri = mock_driver.call_args_list[1][0][0]
+ assert writer_uri == "bolt+s://writer.example:8182"
+ assert reader_uri == "bolt+s://reader.example:8182"
+
+ @patch("api.attack_paths.sink.neptune.neptune_auth_provider")
+ @patch("api.attack_paths.sink.neptune.neo4j.GraphDatabase.driver")
+ def test_neptune_reader_falls_back_to_writer(
+ self, mock_driver, mock_auth_provider, settings
+ ):
+ settings.ATTACK_PATHS_SINK_DATABASE = "neptune"
+ settings.DATABASES = {
+ **settings.DATABASES,
+ "neptune": {
+ "WRITER_ENDPOINT": "writer.example",
+ "READER_ENDPOINT": "",
+ "PORT": "8182",
+ "REGION": "eu-west-1",
+ },
+ }
+ mock_driver.return_value = MagicMock()
+ mock_auth_provider.return_value = lambda: None
+
+ sink_module.init()
+
+ # Only one driver call — reader aliases writer
+ assert mock_driver.call_count == 1
+
+
+def test_neo4j_sync_batch_size_defaults_to_1000():
+ assert Neo4jSink.sync_batch_size == 1000
+
+
+def test_neptune_sync_batch_size_defaults_to_500():
+ assert NeptuneSink.sync_batch_size == 500
+
+
+class TestGetBackendForScan:
+ """``get_backend_for_scan`` routes by the row's recorded sink backend."""
+
+ @patch("api.attack_paths.sink.neo4j.neo4j.GraphDatabase.driver")
+ def test_legacy_scan_in_neo4j_process_uses_active_backend(
+ self, mock_driver, settings
+ ):
+ settings.ATTACK_PATHS_SINK_DATABASE = "neo4j"
+ settings.DATABASES = {
+ **settings.DATABASES,
+ "neo4j": {
+ "HOST": "localhost",
+ "PORT": "7687",
+ "USER": "neo4j",
+ "PASSWORD": "pw",
+ },
+ }
+ mock_driver.return_value = MagicMock()
+
+ scan = MagicMock(sink_backend="neo4j")
+ backend = sink_module.get_backend_for_scan(scan)
+
+ assert backend is sink_module.get_backend()
+
+ def test_neptune_scan_on_neo4j_process_uses_neptune_secondary(self, settings):
+ settings.ATTACK_PATHS_SINK_DATABASE = "neo4j"
+ active_neo4j = MagicMock(name="neo4j-active")
+ factory._backend = active_neo4j
+
+ secondary_neptune = MagicMock(name="neptune-secondary")
+ with patch.object(factory, "_build_backend", return_value=secondary_neptune):
+ scan = MagicMock(sink_backend="neptune")
+ backend = factory.get_backend_for_scan(scan)
+
+ assert backend is secondary_neptune
+ assert backend is not active_neo4j
+
+
+def _session_ctx(session: MagicMock) -> MagicMock:
+ ctx = MagicMock()
+ ctx.__enter__ = MagicMock(return_value=session)
+ ctx.__exit__ = MagicMock(return_value=False)
+ return ctx
+
+
+def _count_result(key: str, count: int) -> MagicMock:
+ return MagicMock(single=MagicMock(return_value={key: count}))
+
+
+def _run_managed_write(session: MagicMock) -> MagicMock:
+ transaction = MagicMock()
+ session.execute_write.call_args.args[0](transaction)
+ return transaction
+
+
+def _managed_write_session(
+ results: list[MagicMock],
+) -> tuple[MagicMock, list[MagicMock]]:
+ session = MagicMock()
+ transactions: list[MagicMock] = []
+ result_iter = iter(results)
+
+ def execute_write(work):
+ transaction = MagicMock()
+ transaction.run.return_value = next(result_iter)
+ transactions.append(transaction)
+ return work(transaction)
+
+ session.execute_write.side_effect = execute_write
+ return session, transactions
+
+
+def _directed_drop_results(
+ outgoing_rels: int,
+ incoming_rels: int,
+ nodes: int,
+) -> list[MagicMock]:
+ return [
+ _count_result("deleted_rels_count", outgoing_rels),
+ _count_result("deleted_rels_count", 0),
+ _count_result("deleted_rels_count", incoming_rels),
+ _count_result("deleted_rels_count", 0),
+ _count_result("deleted_nodes_count", nodes),
+ _count_result("deleted_nodes_count", 0),
+ ]
+
+
+class TestNeo4jSinkSyncWrites:
+ def test_ensure_sync_indexes_runs_create_index_idempotent(self):
+ sink = Neo4jSink()
+ session = MagicMock()
+ with patch.object(sink, "get_session", return_value=_session_ctx(session)):
+ sink.ensure_sync_indexes("db-tenant-x")
+
+ transaction = _run_managed_write(session)
+ query = transaction.run.call_args.args[0]
+ assert "CREATE INDEX" in query
+ assert "IF NOT EXISTS" in query
+ assert "`_ProviderResource`" in query
+ assert "`_provider_element_id`" in query
+ transaction.run.return_value.consume.assert_called_once_with()
+
+ def test_write_nodes_skips_empty_batch(self):
+ sink = Neo4jSink()
+ with patch.object(sink, "get_session") as get_session:
+ sink.write_nodes("db-tenant-x", "`AWSUser`", [])
+ get_session.assert_not_called()
+
+ def test_write_nodes_merges_on_provider_resource_label(self):
+ sink = Neo4jSink()
+ session = MagicMock()
+ with patch.object(sink, "get_session", return_value=_session_ctx(session)):
+ sink.write_nodes(
+ "db-tenant-x",
+ "`AWSUser`:`_ProviderResource`",
+ [{"provider_element_id": "p:e", "props": {"k": "v"}}],
+ )
+
+ transaction = _run_managed_write(session)
+ query, params = transaction.run.call_args.args
+ assert "MERGE (n:`_ProviderResource`" in query
+ assert "`_provider_element_id`: row.provider_element_id" in query
+ assert "SET n:`AWSUser`:`_ProviderResource`" in query
+ assert params == {"rows": [{"provider_element_id": "p:e", "props": {"k": "v"}}]}
+ transaction.run.return_value.consume.assert_called_once_with()
+
+ def test_write_relationships_scopes_endpoints_by_provider_label(self):
+ sink = Neo4jSink()
+ session = MagicMock()
+ provider_id = "00000000-0000-0000-0000-000000000abc"
+ with patch.object(sink, "get_session", return_value=_session_ctx(session)):
+ sink.write_relationships(
+ "db-tenant-x",
+ "RESOURCE",
+ provider_id,
+ [
+ {
+ "start_element_id": "s",
+ "end_element_id": "e",
+ "provider_element_id": "pe",
+ "props": {},
+ }
+ ],
+ )
+
+ transaction = _run_managed_write(session)
+ query = transaction.run.call_args.args[0]
+ assert ":`_Provider_00000000000000000000000000000abc`" in query
+ assert ":RESOURCE" in query.replace("`", "")
+ assert "MERGE (s)-[r:`RESOURCE`" in query
+ transaction.run.return_value.consume.assert_called_once_with()
+
+
+class TestNeptuneSinkSyncWrites:
+ def test_ensure_sync_indexes_is_noop(self):
+ sink = NeptuneSink()
+ with patch.object(sink, "get_session") as get_session:
+ sink.ensure_sync_indexes("ignored")
+ get_session.assert_not_called()
+
+ def test_write_nodes_merges_on_neptune_id_with_provider_resource_label(self):
+ sink = NeptuneSink()
+ session = MagicMock()
+ with patch.object(sink, "get_session", return_value=_session_ctx(session)):
+ sink.write_nodes(
+ "ignored",
+ "`AWSUser`",
+ [{"provider_element_id": "p:e", "props": {"k": "v"}}],
+ )
+
+ transaction = _run_managed_write(session)
+ query = transaction.run.call_args.args[0]
+ # Neptune assigns a default `vertex` label to any unlabeled node,
+ # so the MERGE must pin a real label at creation time.
+ assert "MERGE (n:`_ProviderResource` {`~id`: row.provider_element_id})" in query
+ assert "SET n:`AWSUser`" in query
+ assert "SET n.`_provider_element_id` = row.provider_element_id" in query
+ transaction.run.return_value.consume.assert_called_once_with()
+
+ def test_write_relationships_matches_endpoints_by_id(self):
+ sink = NeptuneSink()
+ session = MagicMock()
+ with patch.object(sink, "get_session", return_value=_session_ctx(session)):
+ sink.write_relationships(
+ "ignored",
+ "RESOURCE",
+ "provider-1",
+ [
+ {
+ "start_element_id": "s",
+ "end_element_id": "e",
+ "provider_element_id": "pe",
+ "props": {},
+ }
+ ],
+ )
+
+ transaction = _run_managed_write(session)
+ query = transaction.run.call_args.args[0]
+ assert "MATCH (s) WHERE id(s) = row.start_element_id" in query
+ assert "MATCH (e) WHERE id(e) = row.end_element_id" in query
+ assert "MERGE (s)-[r:`RESOURCE`" in query
+ transaction.run.return_value.consume.assert_called_once_with()
+
+
+class TestNeptuneRetryPolicy:
+ @pytest.mark.parametrize(
+ "message",
+ [
+ "Unexpected server exception 'Operation failed due to conflicting "
+ "concurrent operations (please retry), 0 transactions are currently "
+ "rolling back.'",
+ "Unexpected server exception 'Operation terminated (deadline exceeded)'",
+ ],
+ )
+ def test_observed_transient_write_errors_are_retryable(self, message):
+ error = MagicMock(spec=neo4j.exceptions.Neo4jError)
+ error.message = message
+
+ assert _is_retryable_write_error(error) is True
+
+ def test_unrelated_database_error_is_not_retryable(self):
+ error = MagicMock(spec=neo4j.exceptions.Neo4jError)
+ error.message = (
+ "Unexpected server exception 'Operation terminated (out of memory)'"
+ )
+
+ assert _is_retryable_write_error(error) is False
+
+ def test_non_neo4j_error_is_not_retryable(self):
+ error = RuntimeError(
+ "Operation failed due to conflicting concurrent operations"
+ )
+
+ assert _is_retryable_write_error(error) is False
+
+ @patch("api.attack_paths.sink.neptune.RetryableSession")
+ def test_writer_session_enables_neptune_retry_policy(self, retryable_session):
+ sink = NeptuneSink()
+ driver = MagicMock()
+ with patch.object(sink, "_get_writer", return_value=driver):
+ with sink.get_session():
+ pass
+
+ kwargs = retryable_session.call_args.kwargs
+ assert kwargs["retry_if"] is _is_retryable_write_error
+ assert (
+ kwargs["initial_retry_delay_seconds"] == NEPTUNE_WRITE_RETRY_DELAY_SECONDS
+ )
+ assert kwargs["retry_context"] == "Neptune write"
+
+ @patch("api.attack_paths.sink.neptune.RetryableSession")
+ def test_reader_session_does_not_enable_write_retry_policy(self, retryable_session):
+ sink = NeptuneSink()
+ driver = MagicMock()
+ with patch.object(sink, "_get_reader", return_value=driver):
+ with sink.get_session(default_access_mode=neo4j.READ_ACCESS):
+ pass
+
+ kwargs = retryable_session.call_args.kwargs
+ assert kwargs["retry_if"] is None
+ assert kwargs["initial_retry_delay_seconds"] == 0
+ assert kwargs["retry_context"] is None
+
+ def test_writer_retry_exhaustion_preserves_neptune_error_details(self):
+ message = (
+ "Unexpected server exception 'Operation failed due to conflicting "
+ "concurrent operations (please retry), 0 transactions are currently "
+ "rolling back.'"
+ )
+ error = neo4j.exceptions.Neo4jError._hydrate_neo4j(
+ code="BoltProtocol.unexpectedException",
+ message=message,
+ )
+ retry_error = RetryExhaustedError(
+ retry_context="Neptune write",
+ method_name="execute_write",
+ attempts=4,
+ elapsed_seconds=27.1234,
+ last_error=error,
+ )
+ sink = NeptuneSink()
+ driver = MagicMock()
+ retryable_session = MagicMock()
+ retryable_session.execute_write.side_effect = retry_error
+
+ with (
+ patch.object(sink, "_get_writer", return_value=driver),
+ patch(
+ "api.attack_paths.sink.neptune.RetryableSession",
+ return_value=retryable_session,
+ ),
+ pytest.raises(NeptuneWriteRetryExhaustedException) as exc_info,
+ ):
+ with sink.get_session() as session:
+ session.execute_write(MagicMock())
+
+ assert exc_info.value.code == "BoltProtocol.unexpectedException"
+ assert str(exc_info.value) == (
+ "BoltProtocol.unexpectedException: Neptune write execute_write failed "
+ "after 4 attempts over 27.123s. Last error: "
+ f"{message}"
+ )
+ assert exc_info.value.__cause__ is error
+
+
+class TestNeptuneSinkDropSubgraph:
+ def test_drop_subgraph_deletes_directed_rels_before_nodes_in_bounded_batches(self):
+ sink = NeptuneSink()
+ session, transactions = _managed_write_session(
+ _directed_drop_results(
+ outgoing_rels=50,
+ incoming_rels=30,
+ nodes=10,
+ )
+ )
+
+ with patch.object(sink, "get_session", return_value=_session_ctx(session)):
+ deleted = sink.drop_subgraph("ignored", "provider-1")
+
+ assert deleted == 10
+ assert session.execute_write.call_count == 6
+ queries = [transaction.run.call_args.args[0] for transaction in transactions]
+
+ assert ")-[r]->()" in queries[0]
+ assert ")<-[r]-()" in queries[2]
+ assert "DELETE n" in queries[4]
+ assert all("DETACH DELETE" not in query for query in queries)
+ assert all("DISTINCT r" not in query for query in queries)
+
+ first_node = next(i for i, q in enumerate(queries) if "DELETE n" in q)
+ last_rel = max(i for i, q in enumerate(queries) if "DELETE r" in q)
+ assert last_rel < first_node
+
+
+class TestNeo4jSinkDropSubgraph:
+ """Neo4j drop deletes relationships then nodes in batches (no ``DETACH DELETE``)."""
+
+ def test_drop_subgraph_deletes_directed_rels_before_nodes_in_bounded_batches(self):
+ sink = Neo4jSink()
+ session, transactions = _managed_write_session(
+ _directed_drop_results(
+ outgoing_rels=50,
+ incoming_rels=30,
+ nodes=10,
+ )
+ )
+
+ provider_id = "00000000-0000-0000-0000-000000000abc"
+ with patch.object(sink, "get_session", return_value=_session_ctx(session)):
+ deleted = sink.drop_subgraph("db-tenant-x", provider_id)
+
+ # Only phase-2 node counts contribute to the return value.
+ assert deleted == 10
+ assert session.execute_write.call_count == 6
+
+ queries = [transaction.run.call_args.args[0] for transaction in transactions]
+ # Regression guard: the memory blow-up was caused by DETACH DELETE.
+ assert all("DETACH DELETE" not in query for query in queries)
+ assert all("DISTINCT r" not in query for query in queries)
+
+ first_query = queries[0]
+ assert "DELETE r" in first_query
+ assert ")-[r]->()" in first_query
+ assert ":`_Provider_00000000000000000000000000000abc`" in first_query
+
+ assert ")<-[r]-()" in queries[2]
+ assert "DELETE n" in queries[4]
+
+ # Relationships must be fully drained before nodes are deleted.
+ first_node = next(i for i, q in enumerate(queries) if "DELETE n" in q)
+ last_rel = max(i for i, q in enumerate(queries) if "DELETE r" in q)
+ assert last_rel < first_node
+
+ def test_drop_subgraph_returns_zero_when_database_does_not_exist(self):
+ sink = Neo4jSink()
+ session = MagicMock()
+ session.execute_write.side_effect = GraphDatabaseQueryException(
+ message="db missing", code=DATABASE_NOT_FOUND_CODE
+ )
+
+ with patch.object(sink, "get_session", return_value=_session_ctx(session)):
+ deleted = sink.drop_subgraph("db-tenant-missing", "provider-1")
+
+ assert deleted == 0
+
+
+class TestSinkHasProviderData:
+ """``has_provider_data`` is the read-path probe used by API views."""
+
+ def test_neo4j_returns_true_when_provider_node_exists(self):
+ sink = Neo4jSink()
+ session = MagicMock()
+ session.run.return_value.single.return_value = MagicMock()
+ with patch.object(sink, "get_session", return_value=_session_ctx(session)):
+ present = sink.has_provider_data(
+ "db-tenant-x", "00000000-0000-0000-0000-000000000abc"
+ )
+
+ assert present is True
+ query = session.run.call_args.args[0]
+ assert ":`_Provider_00000000000000000000000000000abc`" in query
+
+ def test_neo4j_returns_false_when_database_does_not_exist(self):
+ sink = Neo4jSink()
+ session = MagicMock()
+ session.run.side_effect = GraphDatabaseQueryException(
+ message="db missing", code=DATABASE_NOT_FOUND_CODE
+ )
+
+ with patch.object(sink, "get_session", return_value=_session_ctx(session)):
+ present = sink.has_provider_data("db-tenant-missing", "provider-1")
+
+ assert present is False
+
+ def test_neptune_returns_true_when_provider_node_exists(self):
+ sink = NeptuneSink()
+ session = MagicMock()
+ session.run.return_value.single.return_value = MagicMock()
+ with patch.object(sink, "get_session", return_value=_session_ctx(session)):
+ present = sink.has_provider_data("ignored", "provider-1")
+
+ assert present is True
+
+
+class TestGetBackendForScanCutover:
+ """``get_backend_for_scan`` keeps old-sink scans queryable after cutover."""
+
+ def test_legacy_scan_on_neptune_process_uses_neo4j_secondary(self, settings):
+ settings.ATTACK_PATHS_SINK_DATABASE = "neptune"
+ active_neptune = MagicMock(name="neptune-active")
+ factory._backend = active_neptune
+
+ secondary_neo4j = MagicMock(name="neo4j-secondary")
+ with patch.object(factory, "_build_backend", return_value=secondary_neo4j):
+ scan = MagicMock(sink_backend="neo4j")
+ backend = factory.get_backend_for_scan(scan)
+
+ assert backend is secondary_neo4j
+ assert backend is not active_neptune
+
+
+class TestSinkVerifyConnectivity:
+ """The readiness probe calls ``verify_connectivity`` through the shim.
+
+ Neo4j checks its single driver; Neptune checks the reader (the API read
+ path), which on single-endpoint clusters aliases the writer.
+ """
+
+ @patch("api.attack_paths.sink.neo4j.neo4j.GraphDatabase.driver")
+ def test_neo4j_verifies_its_driver(self, mock_driver, settings):
+ settings.DATABASES = {
+ **settings.DATABASES,
+ "neo4j": {
+ "HOST": "localhost",
+ "PORT": "7687",
+ "USER": "neo4j",
+ "PASSWORD": "pw",
+ },
+ }
+ driver = MagicMock()
+ mock_driver.return_value = driver
+
+ sink = Neo4jSink()
+ sink.init()
+ driver.verify_connectivity.reset_mock() # ignore the eager init check
+ sink.verify_connectivity()
+
+ driver.verify_connectivity.assert_called_once_with()
+
+ @patch("api.attack_paths.sink.neptune.neptune_auth_provider")
+ @patch("api.attack_paths.sink.neptune.neo4j.GraphDatabase.driver")
+ def test_neptune_verifies_reader_not_writer(
+ self, mock_driver, mock_auth_provider, settings
+ ):
+ settings.DATABASES = {
+ **settings.DATABASES,
+ "neptune": {
+ "WRITER_ENDPOINT": "writer.example",
+ "READER_ENDPOINT": "reader.example",
+ "PORT": "8182",
+ "REGION": "eu-west-1",
+ },
+ }
+ writer, reader = MagicMock(name="writer"), MagicMock(name="reader")
+ mock_driver.side_effect = [writer, reader]
+ mock_auth_provider.return_value = lambda: None
+
+ sink = NeptuneSink()
+ sink.init()
+ writer.verify_connectivity.reset_mock()
+ reader.verify_connectivity.reset_mock()
+
+ sink.verify_connectivity()
+
+ reader.verify_connectivity.assert_called_once_with()
+ writer.verify_connectivity.assert_not_called()
+
+
+class TestSinkInitToleratesUnreachableSink:
+ """Init must not crash the process when the sink is down at boot.
+
+ Same degradation model as Postgres: the driver is retained and
+ reconnects lazily; /health/ready surfaces the outage until it recovers.
+ """
+
+ @patch("api.attack_paths.sink.neo4j.neo4j.GraphDatabase.driver")
+ def test_neo4j_init_continues_when_verify_fails(self, mock_driver, settings):
+ settings.DATABASES = {
+ **settings.DATABASES,
+ "neo4j": {
+ "HOST": "localhost",
+ "PORT": "7687",
+ "USER": "neo4j",
+ "PASSWORD": "pw",
+ },
+ }
+ driver = MagicMock()
+ driver.verify_connectivity.side_effect = RuntimeError("unreachable")
+ mock_driver.return_value = driver
+
+ sink = Neo4jSink()
+ # Must not raise.
+ assert sink.init() is driver
+ assert sink._driver is driver
+
+ @patch("api.attack_paths.sink.neptune.neptune_auth_provider")
+ @patch("api.attack_paths.sink.neptune.neo4j.GraphDatabase.driver")
+ def test_neptune_init_continues_when_verify_fails(
+ self, mock_driver, mock_auth_provider, settings
+ ):
+ settings.DATABASES = {
+ **settings.DATABASES,
+ "neptune": {
+ "WRITER_ENDPOINT": "writer.example",
+ "READER_ENDPOINT": "reader.example",
+ "PORT": "8182",
+ "REGION": "eu-west-1",
+ },
+ }
+ driver = MagicMock()
+ driver.verify_connectivity.side_effect = RuntimeError("unreachable")
+ mock_driver.return_value = driver
+ mock_auth_provider.return_value = lambda: None
+
+ sink = NeptuneSink()
+ # Must not raise; both drivers retained.
+ sink.init()
+ assert sink._writer is not None
+ assert sink._reader is not None
+
+
+class TestNeptuneAdminNoOps:
+ """Neptune is single-database; admin DDL has no work to do."""
+
+ @pytest.mark.parametrize("method", ["create_database", "drop_database"])
+ def test_admin_ops_return_none_without_touching_a_session(self, method):
+ sink = NeptuneSink()
+ with patch.object(sink, "get_session") as get_session:
+ assert getattr(sink, method)("ignored") is None
+ get_session.assert_not_called()
+
+
+class TestNeptuneAuthToken:
+ """SigV4 signing for the Neptune Bolt endpoint."""
+
+ @patch("api.attack_paths.sink.neptune.SigV4Auth")
+ @patch("api.attack_paths.sink.neptune.BotoSession")
+ def test_host_header_includes_non_default_port(self, mock_boto, mock_sigv4):
+ # Neptune runs on 8182; the SigV4 canonical Host must keep the port or
+ # the signature is rejected.
+ credentials = MagicMock()
+ credentials.get_frozen_credentials.return_value = MagicMock()
+ mock_boto.return_value.get_credentials.return_value = credentials
+
+ token = _NeptuneAuthToken("eu-west-1", "https://writer.example:8182")
+
+ auth_obj = json.loads(token.credentials)
+ assert auth_obj["Host"] == "writer.example:8182"
diff --git a/api/src/backend/api/tests/test_utils.py b/api/src/backend/api/tests/test_utils.py
index 935a15c4f3..4b5e8e1694 100644
--- a/api/src/backend/api/tests/test_utils.py
+++ b/api/src/backend/api/tests/test_utils.py
@@ -171,6 +171,53 @@ class TestInitializeProwlerProvider:
key="value", mutelist_content={"key": "value"}
)
+ @patch("api.utils.return_prowler_provider")
+ def test_initialize_oraclecloud_provider_removes_region_string(
+ self, mock_return_prowler_provider
+ ):
+ provider = MagicMock()
+ provider.provider = Provider.ProviderChoices.ORACLECLOUD.value
+ provider.secret.secret = {
+ "user": "ocid1.user.oc1..fake",
+ "fingerprint": "00:11:22:33:44:55:66:77",
+ "key_content": "fake-base64-key-content",
+ "tenancy": "ocid1.tenancy.oc1..fake",
+ "region": "us-ashburn-1",
+ }
+ mock_return_prowler_provider.return_value = MagicMock()
+
+ initialize_prowler_provider(provider)
+
+ mock_return_prowler_provider.return_value.assert_called_once_with(
+ user="ocid1.user.oc1..fake",
+ fingerprint="00:11:22:33:44:55:66:77",
+ key_content="fake-base64-key-content",
+ tenancy="ocid1.tenancy.oc1..fake",
+ )
+
+ @patch("api.utils.return_prowler_provider")
+ def test_initialize_oraclecloud_provider_without_region_omits_scan_filter(
+ self, mock_return_prowler_provider
+ ):
+ provider = MagicMock()
+ provider.provider = Provider.ProviderChoices.ORACLECLOUD.value
+ provider.secret.secret = {
+ "user": "ocid1.user.oc1..fake",
+ "fingerprint": "00:11:22:33:44:55:66:77",
+ "key_content": "fake-base64-key-content",
+ "tenancy": "ocid1.tenancy.oc1..fake",
+ }
+ mock_return_prowler_provider.return_value = MagicMock()
+
+ initialize_prowler_provider(provider)
+
+ mock_return_prowler_provider.return_value.assert_called_once_with(
+ user="ocid1.user.oc1..fake",
+ fingerprint="00:11:22:33:44:55:66:77",
+ key_content="fake-base64-key-content",
+ tenancy="ocid1.tenancy.oc1..fake",
+ )
+
class TestProwlerProviderConnectionTest:
@patch("api.utils.return_prowler_provider")
@@ -185,13 +232,44 @@ class TestProwlerProviderConnectionTest:
key="value", provider_id="1234567890", raise_on_exception=False
)
+ @patch("api.utils.return_prowler_provider")
+ def test_oraclecloud_connection_test_uses_direct_credentials_without_region(
+ self, mock_return_prowler_provider
+ ):
+ provider = MagicMock()
+ provider.uid = "ocid1.tenancy.oc1..aaaaaaaexample"
+ provider.provider = Provider.ProviderChoices.ORACLECLOUD.value
+ provider.secret.secret = {
+ "user": "ocid1.user.oc1..aaaaaaaexample",
+ "fingerprint": "00:11:22:33:44:55:66:77",
+ "key_content": "fake-base64-key-content",
+ "tenancy": "ocid1.tenancy.oc1..aaaaaaaexample",
+ }
+ mock_return_prowler_provider.return_value = MagicMock()
+
+ prowler_provider_connection_test(provider)
+
+ mock_return_prowler_provider.return_value.test_connection.assert_called_once_with(
+ user="ocid1.user.oc1..aaaaaaaexample",
+ fingerprint="00:11:22:33:44:55:66:77",
+ key_content="fake-base64-key-content",
+ tenancy="ocid1.tenancy.oc1..aaaaaaaexample",
+ region=getattr(
+ OraclecloudProvider,
+ "_bootstrap_region",
+ OraclecloudProvider._home_region,
+ ),
+ provider_id="ocid1.tenancy.oc1..aaaaaaaexample",
+ raise_on_exception=False,
+ )
+
@pytest.mark.django_db
@patch("api.utils.return_prowler_provider")
def test_prowler_provider_connection_test_without_secret(
- self, mock_return_prowler_provider, providers_fixture
+ self, mock_return_prowler_provider, aws_provider
):
mock_return_prowler_provider.return_value = MagicMock()
- connection = prowler_provider_connection_test(providers_fixture[0])
+ connection = prowler_provider_connection_test(aws_provider)
assert connection.is_connected is False
assert isinstance(connection.error, Provider.secret.RelatedObjectDoesNotExist)
@@ -356,7 +434,7 @@ class TestGetProwlerProviderKwargs:
expected_result = {**secret_dict, **expected_extra_kwargs}
assert result == expected_result
- def test_get_prowler_provider_kwargs_oraclecloud_converts_region_string_to_set(
+ def test_get_prowler_provider_kwargs_oraclecloud_removes_region(
self,
):
secret_dict = {
@@ -377,8 +455,13 @@ class TestGetProwlerProviderKwargs:
result = get_prowler_provider_kwargs(provider)
- expected_result = {**secret_dict, "region": {"us-ashburn-1"}}
- assert result == expected_result
+ assert result == {
+ "user": "ocid1.user.oc1..fake",
+ "fingerprint": "00:11:22:33:44:55:66:77",
+ "key_content": "-----BEGIN PRIVATE KEY-----\nfake\n-----END PRIVATE KEY-----",
+ "tenancy": "ocid1.tenancy.oc1..fake",
+ "pass_phrase": "fake-passphrase",
+ }
def test_get_prowler_provider_kwargs_with_mutelist(self):
provider_uid = "provider_uid"
@@ -856,7 +939,7 @@ class TestProwlerIntegrationConnectionTest:
integration.credentials = {
"user_mail": "test@example.com",
"api_token": "test_api_token",
- "domain": "example.atlassian.net",
+ "domain": "example",
}
integration.configuration = {}
@@ -884,7 +967,7 @@ class TestProwlerIntegrationConnectionTest:
mock_jira_class.test_connection.assert_called_once_with(
user_mail="test@example.com",
api_token="test_api_token",
- domain="example.atlassian.net",
+ domain="example",
raise_on_exception=False,
)
@@ -917,7 +1000,7 @@ class TestProwlerIntegrationConnectionTest:
integration.credentials = {
"user_mail": "invalid@example.com",
"api_token": "invalid_token",
- "domain": "invalid.atlassian.net",
+ "domain": "invalid",
}
integration.configuration = {}
@@ -942,7 +1025,7 @@ class TestProwlerIntegrationConnectionTest:
mock_jira_class.test_connection.assert_called_once_with(
user_mail="invalid@example.com",
api_token="invalid_token",
- domain="invalid.atlassian.net",
+ domain="invalid",
raise_on_exception=False,
)
@@ -970,7 +1053,7 @@ class TestProwlerIntegrationConnectionTest:
integration.credentials = {
"user_mail": "test@example.com",
"api_token": "test_api_token",
- "domain": "example.atlassian.net",
+ "domain": "example",
}
integration.configuration = {
"issue_types": {"OLD_PROJ": ["Task"]}, # Existing configuration
diff --git a/api/src/backend/api/tests/test_validators.py b/api/src/backend/api/tests/test_validators.py
new file mode 100644
index 0000000000..a431a659c7
--- /dev/null
+++ b/api/src/backend/api/tests/test_validators.py
@@ -0,0 +1,246 @@
+import socket
+
+import pytest
+from api.validators import (
+ resolve_lighthouse_openai_compatible_host,
+ validate_lighthouse_openai_compatible_base_url,
+)
+from django.core.exceptions import ValidationError
+from django.test import override_settings
+
+
+def test_lighthouse_base_url_rejects_http_scheme():
+ with pytest.raises(ValidationError, match="HTTPS"):
+ validate_lighthouse_openai_compatible_base_url(
+ "http://openrouter.ai/api/v1",
+ resolve_dns=False,
+ )
+
+
+@pytest.mark.parametrize(
+ "base_url",
+ [
+ "https://openrouter.ai:0/api/v1",
+ "https://openrouter.ai:-1/api/v1",
+ "https://openrouter.ai:65536/api/v1",
+ "https://openrouter.ai:invalid/api/v1",
+ ],
+)
+def test_lighthouse_base_url_rejects_invalid_port(base_url):
+ with pytest.raises(ValidationError, match="port is invalid"):
+ validate_lighthouse_openai_compatible_base_url(
+ base_url,
+ resolve_dns=False,
+ )
+
+
+@pytest.mark.parametrize("port", [1, 65535])
+def test_lighthouse_base_url_accepts_valid_port_boundaries(port):
+ assert (
+ validate_lighthouse_openai_compatible_base_url(
+ f"https://openrouter.ai:{port}/api/v1",
+ resolve_dns=False,
+ )
+ is None
+ )
+
+
+def test_lighthouse_base_url_rejects_localhost():
+ with pytest.raises(ValidationError, match="external public endpoint"):
+ validate_lighthouse_openai_compatible_base_url(
+ "https://localhost/v1",
+ resolve_dns=False,
+ )
+
+
+@pytest.mark.parametrize("ip_address", ["10.0.0.1", "172.16.0.1", "192.168.1.1"])
+def test_lighthouse_base_url_rejects_private_ip_literal(ip_address):
+ with pytest.raises(ValidationError, match="external public endpoint"):
+ validate_lighthouse_openai_compatible_base_url(
+ f"https://{ip_address}/v1",
+ resolve_dns=False,
+ )
+
+
+def test_lighthouse_base_url_rejects_metadata_ip_literal():
+ with pytest.raises(ValidationError, match="external public endpoint"):
+ validate_lighthouse_openai_compatible_base_url(
+ "https://169.254.169.254/latest/meta-data",
+ resolve_dns=False,
+ )
+
+
+@pytest.mark.parametrize(
+ "base_url",
+ [
+ "https://[::ffff:169.254.169.254]/v1",
+ "https://[64:ff9b::a9fe:a9fe]/v1",
+ "https://[2002:a9fe:a9fe::]/v1",
+ ],
+)
+def test_lighthouse_base_url_rejects_embedded_non_global_ip(base_url):
+ with pytest.raises(ValidationError, match="external public endpoint"):
+ validate_lighthouse_openai_compatible_base_url(
+ base_url,
+ resolve_dns=False,
+ )
+
+
+@pytest.mark.parametrize(
+ "base_url",
+ [
+ "https://[::ffff:93.184.216.34]/v1",
+ "https://[64:ff9b::5db8:d822]/v1",
+ "https://[2002:5db8:d822::]/v1",
+ ],
+)
+def test_lighthouse_base_url_accepts_embedded_public_ip(base_url):
+ assert (
+ validate_lighthouse_openai_compatible_base_url(
+ base_url,
+ resolve_dns=False,
+ )
+ is None
+ )
+
+
+def test_lighthouse_base_url_accepts_hostname_without_dns_resolution():
+ assert (
+ validate_lighthouse_openai_compatible_base_url(
+ "https://openrouter.ai/api/v1",
+ resolve_dns=False,
+ )
+ is None
+ )
+
+
+def test_lighthouse_base_url_rejects_post_dns_internal_address(monkeypatch):
+ def resolve_to_metadata(*_args, **_kwargs):
+ return [
+ (
+ socket.AF_INET,
+ socket.SOCK_STREAM,
+ 6,
+ "",
+ ("169.254.169.254", 443),
+ )
+ ]
+
+ monkeypatch.setattr("api.validators.socket.getaddrinfo", resolve_to_metadata)
+
+ with pytest.raises(ValidationError, match="external public endpoint"):
+ validate_lighthouse_openai_compatible_base_url(
+ "https://metadata.example.test/v1"
+ )
+
+
+def test_lighthouse_base_url_accepts_public_resolved_address(monkeypatch):
+ def resolve_to_public(*_args, **_kwargs):
+ return [
+ (
+ socket.AF_INET,
+ socket.SOCK_STREAM,
+ 6,
+ "",
+ ("93.184.216.34", 443),
+ )
+ ]
+
+ monkeypatch.setattr("api.validators.socket.getaddrinfo", resolve_to_public)
+
+ assert (
+ validate_lighthouse_openai_compatible_base_url("https://openrouter.ai/api/v1")
+ is None
+ )
+
+
+@override_settings(
+ LIGHTHOUSE_AI_OPENAI_COMPATIBLE_ALLOWED_HOSTS=["custom-openai.internal"]
+)
+def test_lighthouse_base_url_accepts_allowlisted_host_without_resolution(monkeypatch):
+ def fail_resolution(*_args, **_kwargs):
+ raise AssertionError("allowlisted hosts must not be resolved")
+
+ monkeypatch.setattr("api.validators.socket.getaddrinfo", fail_resolution)
+
+ assert (
+ validate_lighthouse_openai_compatible_base_url(
+ "https://custom-openai.internal/v1"
+ )
+ is None
+ )
+
+
+@override_settings(
+ LIGHTHOUSE_AI_OPENAI_COMPATIBLE_ALLOWED_HOSTS=["custom-openai.internal"]
+)
+def test_lighthouse_resolve_returns_allowlisted_hostname_unpinned():
+ assert resolve_lighthouse_openai_compatible_host(
+ "Custom-OpenAI.internal.", 443
+ ) == ("custom-openai.internal",)
+
+
+@override_settings(LIGHTHOUSE_AI_OPENAI_COMPATIBLE_ALLOWED_HOSTS=["localhost"])
+def test_lighthouse_base_url_accepts_allowlisted_blocked_host():
+ assert (
+ validate_lighthouse_openai_compatible_base_url(
+ "https://localhost/v1",
+ resolve_dns=False,
+ )
+ is None
+ )
+
+
+@override_settings(LIGHTHOUSE_AI_OPENAI_COMPATIBLE_ALLOWED_HOSTS=["10.0.0.1"])
+def test_lighthouse_base_url_accepts_allowlisted_private_ip_literal():
+ assert (
+ validate_lighthouse_openai_compatible_base_url(
+ "https://10.0.0.1/v1",
+ resolve_dns=False,
+ )
+ is None
+ )
+
+
+@override_settings(
+ LIGHTHOUSE_AI_OPENAI_COMPATIBLE_ALLOWED_HOSTS=[" Custom-OpenAI.Internal. "]
+)
+def test_lighthouse_allowlist_entries_are_normalized():
+ assert (
+ validate_lighthouse_openai_compatible_base_url(
+ "https://custom-openai.internal/v1",
+ resolve_dns=False,
+ )
+ is None
+ )
+
+
+@override_settings(
+ LIGHTHOUSE_AI_OPENAI_COMPATIBLE_ALLOWED_HOSTS=["custom-openai.internal"]
+)
+def test_lighthouse_base_url_rejects_host_not_in_allowlist():
+ with pytest.raises(ValidationError, match="external public endpoint"):
+ validate_lighthouse_openai_compatible_base_url(
+ "https://localhost/v1",
+ resolve_dns=False,
+ )
+
+
+@override_settings(LIGHTHOUSE_AI_OPENAI_COMPATIBLE_ALLOWED_HOSTS=[""])
+def test_lighthouse_allowlist_ignores_empty_entries():
+ with pytest.raises(ValidationError, match="external public endpoint"):
+ validate_lighthouse_openai_compatible_base_url(
+ "https://localhost/v1",
+ resolve_dns=False,
+ )
+
+
+@override_settings(
+ LIGHTHOUSE_AI_OPENAI_COMPATIBLE_ALLOWED_HOSTS=["custom-openai.internal"]
+)
+def test_lighthouse_base_url_allowlisted_host_still_requires_https():
+ with pytest.raises(ValidationError, match="HTTPS"):
+ validate_lighthouse_openai_compatible_base_url(
+ "http://custom-openai.internal/v1",
+ resolve_dns=False,
+ )
diff --git a/api/src/backend/api/tests/test_views.py b/api/src/backend/api/tests/test_views.py
index 4e8c9336b6..96d366e847 100644
--- a/api/src/backend/api/tests/test_views.py
+++ b/api/src/backend/api/tests/test_views.py
@@ -57,9 +57,14 @@ from api.models import (
UserRoleRelationship,
)
from api.rls import Tenant
-from api.v1.serializers import TokenSerializer
-from api.v1.views import ComplianceOverviewViewSet, TenantFinishACSView
+from api.uuid_utils import datetime_to_uuid7
+from api.v1.views import (
+ ComplianceOverviewViewSet,
+ CustomSAMLLoginView,
+ TenantFinishACSView,
+)
from botocore.exceptions import ClientError, NoCredentialsError
+from celery import states
from conftest import (
API_JSON_CONTENT_TYPE,
TEST_PASSWORD,
@@ -243,6 +248,63 @@ class TestUserViewSet:
create_test_user.refresh_from_db()
assert create_test_user.company_name == new_company_name
+ def test_users_partial_update_same_tenant_other_user_password_denied(
+ self, authenticated_client_no_permissions_rbac, tenants_fixture
+ ):
+ original_password = "OriginalPassword123@"
+ new_password = "UpdatedPassword123@"
+ target_user = User.objects.create_user(
+ password=original_password,
+ email="target-password-update@example.com",
+ )
+ Membership.objects.create(user=target_user, tenant=tenants_fixture[0])
+ payload = {
+ "data": {
+ "type": "users",
+ "id": str(target_user.id),
+ "attributes": {"password": new_password},
+ },
+ }
+
+ response = authenticated_client_no_permissions_rbac.patch(
+ reverse("user-detail", kwargs={"pk": target_user.id}),
+ data=payload,
+ content_type="application/vnd.api+json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ target_user.refresh_from_db()
+ assert target_user.check_password(original_password)
+ assert not target_user.check_password(new_password)
+
+ def test_users_partial_update_same_tenant_other_user_email_denied(
+ self, authenticated_client_no_permissions_rbac, tenants_fixture
+ ):
+ original_email = "target-email-update@example.com"
+ new_email = "updated-target-email@example.com"
+ target_user = User.objects.create_user(
+ password="OriginalPassword123@",
+ email=original_email,
+ )
+ Membership.objects.create(user=target_user, tenant=tenants_fixture[0])
+ payload = {
+ "data": {
+ "type": "users",
+ "id": str(target_user.id),
+ "attributes": {"email": new_email},
+ },
+ }
+
+ response = authenticated_client_no_permissions_rbac.patch(
+ reverse("user-detail", kwargs={"pk": target_user.id}),
+ data=payload,
+ content_type="application/vnd.api+json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ target_user.refresh_from_db()
+ assert target_user.email == original_email
+
def test_users_partial_update_invalid_content_type(
self, authenticated_client, create_test_user
):
@@ -788,21 +850,15 @@ class TestTenantViewSet:
assert response.json()["data"] == []
def test_tenants_list_memberships_as_member(
- self, authenticated_client, tenants_fixture, extra_users
+ self, authenticated_client_for_tenant_factory, tenants_fixture, extra_users
):
_, tenant2, _ = tenants_fixture
_, user3_membership = extra_users
user3, membership3 = user3_membership
- token_response = authenticated_client.post(
- reverse("token-obtain"),
- data={"email": user3.email, "password": TEST_PASSWORD},
- format="json",
- )
- access_token = token_response.json()["data"]["attributes"]["access"]
+ client = authenticated_client_for_tenant_factory(user3, tenant2)
- response = authenticated_client.get(
+ response = client.get(
reverse("tenant-membership-list", kwargs={"tenant_pk": tenant2.id}),
- headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
# User is a member and can only see its own membership
@@ -1365,23 +1421,29 @@ class TestMembershipViewSet:
class TestProviderViewSet:
@pytest.fixture(scope="function")
def create_provider_group_relationship(
- self, tenants_fixture, providers_fixture, provider_groups_fixture
+ self, tenants_fixture, aws_provider, provider_groups_fixture
):
tenant, *_ = tenants_fixture
- provider1, *_ = providers_fixture
+ provider1 = aws_provider
provider_group1, *_ = provider_groups_fixture
provider_group_membership = ProviderGroupMembership.objects.create(
tenant=tenant, provider=provider1, provider_group=provider_group1
)
return provider_group_membership
- def test_providers_list(self, authenticated_client, providers_fixture):
- response = authenticated_client.get(reverse("provider-list"))
+ def test_providers_list(self, authenticated_client, all_provider_types_fixture):
+ response = authenticated_client.get(
+ reverse("provider-list"), {"page[disable]": "true"}
+ )
assert response.status_code == status.HTTP_200_OK
- assert len(response.json()["data"]) == len(providers_fixture)
+ data = response.json()["data"]
+ assert len(data) == len(all_provider_types_fixture)
+ assert {item["attributes"]["provider"] for item in data} == {
+ provider.provider for provider in all_provider_types_fixture
+ }
def test_providers_filter_provider_type(
- self, authenticated_client, providers_fixture
+ self, authenticated_client, aws_provider_pair
):
response = authenticated_client.get(
reverse("provider-list"), {"filter[provider_type]": "aws"}
@@ -1392,7 +1454,7 @@ class TestProviderViewSet:
assert all(item["attributes"]["provider"] == "aws" for item in data)
def test_providers_filter_provider_type_in(
- self, authenticated_client, providers_fixture
+ self, authenticated_client, aws_provider_pair, gcp_provider
):
response = authenticated_client.get(
reverse("provider-list"), {"filter[provider_type__in]": "aws,gcp"}
@@ -1403,7 +1465,7 @@ class TestProviderViewSet:
assert {"aws", "gcp"} >= {item["attributes"]["provider"] for item in data}
def test_providers_filter_provider_type_invalid(
- self, authenticated_client, providers_fixture
+ self, authenticated_client, aws_provider
):
response = authenticated_client.get(
reverse("provider-list"), {"filter[provider_type]": "invalid"}
@@ -1414,11 +1476,11 @@ class TestProviderViewSet:
self,
authenticated_client,
tenants_fixture,
- providers_fixture,
+ aws_provider_pair,
provider_groups_fixture,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
group1, group2, *_ = provider_groups_fixture
ProviderGroupMembership.objects.create(
tenant=tenant, provider=provider1, provider_group=group1
@@ -1447,7 +1509,7 @@ class TestProviderViewSet:
assert len(response.json()["data"]) == 2
def test_providers_disable_pagination(
- self, authenticated_client, providers_fixture, tenants_fixture
+ self, authenticated_client, aws_provider, tenants_fixture
):
tenant, *_ = tenants_fixture
existing_count = Provider.objects.filter(tenant_id=tenant.id).count()
@@ -1490,19 +1552,19 @@ class TestProviderViewSet:
("provider_groups", ["provider-groups"]),
],
)
+ @pytest.mark.usefixtures("create_provider_group_relationship")
def test_providers_list_include(
self,
include_values,
expected_resources,
authenticated_client,
- providers_fixture,
- create_provider_group_relationship,
+ aws_provider,
):
response = authenticated_client.get(
reverse("provider-list"), {"include": include_values}
)
assert response.status_code == status.HTTP_200_OK
- assert len(response.json()["data"]) == len(providers_fixture)
+ assert len(response.json()["data"]) == 1
assert "included" in response.json()
included_data = response.json()["included"]
@@ -1511,8 +1573,8 @@ class TestProviderViewSet:
f"Expected type '{expected_type}' not found in included data"
)
- def test_providers_retrieve(self, authenticated_client, providers_fixture):
- provider1, *_ = providers_fixture
+ def test_providers_retrieve(self, authenticated_client, aws_provider):
+ provider1 = aws_provider
response = authenticated_client.get(
reverse("provider-detail", kwargs={"pk": provider1.id}),
)
@@ -1663,6 +1725,11 @@ class TestProviderViewSet:
"uid": "C12",
"alias": "Google Workspace Minimum Length",
},
+ {
+ "provider": "image",
+ "uid": "registry.example.com/prowler/test:latest",
+ "alias": "Container Image",
+ },
{
"provider": "okta",
"uid": "acme.okta.com",
@@ -2253,8 +2320,8 @@ class TestProviderViewSet:
assert response.status_code == status.HTTP_201_CREATED
assert Provider.objects.get().uid == stored_uid
- def test_providers_partial_update(self, authenticated_client, providers_fixture):
- provider1, *_ = providers_fixture
+ def test_providers_partial_update(self, authenticated_client, aws_provider):
+ provider1 = aws_provider
new_alias = "This is the new name"
payload = {
"data": {
@@ -2273,9 +2340,11 @@ class TestProviderViewSet:
assert provider1.alias == new_alias
def test_providers_partial_update_invalid_content_type(
- self, authenticated_client, providers_fixture
+ self,
+ authenticated_client,
+ aws_provider,
):
- provider1, *_ = providers_fixture
+ provider1 = aws_provider
response = authenticated_client.patch(
reverse("provider-detail", kwargs={"pk": provider1.id}),
data={},
@@ -2283,9 +2352,11 @@ class TestProviderViewSet:
assert response.status_code == status.HTTP_415_UNSUPPORTED_MEDIA_TYPE
def test_providers_partial_update_invalid_content(
- self, authenticated_client, providers_fixture
+ self,
+ authenticated_client,
+ aws_provider,
):
- provider1, *_ = providers_fixture
+ provider1 = aws_provider
new_name = "This is the new name"
payload = {"alias": new_name}
response = authenticated_client.patch(
@@ -2305,11 +2376,11 @@ class TestProviderViewSet:
def test_providers_partial_update_invalid_fields(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
attribute_key,
attribute_value,
):
- provider1, *_ = providers_fixture
+ provider1 = aws_provider
payload = {
"data": {
"type": "providers",
@@ -2331,7 +2402,7 @@ class TestProviderViewSet:
mock_delete_task,
mock_task_get,
authenticated_client,
- providers_fixture,
+ aws_provider,
tasks_fixture,
):
prowler_task = tasks_fixture[0]
@@ -2340,7 +2411,7 @@ class TestProviderViewSet:
mock_delete_task.return_value = task_mock
mock_task_get.return_value = prowler_task
- provider1, *_ = providers_fixture
+ provider1 = aws_provider
response = authenticated_client.delete(
reverse("provider-detail", kwargs={"pk": provider1.id})
)
@@ -2364,7 +2435,7 @@ class TestProviderViewSet:
mock_provider_connection,
mock_task_get,
authenticated_client,
- providers_fixture,
+ aws_provider,
tasks_fixture,
):
prowler_task = tasks_fixture[0]
@@ -2374,7 +2445,7 @@ class TestProviderViewSet:
mock_provider_connection.return_value = task_mock
mock_task_get.return_value = prowler_task
- provider1, *_ = providers_fixture
+ provider1 = aws_provider
assert provider1.connected is None
assert provider1.connection_last_checked_at is None
@@ -2389,7 +2460,8 @@ class TestProviderViewSet:
assert response.headers["Content-Location"] == f"/api/v1/tasks/{task_mock.id}"
def test_providers_connection_invalid_provider(
- self, authenticated_client, providers_fixture
+ self,
+ authenticated_client,
):
response = authenticated_client.post(
reverse("provider-connection", kwargs={"pk": "random_id"})
@@ -2397,42 +2469,24 @@ class TestProviderViewSet:
assert response.status_code == status.HTTP_404_NOT_FOUND
@pytest.mark.parametrize(
- "filter_name, filter_value, expected_count",
+ "filter_name, filter_value",
(
[
- ("provider", "aws", 2),
- ("provider.in", "azure,gcp", 2),
- ("uid", "123456789012", 1),
- (
- "uid.icontains",
- "1",
- 12,
- ),
- ("alias", "aws_testing_1", 1),
- ("alias.icontains", "aws", 2),
- ("inserted_at", TODAY, 14),
- (
- "inserted_at.gte",
- "2024-01-01",
- 14,
- ),
- ("inserted_at.lte", "2024-01-01", 0),
- (
- "updated_at.gte",
- "2024-01-01",
- 14,
- ),
- ("updated_at.lte", "2024-01-01", 0),
+ ("uid", "123456789012"),
+ ("uid.icontains", "1"),
+ ("alias", "aws_testing_1"),
+ ("inserted_at", TODAY),
+ ("inserted_at.gte", "2024-01-01"),
+ ("updated_at.gte", "2024-01-01"),
]
),
)
- def test_providers_filters(
+ def test_providers_filters_single_aws_provider(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
filter_name,
filter_value,
- expected_count,
):
response = authenticated_client.get(
reverse("provider-list"),
@@ -2440,7 +2494,69 @@ class TestProviderViewSet:
)
assert response.status_code == status.HTTP_200_OK
- assert len(response.json()["data"]) == expected_count
+ assert len(response.json()["data"]) == 1
+
+ @pytest.mark.parametrize(
+ "filter_name, filter_value",
+ (
+ [
+ ("inserted_at.lte", "2024-01-01"),
+ ("updated_at.lte", "2024-01-01"),
+ ]
+ ),
+ )
+ def test_providers_filters_single_aws_provider_no_results(
+ self,
+ authenticated_client,
+ aws_provider,
+ filter_name,
+ filter_value,
+ ):
+ response = authenticated_client.get(
+ reverse("provider-list"),
+ {f"filter[{filter_name}]": filter_value},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert len(response.json()["data"]) == 0
+
+ @pytest.mark.parametrize(
+ "filter_name, filter_value",
+ (
+ [
+ ("provider", "aws"),
+ ("alias.icontains", "aws"),
+ ]
+ ),
+ )
+ def test_providers_filters_two_aws_providers(
+ self,
+ authenticated_client,
+ aws_provider_pair,
+ filter_name,
+ filter_value,
+ ):
+ response = authenticated_client.get(
+ reverse("provider-list"),
+ {f"filter[{filter_name}]": filter_value},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert len(response.json()["data"]) == 2
+
+ def test_providers_filters_provider_in(
+ self,
+ authenticated_client,
+ azure_provider,
+ gcp_provider,
+ ):
+ response = authenticated_client.get(
+ reverse("provider-list"),
+ {"filter[provider.in]": "azure,gcp"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert len(response.json()["data"]) == 2
@pytest.mark.parametrize(
"filter_name",
@@ -2634,9 +2750,9 @@ class TestProviderGroupViewSet:
assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
def test_provider_group_create_with_relationships(
- self, authenticated_client, providers_fixture, roles_fixture
+ self, authenticated_client, aws_provider_pair, roles_fixture
):
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
role1, role2, *_ = roles_fixture
data = {
@@ -2677,12 +2793,13 @@ class TestProviderGroupViewSet:
self,
authenticated_client,
provider_groups_fixture,
- providers_fixture,
+ gcp_provider,
+ kubernetes_provider,
roles_fixture,
):
group = provider_groups_fixture[0]
- provider3 = providers_fixture[2]
- provider4 = providers_fixture[3]
+ provider3 = gcp_provider
+ provider4 = kubernetes_provider
role3 = roles_fixture[2]
role4 = roles_fixture[3]
@@ -2719,11 +2836,15 @@ class TestProviderGroupViewSet:
assert set(group.roles.all()) == {role3, role4}
def test_provider_group_clear_relationships(
- self, authenticated_client, providers_fixture, provider_groups_fixture
+ self,
+ authenticated_client,
+ gcp_provider,
+ kubernetes_provider,
+ provider_groups_fixture,
):
group = provider_groups_fixture[0]
- provider3 = providers_fixture[2]
- provider4 = providers_fixture[3]
+ provider3 = gcp_provider
+ provider4 = kubernetes_provider
data = {
"data": {
@@ -2796,10 +2917,57 @@ class TestProviderGroupViewSet:
@pytest.mark.django_db
class TestProviderSecretViewSet:
+ @staticmethod
+ def _oraclecloud_secret(**overrides):
+ secret = {
+ "user": "ocid1.user.oc1..aaaaaaaakldibrbov4ubh25aqdeiroklxjngwka7u6w7no3glmdq3n5sxtkq",
+ "fingerprint": "aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99",
+ "key_content": "test-key-content",
+ "tenancy": "ocid1.tenancy.oc1..aaaaaaaa3dwoazoox4q7wrvriywpokp5grlhgnkwtyt6dmwyou7no6mdmzda",
+ }
+ secret.update(overrides)
+ return secret
+
+ def _create_oraclecloud_secret(
+ self,
+ authenticated_client,
+ oraclecloud_provider,
+ secret,
+ name="OCI Secret",
+ ):
+ data = {
+ "data": {
+ "type": "provider-secrets",
+ "attributes": {
+ "name": name,
+ "secret_type": ProviderSecret.TypeChoices.STATIC,
+ "secret": secret,
+ },
+ "relationships": {
+ "provider": {
+ "data": {
+ "type": "providers",
+ "id": str(oraclecloud_provider.id),
+ }
+ }
+ },
+ }
+ }
+ return authenticated_client.post(
+ reverse("providersecret-list"),
+ data=json.dumps(data),
+ content_type="application/vnd.api+json",
+ )
+
def test_provider_secrets_list(self, authenticated_client, provider_secret_fixture):
response = authenticated_client.get(reverse("providersecret-list"))
assert response.status_code == status.HTTP_200_OK
- assert len(response.json()["data"]) == len(provider_secret_fixture)
+ assert len(response.json()["data"]) == min(
+ settings.REST_FRAMEWORK["PAGE_SIZE"], len(provider_secret_fixture)
+ )
+ assert response.json()["meta"]["pagination"]["count"] == len(
+ provider_secret_fixture
+ )
def test_provider_secrets_retrieve(
self, authenticated_client, provider_secret_fixture
@@ -2897,7 +3065,24 @@ class TestProviderSecretViewSet:
Provider.ProviderChoices.KUBERNETES.value,
ProviderSecret.TypeChoices.STATIC,
{
- "kubeconfig_content": "kubeconfig-content",
+ "kubeconfig_content": """
+apiVersion: v1
+kind: Config
+clusters:
+ - name: test-cluster
+ cluster:
+ server: https://kubernetes.example.test
+users:
+ - name: test-user
+ user:
+ token: test-token
+contexts:
+ - name: test-context
+ context:
+ cluster: test-cluster
+ user: test-user
+current-context: test-context
+""",
},
),
# M365 client secret credentials
@@ -2933,7 +3118,6 @@ class TestProviderSecretViewSet:
"fingerprint": "aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99",
"key_content": "-----BEGIN RSA PRIVATE KEY-----\ntest-key-content\n-----END RSA PRIVATE KEY-----",
"tenancy": "ocid1.tenancy.oc1..aaaaaaaa3dwoazoox4q7wrvriywpokp5grlhgnkwtyt6dmwyou7no6mdmzda",
- "region": "us-ashburn-1",
},
),
# OCI with API key credentials (with key_file)
@@ -2945,7 +3129,6 @@ class TestProviderSecretViewSet:
"fingerprint": "aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99",
"key_file": "/path/to/oci_api_key.pem",
"tenancy": "ocid1.tenancy.oc1..aaaaaaaa3dwoazoox4q7wrvriywpokp5grlhgnkwtyt6dmwyou7no6mdmzda",
- "region": "us-ashburn-1",
},
),
# OCI with API key credentials (with passphrase)
@@ -2957,7 +3140,6 @@ class TestProviderSecretViewSet:
"fingerprint": "aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99",
"key_content": "-----BEGIN RSA PRIVATE KEY-----\ntest-encrypted-key\n-----END RSA PRIVATE KEY-----",
"tenancy": "ocid1.tenancy.oc1..aaaaaaaa3dwoazoox4q7wrvriywpokp5grlhgnkwtyt6dmwyou7no6mdmzda",
- "region": "us-ashburn-1",
"pass_phrase": "my-secure-passphrase",
},
),
@@ -3053,6 +3235,15 @@ class TestProviderSecretViewSet:
"api_token": "fake-vercel-api-token-for-testing",
},
),
+ # Image registry credentials
+ (
+ Provider.ProviderChoices.IMAGE.value,
+ ProviderSecret.TypeChoices.STATIC,
+ {
+ "registry_username": "user",
+ "registry_password": "pass",
+ },
+ ),
# Okta with inline private key credentials
(
Provider.ProviderChoices.OKTA.value,
@@ -3071,16 +3262,12 @@ class TestProviderSecretViewSet:
def test_provider_secrets_create_valid(
self,
authenticated_client,
- providers_fixture,
+ provider_factory,
provider_type,
secret_type,
secret_data,
):
- # Get the provider from the fixture and set its type
- try:
- provider = Provider.objects.filter(provider=provider_type)[0]
- except IndexError:
- print(f"Provider {provider_type} not found")
+ provider = provider_factory(provider_type)
data = {
"data": {
@@ -3110,6 +3297,103 @@ class TestProviderSecretViewSet:
== data["data"]["relationships"]["provider"]["data"]["id"]
)
+ def test_provider_secrets_create_oraclecloud_without_region_stores_no_region(
+ self,
+ authenticated_client,
+ oraclecloud_provider,
+ ):
+ response = self._create_oraclecloud_secret(
+ authenticated_client,
+ oraclecloud_provider,
+ self._oraclecloud_secret(),
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
+ provider_secret = ProviderSecret.objects.get()
+ assert "region" not in provider_secret.secret
+
+ def test_provider_secrets_create_oraclecloud_accepts_and_ignores_region(
+ self,
+ authenticated_client,
+ oraclecloud_provider,
+ ):
+ response = self._create_oraclecloud_secret(
+ authenticated_client,
+ oraclecloud_provider,
+ self._oraclecloud_secret(
+ key_content=" test-key-content ", region=" us-ashburn-1 "
+ ),
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
+ provider_secret = ProviderSecret.objects.get()
+ assert provider_secret.secret["key_content"] == "test-key-content"
+ assert "region" not in provider_secret.secret
+
+ def test_provider_secrets_update_oraclecloud_without_region_stores_no_region(
+ self,
+ authenticated_client,
+ oraclecloud_provider,
+ ):
+ create_response = self._create_oraclecloud_secret(
+ authenticated_client,
+ oraclecloud_provider,
+ self._oraclecloud_secret(),
+ )
+ provider_secret = ProviderSecret.objects.get(
+ id=create_response.json()["data"]["id"]
+ )
+ data = {
+ "data": {
+ "type": "provider-secrets",
+ "id": str(provider_secret.id),
+ "attributes": {"secret": self._oraclecloud_secret()},
+ }
+ }
+
+ response = authenticated_client.patch(
+ reverse("providersecret-detail", kwargs={"pk": provider_secret.id}),
+ data=json.dumps(data),
+ content_type="application/vnd.api+json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ provider_secret.refresh_from_db()
+ assert "region" not in provider_secret.secret
+
+ def test_provider_secrets_update_oraclecloud_accepts_and_ignores_region(
+ self,
+ authenticated_client,
+ oraclecloud_provider,
+ ):
+ create_response = self._create_oraclecloud_secret(
+ authenticated_client,
+ oraclecloud_provider,
+ self._oraclecloud_secret(),
+ )
+ provider_secret = ProviderSecret.objects.get(
+ id=create_response.json()["data"]["id"]
+ )
+ data = {
+ "data": {
+ "type": "provider-secrets",
+ "id": str(provider_secret.id),
+ "attributes": {
+ "secret": self._oraclecloud_secret(region=" us-ashburn-1 ")
+ },
+ }
+ }
+
+ response = authenticated_client.patch(
+ reverse("providersecret-detail", kwargs={"pk": provider_secret.id}),
+ data=json.dumps(data),
+ content_type="application/vnd.api+json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ provider_secret.refresh_from_db()
+ assert "region" not in provider_secret.secret
+
@pytest.mark.parametrize(
"attributes, error_code, error_pointer",
(
@@ -3150,13 +3434,13 @@ class TestProviderSecretViewSet:
)
def test_provider_secrets_invalid_create(
self,
- providers_fixture,
+ aws_provider,
authenticated_client,
attributes,
error_code,
error_pointer,
):
- provider, *_ = providers_fixture
+ provider = aws_provider
data = {
"data": {
"type": "provider-secrets",
@@ -3180,14 +3464,9 @@ class TestProviderSecretViewSet:
def test_provider_secrets_invalid_create_okta_missing_private_key(
self,
- providers_fixture,
+ okta_provider,
authenticated_client,
):
- okta_provider = next(
- provider
- for provider in providers_fixture
- if provider.provider == Provider.ProviderChoices.OKTA.value
- )
data = {
"data": {
"type": "provider-secrets",
@@ -3311,30 +3590,43 @@ class TestProviderSecretViewSet:
)
assert response.status_code == status.HTTP_404_NOT_FOUND
- @pytest.mark.parametrize(
- "filter_name, filter_value, expected_count",
- (
- [
- ("name", "aws_testing_1", 1),
- ("name.icontains", "aws", 2),
- ]
- ),
- )
- def test_provider_secrets_filters(
+ def test_provider_secrets_filter_name(
self,
authenticated_client,
provider_secret_fixture,
- filter_name,
- filter_value,
- expected_count,
):
response = authenticated_client.get(
reverse("providersecret-list"),
- {f"filter[{filter_name}]": filter_value},
+ {"filter[name]": "aws_testing_1"},
)
assert response.status_code == status.HTTP_200_OK
- assert len(response.json()["data"]) == expected_count
+ assert len(response.json()["data"]) == 1
+
+ def test_provider_secrets_filter_name_icontains(
+ self,
+ authenticated_client,
+ provider_secret_fixture,
+ provider_factory,
+ ):
+ provider = provider_factory(
+ Provider.ProviderChoices.AWS.value, alias="aws_testing_extra"
+ )
+ ProviderSecret.objects.create(
+ tenant_id=provider.tenant_id,
+ provider=provider,
+ secret_type=ProviderSecret.TypeChoices.STATIC,
+ secret={"key": "value"},
+ name=provider.alias,
+ )
+
+ response = authenticated_client.get(
+ reverse("providersecret-list"),
+ {"filter[name.icontains]": "aws"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert len(response.json()["data"]) == 2
@pytest.mark.parametrize(
"filter_name",
@@ -3472,18 +3764,9 @@ class TestProviderSecretViewSet:
assert response.status_code == status.HTTP_400_BAD_REQUEST
def test_m365_provider_secrets_invalid_certificate_base64(
- self, authenticated_client, providers_fixture
+ self, authenticated_client, m365_provider
):
"""Test M365 provider secret creation with invalid base64 certificate content"""
- # Find M365 provider from fixture
- m365_provider = None
- for provider in providers_fixture:
- if provider.provider == Provider.ProviderChoices.M365.value:
- m365_provider = provider
- break
-
- assert m365_provider is not None, "M365 provider not found in fixture"
-
data = {
"data": {
"type": "provider-secrets",
@@ -3541,7 +3824,7 @@ class TestScanViewSet:
assert response.status_code == status.HTTP_404_NOT_FOUND
@pytest.mark.parametrize(
- "scan_json_payload, expected_scanner_args",
+ "scan_json_payload, _expected_scanner_args",
[
# Case 1: No scanner_args in payload (should use provider's scanner_args)
(
@@ -3582,22 +3865,16 @@ class TestScanViewSet:
),
],
)
- @patch("api.v1.views.Task.objects.get")
- @patch("api.v1.views.perform_scan_task.apply_async")
+ @patch("api.v1.views.enqueue_scan_execution_on_commit")
def test_scans_create_valid(
self,
- mock_perform_scan_task,
- mock_task_get,
+ mock_enqueue_scan_execution,
authenticated_client,
scan_json_payload,
- expected_scanner_args,
- providers_fixture,
- tasks_fixture,
+ _expected_scanner_args,
+ okta_provider,
):
- prowler_task = tasks_fixture[0]
- mock_perform_scan_task.return_value.id = prowler_task.id
- mock_task_get.return_value = prowler_task
- *_, provider5 = providers_fixture
+ provider5 = okta_provider
# Provider5 has these scanner_args
# scanner_args={"key1": "value1", "key2": {"key21": "value21"}}
@@ -3621,8 +3898,121 @@ class TestScanViewSet:
assert scan.name == scan_json_payload["data"]["attributes"]["name"]
assert scan.provider == provider5
assert scan.trigger == Scan.TriggerChoices.MANUAL
+ mock_enqueue_scan_execution.assert_called_once()
# assert scan.scanner_args == expected_scanner_args
+ @patch("tasks.tasks.perform_scan_task.apply_async")
+ def test_scans_create_queues_scan_when_provider_has_active_scan(
+ self,
+ mock_perform_scan_task,
+ authenticated_client,
+ aws_provider,
+ tenants_fixture,
+ django_capture_on_commit_callbacks,
+ ):
+ tenant, *_ = tenants_fixture
+ provider = aws_provider
+ task_result = TaskResult.objects.create(
+ task_id=str(uuid4()),
+ task_name="scan-perform",
+ status=states.PENDING,
+ )
+ prowler_task = Task.objects.create(
+ id=task_result.task_id,
+ tenant_id=tenant.id,
+ task_runner_task=task_result,
+ )
+ Scan.objects.create(
+ name="Active scan",
+ provider=provider,
+ trigger=Scan.TriggerChoices.MANUAL,
+ state=StateChoices.AVAILABLE,
+ tenant_id=tenant.id,
+ task=prowler_task,
+ )
+
+ with django_capture_on_commit_callbacks(execute=True):
+ response = authenticated_client.post(
+ reverse("scan-list"),
+ data={
+ "data": {
+ "type": "scans",
+ "attributes": {"name": "Duplicate Scan"},
+ "relationships": {
+ "provider": {
+ "data": {"type": "providers", "id": str(provider.id)}
+ }
+ },
+ }
+ },
+ content_type=API_JSON_CONTENT_TYPE,
+ )
+
+ assert response.status_code == status.HTTP_202_ACCEPTED
+ assert response.json()["data"]["id"] != str(prowler_task.id)
+ assert Scan.objects.count() == 2
+ queued_scan = Scan.objects.exclude(task=prowler_task).get()
+ assert queued_scan.trigger == Scan.TriggerChoices.MANUAL
+ assert queued_scan.state == StateChoices.AVAILABLE
+ assert queued_scan.task.task_runner_task.status == "QUEUED"
+ mock_perform_scan_task.assert_not_called()
+
+ @patch("tasks.tasks.perform_scan_task.apply_async")
+ def test_scans_create_queues_scan_when_scheduled_scan_is_claimed(
+ self,
+ mock_perform_scan_task,
+ authenticated_client,
+ aws_provider,
+ tenants_fixture,
+ django_capture_on_commit_callbacks,
+ ):
+ tenant, *_ = tenants_fixture
+ provider = aws_provider
+ task_result = TaskResult.objects.create(
+ task_id=str(uuid4()),
+ task_name="scan-perform-scheduled",
+ status=states.STARTED,
+ )
+ prowler_task = Task.objects.create(
+ id=task_result.task_id,
+ tenant_id=tenant.id,
+ task_runner_task=task_result,
+ )
+ Scan.objects.create(
+ name="Claimed scheduled scan",
+ provider=provider,
+ trigger=Scan.TriggerChoices.SCHEDULED,
+ state=StateChoices.SCHEDULED,
+ tenant_id=tenant.id,
+ task=prowler_task,
+ )
+
+ with django_capture_on_commit_callbacks(execute=True):
+ response = authenticated_client.post(
+ reverse("scan-list"),
+ data={
+ "data": {
+ "type": "scans",
+ "attributes": {"name": "Manual Scan"},
+ "relationships": {
+ "provider": {
+ "data": {"type": "providers", "id": str(provider.id)}
+ }
+ },
+ }
+ },
+ content_type=API_JSON_CONTENT_TYPE,
+ )
+
+ assert response.status_code == status.HTTP_202_ACCEPTED
+ assert response.json()["data"]["id"] != str(prowler_task.id)
+ assert Scan.objects.count() == 2
+ queued_scan = Scan.objects.exclude(task=prowler_task).get()
+ assert queued_scan.trigger == Scan.TriggerChoices.MANUAL
+ assert queued_scan.state == StateChoices.AVAILABLE
+ assert queued_scan.task.task_runner_task.status == "QUEUED"
+ mock_perform_scan_task.assert_not_called()
+
@pytest.mark.parametrize(
"scan_json_payload, error_code",
[
@@ -3649,10 +4039,10 @@ class TestScanViewSet:
self,
authenticated_client,
scan_json_payload,
- providers_fixture,
+ aws_provider,
error_code,
):
- provider1, *_ = providers_fixture
+ provider1 = aws_provider
scan_json_payload["data"]["relationships"]["provider"]["data"]["id"] = str(
provider1.id
)
@@ -4069,7 +4459,7 @@ class TestScanViewSet:
monkeypatch.setattr(
"api.v1.views.env",
- type("env", (), {"str": lambda self, *args, **kwargs: "test-bucket"})(),
+ type("env", (), {"str": lambda self, *_args, **_kwargs: "test-bucket"})(),
)
presigned_url = (
@@ -4175,7 +4565,7 @@ class TestScanViewSet:
monkeypatch.setattr(
"api.v1.views.TaskSerializer",
- lambda *args, **kwargs: type("S", (), {"data": dummy}),
+ lambda *_args, **_kwargs: type("S", (), {"data": dummy}),
)
framework = get_compliance_frameworks(scan.provider.provider)[0]
@@ -4233,7 +4623,7 @@ class TestScanViewSet:
monkeypatch.setattr(
"api.v1.views.env",
- type("env", (), {"str": lambda self, *args, **kwargs: "test-bucket"})(),
+ type("env", (), {"str": lambda self, *_args, **_kwargs: "test-bucket"})(),
)
match_key = "path/compliance/mitre_attack_aws.csv"
@@ -4244,6 +4634,7 @@ class TestScanViewSet:
class FakeS3Client:
def list_objects_v2(self, Bucket, Prefix):
+ del Prefix
return {"Contents": [{"Key": match_key}]}
def generate_presigned_url(self, ClientMethod, Params, ExpiresIn):
@@ -4275,7 +4666,7 @@ class TestScanViewSet:
monkeypatch.setattr(
"api.v1.views.env",
- type("env", (), {"str": lambda self, *args, **kwargs: "test-bucket"})(),
+ type("env", (), {"str": lambda self, *_args, **_kwargs: "test-bucket"})(),
)
old_key = "path/compliance/prowler-output-aws-20240101000000_cis_1.4_aws.csv"
@@ -4283,6 +4674,7 @@ class TestScanViewSet:
class FakeS3Client:
def list_objects_v2(self, Bucket, Prefix):
+ del Prefix
return {
"Contents": [
{
@@ -4356,11 +4748,12 @@ class TestScanViewSet:
monkeypatch.setattr(
"api.v1.views.env",
- type("env", (), {"str": lambda self, *args, **kwargs: "test-bucket"})(),
+ type("env", (), {"str": lambda self, *_args, **_kwargs: "test-bucket"})(),
)
class FakeS3Client:
def list_objects_v2(self, Bucket, Prefix):
+ del Prefix
return {"Contents": []}
def get_object(self, Bucket, Key):
@@ -4546,7 +4939,7 @@ class TestScanViewSet:
inserted_at=base + timedelta(hours=1)
)
- mock_task_serializer.side_effect = lambda instance, *a, **k: SimpleNamespace(
+ mock_task_serializer.side_effect = lambda instance, *_a, **_k: SimpleNamespace(
data={"id": str(instance.id), "state": StateChoices.EXECUTING}
)
@@ -4709,12 +5102,13 @@ class TestAttackPathsScanViewSet:
def test_attack_paths_scans_list_returns_latest_entry_per_provider(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
+ aws_provider_pair,
):
- provider = providers_fixture[0]
- other_provider = providers_fixture[1]
+ provider = aws_provider
+ other_provider = aws_provider_pair[1]
older_scan = create_attack_paths_scan(
provider,
@@ -4754,19 +5148,78 @@ class TestAttackPathsScanViewSet:
assert first_attributes["provider_type"] == provider.provider
assert first_attributes["provider_uid"] == provider.uid
+ def test_attack_paths_scans_list_prefers_active_sink_scan_on_rollback(
+ self,
+ authenticated_client,
+ aws_provider,
+ scans_fixture,
+ create_attack_paths_scan,
+ settings,
+ ):
+ settings.ATTACK_PATHS_SINK_DATABASE = "neo4j"
+ provider = aws_provider
+
+ neo4j_scan = create_attack_paths_scan(
+ provider,
+ scan=scans_fixture[0],
+ state=StateChoices.COMPLETED,
+ graph_data_ready=True,
+ sink_backend="neo4j",
+ )
+ neptune_scan = create_attack_paths_scan(
+ provider,
+ scan=scans_fixture[0],
+ state=StateChoices.COMPLETED,
+ graph_data_ready=True,
+ sink_backend="neptune",
+ )
+
+ response = authenticated_client.get(reverse("attack-paths-scans-list"))
+
+ assert response.status_code == status.HTTP_200_OK
+ ids = {item["id"] for item in response.json()["data"]}
+ assert str(neo4j_scan.id) in ids
+ assert str(neptune_scan.id) not in ids
+
+ def test_attack_paths_scans_list_falls_back_when_active_sink_has_no_scan(
+ self,
+ authenticated_client,
+ aws_provider,
+ scans_fixture,
+ create_attack_paths_scan,
+ settings,
+ ):
+ settings.ATTACK_PATHS_SINK_DATABASE = "neptune"
+ provider = aws_provider
+
+ legacy_scan = create_attack_paths_scan(
+ provider,
+ scan=scans_fixture[0],
+ state=StateChoices.COMPLETED,
+ graph_data_ready=True,
+ sink_backend="neo4j",
+ )
+
+ response = authenticated_client.get(reverse("attack-paths-scans-list"))
+
+ assert response.status_code == status.HTTP_200_OK
+ ids = {item["id"] for item in response.json()["data"]}
+ assert str(legacy_scan.id) in ids
+
def test_attack_paths_scans_list_respects_provider_group_visibility(
self,
authenticated_client_no_permissions_rbac,
- providers_fixture,
+ aws_provider,
create_attack_paths_scan,
+ aws_provider_pair,
):
client = authenticated_client_no_permissions_rbac
limited_user = client.user
membership = Membership.objects.filter(user=limited_user).first()
tenant = membership.tenant
- allowed_provider = providers_fixture[0]
- denied_provider = providers_fixture[1]
+ allowed_provider = aws_provider
+ denied_provider = aws_provider_pair[1]
allowed_scan = create_attack_paths_scan(allowed_provider)
create_attack_paths_scan(denied_provider)
@@ -4797,11 +5250,11 @@ class TestAttackPathsScanViewSet:
def test_attack_paths_scan_retrieve(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -4840,11 +5293,11 @@ class TestAttackPathsScanViewSet:
def test_attack_paths_queries_returns_catalog(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -4874,7 +5327,8 @@ class TestAttackPathsScanViewSet:
)
assert response.status_code == status.HTTP_200_OK
- mock_get_queries.assert_called_once_with(provider.provider)
+ # TODO: drop the is_migrated argument after Neptune cutover
+ mock_get_queries.assert_called_once_with(provider.provider, is_migrated=False)
payload = response.json()["data"]
assert len(payload) == 1
assert payload[0]["id"] == "aws-rds"
@@ -4884,11 +5338,11 @@ class TestAttackPathsScanViewSet:
def test_attack_paths_queries_returns_404_when_catalog_missing(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(provider, scan=scans_fixture[0])
with patch("api.v1.views.get_queries_for_provider", return_value=[]):
@@ -4904,11 +5358,11 @@ class TestAttackPathsScanViewSet:
def test_run_attack_paths_query_returns_graph(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -4974,7 +5428,8 @@ class TestAttackPathsScanViewSet:
)
assert response.status_code == status.HTTP_200_OK
- mock_get_query.assert_called_once_with("aws-rds")
+ # TODO: drop the is_migrated argument after Neptune cutover
+ mock_get_query.assert_called_once_with("aws-rds", is_migrated=False)
mock_get_db_name.assert_called_once_with(attack_paths_scan.provider.tenant_id)
provider_id = str(attack_paths_scan.provider_id)
mock_prepare.assert_called_once_with(
@@ -4988,6 +5443,7 @@ class TestAttackPathsScanViewSet:
query_definition,
prepared_parameters,
provider_id,
+ scan=attack_paths_scan,
)
result = response.json()["data"]
attributes = result["attributes"]
@@ -4997,11 +5453,11 @@ class TestAttackPathsScanViewSet:
def test_run_attack_paths_query_returns_text_when_accept_text_plain(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5064,11 +5520,11 @@ class TestAttackPathsScanViewSet:
def test_run_attack_paths_query_blocks_when_graph_data_not_ready(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5090,11 +5546,11 @@ class TestAttackPathsScanViewSet:
def test_run_attack_paths_query_allows_executing_scan_when_graph_data_ready(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5144,11 +5600,11 @@ class TestAttackPathsScanViewSet:
def test_run_attack_paths_query_allows_failed_scan_when_graph_data_ready(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5198,11 +5654,11 @@ class TestAttackPathsScanViewSet:
def test_run_attack_paths_query_unknown_query(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5225,11 +5681,11 @@ class TestAttackPathsScanViewSet:
def test_run_attack_paths_query_returns_404_when_no_nodes_found(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5292,11 +5748,11 @@ class TestAttackPathsScanViewSet:
def test_run_custom_query_returns_graph(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5339,6 +5795,7 @@ class TestAttackPathsScanViewSet:
"db-test",
"MATCH (n) RETURN n",
str(attack_paths_scan.provider_id),
+ scan=attack_paths_scan,
)
attributes = response.json()["data"]["attributes"]
assert len(attributes["nodes"]) == 1
@@ -5348,11 +5805,11 @@ class TestAttackPathsScanViewSet:
def test_run_custom_query_returns_text_when_accept_text_plain(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5401,11 +5858,11 @@ class TestAttackPathsScanViewSet:
def test_run_custom_query_returns_404_when_no_nodes(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5441,11 +5898,11 @@ class TestAttackPathsScanViewSet:
def test_run_custom_query_returns_400_when_graph_not_ready(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5467,11 +5924,11 @@ class TestAttackPathsScanViewSet:
def test_run_custom_query_returns_403_for_write_query(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5525,12 +5982,12 @@ class TestAttackPathsScanViewSet:
def test_run_custom_query_rejects_ssrf_patterns(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
cypher,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5619,13 +6076,13 @@ class TestAttackPathsScanViewSet:
def test_run_custom_query_returns_401_unauthenticated(
self,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
from rest_framework.test import APIClient
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5646,13 +6103,13 @@ class TestAttackPathsScanViewSet:
def test_cartography_schema_returns_401_unauthenticated(
self,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
from rest_framework.test import APIClient
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5672,11 +6129,11 @@ class TestAttackPathsScanViewSet:
def test_run_custom_query_returns_403_no_manage_scans(
self,
authenticated_client_no_permissions_rbac,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5699,13 +6156,13 @@ class TestAttackPathsScanViewSet:
def test_run_custom_query_does_not_leak_internals_on_error(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
from rest_framework.exceptions import APIException
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5743,11 +6200,11 @@ class TestAttackPathsScanViewSet:
def test_run_custom_query_throttled_after_limit(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5797,13 +6254,13 @@ class TestAttackPathsScanViewSet:
def test_run_custom_query_returns_500_on_database_timeout(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
from rest_framework.exceptions import APIException
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5838,11 +6295,11 @@ class TestAttackPathsScanViewSet:
def test_cartography_schema_returns_urls(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5875,9 +6332,10 @@ class TestAttackPathsScanViewSet:
)
assert response.status_code == status.HTTP_200_OK
- mock_get_schema.assert_called_once_with(
- "db-test", str(attack_paths_scan.provider_id)
- )
+ mock_get_schema.assert_called_once()
+ schema_args = mock_get_schema.call_args[0]
+ assert schema_args[:2] == ("db-test", str(attack_paths_scan.provider_id))
+ assert schema_args[2].id == attack_paths_scan.id
attributes = response.json()["data"]["attributes"]
assert attributes["provider"] == "aws"
assert attributes["cartography_version"] == "0.129.0"
@@ -5887,11 +6345,11 @@ class TestAttackPathsScanViewSet:
def test_cartography_schema_returns_404_when_no_metadata(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -5921,11 +6379,11 @@ class TestAttackPathsScanViewSet:
def test_cartography_schema_returns_400_when_graph_not_ready(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
scans_fixture,
create_attack_paths_scan,
):
- provider = providers_fixture[0]
+ provider = aws_provider
attack_paths_scan = create_attack_paths_scan(
provider,
scan=scans_fixture[0],
@@ -6215,9 +6673,8 @@ class TestResourceViewSet:
)
assert response.status_code == status.HTTP_404_NOT_FOUND
- def test_resources_metadata_retrieve(
- self, authenticated_client, resources_fixture, backfill_scan_metadata_fixture
- ):
+ @pytest.mark.usefixtures("backfill_scan_metadata_fixture")
+ def test_resources_metadata_retrieve(self, authenticated_client, resources_fixture):
resource_1, *_ = resources_fixture
response = authenticated_client.get(
reverse("resource-metadata"),
@@ -6237,8 +6694,9 @@ class TestResourceViewSet:
assert set(data["data"]["attributes"]["types"]) == expected_resource_types
assert set(data["data"]["attributes"]["groups"]) == expected_groups
+ @pytest.mark.usefixtures("backfill_scan_metadata_fixture")
def test_resources_metadata_resource_filter_retrieve(
- self, authenticated_client, resources_fixture, backfill_scan_metadata_fixture
+ self, authenticated_client, resources_fixture
):
resource_1, *_ = resources_fixture
response = authenticated_client.get(
@@ -6344,10 +6802,13 @@ class TestResourceViewSet:
)
def test_resources_latest_filter_by_provider_id_in_multiple(
- self, authenticated_client, providers_fixture
+ self,
+ authenticated_client,
+ aws_provider,
+ aws_provider_pair,
):
"""Test that provider_id__in filter works with multiple provider IDs."""
- provider1, provider2 = providers_fixture[0], providers_fixture[1]
+ provider1, provider2 = aws_provider, aws_provider_pair[1]
tenant_id = str(provider1.tenant_id)
# Create completed scans for both providers
@@ -6416,12 +6877,14 @@ class TestResourceViewSet:
assert len(response.json()["data"]) == 0
# Events endpoint tests
- def test_events_non_aws_provider(self, authenticated_client, providers_fixture):
+ def test_events_non_aws_provider(
+ self,
+ authenticated_client,
+ azure_provider,
+ ):
"""Test events endpoint rejects non-AWS providers."""
from api.models import Resource
- azure_provider = providers_fixture[4] # Azure provider from fixture
-
resource = Resource.objects.create(
uid="test-resource-id",
name="Test Resource",
@@ -6457,7 +6920,7 @@ class TestResourceViewSet:
def test_events_invalid_lookback_days(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
lookback_days,
expected_status,
expected_code,
@@ -6466,8 +6929,6 @@ class TestResourceViewSet:
"""Test events endpoint validates lookback_days with JSON:API compliant errors."""
from api.models import Resource
- aws_provider = providers_fixture[0] # AWS provider from fixture
-
resource = Resource.objects.create(
uid="arn:aws:ec2:us-east-1:123456789012:instance/i-test",
name="Test Instance",
@@ -6504,7 +6965,7 @@ class TestResourceViewSet:
def test_events_invalid_page_size(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
page_size,
expected_status,
expected_code,
@@ -6513,8 +6974,6 @@ class TestResourceViewSet:
"""Test events endpoint validates page[size] with JSON:API compliant errors."""
from api.models import Resource
- aws_provider = providers_fixture[0] # AWS provider from fixture
-
resource = Resource.objects.create(
uid="arn:aws:ec2:us-east-1:123456789012:instance/i-pagesize-test",
name="Test Instance",
@@ -6552,15 +7011,13 @@ class TestResourceViewSet:
def test_events_invalid_query_parameter(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
invalid_params,
expected_invalid_param,
):
"""Test events endpoint rejects unknown query parameters with JSON:API compliant errors."""
from api.models import Resource
- aws_provider = providers_fixture[0] # AWS provider from fixture
-
resource = Resource.objects.create(
uid="arn:aws:ec2:us-east-1:123456789012:instance/i-test",
name="Test Instance",
@@ -6597,13 +7054,11 @@ class TestResourceViewSet:
def test_events_multiple_invalid_query_parameters(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
):
"""Test events endpoint returns error for first unknown parameter."""
from api.models import Resource
- aws_provider = providers_fixture[0]
-
resource = Resource.objects.create(
uid="arn:aws:ec2:us-east-1:123456789012:instance/i-test",
name="Test Instance",
@@ -6640,13 +7095,11 @@ class TestResourceViewSet:
mock_cloudtrail_timeline,
mock_initialize_provider,
authenticated_client,
- providers_fixture,
+ aws_provider,
):
"""Test successful events retrieval."""
from api.models import Resource
- aws_provider = providers_fixture[0] # AWS provider from fixture
-
# Create test resource
resource = Resource.objects.create(
uid="arn:aws:ec2:us-east-1:123456789012:instance/i-test123",
@@ -6732,13 +7185,11 @@ class TestResourceViewSet:
mock_cloudtrail_timeline,
mock_initialize_provider,
authenticated_client,
- providers_fixture,
+ aws_provider,
):
"""Test events uses default lookback_days (90) when not provided."""
from api.models import Resource
- aws_provider = providers_fixture[0] # AWS provider from fixture
-
resource = Resource.objects.create(
uid="arn:aws:s3:::test-bucket",
name="Test Bucket",
@@ -6776,13 +7227,14 @@ class TestResourceViewSet:
@patch("api.v1.views.initialize_prowler_provider")
def test_events_no_credentials_error(
- self, mock_initialize_provider, authenticated_client, providers_fixture
+ self,
+ mock_initialize_provider,
+ authenticated_client,
+ aws_provider,
):
"""Test events handles missing credentials errors."""
from api.models import Resource
- aws_provider = providers_fixture[0] # AWS provider from fixture
-
resource = Resource.objects.create(
uid="arn:aws:rds:us-west-2:123456789012:db:test-db",
name="Test Database",
@@ -6815,13 +7267,11 @@ class TestResourceViewSet:
mock_cloudtrail_timeline,
mock_initialize_provider,
authenticated_client,
- providers_fixture,
+ aws_provider,
):
"""Test events handles AccessDenied errors from AWS."""
from api.models import Resource
- aws_provider = providers_fixture[0] # AWS provider from fixture
-
resource = Resource.objects.create(
uid="arn:aws:lambda:eu-west-1:123456789012:function:test-func",
name="Test Function",
@@ -6866,13 +7316,11 @@ class TestResourceViewSet:
mock_cloudtrail_timeline,
mock_initialize_provider,
authenticated_client,
- providers_fixture,
+ aws_provider,
):
"""Test events handles generic AWS API errors as 503."""
from api.models import Resource
- aws_provider = providers_fixture[0] # AWS provider from fixture
-
resource = Resource.objects.create(
uid="arn:aws:lambda:eu-west-1:123456789012:function:test-func2",
name="Test Function 2",
@@ -6915,7 +7363,7 @@ class TestResourceViewSet:
self,
mock_initialize_provider,
authenticated_client,
- providers_fixture,
+ aws_provider,
):
"""Test events handles AWSAssumeRoleError during provider init.
@@ -6927,8 +7375,6 @@ class TestResourceViewSet:
from api.models import Resource
from prowler.providers.aws.exceptions.exceptions import AWSAssumeRoleError
- aws_provider = providers_fixture[0] # AWS provider from fixture
-
resource = Resource.objects.create(
uid="arn:aws:lambda:eu-west-1:123456789012:function:assume-role-test",
name="AssumeRole Test Function",
@@ -6972,7 +7418,7 @@ class TestResourceViewSet:
assert error["status"] == "502"
assert "detail" in error
- def test_events_unauthenticated_returns_401(self, providers_fixture):
+ def test_events_unauthenticated_returns_401(self, aws_provider):
"""Test events endpoint returns 401 when no credentials are provided.
This ensures the endpoint follows API conventions where missing authentication
@@ -6981,8 +7427,6 @@ class TestResourceViewSet:
from api.models import Resource
from rest_framework.test import APIClient
- aws_provider = providers_fixture[0] # AWS provider from fixture
-
resource = Resource.objects.create(
uid="arn:aws:ec2:us-east-1:123456789012:instance/i-unauth-test",
name="Test Instance",
@@ -7045,7 +7489,7 @@ class TestResourceViewSet:
# RLS hides resources from other tenants - should appear as not found
assert response.status_code == status.HTTP_404_NOT_FOUND
- def test_events_expired_token_returns_401(self, providers_fixture, tenants_fixture):
+ def test_events_expired_token_returns_401(self, aws_provider, tenants_fixture):
"""Test events endpoint returns 401 when JWT token is expired.
Expired tokens should return 401 Unauthorized, not 404 Not Found.
@@ -7055,8 +7499,6 @@ class TestResourceViewSet:
from api.models import Resource
from rest_framework.test import APIClient
- aws_provider = providers_fixture[0]
-
resource = Resource.objects.create(
uid="arn:aws:ec2:us-east-1:123456789012:instance/i-expired-test",
name="Test Instance",
@@ -7092,7 +7534,7 @@ class TestResourceViewSet:
"Expired tokens should return 401, not 404."
)
- def test_events_invalid_token_returns_401(self, providers_fixture):
+ def test_events_invalid_token_returns_401(self, aws_provider):
"""Test events endpoint returns 401 when JWT token is completely invalid.
Malformed or invalid tokens should return 401 Unauthorized, not 404 Not Found.
@@ -7100,8 +7542,6 @@ class TestResourceViewSet:
from api.models import Resource
from rest_framework.test import APIClient
- aws_provider = providers_fixture[0]
-
resource = Resource.objects.create(
uid="arn:aws:ec2:us-east-1:123456789012:instance/i-invalid-test",
name="Test Instance",
@@ -7155,6 +7595,26 @@ class TestFindingViewSet:
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json()["errors"][0]["code"] == "invalid"
+ def test_findings_updated_at_range_too_large_with_inserted_at_filter(
+ self, authenticated_client
+ ):
+ response = authenticated_client.get(
+ reverse("finding-list"),
+ {
+ "filter[inserted_at]": TODAY,
+ "filter[updated_at.gte]": today_after_n_days(
+ -(settings.FINDINGS_MAX_DAYS_IN_RANGE + 1)
+ ),
+ "filter[updated_at.lte]": TODAY,
+ },
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["errors"][0]["code"] == "invalid"
+ assert response.json()["errors"][0]["source"]["pointer"] == (
+ "/data/attributes/updated_at"
+ )
+
def test_findings_list(self, authenticated_client, findings_fixture):
response = authenticated_client.get(
reverse("finding-list"), {"filter[inserted_at]": TODAY}
@@ -7166,6 +7626,170 @@ class TestFindingViewSet:
== findings_fixture[0].status
)
+ def test_findings_list_inserted_at_accepts_timestamp_precision_filters(
+ self, authenticated_client, scans_fixture
+ ):
+ scan, *_ = scans_fixture
+
+ def create_finding(uid, inserted_at):
+ finding = Finding.objects.create(
+ id=datetime_to_uuid7(inserted_at),
+ tenant_id=scan.tenant_id,
+ uid=uid,
+ scan=scan,
+ status=Status.FAIL,
+ status_extended="timestamp precision status",
+ impact=Severity.medium,
+ severity=Severity.medium,
+ check_id="timestamp_precision_check",
+ check_metadata={
+ "CheckId": "timestamp_precision_check",
+ "Description": "timestamp precision check",
+ "servicename": "ec2",
+ },
+ first_seen_at=inserted_at,
+ )
+ Finding.all_objects.filter(pk=finding.pk).update(
+ inserted_at=inserted_at,
+ updated_at=inserted_at,
+ )
+ finding.refresh_from_db()
+ return finding
+
+ create_finding(
+ "timestamp_precision_early",
+ datetime(2026, 1, 15, 10, 30, 0, 100000, tzinfo=UTC),
+ )
+ late_finding = create_finding(
+ "timestamp_precision_late",
+ datetime(2026, 1, 15, 10, 30, 0, 200000, tzinfo=UTC),
+ )
+
+ response = authenticated_client.get(
+ reverse("finding-list"),
+ {
+ "filter[inserted_at.gte]": "2026-01-15T10:30:00.150Z",
+ "filter[inserted_at.lte]": "2026-01-15T10:30:00.250Z",
+ },
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ returned_uids = {
+ finding["attributes"]["uid"] for finding in response.json()["data"]
+ }
+ assert returned_uids == {late_finding.uid}
+
+ response = authenticated_client.get(
+ reverse("finding-list"),
+ {"filter[inserted_at]": "2026-01-15T10:30:00.200Z"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ returned_uids = {
+ finding["attributes"]["uid"] for finding in response.json()["data"]
+ }
+ assert returned_uids == {late_finding.uid}
+
+ def test_findings_list_updated_at_accepts_timestamp_precision_filters(
+ self, authenticated_client, findings_fixture
+ ):
+ early_finding, late_finding, *_ = findings_fixture
+ early_updated_at = datetime(2026, 1, 15, 10, 30, 0, 100000, tzinfo=UTC)
+ late_updated_at = datetime(2026, 1, 15, 10, 30, 0, 200000, tzinfo=UTC)
+ Finding.all_objects.filter(pk=early_finding.pk).update(
+ updated_at=early_updated_at
+ )
+ Finding.all_objects.filter(pk=late_finding.pk).update(
+ updated_at=late_updated_at
+ )
+
+ response = authenticated_client.get(
+ reverse("finding-list"),
+ {
+ "filter[updated_at.gte]": "2026-01-15T10:30:00.150Z",
+ "filter[updated_at.lte]": "2026-01-15T10:30:00.250Z",
+ },
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ returned_uids = {
+ finding["attributes"]["uid"] for finding in response.json()["data"]
+ }
+ assert returned_uids == {late_finding.uid}
+
+ response = authenticated_client.get(
+ reverse("finding-list"),
+ {"filter[updated_at]": "2026-01-15T10:30:00.200Z"},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ returned_uids = {
+ finding["attributes"]["uid"] for finding in response.json()["data"]
+ }
+ assert returned_uids == {late_finding.uid}
+
+ def test_findings_list_inserted_at_and_updated_at_filters_are_combined(
+ self, authenticated_client, scans_fixture
+ ):
+ scan, *_ = scans_fixture
+
+ def create_finding(uid, inserted_at, updated_at):
+ finding = Finding.objects.create(
+ id=datetime_to_uuid7(inserted_at),
+ tenant_id=scan.tenant_id,
+ uid=uid,
+ scan=scan,
+ status=Status.FAIL,
+ status_extended="timestamp precision status",
+ impact=Severity.medium,
+ severity=Severity.medium,
+ check_id="timestamp_precision_check",
+ check_metadata={
+ "CheckId": "timestamp_precision_check",
+ "Description": "timestamp precision check",
+ "servicename": "ec2",
+ },
+ first_seen_at=inserted_at,
+ )
+ Finding.all_objects.filter(pk=finding.pk).update(
+ inserted_at=inserted_at,
+ updated_at=updated_at,
+ )
+ finding.refresh_from_db()
+ return finding
+
+ matching_finding = create_finding(
+ "timestamp_precision_combined_match",
+ datetime(2026, 1, 15, 10, 30, 0, 200000, tzinfo=UTC),
+ datetime(2026, 1, 15, 11, 30, 0, 200000, tzinfo=UTC),
+ )
+ create_finding(
+ "timestamp_precision_combined_inserted_only",
+ datetime(2026, 1, 15, 10, 30, 0, 200000, tzinfo=UTC),
+ datetime(2026, 1, 15, 12, 30, 0, 200000, tzinfo=UTC),
+ )
+ create_finding(
+ "timestamp_precision_combined_updated_only",
+ datetime(2026, 1, 15, 9, 30, 0, 200000, tzinfo=UTC),
+ datetime(2026, 1, 15, 11, 30, 0, 200000, tzinfo=UTC),
+ )
+
+ response = authenticated_client.get(
+ reverse("finding-list"),
+ {
+ "filter[inserted_at.gte]": "2026-01-15T10:30:00.150Z",
+ "filter[inserted_at.lte]": "2026-01-15T10:30:00.250Z",
+ "filter[updated_at.gte]": "2026-01-15T11:30:00.150Z",
+ "filter[updated_at.lte]": "2026-01-15T11:30:00.250Z",
+ },
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ returned_uids = {
+ finding["attributes"]["uid"] for finding in response.json()["data"]
+ }
+ assert returned_uids == {matching_finding.uid}
+
def test_findings_list_resource_tags_no_n_plus_one(
self, authenticated_client, findings_fixture
):
@@ -7548,9 +8172,8 @@ class TestFindingViewSet:
)
assert response.status_code == status.HTTP_404_NOT_FOUND
- def test_findings_metadata_retrieve(
- self, authenticated_client, findings_fixture, backfill_scan_metadata_fixture
- ):
+ @pytest.mark.usefixtures("backfill_scan_metadata_fixture")
+ def test_findings_metadata_retrieve(self, authenticated_client, findings_fixture):
finding_1, *_ = findings_fixture
response = authenticated_client.get(
reverse("finding-metadata"),
@@ -7573,8 +8196,9 @@ class TestFindingViewSet:
)
# assert data["data"]["attributes"]["tags"] == expected_tags
+ @pytest.mark.usefixtures("backfill_scan_metadata_fixture")
def test_findings_metadata_resource_filter_retrieve(
- self, authenticated_client, findings_fixture, backfill_scan_metadata_fixture
+ self, authenticated_client, findings_fixture
):
finding_1, *_ = findings_fixture
response = authenticated_client.get(
@@ -7631,6 +8255,23 @@ class TestFindingViewSet:
]
}
+ @pytest.mark.parametrize(
+ "filter_name",
+ ["inserted_at", "inserted_at.gte", "inserted_at.lte"],
+ )
+ def test_findings_metadata_rejects_timestamp_precision_filters(
+ self, authenticated_client, filter_name
+ ):
+ response = authenticated_client.get(
+ reverse("finding-metadata"),
+ {f"filter[{filter_name}]": "2048-01-01T10:30:00Z"},
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ error = response.json()["errors"][0]
+ assert error["detail"] == "Enter a valid date."
+ assert error["code"] == "invalid"
+
def test_findings_metadata_backfill(
self, authenticated_client, scans_fixture, findings_fixture
):
@@ -7743,9 +8384,8 @@ class TestFindingViewSet:
attributes = response.json()["data"]["attributes"]
assert set(attributes["categories"]) == {"gen-ai", "security"}
- def test_findings_metadata_latest_categories(
- self, authenticated_client, latest_scan_finding_with_categories
- ):
+ @pytest.mark.usefixtures("latest_scan_finding_with_categories")
+ def test_findings_metadata_latest_categories(self, authenticated_client):
response = authenticated_client.get(
reverse("finding-metadata_latest"),
)
@@ -7753,9 +8393,8 @@ class TestFindingViewSet:
attributes = response.json()["data"]["attributes"]
assert set(attributes["categories"]) == {"gen-ai", "iam"}
- def test_findings_metadata_latest_groups(
- self, authenticated_client, latest_scan_finding_with_categories
- ):
+ @pytest.mark.usefixtures("latest_scan_finding_with_categories")
+ def test_findings_metadata_latest_groups(self, authenticated_client):
response = authenticated_client.get(
reverse("finding-metadata_latest"),
)
@@ -7856,11 +8495,17 @@ class TestFindingViewSet:
@pytest.mark.django_db
class TestJWTFields:
- def test_jwt_fields(self, authenticated_client, create_test_user):
- data = {"type": "tokens", "email": TEST_USER, "password": TEST_PASSWORD}
- response = authenticated_client.post(
- reverse("token-obtain"), data, format="json"
- )
+ def test_jwt_fields(self, create_test_user, tenants_fixture):
+ from rest_framework.test import APIClient
+
+ client = APIClient()
+ data = {
+ "data": {
+ "type": "tokens",
+ "attributes": {"email": TEST_USER, "password": TEST_PASSWORD},
+ }
+ }
+ response = client.post(reverse("token-obtain"), data, format="vnd.api+json")
assert response.status_code == status.HTTP_200_OK, (
f"Unexpected status code: {response.status_code}"
@@ -8275,16 +8920,14 @@ class TestInvitationViewSet:
expires_at=self.TOMORROW,
)
- data = {
- "invitation_token": invitation.token,
- }
+ data = {"invitation_token": invitation.token}
assert not Membership.objects.filter(
user__email__iexact=user.email, tenant=tenant
).exists()
response = authenticated_client.post(
- reverse("invitation-accept"), data=data, format="json"
+ reverse("invitation-accept"), data=data, format="vnd.api+json"
)
assert response.status_code == status.HTTP_201_CREATED
invitation.refresh_from_db()
@@ -8293,13 +8936,46 @@ class TestInvitationViewSet:
).exists()
assert invitation.state == Invitation.State.ACCEPTED.value
- def test_invitations_accept_invitation_invalid_token(self, authenticated_client):
- data = {
- "invitation_token": "invalid_token",
- }
+ def test_invitations_accept_invitation_existing_membership(
+ self,
+ authenticated_client,
+ create_test_user,
+ tenants_fixture,
+ ):
+ *_, tenant = tenants_fixture
+ user = create_test_user
+
+ invitation = Invitation.objects.create(
+ tenant=tenant,
+ email=TEST_USER,
+ inviter=user,
+ expires_at=self.TOMORROW,
+ )
+ Membership.objects.create(user=user, tenant=tenant)
+
+ data = {"invitation_token": invitation.token}
response = authenticated_client.post(
- reverse("invitation-accept"), data=data, format="json"
+ reverse("invitation-accept"),
+ data=data,
+ format="vnd.api+json",
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED
+ invitation.refresh_from_db()
+ assert invitation.state == Invitation.State.ACCEPTED.value
+ assert (
+ Membership.objects.filter(
+ user__email__iexact=user.email, tenant=tenant
+ ).count()
+ == 1
+ )
+
+ def test_invitations_accept_invitation_invalid_token(self, authenticated_client):
+ data = {"invitation_token": "invalid_token"}
+
+ response = authenticated_client.post(
+ reverse("invitation-accept"), data=data, format="vnd.api+json"
)
assert response.status_code == status.HTTP_404_NOT_FOUND
@@ -8313,12 +8989,10 @@ class TestInvitationViewSet:
invitation.email = TEST_USER
invitation.save()
- data = {
- "invitation_token": invitation.token,
- }
+ data = {"invitation_token": invitation.token}
response = authenticated_client.post(
- reverse("invitation-accept"), data=data, format="json"
+ reverse("invitation-accept"), data=data, format="vnd.api+json"
)
assert response.status_code == status.HTTP_410_GONE
@@ -8354,12 +9028,10 @@ class TestInvitationViewSet:
invitation.email = TEST_USER
invitation.save()
- data = {
- "invitation_token": invitation.token,
- }
+ data = {"invitation_token": invitation.token}
response = authenticated_client.post(
- reverse("invitation-accept"), data=data, format="json"
+ reverse("invitation-accept"), data=data, format="vnd.api+json"
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
@@ -8377,12 +9049,10 @@ class TestInvitationViewSet:
invitation.email = TEST_USER
invitation.save()
- data = {
- "invitation_token": invitation.token,
- }
+ data = {"invitation_token": invitation.token}
response = authenticated_client.post(
- reverse("invitation-accept"), data=data, format="json"
+ reverse("invitation-accept"), data=data, format="vnd.api+json"
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
@@ -8901,20 +9571,22 @@ class TestUserRoleRelationshipViewSet:
assert added_role_ids.issubset(relationship_role_ids)
def test_create_relationship_already_exists(
- self, authenticated_client, roles_fixture, create_test_user
+ self, authenticated_client, roles_fixture, create_test_user_rbac_no_roles
):
- # Only add Role One (which has manage_account=True) to ensure
- # the second request has permission to add roles
data = {
"data": [
- {"type": "roles", "id": str(roles_fixture[0].id)},
+ {"type": "roles", "id": str(role.id)} for role in roles_fixture[:2]
]
}
- authenticated_client.post(
- reverse("user-roles-relationship", kwargs={"pk": create_test_user.id}),
+ setup_response = authenticated_client.post(
+ reverse(
+ "user-roles-relationship",
+ kwargs={"pk": create_test_user_rbac_no_roles.id},
+ ),
data=data,
content_type="application/vnd.api+json",
)
+ assert setup_response.status_code == status.HTTP_204_NO_CONTENT
data = {
"data": [
@@ -8922,7 +9594,10 @@ class TestUserRoleRelationshipViewSet:
]
}
response = authenticated_client.post(
- reverse("user-roles-relationship", kwargs={"pk": create_test_user.id}),
+ reverse(
+ "user-roles-relationship",
+ kwargs={"pk": create_test_user_rbac_no_roles.id},
+ ),
data=data,
content_type="application/vnd.api+json",
)
@@ -8944,9 +9619,15 @@ class TestUserRoleRelationshipViewSet:
content_type="application/vnd.api+json",
)
assert response.status_code == status.HTTP_204_NO_CONTENT
- relationships = UserRoleRelationship.objects.filter(user=create_test_user.id)
+ tenant = roles_fixture[2].tenant
+ relationships = UserRoleRelationship.objects.filter(
+ user=create_test_user.id, tenant=tenant
+ )
assert relationships.count() == 1
assert {rel.role.id for rel in relationships} == {roles_fixture[2].id}
+ assert (
+ UserRoleRelationship.objects.filter(user=create_test_user.id).count() == 2
+ )
data = {
"data": [
@@ -8960,12 +9641,66 @@ class TestUserRoleRelationshipViewSet:
content_type="application/vnd.api+json",
)
assert response.status_code == status.HTTP_204_NO_CONTENT
- relationships = UserRoleRelationship.objects.filter(user=create_test_user.id)
+ relationships = UserRoleRelationship.objects.filter(
+ user=create_test_user.id, tenant=tenant
+ )
assert relationships.count() == 2
assert {rel.role.id for rel in relationships} == {
roles_fixture[1].id,
roles_fixture[2].id,
}
+ assert (
+ UserRoleRelationship.objects.filter(user=create_test_user.id).count() == 3
+ )
+
+ def test_partial_update_relationship_preserves_foreign_tenant_roles(
+ self, authenticated_client, roles_fixture, tenants_fixture
+ ):
+ tenant_a, tenant_b, _ = tenants_fixture
+ tenant_a_role = roles_fixture[1]
+ replacement_role = roles_fixture[2]
+ foreign_role = Role.objects.create(
+ name=f"foreign-role-{uuid4()}",
+ tenant=tenant_b,
+ manage_users=False,
+ manage_account=False,
+ manage_billing=False,
+ manage_providers=False,
+ manage_integrations=False,
+ manage_scans=False,
+ unlimited_visibility=False,
+ )
+ shared_user = User.objects.create_user(
+ name="shared_user",
+ email=f"shared-user-{uuid4()}@prowler.com",
+ password="TmpPass123@",
+ )
+ Membership.objects.create(user=shared_user, tenant=tenant_a)
+ Membership.objects.create(user=shared_user, tenant=tenant_b)
+ UserRoleRelationship.objects.create(
+ user=shared_user, role=tenant_a_role, tenant=tenant_a
+ )
+ UserRoleRelationship.objects.create(
+ user=shared_user, role=foreign_role, tenant=tenant_b
+ )
+
+ data = {"data": [{"type": "roles", "id": str(replacement_role.id)}]}
+ response = authenticated_client.patch(
+ reverse("user-roles-relationship", kwargs={"pk": shared_user.id}),
+ data=data,
+ content_type="application/vnd.api+json",
+ )
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ tenant_a_relationships = UserRoleRelationship.objects.filter(
+ user=shared_user, tenant=tenant_a
+ )
+ assert tenant_a_relationships.count() == 1
+ assert {rel.role_id for rel in tenant_a_relationships} == {replacement_role.id}
+ assert UserRoleRelationship.objects.filter(
+ user=shared_user, tenant=tenant_b, role=foreign_role
+ ).exists()
+ assert UserRoleRelationship.objects.filter(user=shared_user).count() == 2
def test_destroy_relationship_other_user(
self, authenticated_client, roles_fixture, create_test_user, tenants_fixture
@@ -9055,7 +9790,7 @@ class TestUserRoleRelationshipViewSet:
assert response.status_code == status.HTTP_204_NO_CONTENT
def test_role_destroy_only_manage_account_blocked(
- self, authenticated_client, tenants_fixture
+ self, authenticated_client_for_tenant_factory, tenants_fixture
):
# Use a tenant without default admin role (tenant3)
tenant = tenants_fixture[2]
@@ -9077,24 +9812,10 @@ class TestUserRoleRelationshipViewSet:
)
# Assign the role to the user
UserRoleRelationship.objects.create(user=user, role=only_role, tenant=tenant)
-
- # Switch token to this tenant
- serializer = TokenSerializer(
- data={
- "type": "tokens",
- "email": TEST_USER,
- "password": TEST_PASSWORD,
- "tenant_id": str(tenant.id),
- }
- )
- serializer.is_valid(raise_exception=True)
- access_token = serializer.validated_data["access"]
- authenticated_client.defaults["HTTP_AUTHORIZATION"] = f"Bearer {access_token}"
+ client = authenticated_client_for_tenant_factory(user, tenant)
# Attempt to delete the only MANAGE_ACCOUNT role
- response = authenticated_client.delete(
- reverse("role-detail", kwargs={"pk": only_role.id})
- )
+ response = client.delete(reverse("role-detail", kwargs={"pk": only_role.id}))
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert Role.objects.filter(id=only_role.id).exists()
@@ -9251,13 +9972,16 @@ class TestRoleProviderGroupRelationshipViewSet:
@pytest.mark.django_db
class TestProviderGroupMembershipViewSet:
def test_create_relationship(
- self, authenticated_client, providers_fixture, provider_groups_fixture
+ self,
+ authenticated_client,
+ provider_groups_fixture,
+ aws_provider_pair,
):
provider_group, *_ = provider_groups_fixture
data = {
"data": [
{"type": "provider", "id": str(provider.id)}
- for provider in providers_fixture[:2]
+ for provider in aws_provider_pair
]
}
response = authenticated_client.post(
@@ -9274,16 +9998,20 @@ class TestProviderGroupMembershipViewSet:
)
assert relationships.count() == 2
for relationship in relationships:
- assert relationship.provider.id in [p.id for p in providers_fixture[:2]]
+ assert relationship.provider.id in [p.id for p in aws_provider_pair]
def test_create_relationship_already_exists(
- self, authenticated_client, providers_fixture, provider_groups_fixture
+ self,
+ authenticated_client,
+ aws_provider,
+ provider_groups_fixture,
+ aws_provider_pair,
):
provider_group, *_ = provider_groups_fixture
data = {
"data": [
{"type": "provider", "id": str(provider.id)}
- for provider in providers_fixture[:2]
+ for provider in aws_provider_pair
]
}
authenticated_client.post(
@@ -9297,7 +10025,7 @@ class TestProviderGroupMembershipViewSet:
data = {
"data": [
- {"type": "provider", "id": str(providers_fixture[0].id)},
+ {"type": "provider", "id": str(aws_provider.id)},
]
}
response = authenticated_client.post(
@@ -9313,12 +10041,16 @@ class TestProviderGroupMembershipViewSet:
assert "already associated" in errors
def test_partial_update_relationship(
- self, authenticated_client, providers_fixture, provider_groups_fixture
+ self,
+ authenticated_client,
+ provider_groups_fixture,
+ aws_provider_pair,
+ gcp_provider,
):
provider_group, *_ = provider_groups_fixture
data = {
"data": [
- {"type": "provider", "id": str(providers_fixture[1].id)},
+ {"type": "provider", "id": str(aws_provider_pair[1].id)},
]
}
response = authenticated_client.patch(
@@ -9334,12 +10066,12 @@ class TestProviderGroupMembershipViewSet:
provider_group=provider_group.id
)
assert relationships.count() == 1
- assert {rel.provider.id for rel in relationships} == {providers_fixture[1].id}
+ assert {rel.provider.id for rel in relationships} == {aws_provider_pair[1].id}
data = {
"data": [
- {"type": "provider", "id": str(providers_fixture[1].id)},
- {"type": "provider", "id": str(providers_fixture[2].id)},
+ {"type": "provider", "id": str(aws_provider_pair[1].id)},
+ {"type": "provider", "id": str(gcp_provider.id)},
]
}
response = authenticated_client.patch(
@@ -9356,18 +10088,21 @@ class TestProviderGroupMembershipViewSet:
)
assert relationships.count() == 2
assert {rel.provider.id for rel in relationships} == {
- providers_fixture[1].id,
- providers_fixture[2].id,
+ aws_provider_pair[1].id,
+ gcp_provider.id,
}
def test_destroy_relationship(
- self, authenticated_client, providers_fixture, provider_groups_fixture
+ self,
+ authenticated_client,
+ provider_groups_fixture,
+ aws_provider_pair,
):
provider_group, *_ = provider_groups_fixture
data = {
"data": [
{"type": "provider", "id": str(provider.id)}
- for provider in providers_fixture[:2]
+ for provider in aws_provider_pair
]
}
response = authenticated_client.post(
@@ -9387,7 +10122,7 @@ class TestProviderGroupMembershipViewSet:
)
assert response.status_code == status.HTTP_204_NO_CONTENT
relationships = ProviderGroupMembership.objects.filter(
- provider_group=providers_fixture[0].id
+ provider_group=provider_group.id
)
assert relationships.count() == 0
@@ -9480,8 +10215,13 @@ class TestComplianceOverviewViewSet:
assert response.status_code == status.HTTP_200_OK
return {item["id"]: item["attributes"] for item in response.json()["data"]}
- def _prepare_latest_compliance_data(self, providers_fixture):
- provider1, provider2, provider3, *_ = providers_fixture
+ def _prepare_latest_compliance_data(
+ self,
+ aws_provider_pair,
+ gcp_provider,
+ ):
+ provider1, provider2 = aws_provider_pair
+ provider3 = gcp_provider
old_scan = self._create_completed_scan(provider1, "old aws compliance scan")
latest_scan1 = self._create_completed_scan(
provider1, "latest aws compliance scan 1"
@@ -9533,11 +10273,11 @@ class TestComplianceOverviewViewSet:
self,
authenticated_client,
tenants_fixture,
- providers_fixture,
+ aws_provider,
mock_backfill_task,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
scan = Scan.objects.create(
name="empty-compliance-scan",
provider=provider,
@@ -9599,11 +10339,11 @@ class TestComplianceOverviewViewSet:
self,
authenticated_client,
tenants_fixture,
- providers_fixture,
+ aws_provider,
mock_backfill_task,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
scan = Scan.objects.create(
name="preaggregated-scan",
provider=provider,
@@ -9679,10 +10419,13 @@ class TestComplianceOverviewViewSet:
def test_compliance_overview_provider_id_filter_uses_latest_scan(
self,
authenticated_client,
- providers_fixture,
mock_backfill_task,
+ aws_provider_pair,
+ gcp_provider,
):
- _, latest_scan, *_ = self._prepare_latest_compliance_data(providers_fixture)
+ _, latest_scan, *_ = self._prepare_latest_compliance_data(
+ aws_provider_pair, gcp_provider
+ )
response = authenticated_client.get(
reverse("complianceoverview-list"),
@@ -9698,10 +10441,11 @@ class TestComplianceOverviewViewSet:
def test_compliance_overview_provider_id_in_filter_aggregates_latest_scans(
self,
authenticated_client,
- providers_fixture,
+ aws_provider_pair,
+ gcp_provider,
):
_, latest_scan1, latest_scan2, *_ = self._prepare_latest_compliance_data(
- providers_fixture
+ aws_provider_pair, gcp_provider
)
response = authenticated_client.get(
@@ -9722,9 +10466,10 @@ class TestComplianceOverviewViewSet:
def test_compliance_overview_provider_type_filter_uses_latest_scans(
self,
authenticated_client,
- providers_fixture,
+ aws_provider_pair,
+ gcp_provider,
):
- self._prepare_latest_compliance_data(providers_fixture)
+ self._prepare_latest_compliance_data(aws_provider_pair, gcp_provider)
response = authenticated_client.get(
reverse("complianceoverview-list"),
@@ -9740,15 +10485,16 @@ class TestComplianceOverviewViewSet:
def test_compliance_overview_provider_groups_filters_use_latest_scans(
self,
authenticated_client,
- providers_fixture,
provider_groups_fixture,
tenants_fixture,
+ aws_provider_pair,
+ gcp_provider,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
group1, group2, *_ = provider_groups_fixture
_, latest_scan1, latest_scan2, *_ = self._prepare_latest_compliance_data(
- providers_fixture
+ aws_provider_pair, gcp_provider
)
ProviderGroupMembership.objects.create(
tenant_id=tenant.id,
@@ -9814,10 +10560,10 @@ class TestComplianceOverviewViewSet:
def test_compliance_overview_provider_filter_returns_running_task_without_data(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
):
scan = self._create_completed_scan(
- providers_fixture[0], "latest scan without compliance data"
+ aws_provider, "latest scan without compliance data"
)
self._assert_latest_provider_scan_task_response(
@@ -9829,9 +10575,9 @@ class TestComplianceOverviewViewSet:
def test_compliance_overview_provider_filter_returns_running_task_for_partial_data(
self,
authenticated_client,
- providers_fixture,
+ aws_provider_pair,
):
- provider_with_data, provider_without_data, *_ = providers_fixture
+ provider_with_data, provider_without_data = aws_provider_pair
scan_with_data = self._create_completed_scan(
provider_with_data, "latest scan with compliance data"
)
@@ -9854,10 +10600,10 @@ class TestComplianceOverviewViewSet:
def test_compliance_overview_provider_filter_empty_response_uses_scan_data_presence(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
):
scan = self._create_completed_scan(
- providers_fixture[0], "latest scan with filtered compliance data"
+ aws_provider, "latest scan with filtered compliance data"
)
self._create_requirement(scan, "1.1", StatusChoices.PASS, region="eu-west-1")
@@ -9883,10 +10629,10 @@ class TestComplianceOverviewViewSet:
def test_compliance_overview_metadata_provider_filter_returns_running_task_without_data(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
):
scan = self._create_completed_scan(
- providers_fixture[0], "latest scan without compliance metadata"
+ aws_provider, "latest scan without compliance metadata"
)
self._assert_latest_provider_scan_task_response(
@@ -9898,10 +10644,10 @@ class TestComplianceOverviewViewSet:
def test_compliance_overview_requirements_provider_filter_returns_running_task_without_data(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
):
scan = self._create_completed_scan(
- providers_fixture[0], "latest scan without compliance requirements"
+ aws_provider, "latest scan without compliance requirements"
)
self._assert_latest_provider_scan_task_response(
@@ -9914,9 +10660,12 @@ class TestComplianceOverviewViewSet:
def test_compliance_overview_metadata_accepts_provider_filters(
self,
authenticated_client,
- providers_fixture,
+ aws_provider_pair,
+ gcp_provider,
):
- _, latest_scan, *_ = self._prepare_latest_compliance_data(providers_fixture)
+ _, latest_scan, *_ = self._prepare_latest_compliance_data(
+ aws_provider_pair, gcp_provider
+ )
response = authenticated_client.get(
reverse("complianceoverview-metadata"),
@@ -9930,10 +10679,11 @@ class TestComplianceOverviewViewSet:
def test_compliance_overview_requirements_accepts_provider_filters(
self,
authenticated_client,
- providers_fixture,
+ aws_provider_pair,
+ gcp_provider,
):
_, latest_scan1, latest_scan2, *_ = self._prepare_latest_compliance_data(
- providers_fixture
+ aws_provider_pair, gcp_provider
)
response = authenticated_client.get(
@@ -10099,7 +10849,11 @@ class TestComplianceOverviewViewSet:
assert "AWSService" in first_attr
def test_compliance_overview_attributes_resolves_provider_from_scan(
- self, authenticated_client, tenants_fixture, providers_fixture
+ self,
+ authenticated_client,
+ tenants_fixture,
+ gcp_provider,
+ azure_provider,
):
# csa_ccm_4.0 is a multi-provider universal framework: a single
# compliance_id whose requirements expose different checks per provider.
@@ -10108,8 +10862,6 @@ class TestComplianceOverviewViewSet:
# framework and azure/gcp requirements end up with check IDs that match
# no findings.
tenant = tenants_fixture[0]
- gcp_provider = providers_fixture[2]
- azure_provider = providers_fixture[4]
assert gcp_provider.provider == Provider.ProviderChoices.GCP.value
assert azure_provider.provider == Provider.ProviderChoices.AZURE.value
@@ -10210,7 +10962,8 @@ class TestComplianceOverviewViewSet:
def test_compliance_overview_attributes_scan_scoped_by_provider_group(
self,
authenticated_client_no_permissions_rbac,
- providers_fixture,
+ gcp_provider,
+ azure_provider,
):
# A user with limited visibility (no UNLIMITED_VISIBILITY) must only be
# able to resolve scans for providers in its provider groups. Tenant RLS
@@ -10222,8 +10975,8 @@ class TestComplianceOverviewViewSet:
membership = Membership.objects.filter(user=limited_user).first()
tenant = membership.tenant
- allowed_provider = providers_fixture[2]
- denied_provider = providers_fixture[4]
+ allowed_provider = gcp_provider
+ denied_provider = azure_provider
assert allowed_provider.provider == Provider.ProviderChoices.GCP.value
assert denied_provider.provider == Provider.ProviderChoices.AZURE.value
@@ -10458,9 +11211,8 @@ class TestOverviewViewSet:
response = authenticated_client.put(reverse("overview-list"))
assert response.status_code == status.HTTP_405_METHOD_NOT_ALLOWED
- def test_overview_providers_list(
- self, authenticated_client, scan_summaries_fixture, resources_fixture
- ):
+ @pytest.mark.usefixtures("scan_summaries_fixture")
+ def test_overview_providers_list(self, authenticated_client, resources_fixture):
response = authenticated_client.get(reverse("overview-providers"))
assert response.status_code == status.HTTP_200_OK
assert len(response.json()["data"]) == 1
@@ -10471,16 +11223,16 @@ class TestOverviewViewSet:
# Aggregated resources include all AWS providers present in the tenant
assert response.json()["data"][0]["attributes"]["resources"]["total"] == 3
+ @pytest.mark.usefixtures("scan_summaries_fixture")
def test_overview_providers_aggregates_same_provider_type(
self,
authenticated_client,
- scan_summaries_fixture,
resources_fixture,
- providers_fixture,
tenants_fixture,
+ aws_provider_pair,
):
tenant = tenants_fixture[0]
- _provider1, provider2, *_ = providers_fixture
+ _provider1, provider2 = aws_provider_pair
scan = Scan.objects.create(
name="overview scan aws account 2",
@@ -10525,12 +11277,12 @@ class TestOverviewViewSet:
assert attributes["findings"]["muted"] == 7
assert attributes["resources"]["total"] == 4
+ @pytest.mark.usefixtures("scan_summaries_fixture")
def test_overview_providers_count(
self,
authenticated_client,
- scan_summaries_fixture,
resources_fixture,
- providers_fixture,
+ aws_provider,
tenants_fixture,
):
tenant = tenants_fixture[0]
@@ -10562,14 +11314,15 @@ class TestOverviewViewSet:
def test_overview_providers_count_applies_limited_visibility(
self,
authenticated_client_no_permissions_rbac,
- providers_fixture,
provider_groups_fixture,
tenants_fixture,
+ gcp_provider,
+ azure_provider,
):
tenant = tenants_fixture[0]
client = authenticated_client_no_permissions_rbac
- allowed_provider = providers_fixture[2]
- denied_provider = providers_fixture[4]
+ allowed_provider = gcp_provider
+ denied_provider = azure_provider
provider_group = provider_groups_fixture[0]
ProviderGroupMembership.objects.create(
@@ -10643,10 +11396,13 @@ class TestOverviewViewSet:
)
def test_overview_threatscore_returns_weighted_aggregate_snapshot(
- self, authenticated_client, tenants_fixture, providers_fixture
+ self,
+ authenticated_client,
+ tenants_fixture,
+ aws_provider_pair,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
scan1 = self._create_scan(tenant, provider1, "agg-scan-one")
scan2 = self._create_scan(tenant, provider2, "agg-scan-two")
@@ -10816,10 +11572,13 @@ class TestOverviewViewSet:
assert attrs["critical_requirements"] == expected_critical
def test_overview_threatscore_weight_fallback_to_requirements(
- self, authenticated_client, tenants_fixture, providers_fixture
+ self,
+ authenticated_client,
+ tenants_fixture,
+ aws_provider_pair,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
scan1 = self._create_scan(tenant, provider1, "fallback-scan-1")
scan2 = self._create_scan(tenant, provider2, "fallback-scan-2")
@@ -10871,10 +11630,13 @@ class TestOverviewViewSet:
assert aggregate["section_scores"] == {"1. IAM": "62.22"}
def test_overview_threatscore_filter_by_scan_id_returns_snapshot(
- self, authenticated_client, tenants_fixture, providers_fixture
+ self,
+ authenticated_client,
+ tenants_fixture,
+ aws_provider,
):
tenant = tenants_fixture[0]
- provider1, *_ = providers_fixture
+ provider1 = aws_provider
scan = self._create_scan(tenant, provider1, "filter-scan")
snapshot = self._create_threatscore_snapshot(
@@ -10906,10 +11668,13 @@ class TestOverviewViewSet:
assert body["data"][0]["attributes"]["overall_score"] == "75.00"
def test_overview_threatscore_snapshot_id_returns_specific_snapshot(
- self, authenticated_client, tenants_fixture, providers_fixture
+ self,
+ authenticated_client,
+ tenants_fixture,
+ aws_provider,
):
tenant = tenants_fixture[0]
- provider1, *_ = providers_fixture
+ provider1 = aws_provider
scan = self._create_scan(tenant, provider1, "snapshot-id-scan")
snapshot = self._create_threatscore_snapshot(
@@ -10940,10 +11705,13 @@ class TestOverviewViewSet:
assert data["data"]["attributes"]["score_delta"] is None
def test_overview_threatscore_provider_filter_returns_unaggregated_snapshot(
- self, authenticated_client, tenants_fixture, providers_fixture
+ self,
+ authenticated_client,
+ tenants_fixture,
+ aws_provider_pair,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
scan1 = self._create_scan(tenant, provider1, "provider-filter-scan-1")
scan2 = self._create_scan(tenant, provider2, "provider-filter-scan-2")
@@ -10994,15 +11762,15 @@ class TestOverviewViewSet:
assert data[0]["id"] == str(snapshot1.id)
assert data[0]["attributes"]["overall_score"] == "55.55"
- def test_overview_services_list_no_required_filters(
- self, authenticated_client, scan_summaries_fixture
- ):
+ @pytest.mark.usefixtures("scan_summaries_fixture")
+ def test_overview_services_list_no_required_filters(self, authenticated_client):
response = authenticated_client.get(reverse("overview-services"))
assert response.status_code == status.HTTP_200_OK
# Should return services from latest scans
assert len(response.json()["data"]) == 2
- def test_overview_regions_list(self, authenticated_client, scan_summaries_fixture):
+ @pytest.mark.usefixtures("scan_summaries_fixture")
+ def test_overview_regions_list(self, authenticated_client):
response = authenticated_client.get(
reverse("overview-regions"), {"filter[inserted_at]": TODAY}
)
@@ -11028,7 +11796,8 @@ class TestOverviewViewSet:
assert regions["aws:region2"]["fail"] == 1
assert regions["aws:region2"]["muted"] == 3
- def test_overview_services_list(self, authenticated_client, scan_summaries_fixture):
+ @pytest.mark.usefixtures("scan_summaries_fixture")
+ def test_overview_services_list(self, authenticated_client):
response = authenticated_client.get(
reverse("overview-services"), {"filter[inserted_at]": TODAY}
)
@@ -11054,10 +11823,13 @@ class TestOverviewViewSet:
assert service2_data["attributes"]["muted"] == 1
def test_overview_findings_provider_id_in_filter(
- self, authenticated_client, tenants_fixture, providers_fixture
+ self,
+ authenticated_client,
+ tenants_fixture,
+ aws_provider_pair,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
scan1 = Scan.objects.create(
name="scan-one",
@@ -11144,11 +11916,11 @@ class TestOverviewViewSet:
self,
authenticated_client,
tenants_fixture,
- providers_fixture,
provider_groups_fixture,
+ aws_provider_pair,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
group1, group2, *_ = provider_groups_fixture
ProviderGroupMembership.objects.create(
tenant=tenant, provider=provider1, provider_group=group1
@@ -11222,10 +11994,13 @@ class TestOverviewViewSet:
assert attributes["total"] == 14
def test_overview_findings_severity_provider_id_in_filter(
- self, authenticated_client, tenants_fixture, providers_fixture
+ self,
+ authenticated_client,
+ tenants_fixture,
+ aws_provider_pair,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
scan1 = Scan.objects.create(
name="severity-scan-one",
@@ -11345,10 +12120,13 @@ class TestOverviewViewSet:
assert item["attributes"]["scan_ids"] == []
def test_overview_findings_severity_timeseries_with_data(
- self, authenticated_client, tenants_fixture, providers_fixture
+ self,
+ authenticated_client,
+ tenants_fixture,
+ aws_provider_pair,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
# Create scan for day 1
scan1 = Scan.objects.create(
@@ -11428,10 +12206,13 @@ class TestOverviewViewSet:
assert data[2]["attributes"]["scan_ids"] == [str(scan3.id)]
def test_overview_findings_severity_timeseries_aggregates_providers(
- self, authenticated_client, tenants_fixture, providers_fixture
+ self,
+ authenticated_client,
+ tenants_fixture,
+ aws_provider_pair,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
# Same day, different providers
scan1 = Scan.objects.create(
@@ -11501,10 +12282,13 @@ class TestOverviewViewSet:
assert set(data[0]["attributes"]["scan_ids"]) == {str(scan1.id), str(scan2.id)}
def test_overview_findings_severity_timeseries_provider_filter(
- self, authenticated_client, tenants_fixture, providers_fixture
+ self,
+ authenticated_client,
+ tenants_fixture,
+ aws_provider_pair,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
scan1 = Scan.objects.create(
name="severity-over-time-filter-scan-p1",
@@ -11580,11 +12364,11 @@ class TestOverviewViewSet:
self,
authenticated_client,
tenants_fixture,
- providers_fixture,
+ aws_provider,
create_attack_surface_overview,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
scan = Scan.objects.create(
name="attack-surface-scan",
@@ -11628,11 +12412,11 @@ class TestOverviewViewSet:
self,
authenticated_client,
tenants_fixture,
- providers_fixture,
create_attack_surface_overview,
+ aws_provider_pair,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
scan1 = Scan.objects.create(
name="attack-surface-scan-1",
@@ -11676,9 +12460,8 @@ class TestOverviewViewSet:
assert results_by_type["internet-exposed"]["total_findings"] == 10
assert results_by_type["internet-exposed"]["failed_findings"] == 5
- def test_overview_services_region_filter(
- self, authenticated_client, scan_summaries_fixture
- ):
+ @pytest.mark.usefixtures("scan_summaries_fixture")
+ def test_overview_services_region_filter(self, authenticated_client):
response = authenticated_client.get(
reverse("overview-services"),
{"filter[region]": "region1"},
@@ -11690,10 +12473,13 @@ class TestOverviewViewSet:
assert service_ids == {"service1", "service2"}
def test_overview_services_provider_type_filter(
- self, authenticated_client, tenants_fixture, providers_fixture
+ self,
+ authenticated_client,
+ tenants_fixture,
+ aws_provider,
+ gcp_provider,
):
tenant = tenants_fixture[0]
- aws_provider, _, gcp_provider, *_ = providers_fixture
aws_scan = Scan.objects.create(
name="aws-scan",
@@ -11746,7 +12532,7 @@ class TestOverviewViewSet:
assert "gcp-service" not in service_ids
@pytest.mark.parametrize(
- "status_filter,field_to_check",
+ "status_filter,_field_to_check",
[
("FAIL", "fail"),
("PASS", "_pass"),
@@ -11756,12 +12542,12 @@ class TestOverviewViewSet:
self,
authenticated_client,
tenants_fixture,
- providers_fixture,
+ aws_provider,
status_filter,
- field_to_check,
+ _field_to_check,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
scan = Scan.objects.create(
name="status-filter-scan",
@@ -11813,10 +12599,13 @@ class TestOverviewViewSet:
assert attrs["medium"] == 8
def test_overview_threatscore_compliance_id_filter(
- self, authenticated_client, tenants_fixture, providers_fixture
+ self,
+ authenticated_client,
+ tenants_fixture,
+ aws_provider,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
scan = self._create_scan(tenant, provider, "compliance-filter-scan")
self._create_threatscore_snapshot(
@@ -11865,10 +12654,13 @@ class TestOverviewViewSet:
assert data[0]["attributes"]["compliance_id"] == "prowler_threatscore_aws"
def test_overview_threatscore_provider_type_filter(
- self, authenticated_client, tenants_fixture, providers_fixture
+ self,
+ authenticated_client,
+ tenants_fixture,
+ aws_provider,
+ gcp_provider,
):
tenant = tenants_fixture[0]
- aws_provider, _, gcp_provider, *_ = providers_fixture
aws_scan = self._create_scan(tenant, aws_provider, "aws-threatscore-scan")
gcp_scan = self._create_scan(tenant, gcp_provider, "gcp-threatscore-scan")
@@ -11926,11 +12718,11 @@ class TestOverviewViewSet:
self,
authenticated_client,
tenants_fixture,
- providers_fixture,
+ aws_provider,
create_scan_category_summary,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
scan = Scan.objects.create(
name="categories-scan",
@@ -12010,16 +12802,17 @@ class TestOverviewViewSet:
self,
authenticated_client,
tenants_fixture,
- providers_fixture,
+ aws_provider,
provider_groups_fixture,
create_scan_category_summary,
filter_key,
filter_value_fn,
expected_total,
expected_failed,
+ gcp_provider,
):
tenant = tenants_fixture[0]
- provider1, _, gcp_provider, *_ = providers_fixture
+ provider1 = aws_provider
group1, group2, *_ = provider_groups_fixture
ProviderGroupMembership.objects.create(
tenant=tenant, provider=provider1, provider_group=group1
@@ -12067,11 +12860,11 @@ class TestOverviewViewSet:
self,
authenticated_client,
tenants_fixture,
- providers_fixture,
+ aws_provider,
create_scan_category_summary,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
scan = Scan.objects.create(
name="category-filter-scan",
@@ -12104,11 +12897,11 @@ class TestOverviewViewSet:
self,
authenticated_client,
tenants_fixture,
- providers_fixture,
create_scan_category_summary,
+ aws_provider_pair,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
scan1 = Scan.objects.create(
name="multi-provider-scan-1",
@@ -12162,11 +12955,11 @@ class TestOverviewViewSet:
self,
authenticated_client,
tenants_fixture,
- providers_fixture,
+ aws_provider,
create_scan_resource_group_summary,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
scan = Scan.objects.create(
name="resource-groups-scan",
@@ -12251,17 +13044,17 @@ class TestOverviewViewSet:
self,
authenticated_client,
tenants_fixture,
- providers_fixture,
+ aws_provider,
provider_groups_fixture,
create_scan_resource_group_summary,
filter_key,
filter_value_fn,
expected_total,
expected_failed,
+ gcp_provider,
):
tenant = tenants_fixture[0]
- provider1 = providers_fixture[0] # AWS
- gcp_provider = providers_fixture[2] # GCP
+ provider1 = aws_provider # AWS
group1, group2, *_ = provider_groups_fixture
ProviderGroupMembership.objects.create(
tenant=tenant, provider=provider1, provider_group=group1
@@ -12309,11 +13102,11 @@ class TestOverviewViewSet:
self,
authenticated_client,
tenants_fixture,
- providers_fixture,
+ aws_provider,
create_scan_resource_group_summary,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
scan = Scan.objects.create(
name="rg-filter-scan",
@@ -12346,11 +13139,11 @@ class TestOverviewViewSet:
self,
authenticated_client,
tenants_fixture,
- providers_fixture,
create_scan_resource_group_summary,
+ aws_provider_pair,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
scan1 = Scan.objects.create(
name="multi-provider-rg-scan-1",
@@ -12398,8 +13191,9 @@ class TestOverviewViewSet:
assert data[0]["attributes"]["new_failed_findings"] == 5
assert data[0]["attributes"]["resources_count"] == 10
+ @pytest.mark.usefixtures("tenant_compliance_summary_fixture")
def test_compliance_watchlist_no_filters_uses_tenant_summary(
- self, authenticated_client, tenant_compliance_summary_fixture
+ self, authenticated_client
):
response = authenticated_client.get(reverse("overview-compliance-watchlist"))
assert response.status_code == status.HTTP_200_OK
@@ -12419,13 +13213,13 @@ class TestOverviewViewSet:
assert by_id["gdpr_aws"]["requirements_failed"] == 0
assert by_id["gdpr_aws"]["total_requirements"] == 7
+ @pytest.mark.usefixtures("provider_compliance_scores_fixture")
def test_compliance_watchlist_with_provider_filter_uses_provider_scores(
self,
authenticated_client,
- provider_compliance_scores_fixture,
- providers_fixture,
+ aws_provider,
):
- provider1 = providers_fixture[0]
+ provider1 = aws_provider
url = f"{reverse('overview-compliance-watchlist')}?filter[provider_id]={provider1.id}"
response = authenticated_client.get(url)
assert response.status_code == status.HTTP_200_OK
@@ -12439,9 +13233,8 @@ class TestOverviewViewSet:
assert by_id["aws_cis_2.0"]["requirements_manual"] == 1
assert by_id["aws_cis_2.0"]["total_requirements"] == 3
- def test_compliance_watchlist_fail_dominant_logic(
- self, authenticated_client, provider_compliance_scores_fixture
- ):
+ @pytest.mark.usefixtures("provider_compliance_scores_fixture")
+ def test_compliance_watchlist_fail_dominant_logic(self, authenticated_client):
response = authenticated_client.get(
f"{reverse('overview-compliance-watchlist')}?filter[provider_type]=aws"
)
@@ -12456,13 +13249,13 @@ class TestOverviewViewSet:
assert aws_cis["requirements_manual"] == 1
assert aws_cis["total_requirements"] == 3
+ @pytest.mark.usefixtures("provider_compliance_scores_fixture")
def test_compliance_watchlist_provider_id_in_filter(
self,
authenticated_client,
- provider_compliance_scores_fixture,
- providers_fixture,
+ aws_provider_pair,
):
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
url = (
f"{reverse('overview-compliance-watchlist')}"
f"?filter[provider_id__in]={provider1.id},{provider2.id}"
@@ -12472,16 +13265,16 @@ class TestOverviewViewSet:
data = response.json()["data"]
assert len(data) >= 1
+ @pytest.mark.usefixtures("provider_compliance_scores_fixture")
def test_compliance_watchlist_provider_groups_filter(
self,
authenticated_client,
- provider_compliance_scores_fixture,
- providers_fixture,
provider_groups_fixture,
tenants_fixture,
+ aws_provider_pair,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
group1, group2, *_ = provider_groups_fixture
ProviderGroupMembership.objects.create(
tenant=tenant, provider=provider1, provider_group=group1
@@ -12547,10 +13340,10 @@ class TestScheduleViewSet:
mock_schedule_scan,
mock_task_get,
authenticated_client,
- providers_fixture,
+ aws_provider,
tasks_fixture,
):
- provider, *_ = providers_fixture
+ provider = aws_provider
prowler_task = tasks_fixture[0]
mock_schedule_scan.return_value.id = prowler_task.id
mock_task_get.return_value = prowler_task
@@ -12578,10 +13371,10 @@ class TestScheduleViewSet:
mock_task_get,
mock_apply_async,
authenticated_client,
- providers_fixture,
+ aws_provider,
tasks_fixture,
):
- provider, *_ = providers_fixture
+ provider = aws_provider
prowler_task = tasks_fixture[0]
mock_task_get.return_value = prowler_task
mock_apply_async.return_value.id = prowler_task.id
@@ -12682,7 +13475,7 @@ class TestIntegrationViewSet:
def test_integrations_create_valid(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
integration_type,
configuration,
credentials,
@@ -12766,12 +13559,51 @@ class TestIntegrationViewSet:
)
assert "credentials" not in response.json()["data"]["attributes"]
+ @pytest.mark.parametrize(
+ "domain",
+ (
+ "169.254.169.254#",
+ "internal/service",
+ "internal?target",
+ "internal\\target",
+ "internal:8000",
+ "user@internal",
+ ),
+ )
+ def test_integrations_create_jira_rejects_invalid_domain(
+ self, authenticated_client, domain
+ ):
+ data = {
+ "data": {
+ "type": "integrations",
+ "attributes": {
+ "integration_type": Integration.IntegrationChoices.JIRA,
+ "configuration": {},
+ "credentials": {
+ "domain": domain,
+ "api_token": "fake-api-token",
+ "user_mail": "testing@prowler.com",
+ },
+ "enabled": True,
+ },
+ }
+ }
+
+ response = authenticated_client.post(
+ reverse("integration-list"),
+ data=json.dumps(data),
+ content_type="application/vnd.api+json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert Integration.objects.count() == 0
+
def test_integrations_create_valid_relationships(
self,
authenticated_client,
- providers_fixture,
+ aws_provider_pair,
):
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
data = {
"data": {
@@ -13094,9 +13926,11 @@ class TestIntegrationViewSet:
assert response.status_code == status.HTTP_400_BAD_REQUEST
def test_integrations_create_duplicate_amazon_s3(
- self, authenticated_client, providers_fixture
+ self,
+ authenticated_client,
+ aws_provider,
):
- provider = providers_fixture[0]
+ provider = aws_provider
# Create first S3 integration
data = {
@@ -13304,6 +14138,55 @@ class TestIntegrationViewSet:
assert "projects" in configuration
assert "issue_types" in configuration
+ def test_integrations_update_jira_rejects_invalid_domain(
+ self, authenticated_client
+ ):
+ create_data = {
+ "data": {
+ "type": "integrations",
+ "attributes": {
+ "integration_type": Integration.IntegrationChoices.JIRA,
+ "configuration": {},
+ "credentials": {
+ "user_mail": "test@example.com",
+ "api_token": "fake-api-token",
+ "domain": "original-domain",
+ },
+ "enabled": True,
+ },
+ }
+ }
+ create_response = authenticated_client.post(
+ reverse("integration-list"),
+ data=json.dumps(create_data),
+ content_type="application/vnd.api+json",
+ )
+ assert create_response.status_code == status.HTTP_201_CREATED
+ integration_id = create_response.json()["data"]["id"]
+
+ update_data = {
+ "data": {
+ "type": "integrations",
+ "id": integration_id,
+ "attributes": {
+ "credentials": {
+ "user_mail": "test@example.com",
+ "api_token": "fake-api-token",
+ "domain": "169.254.169.254#",
+ }
+ },
+ }
+ }
+ response = authenticated_client.patch(
+ reverse("integration-detail", kwargs={"pk": integration_id}),
+ data=json.dumps(update_data),
+ content_type="application/vnd.api+json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ integration = Integration.objects.get(id=integration_id)
+ assert integration.credentials["domain"] == "original-domain"
+
@pytest.mark.django_db
class TestSAMLTokenValidation:
@@ -13375,6 +14258,26 @@ class TestSAMLTokenValidation:
assert response2.status_code == status.HTTP_404_NOT_FOUND
+@pytest.mark.django_db
+class TestCustomSAMLLoginView:
+ def test_dispatch_clears_stale_callback_url_when_request_has_none(self):
+ request = RequestFactory().get("/api/v1/saml/login/testtenant/")
+ request.session = {
+ "saml_callback_url": "/invitation/accept?invitation_token=old-token"
+ }
+
+ with patch(
+ "allauth.socialaccount.providers.saml.views.LoginView.dispatch",
+ return_value=JsonResponse({}),
+ ):
+ response = CustomSAMLLoginView.as_view()(
+ request, organization_slug="testtenant"
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert "saml_callback_url" not in request.session
+
+
@pytest.mark.django_db
class TestSAMLInitiateAPIView:
def test_valid_email_domain_and_certificates(
@@ -13386,7 +14289,7 @@ class TestSAMLInitiateAPIView:
url = reverse("api_saml_initiate")
payload = {"email_domain": saml_setup["email"]}
- response = authenticated_client.post(url, data=payload, format="json")
+ response = authenticated_client.post(url, data=payload, format="vnd.api+json")
assert response.status_code == status.HTTP_302_FOUND
assert (
@@ -13395,11 +14298,42 @@ class TestSAMLInitiateAPIView:
)
assert "SAMLRequest" not in response.url
+ def test_valid_email_domain_preserves_safe_callback_url(
+ self, authenticated_client, saml_setup
+ ):
+ url = reverse("api_saml_initiate")
+ callback_url = "/invitation/accept?invitation_token=test-token"
+ payload = {
+ "email_domain": saml_setup["email"],
+ "callback_url": callback_url,
+ }
+
+ response = authenticated_client.post(url, data=payload, format="vnd.api+json")
+
+ assert response.status_code == status.HTTP_302_FOUND
+ query_params = parse_qs(urlparse(response.url).query)
+ assert query_params["callback_url"] == [callback_url]
+
+ def test_valid_email_domain_rejects_external_callback_url(
+ self, authenticated_client, saml_setup
+ ):
+ url = reverse("api_saml_initiate")
+ payload = {
+ "email_domain": saml_setup["email"],
+ "callback_url": "https://attacker.example/invitation",
+ }
+
+ response = authenticated_client.post(url, data=payload, format="vnd.api+json")
+
+ assert response.status_code == status.HTTP_302_FOUND
+ query_params = parse_qs(urlparse(response.url).query)
+ assert "callback_url" not in query_params
+
def test_invalid_email_domain(self, authenticated_client):
url = reverse("api_saml_initiate")
payload = {"email_domain": "user@unauthorized.com"}
- response = authenticated_client.post(url, data=payload, format="json")
+ response = authenticated_client.post(url, data=payload, format="vnd.api+json")
assert response.status_code == status.HTTP_403_FORBIDDEN
assert response.json()["errors"]["detail"] == "Unauthorized domain."
@@ -13582,7 +14516,8 @@ class TestTenantFinishACSView:
)
)
request.user = user
- request.session = {}
+ callback_url = "/invitation/accept?invitation_token=test-token"
+ request.session = {"saml_callback_url": callback_url}
with (
patch(
@@ -13624,6 +14559,7 @@ class TestTenantFinishACSView:
assert parsed_url.netloc == expected_callback_host
query_params = parse_qs(parsed_url.query)
assert "id" in query_params
+ assert query_params["callbackUrl"] == [callback_url]
token_id = query_params["id"][0]
token_obj = SAMLToken.objects.get(id=token_id)
@@ -16601,6 +17537,76 @@ class TestLighthouseProviderConfigViewSet:
error_detail = str(resp.json()).lower()
assert "base_url" in error_detail
+ @pytest.mark.parametrize(
+ "base_url",
+ [
+ "https://127.0.0.1/v1",
+ "https://169.254.169.254/latest/meta-data",
+ ],
+ )
+ def test_openai_compatible_rejects_internal_base_url_on_create(
+ self, authenticated_client, base_url
+ ):
+ payload = {
+ "data": {
+ "type": "lighthouse-providers",
+ "attributes": {
+ "provider_type": "openai_compatible",
+ "base_url": base_url,
+ "credentials": {"api_key": "compat-key"},
+ },
+ }
+ }
+
+ resp = authenticated_client.post(
+ reverse("lighthouse-providers-list"),
+ data=payload,
+ content_type=API_JSON_CONTENT_TYPE,
+ )
+
+ assert resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert "base_url" in str(resp.json()).lower()
+
+ def test_openai_compatible_rejects_internal_base_url_on_update(
+ self, authenticated_client
+ ):
+ create_payload = {
+ "data": {
+ "type": "lighthouse-providers",
+ "attributes": {
+ "provider_type": "openai_compatible",
+ "base_url": "https://openrouter.ai/api/v1",
+ "credentials": {"api_key": "compat-key-123"},
+ },
+ }
+ }
+ create_resp = authenticated_client.post(
+ reverse("lighthouse-providers-list"),
+ data=create_payload,
+ content_type=API_JSON_CONTENT_TYPE,
+ )
+ assert create_resp.status_code == status.HTTP_201_CREATED
+ provider_id = create_resp.json()["data"]["id"]
+
+ patch_payload = {
+ "data": {
+ "type": "lighthouse-providers",
+ "id": provider_id,
+ "attributes": {
+ "base_url": "https://169.254.169.254/latest/meta-data",
+ },
+ }
+ }
+
+ patch_resp = authenticated_client.patch(
+ reverse("lighthouse-providers-detail", kwargs={"pk": provider_id}),
+ data=patch_payload,
+ content_type=API_JSON_CONTENT_TYPE,
+ )
+
+ assert patch_resp.status_code == status.HTTP_400_BAD_REQUEST
+ assert "base_url" in str(patch_resp.json()).lower()
+
def test_openai_compatible_invalid_credentials(self, authenticated_client):
payload = {
"data": {
@@ -16913,7 +17919,7 @@ class TestMuteRuleViewSet:
mock_task,
authenticated_client,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
):
"""Test that multiple findings with same UID result in only one UID in the rule."""
@@ -17912,10 +18918,13 @@ class TestFindingGroupViewSet:
assert response.json()["errors"][0]["code"] == "invalid"
def test_finding_groups_provider_filter(
- self, authenticated_client, finding_groups_fixture, providers_fixture
+ self,
+ authenticated_client,
+ finding_groups_fixture,
+ aws_provider,
):
"""Test filtering by provider UUID."""
- provider = providers_fixture[0]
+ provider = aws_provider
response = authenticated_client.get(
reverse("finding-group-list"),
{"filter[inserted_at]": TODAY, "filter[provider_id]": str(provider.id)},
@@ -17943,11 +18952,11 @@ class TestFindingGroupViewSet:
authenticated_client,
tenants_fixture,
finding_groups_fixture,
- providers_fixture,
provider_groups_fixture,
+ aws_provider_pair,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
group1, group2, *_ = provider_groups_fixture
ProviderGroupMembership.objects.create(
tenant=tenant, provider=provider1, provider_group=group1
@@ -18027,10 +19036,10 @@ class TestFindingGroupViewSet:
],
ids=["summary_path", "finding_level_path"],
)
+ @pytest.mark.usefixtures("finding_groups_title_variants_fixture")
def test_check_title_icontains_includes_all_title_variants(
self,
authenticated_client,
- finding_groups_title_variants_fixture,
extra_filters,
):
"""
@@ -18438,7 +19447,11 @@ class TestFindingGroupViewSet:
# Test provider_id filter actually filters data
def test_finding_groups_provider_id_filter_actually_filters(
- self, authenticated_client, finding_groups_fixture, providers_fixture
+ self,
+ authenticated_client,
+ finding_groups_fixture,
+ aws_provider,
+ aws_provider_pair,
):
"""
Test that provider_id filter returns ONLY data from that provider.
@@ -18446,8 +19459,8 @@ class TestFindingGroupViewSet:
This is a critical test - it verifies the filter doesn't just return 200 OK,
but actually restricts the data to the specified provider.
"""
- provider1 = providers_fixture[0] # Has scan1 with 4 checks
- provider2 = providers_fixture[1] # Has scan2 with 1 check (cloudtrail_enabled)
+ provider1 = aws_provider # Has scan1 with 4 checks
+ provider2 = aws_provider_pair[1] # Has scan2 with 1 check (cloudtrail_enabled)
# Get ALL finding groups (without provider filter)
response_all = authenticated_client.get(
@@ -18588,11 +19601,15 @@ class TestFindingGroupViewSet:
assert len(data) == 0
def test_finding_groups_latest_provider_id_filter(
- self, authenticated_client, finding_groups_fixture, providers_fixture
+ self,
+ authenticated_client,
+ finding_groups_fixture,
+ aws_provider,
+ aws_provider_pair,
):
"""Test /latest with provider_id filter returns only that provider's data."""
- provider1 = providers_fixture[0] # Has 4 checks
- provider2 = providers_fixture[1] # Has 1 check
+ provider1 = aws_provider # Has 4 checks
+ provider2 = aws_provider_pair[1] # Has 1 check
# Filter by provider1
response = authenticated_client.get(
@@ -18756,8 +19773,9 @@ class TestFindingGroupViewSet:
def test_finding_groups_latest_aggregates_latest_per_provider(
self,
authenticated_client,
- providers_fixture,
+ aws_provider,
resources_fixture,
+ aws_provider_pair,
):
"""Test /latest keeps all findings from the latest scan per provider.
@@ -18765,8 +19783,8 @@ class TestFindingGroupViewSet:
same check_id (e.g. one per resource), all of them are included in the
aggregation — not just one.
"""
- provider1 = providers_fixture[0]
- provider2 = providers_fixture[1]
+ provider1 = aws_provider
+ provider2 = aws_provider_pair[1]
resource1 = resources_fixture[0]
resource2 = resources_fixture[1]
resource3 = resources_fixture[2]
@@ -18891,11 +19909,11 @@ class TestFindingGroupViewSet:
authenticated_client,
tenants_fixture,
finding_groups_fixture,
- providers_fixture,
provider_groups_fixture,
+ aws_provider_pair,
):
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
group1, group2, *_ = provider_groups_fixture
ProviderGroupMembership.objects.create(
tenant=tenant, provider=provider1, provider_group=group1
@@ -19373,7 +20391,7 @@ class TestFindingGroupViewSet:
self,
authenticated_client,
tenants_fixture,
- providers_fixture,
+ aws_provider,
resources_fixture,
):
"""Overlapping scans on the same provider must resolve to the scan
@@ -19383,7 +20401,7 @@ class TestFindingGroupViewSet:
different scans and reporting diverging delta/new counts.
"""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
resource = resources_fixture[0]
check_id = "overlap_regression_check"
diff --git a/api/src/backend/api/utils.py b/api/src/backend/api/utils.py
index ce1dc0f10d..8e73b96a39 100644
--- a/api/src/backend/api/utils.py
+++ b/api/src/backend/api/utils.py
@@ -7,9 +7,19 @@ from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from api.db_router import MainRouter
from api.db_utils import rls_transaction
from api.exceptions import InvitationTokenExpiredException
-from api.models import Integration, Invitation, Processor, Provider, Resource
+from api.models import (
+ Integration,
+ Invitation,
+ Membership,
+ Processor,
+ Provider,
+ Resource,
+ Role,
+ UserRoleRelationship,
+)
from api.v1.serializers import FindingMetadataSerializer
from django.contrib.postgres.aggregates import ArrayAgg
+from django.db import transaction
from django.db.models import Subquery
from prowler.lib.outputs.jira.jira import Jira, JiraBasicAuthError
from prowler.providers.aws.lib.s3.s3 import S3
@@ -242,12 +252,6 @@ def get_prowler_provider_kwargs(
**prowler_provider_kwargs,
"filter_accounts": [provider.uid],
}
- elif provider.provider == Provider.ProviderChoices.ORACLECLOUD.value:
- if isinstance(prowler_provider_kwargs.get("region"), str):
- prowler_provider_kwargs = {
- **prowler_provider_kwargs,
- "region": {prowler_provider_kwargs["region"]},
- }
elif provider.provider == Provider.ProviderChoices.OPENSTACK.value:
# clouds_yaml_content, clouds_yaml_cloud and provider_id are validated
# in the provider itself, so it's not needed here.
@@ -278,6 +282,11 @@ def get_prowler_provider_kwargs(
**{k: v for k, v in prowler_provider_kwargs.items() if v},
}
+ elif provider.provider == Provider.ProviderChoices.ORACLECLOUD.value:
+ prowler_provider_kwargs = _normalize_oraclecloud_provider_kwargs(
+ prowler_provider_kwargs
+ )
+
if mutelist_processor:
mutelist_content = mutelist_processor.configuration.get("Mutelist", {})
# IaC and Image providers don't support mutelist (both use Trivy's built-in logic)
@@ -290,6 +299,40 @@ def get_prowler_provider_kwargs(
return prowler_provider_kwargs
+def _normalize_oraclecloud_provider_kwargs(secret: dict) -> dict:
+ """Normalize external OCI secret fields into SDK provider kwargs."""
+ prowler_provider_kwargs = secret.copy()
+ prowler_provider_kwargs.pop("region", None)
+
+ return prowler_provider_kwargs
+
+
+def _normalize_oraclecloud_connection_test_kwargs(secret: dict) -> dict:
+ """Normalize external OCI secret fields into test_connection kwargs."""
+ from prowler.providers.oraclecloud.oraclecloud_provider import OraclecloudProvider
+
+ prowler_provider_kwargs = secret.copy()
+ prowler_provider_kwargs.pop("region", None)
+
+ if (
+ prowler_provider_kwargs.get("user")
+ and prowler_provider_kwargs.get("fingerprint")
+ and prowler_provider_kwargs.get("tenancy")
+ and (
+ prowler_provider_kwargs.get("key_content")
+ or prowler_provider_kwargs.get("key_file")
+ )
+ ):
+ # Connection validation needs one OCI endpoint, but scans remain unfiltered.
+ prowler_provider_kwargs["region"] = getattr(
+ OraclecloudProvider,
+ "_bootstrap_region",
+ OraclecloudProvider._home_region,
+ )
+
+ return prowler_provider_kwargs
+
+
def initialize_prowler_provider(
provider: Provider,
mutelist_processor: Processor | None = None,
@@ -392,6 +435,15 @@ def prowler_provider_connection_test(provider: Provider) -> Connection:
if prowler_provider_kwargs.get("registry_token"):
image_kwargs["registry_token"] = prowler_provider_kwargs["registry_token"]
return prowler_provider.test_connection(**image_kwargs)
+ elif provider.provider == Provider.ProviderChoices.ORACLECLOUD.value:
+ oraclecloud_kwargs = _normalize_oraclecloud_connection_test_kwargs(
+ prowler_provider_kwargs
+ )
+ return prowler_provider.test_connection(
+ **oraclecloud_kwargs,
+ provider_id=provider.uid,
+ raise_on_exception=False,
+ )
else:
return prowler_provider.test_connection(
**prowler_provider_kwargs,
@@ -538,6 +590,35 @@ def validate_invitation(
return invitation
+def accept_invitation_for_user(
+ *, user, invitation_token: str, raise_not_found: bool = False
+):
+ with transaction.atomic(using=MainRouter.admin_db):
+ invitation = validate_invitation(
+ invitation_token, user.email, raise_not_found=raise_not_found
+ )
+ with rls_transaction(str(invitation.tenant_id), using=MainRouter.admin_db):
+ membership, _ = Membership.objects.using(MainRouter.admin_db).get_or_create(
+ user=user,
+ tenant=invitation.tenant,
+ defaults={"role": Membership.RoleChoices.MEMBER},
+ )
+ invitation_roles = Role.objects.using(MainRouter.admin_db).filter(
+ invitations=invitation
+ )
+ for role in invitation_roles:
+ UserRoleRelationship.objects.using(MainRouter.admin_db).get_or_create(
+ user=user,
+ role=role,
+ defaults={"tenant": invitation.tenant},
+ )
+
+ invitation.state = Invitation.State.ACCEPTED
+ invitation.save(using=MainRouter.admin_db)
+
+ return invitation, membership
+
+
# ToRemove after removing the fallback mechanism in /findings/metadata
def get_findings_metadata_no_aggregations(tenant_id: str, filtered_queryset):
filtered_ids = filtered_queryset.order_by().values("id")
diff --git a/api/src/backend/api/v1/serializer_utils/authentication.py b/api/src/backend/api/v1/serializer_utils/authentication.py
new file mode 100644
index 0000000000..840cb44a0a
--- /dev/null
+++ b/api/src/backend/api/v1/serializer_utils/authentication.py
@@ -0,0 +1,18 @@
+from api.db_router import MainRouter
+from rest_framework_simplejwt.token_blacklist.models import (
+ BlacklistedToken,
+ OutstandingToken,
+)
+
+
+def blacklist_user_refresh_tokens(user_id):
+ outstanding_token_ids = list(
+ OutstandingToken.objects.using(MainRouter.admin_db)
+ .filter(user_id=user_id)
+ .values_list("id", flat=True)
+ )
+ if outstanding_token_ids:
+ BlacklistedToken.objects.using(MainRouter.admin_db).bulk_create(
+ [BlacklistedToken(token_id=token_id) for token_id in outstanding_token_ids],
+ ignore_conflicts=True,
+ )
diff --git a/api/src/backend/api/v1/serializer_utils/integrations.py b/api/src/backend/api/v1/serializer_utils/integrations.py
index a77de9c237..ac876d1d5b 100644
--- a/api/src/backend/api/v1/serializer_utils/integrations.py
+++ b/api/src/backend/api/v1/serializer_utils/integrations.py
@@ -5,6 +5,10 @@ from api.v1.serializer_utils.base import BaseValidateSerializer
from drf_spectacular.utils import extend_schema_field
from rest_framework_json_api import serializers
+ATLASSIAN_SITE_NAME_REGEX = re.compile(
+ r"\A[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\Z"
+)
+
class S3ConfigSerializer(BaseValidateSerializer):
bucket_name = serializers.CharField()
@@ -97,7 +101,17 @@ class AWSCredentialSerializer(BaseValidateSerializer):
class JiraCredentialSerializer(BaseValidateSerializer):
user_mail = serializers.EmailField(required=True)
api_token = serializers.CharField(required=True)
- domain = serializers.CharField(required=True)
+ domain = serializers.RegexField(
+ regex=ATLASSIAN_SITE_NAME_REGEX,
+ required=True,
+ trim_whitespace=False,
+ error_messages={
+ "invalid": (
+ "Domain must be a valid Atlassian site name containing only "
+ "letters, numbers, and hyphens."
+ )
+ },
+ )
class Meta:
resource_name = "integrations"
@@ -170,7 +184,10 @@ class JiraCredentialSerializer(BaseValidateSerializer):
},
"domain": {
"type": "string",
- "description": "The JIRA domain/instance URL (e.g., 'your-domain.atlassian.net').",
+ "description": "The Jira site name without the '.atlassian.net' suffix (e.g., 'your-domain').",
+ "minLength": 1,
+ "maxLength": 63,
+ "pattern": "^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$",
},
},
"required": ["user_mail", "api_token", "domain"],
diff --git a/api/src/backend/api/v1/serializer_utils/providers.py b/api/src/backend/api/v1/serializer_utils/providers.py
index 0b8b4eacf4..49b593049f 100644
--- a/api/src/backend/api/v1/serializer_utils/providers.py
+++ b/api/src/backend/api/v1/serializer_utils/providers.py
@@ -213,7 +213,8 @@ from rest_framework_json_api import serializers
"properties": {
"kubeconfig_content": {
"type": "string",
- "description": "The content of the Kubernetes kubeconfig file, encoded as a string.",
+ "description": "The content of the Kubernetes kubeconfig file, encoded as a string. "
+ "Kubeconfig exec authentication is not supported in Prowler Cloud for security reasons.",
}
},
"required": ["kubeconfig_content"],
@@ -294,16 +295,21 @@ from rest_framework_json_api import serializers
"type": "string",
"description": "The OCID of the tenancy.",
},
- "region": {
- "type": "string",
- "description": "The OCI region identifier (e.g., us-ashburn-1, us-phoenix-1).",
- },
"pass_phrase": {
"type": "string",
"description": "The passphrase for the private key, if encrypted.",
},
+ "region": {
+ "type": "string",
+ "deprecated": True,
+ "description": "Legacy OCI region field accepted for backwards compatibility but ignored; OCI scans all regions.",
+ },
},
- "required": ["user", "fingerprint", "tenancy", "region"],
+ "required": ["user", "fingerprint", "tenancy"],
+ "anyOf": [
+ {"required": ["key_file"]},
+ {"required": ["key_content"]},
+ ],
},
{
"type": "object",
diff --git a/api/src/backend/api/v1/serializers.py b/api/src/backend/api/v1/serializers.py
index 1d160b4048..750174e7a8 100644
--- a/api/src/backend/api/v1/serializers.py
+++ b/api/src/backend/api/v1/serializers.py
@@ -2,6 +2,7 @@ import base64
import json
from datetime import UTC, datetime, timedelta
+import yaml
from api.db_router import MainRouter
from api.exceptions import ConflictException
from api.models import (
@@ -37,6 +38,7 @@ from api.models import (
UserRoleRelationship,
)
from api.rls import Tenant
+from api.v1.serializer_utils.authentication import blacklist_user_refresh_tokens
from api.v1.serializer_utils.integrations import (
AWSCredentialSerializer,
IntegrationConfigField,
@@ -55,12 +57,13 @@ from api.v1.serializer_utils.lighthouse import (
)
from api.v1.serializer_utils.processors import ProcessorConfigField
from api.v1.serializer_utils.providers import ProviderSecretField
+from api.validators import validate_lighthouse_openai_compatible_base_url
from django.conf import settings
from django.contrib.auth import authenticate
from django.contrib.auth.models import update_last_login
from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError as DjangoValidationError
-from django.db import IntegrityError
+from django.db import IntegrityError, transaction
from drf_spectacular.utils import extend_schema_field
from jwt.exceptions import InvalidKeyError
from prowler.lib.mutelist.mutelist import Mutelist
@@ -71,11 +74,28 @@ from rest_framework_json_api.relations import SerializerMethodResourceRelatedFie
from rest_framework_json_api.serializers import ValidationError
from rest_framework_simplejwt.exceptions import TokenError
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
+from rest_framework_simplejwt.settings import api_settings
from rest_framework_simplejwt.tokens import RefreshToken
+from rest_framework_simplejwt.utils import get_md5_hash_password
# Base
+def _validate_lighthouse_base_url_without_dns(base_url: str) -> None:
+ try:
+ validate_lighthouse_openai_compatible_base_url(base_url, resolve_dns=False)
+ except DjangoValidationError as error:
+ raise ValidationError({"base_url": error.messages[0]}) from error
+
+
+def _reraise_lighthouse_credentials_errors(error: ValidationError) -> None:
+ details = error.detail.copy()
+ for key, value in details.items():
+ error.detail[f"credentials/{key}"] = value
+ del error.detail[key]
+ raise error
+
+
class BaseModelSerializerV1(serializers.ModelSerializer):
def get_root_meta(self, _resource, _many):
return {"version": "v1"}
@@ -231,6 +251,18 @@ class TokenRefreshSerializer(BaseSerializerV1):
try:
# Validate the refresh token
refresh = RefreshToken(refresh_token)
+ if api_settings.CHECK_REVOKE_TOKEN:
+ user_id = refresh.payload.get(api_settings.USER_ID_CLAIM)
+ try:
+ user = User.objects.using(MainRouter.admin_db).get(
+ **{api_settings.USER_ID_FIELD: user_id}
+ )
+ except User.DoesNotExist:
+ raise TokenError("User not found.") from None
+ if refresh.get(api_settings.REVOKE_TOKEN_CLAIM) != (
+ get_md5_hash_password(user.password)
+ ):
+ raise TokenError("The user's password has been changed.")
# Generate new access token
access_token = refresh.access_token
@@ -404,7 +436,13 @@ class UserUpdateSerializer(BaseWriteSerializer):
password = validated_data.pop("password", None)
if password:
validate_password(password, user=instance)
- instance.set_password(password)
+ with transaction.atomic(using=MainRouter.admin_db):
+ instance.set_password(password)
+ for attr, value in validated_data.items():
+ setattr(instance, attr, value)
+ blacklist_user_refresh_tokens(instance.id)
+ instance.save(using=MainRouter.admin_db)
+ return instance
return super().update(instance, validated_data)
@@ -443,8 +481,8 @@ class UserRoleRelationshipSerializer(RLSSerializer, BaseWriteSerializer):
def create(self, validated_data):
role_ids = [item["id"] for item in validated_data["roles"]]
- roles = Role.objects.filter(id__in=role_ids)
tenant_id = self.context.get("tenant_id")
+ roles = Role.objects.filter(id__in=role_ids, tenant_id=tenant_id)
new_relationships = [
UserRoleRelationship(
@@ -458,8 +496,8 @@ class UserRoleRelationshipSerializer(RLSSerializer, BaseWriteSerializer):
def update(self, instance, validated_data):
role_ids = [item["id"] for item in validated_data["roles"]]
- roles = Role.objects.filter(id__in=role_ids)
tenant_id = self.context.get("tenant_id")
+ roles = Role.objects.filter(id__in=role_ids, tenant_id=tenant_id)
# Safeguard: A tenant must always have at least one user with MANAGE_ACCOUNT.
# If the target roles do NOT include MANAGE_ACCOUNT, and the current user is
@@ -489,7 +527,7 @@ class UserRoleRelationshipSerializer(RLSSerializer, BaseWriteSerializer):
}
)
- instance.roles.clear()
+ UserRoleRelationship.objects.filter(user=instance, tenant_id=tenant_id).delete()
new_relationships = [
UserRoleRelationship(user=instance, role=r, tenant_id=tenant_id)
for r in roles
@@ -1530,6 +1568,32 @@ class FindingMetadataSerializer(BaseSerializerV1):
# Provider secrets
+KUBERNETES_KUBECONFIG_EXEC_ERROR = (
+ "Kubernetes kubeconfig exec authentication is not supported in Prowler Cloud "
+ "for security reasons."
+)
+KUBERNETES_KUBECONFIG_INVALID_ERROR = "Invalid Kubernetes kubeconfig content."
+
+
+def kubeconfig_contains_exec_auth(kubeconfig: dict) -> bool:
+ users = kubeconfig.get("users", [])
+ if not isinstance(users, list):
+ raise ValidationError(KUBERNETES_KUBECONFIG_INVALID_ERROR)
+
+ for user_entry in users:
+ if not isinstance(user_entry, dict):
+ raise ValidationError(KUBERNETES_KUBECONFIG_INVALID_ERROR)
+
+ user = user_entry.get("user", {})
+ if not isinstance(user, dict):
+ raise ValidationError(KUBERNETES_KUBECONFIG_INVALID_ERROR)
+
+ if "exec" in user:
+ return True
+
+ return False
+
+
class BaseWriteProviderSecretSerializer(BaseWriteSerializer):
@staticmethod
def validate_secret_based_on_provider(
@@ -1608,6 +1672,7 @@ class BaseWriteProviderSecretSerializer(BaseWriteSerializer):
validation_error.detail[f"secret/{key}"] = value
del validation_error.detail[key]
raise validation_error
+ return serializer.validated_data
class AwsProviderSecret(serializers.Serializer):
@@ -1711,6 +1776,22 @@ class MongoDBAtlasProviderSecret(serializers.Serializer):
class KubernetesProviderSecret(serializers.Serializer):
kubeconfig_content = serializers.CharField()
+ def validate_kubeconfig_content(self, kubeconfig_content):
+ try:
+ kubeconfig = yaml.safe_load(kubeconfig_content)
+ except yaml.YAMLError as exc:
+ raise serializers.ValidationError(
+ KUBERNETES_KUBECONFIG_INVALID_ERROR
+ ) from exc
+
+ if not isinstance(kubeconfig, dict):
+ raise serializers.ValidationError(KUBERNETES_KUBECONFIG_INVALID_ERROR)
+
+ if kubeconfig_contains_exec_auth(kubeconfig):
+ raise serializers.ValidationError(KUBERNETES_KUBECONFIG_EXEC_ERROR)
+
+ return kubeconfig_content
+
class Meta:
resource_name = "provider-secrets"
@@ -1733,14 +1814,32 @@ class IacProviderSecret(serializers.Serializer):
resource_name = "provider-secrets"
+class LegacyOCIRegionField(serializers.Field):
+ def to_internal_value(self, data):
+ return data
+
+ def to_representation(self, value):
+ return value
+
+
class OracleCloudProviderSecret(serializers.Serializer):
user = serializers.CharField()
fingerprint = serializers.CharField()
key_file = serializers.CharField(required=False)
key_content = serializers.CharField(required=False)
tenancy = serializers.CharField()
- region = serializers.CharField()
pass_phrase = serializers.CharField(required=False)
+ region = LegacyOCIRegionField(required=False, allow_null=True)
+
+ def validate(self, attrs):
+ attrs.pop("region", None)
+
+ if "key_file" not in attrs and "key_content" not in attrs:
+ raise serializers.ValidationError(
+ {"key_file": "Either key_file or key_content must be provided."}
+ )
+
+ return attrs
class Meta:
resource_name = "provider-secrets"
@@ -1885,7 +1984,11 @@ class ProviderSecretCreateSerializer(RLSSerializer, BaseWriteProviderSecretSeria
secret = attrs.get("secret")
validated_attrs = super().validate(attrs)
- self.validate_secret_based_on_provider(provider.provider, secret_type, secret)
+ validated_secret = self.validate_secret_based_on_provider(
+ provider.provider, secret_type, secret
+ )
+ if provider.provider == Provider.ProviderChoices.ORACLECLOUD.value:
+ validated_attrs["secret"] = validated_secret
return validated_attrs
@@ -1917,7 +2020,11 @@ class ProviderSecretUpdateSerializer(BaseWriteProviderSecretSerializer):
secret = attrs.get("secret")
validated_attrs = super().validate(attrs)
- self.validate_secret_based_on_provider(provider.provider, secret_type, secret)
+ validated_secret = self.validate_secret_based_on_provider(
+ provider.provider, secret_type, secret
+ )
+ if provider.provider == Provider.ProviderChoices.ORACLECLOUD.value:
+ validated_attrs["secret"] = validated_secret
return validated_attrs
@@ -3147,6 +3254,9 @@ class ProcessorUpdateSerializer(BaseWriteSerializer):
class SamlInitiateSerializer(BaseSerializerV1):
email_domain = serializers.CharField()
+ callback_url = serializers.CharField(
+ required=False, allow_blank=True, max_length=2048
+ )
class JSONAPIMeta:
resource_name = "saml-initiate"
@@ -3578,11 +3688,7 @@ class LighthouseProviderConfigCreateSerializer(RLSSerializer, BaseWriteSerialize
raise_exception=True
)
except ValidationError as e:
- details = e.detail.copy()
- for key, value in details.items():
- e.detail[f"credentials/{key}"] = value
- del e.detail[key]
- raise e
+ _reraise_lighthouse_credentials_errors(e)
elif (
provider_type == LighthouseProviderConfiguration.LLMProviderChoices.BEDROCK
):
@@ -3591,27 +3697,20 @@ class LighthouseProviderConfigCreateSerializer(RLSSerializer, BaseWriteSerialize
raise_exception=True
)
except ValidationError as e:
- details = e.detail.copy()
- for key, value in details.items():
- e.detail[f"credentials/{key}"] = value
- del e.detail[key]
- raise e
+ _reraise_lighthouse_credentials_errors(e)
elif (
provider_type
== LighthouseProviderConfiguration.LLMProviderChoices.OPENAI_COMPATIBLE
):
if not base_url:
raise ValidationError({"base_url": "Base URL is required."})
+ _validate_lighthouse_base_url_without_dns(base_url)
try:
OpenAICompatibleCredentialsSerializer(data=credentials).is_valid(
raise_exception=True
)
except ValidationError as e:
- details = e.detail.copy()
- for key, value in details.items():
- e.detail[f"credentials/{key}"] = value
- del e.detail[key]
- raise e
+ _reraise_lighthouse_credentials_errors(e)
return super().validate(attrs)
@@ -3674,11 +3773,7 @@ class LighthouseProviderConfigUpdateSerializer(BaseWriteSerializer):
raise_exception=True
)
except ValidationError as e:
- details = e.detail.copy()
- for key, value in details.items():
- e.detail[f"credentials/{key}"] = value
- del e.detail[key]
- raise e
+ _reraise_lighthouse_credentials_errors(e)
elif (
credentials is not None
and provider_type
@@ -3702,11 +3797,7 @@ class LighthouseProviderConfigUpdateSerializer(BaseWriteSerializer):
raise_exception=True
)
except ValidationError as e:
- details = e.detail.copy()
- for key, value in details.items():
- e.detail[f"credentials/{key}"] = value
- del e.detail[key]
- raise e
+ _reraise_lighthouse_credentials_errors(e)
# Then enforce invariants about not changing the auth method
# If the existing config uses an API key, forbid introducing access keys.
@@ -3733,24 +3824,23 @@ class LighthouseProviderConfigUpdateSerializer(BaseWriteSerializer):
}
)
elif (
- credentials is not None
- and provider_type
+ provider_type
== LighthouseProviderConfiguration.LLMProviderChoices.OPENAI_COMPATIBLE
):
- if base_url is None:
- pass
- elif not base_url:
+ effective_base_url = (
+ base_url if "base_url" in attrs else getattr(self.instance, "base_url")
+ )
+ if not effective_base_url:
raise ValidationError({"base_url": "Base URL cannot be empty."})
- try:
- OpenAICompatibleCredentialsSerializer(data=credentials).is_valid(
- raise_exception=True
- )
- except ValidationError as e:
- details = e.detail.copy()
- for key, value in details.items():
- e.detail[f"credentials/{key}"] = value
- del e.detail[key]
- raise e
+ if "base_url" in attrs:
+ _validate_lighthouse_base_url_without_dns(effective_base_url)
+ if credentials is not None:
+ try:
+ OpenAICompatibleCredentialsSerializer(data=credentials).is_valid(
+ raise_exception=True
+ )
+ except ValidationError as e:
+ _reraise_lighthouse_credentials_errors(e)
return super().validate(attrs)
diff --git a/api/src/backend/api/v1/views.py b/api/src/backend/api/v1/views.py
index 89c2f344a2..e392505818 100644
--- a/api/src/backend/api/v1/views.py
+++ b/api/src/backend/api/v1/views.py
@@ -9,7 +9,7 @@ from collections import defaultdict
from copy import deepcopy
from datetime import UTC, datetime, timedelta
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
-from urllib.parse import urljoin
+from urllib.parse import urlencode, urljoin
import sentry_sdk
from allauth.socialaccount.models import SocialAccount, SocialApp
@@ -50,6 +50,7 @@ from api.filters import (
FindingGroupAggregatedComputedFilter,
FindingGroupFilter,
FindingGroupSummaryFilter,
+ FindingMetadataFilter,
IntegrationFilter,
IntegrationJiraFindingsFilter,
InvitationFilter,
@@ -128,6 +129,7 @@ from api.renderers import APIJSONRenderer, PlainTextRenderer
from api.rls import Tenant
from api.utils import (
CustomOAuth2Client,
+ accept_invitation_for_user,
get_findings_metadata_no_aggregations,
initialize_prowler_integration,
initialize_prowler_provider,
@@ -235,7 +237,7 @@ from api.v1.serializers import (
UserUpdateSerializer,
)
from botocore.exceptions import ClientError, NoCredentialsError, ParamValidationError
-from celery import chain, states
+from celery import chain
from celery.result import AsyncResult
from config.custom_logging import BackendLogger
from config.env import env
@@ -281,7 +283,6 @@ from django.utils.dateparse import parse_date
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_control
from django_celery_beat.models import PeriodicTask
-from django_celery_results.models import TaskResult
from drf_spectacular.settings import spectacular_settings
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import (
@@ -320,17 +321,20 @@ from tasks.beat import schedule_provider_scan
from tasks.jobs.attack_paths import db_utils as attack_paths_db_utils
from tasks.jobs.export import get_s3_client
from tasks.tasks import (
+ QUEUED_SCAN_TASK_STATE,
backfill_compliance_summaries_task,
backfill_scan_resource_summaries_task,
check_integration_connection_task,
check_lighthouse_connection_task,
check_lighthouse_provider_connection_task,
check_provider_connection_task,
+ create_scan_task_record,
delete_provider_task,
delete_tenant_task,
+ enqueue_scan_execution_on_commit,
+ get_active_provider_scan,
jira_integration_task,
mute_historical_findings_task,
- perform_scan_task,
reaggregate_all_finding_group_summaries_task,
refresh_lighthouse_provider_models_task,
)
@@ -541,6 +545,46 @@ class SchemaView(SpectacularAPIView):
return super().get(request, *args, **kwargs)
+SAML_CALLBACK_SESSION_KEY = "saml_callback_url"
+
+
+def _safe_callback_path(value):
+ if not value or not isinstance(value, str):
+ return None
+ if not value.startswith("/") or value.startswith("//"):
+ return None
+ return value
+
+
+def _get_request_invitation_token(request):
+ for source_name in ("data", "POST"):
+ data = getattr(request, source_name, None) or {}
+ if not hasattr(data, "get"):
+ continue
+ invitation_token = data.get("invitation_token")
+ if invitation_token:
+ return invitation_token
+
+ wrapped_request = getattr(request, "_request", None)
+ if wrapped_request and wrapped_request is not request:
+ return _get_request_invitation_token(wrapped_request)
+
+ return None
+
+
+def _accept_social_invitation(request, user):
+ invitation_token = _get_request_invitation_token(request)
+ tenant_id = getattr(request, "prowler_invitation_tenant_id", None)
+ if invitation_token and not tenant_id:
+ invitation, _ = accept_invitation_for_user(
+ user=user,
+ invitation_token=invitation_token,
+ raise_not_found=True,
+ )
+ tenant_id = str(invitation.tenant_id)
+ return tenant_id
+
+
@extend_schema(exclude=True)
class GoogleSocialLoginView(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
@@ -551,7 +595,11 @@ class GoogleSocialLoginView(SocialLoginView):
original_response = super().get_response()
if self.user and self.user.is_authenticated:
- serializer = TokenSocialLoginSerializer(data={"email": self.user.email})
+ tenant_id = _accept_social_invitation(self.request, self.user)
+ serializer_data = {"email": self.user.email}
+ if tenant_id:
+ serializer_data["tenant_id"] = tenant_id
+ serializer = TokenSocialLoginSerializer(data=serializer_data)
try:
serializer.is_valid(raise_exception=True)
except TokenError as e:
@@ -576,7 +624,11 @@ class GithubSocialLoginView(SocialLoginView):
original_response = super().get_response()
if self.user and self.user.is_authenticated:
- serializer = TokenSocialLoginSerializer(data={"email": self.user.email})
+ tenant_id = _accept_social_invitation(self.request, self.user)
+ serializer_data = {"email": self.user.email}
+ if tenant_id:
+ serializer_data["tenant_id"] = tenant_id
+ serializer = TokenSocialLoginSerializer(data=serializer_data)
try:
serializer.is_valid(raise_exception=True)
@@ -636,6 +688,10 @@ class CustomSAMLLoginView(LoginView):
This approach maintains security while providing better UX.
"""
+ callback_url = _safe_callback_path(request.GET.get("callback_url"))
+ request.session.pop(SAML_CALLBACK_SESSION_KEY, None)
+ if callback_url:
+ request.session[SAML_CALLBACK_SESSION_KEY] = callback_url
if request.method == "GET":
# Convert GET to POST while preserving parameters
request.method = "POST"
@@ -680,6 +736,11 @@ class SAMLInitiateAPIView(GenericAPIView):
"saml_login", kwargs={"organization_slug": config.email_domain}
)
login_url = urljoin(api_host, login_path)
+ callback_url = _safe_callback_path(
+ serializer.validated_data.get("callback_url")
+ )
+ if callback_url:
+ login_url = f"{login_url}?{urlencode({'callback_url': callback_url})}"
return redirect(login_url)
@@ -895,7 +956,13 @@ class TenantFinishACSView(FinishACSView):
token=token_data, user=user
)
callback_url = env.str("SAML_SSO_CALLBACK_URL")
- redirect_url = f"{callback_url}?id={saml_token.id}"
+ redirect_params = {"id": str(saml_token.id)}
+ saml_callback_url = _safe_callback_path(
+ request.session.pop(SAML_CALLBACK_SESSION_KEY, None)
+ )
+ if saml_callback_url:
+ redirect_params["callbackUrl"] = saml_callback_url
+ redirect_url = f"{callback_url}?{urlencode(redirect_params)}"
request.session.pop("saml_user_created", None)
return redirect(redirect_url)
@@ -947,8 +1014,8 @@ class UserViewSet(BaseUserViewset):
"""
Returns the required permissions based on the request method.
"""
- if self.action == "me":
- # No permissions required for me request
+ if self.action in ["me", "partial_update"]:
+ # No permissions required for me and partial_update requests
self.required_permissions = []
else:
# Require permission for the rest of the requests
@@ -1002,6 +1069,24 @@ class UserViewSet(BaseUserViewset):
status=status.HTTP_200_OK,
)
+ def partial_update(self, request, *args, **kwargs):
+ user = self.get_object()
+ if user.id != self.request.user.id:
+ role = get_role(self.request.user, self.request.tenant_id)
+ if not getattr(role, Permissions.MANAGE_USERS.value, False):
+ raise ValidationError(
+ "Only users with manage users permission can update other users."
+ )
+
+ serializer = self.get_serializer(user, data=request.data, partial=True)
+ serializer.is_valid(raise_exception=True)
+ self.perform_update(serializer)
+
+ if getattr(user, "_prefetched_objects_cache", None):
+ user._prefetched_objects_cache = {}
+
+ return Response(serializer.data)
+
def destroy(self, request, *args, **kwargs):
if kwargs["pk"] != str(self.request.user.id):
raise ValidationError("Only the current user can be deleted.")
@@ -1888,8 +1973,8 @@ class ProviderViewSet(DisablePaginationMixin, BaseRLSViewSet):
description=(
"Download a specific compliance report as an OCSF JSON file. "
"Only universal frameworks that declare an output configuration "
- "produce this artifact (currently 'dora_2022_2554' and 'csa_ccm_4.0'); any "
- "other framework returns 404."
+ "produce this artifact (currently 'dora_2022_2554', 'csa_ccm_4.0' "
+ "and 'cis_controls_8.1'); any other framework returns 404."
),
parameters=[
OpenApiParameter(
@@ -2634,12 +2719,23 @@ class ScanViewSet(BaseRLSViewSet):
def create(self, request, *args, **kwargs):
input_serializer = self.get_serializer(data=request.data)
input_serializer.is_valid(raise_exception=True)
+ provider = input_serializer.validated_data.get("provider")
+ active_scan = None
# Broker publish is deferred to on_commit so the worker cannot read
# Scan before BaseRLSViewSet's dispatch-wide atomic commits.
pre_task_id = str(uuid.uuid4())
with transaction.atomic():
+ if provider:
+ provider = Provider.objects.select_for_update().get(
+ id=provider.id,
+ tenant_id=self.request.tenant_id,
+ )
+ active_scan = get_active_provider_scan(
+ self.request.tenant_id, provider.id
+ )
+
scan = input_serializer.save()
scan.task_id = pre_task_id
scan.save(update_fields=["task_id"])
@@ -2650,29 +2746,18 @@ class ScanViewSet(BaseRLSViewSet):
provider_id=str(scan.provider_id),
)
- task_result, _ = TaskResult.objects.get_or_create(
- task_id=pre_task_id,
- defaults={"status": states.PENDING, "task_name": "scan-perform"},
- )
- prowler_task, _ = Task.objects.update_or_create(
- id=pre_task_id,
+ prowler_task = create_scan_task_record(
tenant_id=self.request.tenant_id,
- defaults={"task_runner_task": task_result},
+ task_id=pre_task_id,
+ task_status=(QUEUED_SCAN_TASK_STATE if active_scan else None),
)
- scan_kwargs = {
- "tenant_id": self.request.tenant_id,
- "scan_id": str(scan.id),
- "provider_id": str(scan.provider_id),
- # Disabled for now
- # checks_to_execute=scan.scanner_args.get("checks_to_execute")
- }
-
- transaction.on_commit(
- lambda: perform_scan_task.apply_async(
- kwargs=scan_kwargs, task_id=pre_task_id
+ if not active_scan:
+ enqueue_scan_execution_on_commit(
+ tenant_id=self.request.tenant_id,
+ scan=scan,
+ task_id=pre_task_id,
)
- )
self.response_serializer_class = TaskSerializer
output_serializer = self.get_serializer(prowler_task)
@@ -2876,13 +2961,22 @@ class AttackPathsScanViewSet(BaseRLSViewSet):
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
+ active_sink_backend = django_settings.ATTACK_PATHS_SINK_DATABASE
latest_per_provider = queryset.annotate(
+ active_sink_rank=Case(
+ When(sink_backend=active_sink_backend, then=Value(0)),
+ default=Value(1),
+ output_field=IntegerField(),
+ ),
latest_scan_rank=Window(
expression=RowNumber(),
partition_by=[F("provider_id")],
- order_by=[F("inserted_at").desc()],
- )
+ order_by=[
+ F("active_sink_rank").asc(),
+ F("inserted_at").desc(),
+ ],
+ ),
).filter(latest_scan_rank=1)
page = self.paginate_queryset(latest_per_provider)
@@ -2909,7 +3003,11 @@ class AttackPathsScanViewSet(BaseRLSViewSet):
)
def attack_paths_queries(self, request, pk=None):
attack_paths_scan = self.get_object()
- queries = get_queries_for_provider(attack_paths_scan.provider.provider)
+ # TODO: drop the is_migrated argument after Neptune cutover
+ queries = get_queries_for_provider(
+ attack_paths_scan.provider.provider,
+ is_migrated=attack_paths_scan.is_migrated,
+ )
if not queries:
return Response(
@@ -2942,7 +3040,11 @@ class AttackPathsScanViewSet(BaseRLSViewSet):
serializer = AttackPathsQueryRunRequestSerializer(data=payload)
serializer.is_valid(raise_exception=True)
- query_definition = get_query_by_id(serializer.validated_data["id"])
+ # TODO: drop the is_migrated argument after Neptune cutover
+ query_definition = get_query_by_id(
+ serializer.validated_data["id"],
+ is_migrated=attack_paths_scan.is_migrated,
+ )
if (
query_definition is None
or query_definition.provider != attack_paths_scan.provider.provider
@@ -2968,6 +3070,7 @@ class AttackPathsScanViewSet(BaseRLSViewSet):
query_definition,
parameters,
provider_id,
+ scan=attack_paths_scan,
)
query_duration = time.monotonic() - start
@@ -3035,6 +3138,7 @@ class AttackPathsScanViewSet(BaseRLSViewSet):
database_name,
serializer.validated_data["query"],
provider_id,
+ scan=attack_paths_scan,
)
query_duration = time.monotonic() - start
@@ -3091,7 +3195,7 @@ class AttackPathsScanViewSet(BaseRLSViewSet):
provider_id = str(attack_paths_scan.provider_id)
schema = attack_paths_views_helpers.get_cartography_schema(
- database_name, provider_id
+ database_name, provider_id, attack_paths_scan
)
if not schema:
return Response(
@@ -3814,6 +3918,8 @@ class FindingViewSet(PaginateByPkMixin, BaseRLSViewSet):
def get_filterset_class(self):
if self.action in ["latest", "metadata_latest"]:
return LatestFindingFilter
+ if self.action == "metadata":
+ return FindingMetadataFilter
return FindingFilter
def get_queryset(self):
@@ -4349,25 +4455,12 @@ class InvitationAcceptViewSet(BaseRLSViewSet):
invitation_token = serializer.validated_data["invitation_token"]
user_email = request.user.email
- invitation = validate_invitation(
- invitation_token, user_email, raise_not_found=True
- )
-
- # Proceed with accepting the invitation
user = User.objects.using(MainRouter.admin_db).get(email=user_email)
- membership = Membership.objects.using(MainRouter.admin_db).create(
+ invitation, membership = accept_invitation_for_user(
user=user,
- tenant=invitation.tenant,
+ invitation_token=invitation_token,
+ raise_not_found=True,
)
- user_role = []
- for role in invitation.roles.all():
- user_role.append(
- UserRoleRelationship.objects.using(MainRouter.admin_db).create(
- user=user, role=role, tenant=invitation.tenant
- )
- )
- invitation.state = Invitation.State.ACCEPTED
- invitation.save(using=MainRouter.admin_db)
self.response_serializer_class = MembershipSerializer
membership_serializer = self.get_serializer(membership)
diff --git a/api/src/backend/api/validators.py b/api/src/backend/api/validators.py
index 543406f202..6ad7ccfe0f 100644
--- a/api/src/backend/api/validators.py
+++ b/api/src/backend/api/validators.py
@@ -1,14 +1,155 @@
+import ipaddress
+import socket
import string
+from urllib.parse import urlparse
+from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
+LIGHTHOUSE_OPENAI_COMPATIBLE_ALLOWED_SCHEMES = frozenset({"https"})
+LIGHTHOUSE_NAT64_WELL_KNOWN_PREFIX = ipaddress.IPv6Network("64:ff9b::/96")
+LIGHTHOUSE_BLOCKED_METADATA_HOSTS = frozenset(
+ {
+ "169.254.169.254",
+ "169.254.170.2",
+ "fd00:ec2::254",
+ "localhost",
+ "metadata.google.internal",
+ }
+)
+
+
+def _normalize_hostname(hostname: str) -> str:
+ return hostname.rstrip(".").lower()
+
+
+def _lighthouse_openai_compatible_allowed_hosts() -> frozenset[str]:
+ return frozenset(
+ _normalize_hostname(allowed_host.strip())
+ for allowed_host in settings.LIGHTHOUSE_AI_OPENAI_COMPATIBLE_ALLOWED_HOSTS
+ if allowed_host and allowed_host.strip()
+ )
+
+
+def _validate_lighthouse_public_ip(address: str) -> None:
+ ip_address = ipaddress.ip_address(address)
+ if isinstance(ip_address, ipaddress.IPv6Address):
+ # Classify transition addresses by their effective IPv4 destination.
+ embedded_ip_address = ip_address.ipv4_mapped or ip_address.sixtofour
+ if (
+ embedded_ip_address is None
+ and ip_address in LIGHTHOUSE_NAT64_WELL_KNOWN_PREFIX
+ ):
+ embedded_ip_address = ipaddress.IPv4Address(int(ip_address) & 0xFFFFFFFF)
+ if embedded_ip_address is not None:
+ ip_address = embedded_ip_address
+ if not ip_address.is_global:
+ raise ValidationError(
+ _("Base URL must use an external public endpoint."),
+ code="lighthouse_base_url_not_public",
+ )
+
+
+def resolve_lighthouse_openai_compatible_host(
+ hostname: str,
+ port: int,
+ *,
+ resolve_dns: bool = True,
+) -> tuple[str, ...]:
+ """Return public IP addresses that are safe for Lighthouse outbound use."""
+ hostname = _normalize_hostname(hostname)
+ if hostname in _lighthouse_openai_compatible_allowed_hosts():
+ # Operator-allowlisted hosts skip the public-endpoint checks; returning
+ # the hostname makes the network backend connect through regular DNS
+ # resolution instead of pinned addresses.
+ return (hostname,)
+
+ if hostname in LIGHTHOUSE_BLOCKED_METADATA_HOSTS or hostname.endswith(".localhost"):
+ raise ValidationError(
+ _("Base URL must use an external public endpoint."),
+ code="lighthouse_base_url_blocked_host",
+ )
+
+ try:
+ _validate_lighthouse_public_ip(hostname)
+ except ValueError:
+ if not resolve_dns:
+ return ()
+ else:
+ return (hostname,)
+
+ try:
+ resolved_addresses = socket.getaddrinfo(hostname, port, type=socket.SOCK_STREAM)
+ except socket.gaierror as error:
+ raise ValidationError(
+ _("Base URL host could not be resolved."),
+ code="lighthouse_base_url_resolution_failed",
+ ) from error
+
+ if not resolved_addresses:
+ raise ValidationError(
+ _("Base URL host could not be resolved."),
+ code="lighthouse_base_url_resolution_failed",
+ )
+
+ public_addresses: list[str] = []
+ for resolved_address in resolved_addresses:
+ socket_address = resolved_address[4]
+ resolved_ip_address = socket_address[0]
+ _validate_lighthouse_public_ip(resolved_ip_address)
+ if resolved_ip_address not in public_addresses:
+ public_addresses.append(resolved_ip_address)
+
+ return tuple(public_addresses)
+
+
+def validate_lighthouse_openai_compatible_base_url(
+ base_url: str,
+ *,
+ resolve_dns: bool = True,
+) -> None:
+ """Validate an OpenAI-compatible Lighthouse base URL before outbound use."""
+ parsed = urlparse(str(base_url))
+ if parsed.scheme.lower() not in LIGHTHOUSE_OPENAI_COMPATIBLE_ALLOWED_SCHEMES:
+ raise ValidationError(
+ _("Base URL must use HTTPS."),
+ code="lighthouse_base_url_invalid_scheme",
+ )
+
+ if not parsed.hostname:
+ raise ValidationError(
+ _("Base URL must include a host."),
+ code="lighthouse_base_url_missing_host",
+ )
+
+ try:
+ port = parsed.port
+ except ValueError as error:
+ raise ValidationError(
+ _("Base URL port is invalid."),
+ code="lighthouse_base_url_invalid_port",
+ ) from error
+
+ if port is not None and not 1 <= port <= 65535:
+ raise ValidationError(
+ _("Base URL port is invalid."),
+ code="lighthouse_base_url_invalid_port",
+ )
+
+ resolve_lighthouse_openai_compatible_host(
+ parsed.hostname,
+ port or 443,
+ resolve_dns=resolve_dns,
+ )
+
class MaximumLengthValidator:
def __init__(self, max_length=72):
self.max_length = max_length
def validate(self, password, user=None):
+ del user
if len(password) > self.max_length:
raise ValidationError(
_(
@@ -31,6 +172,7 @@ class SpecialCharactersValidator:
self.min_special_characters = min_special_characters
def validate(self, password, user=None):
+ del user
if (
sum(1 for char in password if char in self.special_characters)
< self.min_special_characters
@@ -55,6 +197,7 @@ class UppercaseValidator:
self.min_uppercase = min_uppercase
def validate(self, password, user=None):
+ del user
if sum(1 for char in password if char.isupper()) < self.min_uppercase:
raise ValidationError(
_(
@@ -75,6 +218,7 @@ class LowercaseValidator:
self.min_lowercase = min_lowercase
def validate(self, password, user=None):
+ del user
if sum(1 for char in password if char.islower()) < self.min_lowercase:
raise ValidationError(
_(
@@ -95,6 +239,7 @@ class NumericValidator:
self.min_numeric = min_numeric
def validate(self, password, user=None):
+ del user
if sum(1 for char in password if char.isdigit()) < self.min_numeric:
raise ValidationError(
_(
diff --git a/api/src/backend/config/celery.py b/api/src/backend/config/celery.py
index 1a35a1a753..9ac4f1e4ef 100644
--- a/api/src/backend/config/celery.py
+++ b/api/src/backend/config/celery.py
@@ -74,6 +74,7 @@ celery_app.conf.task_annotations = {
for name in (
"scan-perform",
"scan-perform-scheduled",
+ "attack-paths-scan-perform",
"provider-deletion",
"tenant-deletion",
)
diff --git a/api/src/backend/config/django/base.py b/api/src/backend/config/django/base.py
index 31a9537b5f..a079942600 100644
--- a/api/src/backend/config/django/base.py
+++ b/api/src/backend/config/django/base.py
@@ -230,6 +230,7 @@ SIMPLE_JWT = {
"JTI_CLAIM": "jti",
"USER_ID_FIELD": "id",
"USER_ID_CLAIM": "sub",
+ "CHECK_REVOKE_TOKEN": True,
# Issuer and Audience claims, for the moment we will keep these values as default values, they may change in the
# future.
"AUDIENCE": env.str("DJANGO_JWT_AUDIENCE", "https://api.prowler.com"),
@@ -307,9 +308,26 @@ CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
# Attack Paths
+ATTACK_PATHS_SCAN_INACTIVITY_THRESHOLD_MINUTES = env.int(
+ "ATTACK_PATHS_SCAN_INACTIVITY_THRESHOLD_MINUTES", 30
+)
ATTACK_PATHS_SCAN_STALE_THRESHOLD_MINUTES = env.int(
- "ATTACK_PATHS_SCAN_STALE_THRESHOLD_MINUTES", 2880
-) # 48h
+ "ATTACK_PATHS_SCAN_STALE_THRESHOLD_MINUTES", 960
+) # 16h
+
+# Selects where the persistent attack-paths graph is stored. The scan
+# temporary database is always Neo4j; only the sink is configurable.
+# Valid values: "neo4j" (default, OSS and local dev), "neptune" (hosted).
+ATTACK_PATHS_SINK_DATABASE = env.str("ATTACK_PATHS_SINK_DATABASE", default="neo4j")
+
+# Lighthouse AI
+# Comma-separated hostnames (or IP literals) that bypass the SSRF validation
+# applied to OpenAI-compatible provider base URLs, so self-hosted deployments
+# can point Lighthouse AI at internal endpoints. Empty by default: every base
+# URL must resolve to a public endpoint.
+LIGHTHOUSE_AI_OPENAI_COMPATIBLE_ALLOWED_HOSTS = env.list(
+ "LIGHTHOUSE_AI_OPENAI_COMPATIBLE_ALLOWED_HOSTS", default=[]
+)
# Orphan task recovery feature flags. The master switch is OFF by default, so task
# recovery is opt-in; enable it with DJANGO_TASK_RECOVERY_ENABLED=true. The per-group
diff --git a/api/src/backend/config/django/devel.py b/api/src/backend/config/django/devel.py
index 6921790ca3..5b3871aa8b 100644
--- a/api/src/backend/config/django/devel.py
+++ b/api/src/backend/config/django/devel.py
@@ -50,6 +50,12 @@ DATABASES = {
"USER": env.str("NEO4J_USER", "neo4j"),
"PASSWORD": env.str("NEO4J_PASSWORD", "neo4j_password"),
},
+ "neptune": {
+ "WRITER_ENDPOINT": env.str("NEPTUNE_WRITER_ENDPOINT", ""),
+ "READER_ENDPOINT": env.str("NEPTUNE_READER_ENDPOINT", ""),
+ "PORT": env.str("NEPTUNE_PORT", "8182"),
+ "REGION": env.str("AWS_REGION", ""),
+ },
}
DATABASES["default"] = DATABASES["prowler_user"]
diff --git a/api/src/backend/config/django/production.py b/api/src/backend/config/django/production.py
index cb651f6e76..79d8993b10 100644
--- a/api/src/backend/config/django/production.py
+++ b/api/src/backend/config/django/production.py
@@ -49,12 +49,19 @@ DATABASES = {
"HOST": env("POSTGRES_REPLICA_HOST", default=default_db_host),
"PORT": env("POSTGRES_REPLICA_PORT", default=default_db_port),
},
+ # TODO: drop after Neptune cutover just loosen defaults to `""`
"neo4j": {
"HOST": env.str("NEO4J_HOST"),
"PORT": env.str("NEO4J_PORT"),
"USER": env.str("NEO4J_USER"),
"PASSWORD": env.str("NEO4J_PASSWORD"),
},
+ "neptune": {
+ "WRITER_ENDPOINT": env.str("NEPTUNE_WRITER_ENDPOINT", default=""),
+ "READER_ENDPOINT": env.str("NEPTUNE_READER_ENDPOINT", default=""),
+ "PORT": env.str("NEPTUNE_PORT", default="8182"),
+ "REGION": env.str("AWS_REGION", default=""),
+ },
}
DATABASES["default"] = DATABASES["prowler_user"]
diff --git a/api/src/backend/config/guniconf.py b/api/src/backend/config/guniconf.py
index 9ede1d3164..8b17ad669d 100644
--- a/api/src/backend/config/guniconf.py
+++ b/api/src/backend/config/guniconf.py
@@ -83,12 +83,32 @@ def _warm_compliance_caches_in_background():
def post_fork(_server, worker):
- """Warm compliance caches after each worker fork.
+ """Re-initialize attack-paths drivers and warm compliance caches per worker.
- Warm compliance caches in a background thread so the worker becomes ready
- immediately. A request for a not-yet-warmed provider lazily loads just that
- provider, which stays well under the worker timeout.
+ Neo4j / Neptune drivers spawn background IO threads that do not survive
+ ``fork()``. When the gunicorn master runs with ``preload_app=True``, the
+ child inherits driver objects whose pool references dead threads and
+ hangs on the first ``pool.acquire`` call until the watchdog kills the
+ worker. Re-initializing per worker guarantees each child owns its own
+ live threads. See GUNICORN_WORKER_TIMEOUTS_ANALYSIS.md for detail.
+
+ Compliance caches are then warmed in a background thread so the worker
+ becomes ready immediately. A request for a not-yet-warmed provider lazily
+ loads just that provider, which stays well under the worker timeout.
"""
+ from api.attack_paths import database as graph_database
+
+ try:
+ graph_database.close_driver()
+ except Exception: # pragma: no cover - best-effort cleanup
+ gunicorn_logger.debug(
+ "Failed to close inherited Neo4j driver in post_fork for worker pid=%s",
+ worker.pid,
+ exc_info=True,
+ )
+ graph_database.init_driver()
+ gunicorn_logger.info(f"Attack-paths drivers initialized for worker {worker.pid}")
+
threading.Thread(
target=_warm_compliance_caches_in_background,
name="warm-compliance-caches",
diff --git a/api/src/backend/config/settings/sentry.py b/api/src/backend/config/settings/sentry.py
index 5fd6e39cc9..a3acbe37bb 100644
--- a/api/src/backend/config/settings/sentry.py
+++ b/api/src/backend/config/settings/sentry.py
@@ -91,6 +91,13 @@ def before_send(event, hint):
log_msg = log_record.getMessage()
log_lvl = log_record.levelno
+ if (
+ getattr(log_record, "name", "") == "cartography.graph.job"
+ and "Neo.ClientError.Database.DatabaseNotFound" in log_msg
+ and "db-tmp-scan-" in log_msg
+ ):
+ return None
+
# The Neo4j driver logs transient connection errors (defunct
# connections, resets) at ERROR level via the `neo4j.io` logger.
# `RetryableSession` handles these with retries. If all retries
@@ -115,19 +122,27 @@ def before_send(event, hint):
return event
-sentry_sdk.init(
- dsn=env.str("DJANGO_SENTRY_DSN", ""),
- # Add data like request headers and IP for users,
- # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info
- before_send=before_send,
- send_default_pii=True,
- traces_sample_rate=env.float("DJANGO_SENTRY_TRACES_SAMPLE_RATE", default=0.02),
- _experiments={
- # Set continuous_profiling_auto_start to True
- # to automatically start the profiler on when
- # possible.
- "continuous_profiling_auto_start": True,
- },
- attach_stacktrace=True,
- ignore_errors=IGNORED_EXCEPTIONS,
-)
+def initialize_sentry():
+ sentry_dsn = env.str("DJANGO_SENTRY_DSN", "")
+ if not sentry_dsn:
+ return
+
+ sentry_sdk.init(
+ dsn=sentry_dsn,
+ # Add data like request headers and IP for users,
+ # see https://docs.sentry.io/platforms/python/data-management/data-collected/ for more info
+ before_send=before_send,
+ send_default_pii=True,
+ traces_sample_rate=env.float("DJANGO_SENTRY_TRACES_SAMPLE_RATE", default=0.02),
+ _experiments={
+ # Set continuous_profiling_auto_start to True
+ # to automatically start the profiler on when
+ # possible.
+ "continuous_profiling_auto_start": True,
+ },
+ attach_stacktrace=True,
+ ignore_errors=IGNORED_EXCEPTIONS,
+ )
+
+
+initialize_sentry()
diff --git a/api/src/backend/config/settings/social_login.py b/api/src/backend/config/settings/social_login.py
index d6b5b53df2..ffc6a4724e 100644
--- a/api/src/backend/config/settings/social_login.py
+++ b/api/src/backend/config/settings/social_login.py
@@ -13,16 +13,17 @@ GITHUB_OAUTH_CALLBACK_URL = env("SOCIAL_GITHUB_OAUTH_CALLBACK_URL", default="")
ACCOUNT_LOGIN_METHODS = {"email"} # Use Email / Password authentication
ACCOUNT_SIGNUP_FIELDS = ["email*", "password1*", "password2*"]
ACCOUNT_EMAIL_VERIFICATION = "none" # Do not require email confirmation
+ACCOUNT_EMAIL_NOTIFICATIONS = False
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
REST_AUTH = {
"TOKEN_MODEL": None,
"REST_USE_JWT": True,
}
# django-allauth (social)
-# Authenticate if local account with this email address already exists
-SOCIALACCOUNT_EMAIL_AUTHENTICATION = True
-# Connect local account and social account if local account with that email address already exists
-SOCIALACCOUNT_EMAIL_AUTHENTICATION_AUTO_CONNECT = True
+# Email-based account matching is handled by ProwlerSocialAccountAdapter, which
+# verifies both the provider email and the existing account email before linking.
+SOCIALACCOUNT_EMAIL_AUTHENTICATION = False
+SOCIALACCOUNT_EMAIL_AUTHENTICATION_AUTO_CONNECT = False
SOCIALACCOUNT_ADAPTER = "api.adapters.ProwlerSocialAccountAdapter"
diff --git a/api/src/backend/conftest.py b/api/src/backend/conftest.py
index af58730e7d..daa0616971 100644
--- a/api/src/backend/conftest.py
+++ b/api/src/backend/conftest.py
@@ -2,6 +2,7 @@ import logging
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
+from uuid import uuid4
import pytest
from allauth.socialaccount.models import SocialLogin
@@ -50,12 +51,14 @@ from api.v1.serializers import TokenSerializer
from django.conf import settings
from django.db import connection as django_connection
from django.db import connections as django_connections
+from django.test import Client
from django.urls import reverse
from django_celery_results.models import TaskResult
from prowler.lib.check.models import Severity
from prowler.lib.outputs.finding import Status
from rest_framework import status
from rest_framework.test import APIClient
+from rest_framework_simplejwt.tokens import AccessToken
from tasks.jobs.backfill import (
aggregate_scan_category_summaries,
aggregate_scan_resource_group_summaries,
@@ -67,6 +70,7 @@ API_JSON_CONTENT_TYPE = "application/vnd.api+json"
NO_TENANT_HTTP_STATUS = status.HTTP_401_UNAUTHORIZED
TEST_USER = "dev@prowler.com"
TEST_PASSWORD = "testing_psswd"
+TEST_REPLICA_ALIAS = "test_replica"
def _install_compliance_catalog_test_cache() -> None:
@@ -228,14 +232,15 @@ def create_test_user(_session_test_user, django_db_blocker):
"""Re-create the session-scoped test user when a TransactionTestCase
has truncated the users table."""
with django_db_blocker.unblock():
- if not User.objects.filter(pk=_session_test_user.pk).exists():
- User.objects.create_user(
+ user = User.objects.filter(pk=_session_test_user.pk).first()
+ if user is None:
+ user = User.objects.create_user(
id=_session_test_user.pk,
name="testing",
email=TEST_USER,
password=TEST_PASSWORD,
)
- return _session_test_user
+ return user
@pytest.fixture(scope="function")
@@ -358,22 +363,42 @@ def create_test_user_rbac_manage_account(django_db_setup, django_db_blocker):
return user
+def first_membership_tenant(user):
+ return user.memberships.order_by("date_joined").first().tenant
+
+
+def access_token_for_tenant(user, tenant):
+ access_token = AccessToken.for_user(user)
+ access_token["tenant_id"] = str(tenant.id)
+ access_token.payload["nbf"] = access_token["iat"]
+ return str(access_token)
+
+
+def authenticate_client_for_tenant(client, user, tenant):
+ client.user = user
+ client.defaults["HTTP_AUTHORIZATION"] = (
+ f"Bearer {access_token_for_tenant(user, tenant)}"
+ )
+ return client
+
+
+@pytest.fixture
+def authenticated_client_for_tenant_factory():
+ def create_authenticated_client(user, tenant):
+ return authenticate_client_for_tenant(Client(), user, tenant)
+
+ return create_authenticated_client
+
+
@pytest.fixture
def authenticated_client_rbac_manage_account(
- create_test_user_rbac_manage_account, tenants_fixture, client
+ create_test_user_rbac_manage_account, client
):
- client.user = create_test_user_rbac_manage_account
- serializer = TokenSerializer(
- data={
- "type": "tokens",
- "email": "rbac_manage_account@rbac.com",
- "password": TEST_PASSWORD,
- }
+ return authenticate_client_for_tenant(
+ client,
+ create_test_user_rbac_manage_account,
+ first_membership_tenant(create_test_user_rbac_manage_account),
)
- serializer.is_valid()
- access_token = serializer.validated_data["access"]
- client.defaults["HTTP_AUTHORIZATION"] = f"Bearer {access_token}"
- return client
@pytest.fixture(scope="function")
@@ -410,86 +435,43 @@ def create_test_user_rbac_manage_users_only(django_db_setup, django_db_blocker):
def authenticated_client_rbac_manage_users_only(
create_test_user_rbac_manage_users_only, client
):
- client.user = create_test_user_rbac_manage_users_only
- serializer = TokenSerializer(
- data={
- "type": "tokens",
- "email": "rbac_manage_users_only@rbac.com",
- "password": TEST_PASSWORD,
- }
+ return authenticate_client_for_tenant(
+ client,
+ create_test_user_rbac_manage_users_only,
+ first_membership_tenant(create_test_user_rbac_manage_users_only),
)
- serializer.is_valid()
- access_token = serializer.validated_data["access"]
- client.defaults["HTTP_AUTHORIZATION"] = f"Bearer {access_token}"
- return client
@pytest.fixture
def authenticated_client_rbac(create_test_user_rbac, tenants_fixture, client):
- client.user = create_test_user_rbac
- tenant_id = tenants_fixture[0].id
- serializer = TokenSerializer(
- data={
- "type": "tokens",
- "email": "rbac@rbac.com",
- "password": TEST_PASSWORD,
- "tenant_id": tenant_id,
- }
+ return authenticate_client_for_tenant(
+ client, create_test_user_rbac, tenants_fixture[0]
)
- serializer.is_valid(raise_exception=True)
- access_token = serializer.validated_data["access"]
- client.defaults["HTTP_AUTHORIZATION"] = f"Bearer {access_token}"
- return client
@pytest.fixture
def authenticated_client_rbac_noroles(
create_test_user_rbac_no_roles, tenants_fixture, client
):
- client.user = create_test_user_rbac_no_roles
- serializer = TokenSerializer(
- data={
- "type": "tokens",
- "email": "rbac_noroles@rbac.com",
- "password": TEST_PASSWORD,
- }
+ return authenticate_client_for_tenant(
+ client, create_test_user_rbac_no_roles, tenants_fixture[0]
)
- serializer.is_valid()
- access_token = serializer.validated_data["access"]
- client.defaults["HTTP_AUTHORIZATION"] = f"Bearer {access_token}"
- return client
@pytest.fixture
def authenticated_client_no_permissions_rbac(
create_test_user_rbac_limited, tenants_fixture, client
):
- client.user = create_test_user_rbac_limited
- serializer = TokenSerializer(
- data={
- "type": "tokens",
- "email": "rbac_limited@rbac.com",
- "password": TEST_PASSWORD,
- }
+ return authenticate_client_for_tenant(
+ client, create_test_user_rbac_limited, tenants_fixture[0]
)
- serializer.is_valid()
- access_token = serializer.validated_data["access"]
- client.defaults["HTTP_AUTHORIZATION"] = f"Bearer {access_token}"
- return client
@pytest.fixture
def authenticated_client(
create_test_user, tenants_fixture, set_user_admin_roles_fixture, client
):
- client.user = create_test_user
- serializer = TokenSerializer(
- data={"type": "tokens", "email": TEST_USER, "password": TEST_PASSWORD}
- )
- serializer.is_valid()
- access_token = serializer.validated_data["access"]
- client.defaults["HTTP_AUTHORIZATION"] = f"Bearer {access_token}"
- return client
+ return authenticate_client_for_tenant(client, create_test_user, tenants_fixture[0])
@pytest.fixture
@@ -590,109 +572,191 @@ def users_fixture(django_user_model):
@pytest.fixture
-def providers_fixture(tenants_fixture):
- tenant, *_ = tenants_fixture
- provider1 = Provider.objects.create(
- provider="aws",
- uid="123456789012",
- alias="aws_testing_1",
- tenant_id=tenant.id,
- )
- provider2 = Provider.objects.create(
- provider="aws",
- uid="123456789013",
- alias="aws_testing_2",
- tenant_id=tenant.id,
- )
- provider3 = Provider.objects.create(
- provider="gcp",
- uid="a12322-test321",
- alias="gcp_testing",
- tenant_id=tenant.id,
- )
- provider4 = Provider.objects.create(
- provider="kubernetes",
- uid="kubernetes-test-12345",
- alias="k8s_testing",
- tenant_id=tenant.id,
- )
- provider5 = Provider.objects.create(
- provider="azure",
- uid="37b065f8-26b0-4218-a665-0b23d07b27d9",
- alias="azure_testing",
- tenant_id=tenant.id,
- scanner_args={"key1": "value1", "key2": {"key21": "value21"}},
- )
- provider6 = Provider.objects.create(
- provider="m365",
- uid="m365.test.com",
- alias="m365_testing",
- tenant_id=tenant.id,
- )
- provider7 = Provider.objects.create(
- provider="oraclecloud",
- uid="ocid1.tenancy.oc1..aaaaaaaa3dwoazoox4q7wrvriywpokp5grlhgnkwtyt6dmwyou7no6mdmzda",
- alias="oci_testing",
- tenant_id=tenant.id,
- )
- provider8 = Provider.objects.create(
- provider="mongodbatlas",
- uid="64b1d3c0e4b03b1234567890",
- alias="mongodbatlas_testing",
- tenant_id=tenant.id,
- )
- provider9 = Provider.objects.create(
- provider="alibabacloud",
- uid="1234567890123456",
- alias="alibabacloud_testing",
- tenant_id=tenant.id,
- )
- provider10 = Provider.objects.create(
- provider="cloudflare",
- uid="a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4",
- alias="cloudflare_testing",
- tenant_id=tenant.id,
- )
- provider11 = Provider.objects.create(
- provider="openstack",
- uid="a1b2c3d4-e5f6-7890-abcd-ef1234567890",
- alias="openstack_testing",
- tenant_id=tenant.id,
- )
- provider12 = Provider.objects.create(
- provider="googleworkspace",
- uid="C12345678",
- alias="googleworkspace_testing",
- tenant_id=tenant.id,
- )
- provider13 = Provider.objects.create(
- provider="vercel",
- uid="team_abcdef1234567890ab",
- alias="vercel_testing",
- tenant_id=tenant.id,
- )
- provider14 = Provider.objects.create(
- provider="okta",
- uid="acme.okta.com",
- alias="okta_testing",
- tenant_id=tenant.id,
+def provider_factory(tenants_fixture):
+ tenant = tenants_fixture[0]
+ counters = {}
+
+ def next_counter(provider):
+ counters[provider] = counters.get(provider, 0) + 1
+ return counters[provider]
+
+ def defaults_for(provider, sequence):
+ return {
+ Provider.ProviderChoices.AWS.value: {
+ "uid": f"{123456789011 + sequence:012d}",
+ "alias": f"aws_testing_{sequence}",
+ },
+ Provider.ProviderChoices.AZURE.value: {
+ "uid": str(uuid4()),
+ "alias": f"azure_testing_{sequence}",
+ "scanner_args": {"key1": "value1", "key2": {"key21": "value21"}},
+ },
+ Provider.ProviderChoices.GCP.value: {
+ "uid": f"a12322-test{sequence:05d}",
+ "alias": f"gcp_testing_{sequence}",
+ },
+ Provider.ProviderChoices.KUBERNETES.value: {
+ "uid": f"kubernetes-test-{sequence}",
+ "alias": f"k8s_testing_{sequence}",
+ },
+ Provider.ProviderChoices.M365.value: {
+ "uid": f"m365-{sequence}.test.com",
+ "alias": f"m365_testing_{sequence}",
+ },
+ Provider.ProviderChoices.GITHUB.value: {
+ "uid": f"github-test-{sequence}",
+ "alias": f"github_testing_{sequence}",
+ },
+ Provider.ProviderChoices.MONGODBATLAS.value: {
+ "uid": f"64b1d3c0e4b03b{sequence:010x}",
+ "alias": f"mongodbatlas_testing_{sequence}",
+ },
+ Provider.ProviderChoices.IAC.value: {
+ "uid": f"https://github.com/prowler-cloud/test-{sequence}.git",
+ "alias": f"iac_testing_{sequence}",
+ },
+ Provider.ProviderChoices.ORACLECLOUD.value: {
+ "uid": f"ocid1.tenancy.oc1..aaaaaaaa{sequence:024d}",
+ "alias": f"oci_testing_{sequence}",
+ },
+ Provider.ProviderChoices.ALIBABACLOUD.value: {
+ "uid": f"{1234567890123455 + sequence:016d}",
+ "alias": f"alibabacloud_testing_{sequence}",
+ },
+ Provider.ProviderChoices.CLOUDFLARE.value: {
+ "uid": f"{0x1000000000000000000000000000000 + sequence:032x}",
+ "alias": f"cloudflare_testing_{sequence}",
+ },
+ Provider.ProviderChoices.OPENSTACK.value: {
+ "uid": f"openstack-project-{sequence}",
+ "alias": f"openstack_testing_{sequence}",
+ },
+ Provider.ProviderChoices.IMAGE.value: {
+ "uid": f"registry.example.com/prowler/test:{sequence}",
+ "alias": f"image_testing_{sequence}",
+ },
+ Provider.ProviderChoices.GOOGLEWORKSPACE.value: {
+ "uid": f"C{12345677 + sequence}",
+ "alias": f"googleworkspace_testing_{sequence}",
+ },
+ Provider.ProviderChoices.VERCEL.value: {
+ "uid": f"team_{sequence:016x}",
+ "alias": f"vercel_testing_{sequence}",
+ },
+ Provider.ProviderChoices.OKTA.value: {
+ "uid": f"acme-{sequence}.okta.com",
+ "alias": f"okta_testing_{sequence}",
+ },
+ }[provider]
+
+ def create_provider(provider=Provider.ProviderChoices.AWS.value, **overrides):
+ provider_value = getattr(provider, "value", provider)
+ selected_tenant = overrides.pop("tenant", tenant)
+ sequence = next_counter(provider_value)
+ attributes = {
+ "provider": provider_value,
+ "tenant_id": selected_tenant.id,
+ **defaults_for(provider_value, sequence),
+ }
+ attributes.update(overrides)
+ return Provider.objects.create(**attributes)
+
+ return create_provider
+
+
+@pytest.fixture
+def aws_provider(provider_factory):
+ return provider_factory(Provider.ProviderChoices.AWS.value)
+
+
+@pytest.fixture
+def aws_provider_pair(aws_provider, provider_factory):
+ return (
+ aws_provider,
+ provider_factory(Provider.ProviderChoices.AWS.value),
)
- return (
- provider1,
- provider2,
- provider3,
- provider4,
- provider5,
- provider6,
- provider7,
- provider8,
- provider9,
- provider10,
- provider11,
- provider12,
- provider13,
- provider14,
+
+@pytest.fixture
+def azure_provider(provider_factory):
+ return provider_factory(Provider.ProviderChoices.AZURE.value)
+
+
+@pytest.fixture
+def gcp_provider(provider_factory):
+ return provider_factory(Provider.ProviderChoices.GCP.value)
+
+
+@pytest.fixture
+def kubernetes_provider(provider_factory):
+ return provider_factory(Provider.ProviderChoices.KUBERNETES.value)
+
+
+@pytest.fixture
+def m365_provider(provider_factory):
+ return provider_factory(Provider.ProviderChoices.M365.value)
+
+
+@pytest.fixture
+def github_provider(provider_factory):
+ return provider_factory(Provider.ProviderChoices.GITHUB.value)
+
+
+@pytest.fixture
+def mongodbatlas_provider(provider_factory):
+ return provider_factory(Provider.ProviderChoices.MONGODBATLAS.value)
+
+
+@pytest.fixture
+def iac_provider(provider_factory):
+ return provider_factory(Provider.ProviderChoices.IAC.value)
+
+
+@pytest.fixture
+def oraclecloud_provider(provider_factory):
+ return provider_factory(Provider.ProviderChoices.ORACLECLOUD.value)
+
+
+@pytest.fixture
+def alibabacloud_provider(provider_factory):
+ return provider_factory(Provider.ProviderChoices.ALIBABACLOUD.value)
+
+
+@pytest.fixture
+def cloudflare_provider(provider_factory):
+ return provider_factory(Provider.ProviderChoices.CLOUDFLARE.value)
+
+
+@pytest.fixture
+def openstack_provider(provider_factory):
+ return provider_factory(Provider.ProviderChoices.OPENSTACK.value)
+
+
+@pytest.fixture
+def image_provider(provider_factory):
+ return provider_factory(Provider.ProviderChoices.IMAGE.value)
+
+
+@pytest.fixture
+def googleworkspace_provider(provider_factory):
+ return provider_factory(Provider.ProviderChoices.GOOGLEWORKSPACE.value)
+
+
+@pytest.fixture
+def vercel_provider(provider_factory):
+ return provider_factory(Provider.ProviderChoices.VERCEL.value)
+
+
+@pytest.fixture
+def okta_provider(provider_factory):
+ return provider_factory(Provider.ProviderChoices.OKTA.value)
+
+
+@pytest.fixture
+def all_provider_types_fixture(provider_factory):
+ return tuple(
+ provider_factory(provider_choice.value)
+ for provider_choice in Provider.ProviderChoices
)
@@ -797,7 +861,7 @@ def roles_fixture(tenants_fixture):
@pytest.fixture
-def provider_secret_fixture(providers_fixture):
+def provider_secret_fixture(all_provider_types_fixture):
return tuple(
ProviderSecret.objects.create(
tenant_id=provider.tenant_id,
@@ -806,14 +870,14 @@ def provider_secret_fixture(providers_fixture):
secret={"key": "value"},
name=provider.alias,
)
- for provider in providers_fixture
+ for provider in all_provider_types_fixture
)
@pytest.fixture
-def scans_fixture(tenants_fixture, providers_fixture):
+def scans_fixture(tenants_fixture, aws_provider_pair):
tenant, *_ = tenants_fixture
- provider, provider2, *_ = providers_fixture
+ provider, provider2 = aws_provider_pair
now = datetime.now(UTC)
@@ -876,8 +940,8 @@ def tasks_fixture(tenants_fixture):
@pytest.fixture
-def resources_fixture(providers_fixture):
- provider, *_ = providers_fixture
+def resources_fixture(aws_provider_pair):
+ provider, provider2 = aws_provider_pair
tags = [
ResourceTag.objects.create(
@@ -918,8 +982,8 @@ def resources_fixture(providers_fixture):
resource2.upsert_or_delete_tags(tags)
resource3 = Resource.objects.create(
- tenant_id=providers_fixture[1].tenant_id,
- provider=providers_fixture[1],
+ tenant_id=provider2.tenant_id,
+ provider=provider2,
uid="arn:aws:ec2:us-east-1:123456789012:bucket/i-1234567890abcdef2",
name="My Bucket 3",
region="us-east-1",
@@ -1267,9 +1331,9 @@ def get_api_tokens(
@pytest.fixture
-def scan_summaries_fixture(tenants_fixture, providers_fixture):
+def scan_summaries_fixture(tenants_fixture, aws_provider):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
scan = Scan.objects.create(
name="overview scan",
provider=provider,
@@ -1346,8 +1410,8 @@ def scan_summaries_fixture(tenants_fixture, providers_fixture):
@pytest.fixture
-def integrations_fixture(providers_fixture):
- provider1, provider2, *_ = providers_fixture
+def integrations_fixture(aws_provider_pair):
+ provider1, provider2 = aws_provider_pair
tenant_id = provider1.tenant_id
integration1 = Integration.objects.create(
tenant_id=tenant_id,
@@ -1408,9 +1472,9 @@ def lighthouse_config_fixture(authenticated_client, tenants_fixture):
@pytest.fixture(scope="function")
-def latest_scan_finding(authenticated_client, providers_fixture, resources_fixture):
- provider = providers_fixture[0]
- tenant_id = str(providers_fixture[0].tenant_id)
+def latest_scan_finding(authenticated_client, aws_provider, resources_fixture):
+ provider = aws_provider
+ tenant_id = str(aws_provider.tenant_id)
resource = resources_fixture[0]
scan = Scan.objects.create(
name="latest completed scan",
@@ -1521,10 +1585,10 @@ def findings_with_multiple_categories(scans_fixture, resources_fixture):
@pytest.fixture(scope="function")
def latest_scan_finding_with_categories(
- authenticated_client, providers_fixture, resources_fixture
+ authenticated_client, aws_provider, resources_fixture
):
- provider = providers_fixture[0]
- tenant_id = str(providers_fixture[0].tenant_id)
+ provider = aws_provider
+ tenant_id = str(aws_provider.tenant_id)
resource = resources_fixture[0]
scan = Scan.objects.create(
name="latest completed scan with categories",
@@ -1558,9 +1622,9 @@ def latest_scan_finding_with_categories(
@pytest.fixture(scope="function")
-def latest_scan_resource(authenticated_client, providers_fixture):
- provider = providers_fixture[0]
- tenant_id = str(providers_fixture[0].tenant_id)
+def latest_scan_resource(authenticated_client, aws_provider):
+ provider = aws_provider
+ tenant_id = str(aws_provider.tenant_id)
scan = Scan.objects.create(
name="latest completed scan for resource",
provider=provider,
@@ -1821,6 +1885,36 @@ def attack_paths_query_definition_factory():
return _create
+@pytest.fixture
+def sink_backend_stub():
+ """Install a stub `SinkDatabase` into the sink factory for the test's duration.
+
+ The sink factory caches a process-wide backend and lazily initializes it
+ against `settings.DATABASES["neo4j"]` / `["neptune"]`. Tests that don't
+ want to stand up a real Bolt driver can yield this fixture's mock and
+ configure its return values directly:
+
+ sink_backend_stub.execute_read_query.return_value = some_graph
+
+ Both the active backend and the secondary-backend cache are restored on
+ teardown so tests stay isolated.
+ """
+ from api.attack_paths.sink import factory
+ from api.attack_paths.sink.base import SinkDatabase
+
+ stub = MagicMock(spec=SinkDatabase)
+ previous_backend = factory._backend
+ previous_secondary = dict(factory._secondary_backends)
+ factory._backend = stub
+ factory._secondary_backends.clear()
+ try:
+ yield stub
+ finally:
+ factory._backend = previous_backend
+ factory._secondary_backends.clear()
+ factory._secondary_backends.update(previous_secondary)
+
+
@pytest.fixture
def attack_paths_graph_stub_classes():
"""Provide lightweight graph element stubs for Attack Paths serialization tests."""
@@ -1995,11 +2089,11 @@ def get_authorization_header(access_token: str) -> dict:
@pytest.fixture
def provider_compliance_scores_fixture(
- tenants_fixture, providers_fixture, scans_fixture
+ tenants_fixture, aws_provider_pair, scans_fixture
):
"""Create ProviderComplianceScore entries for compliance watchlist tests."""
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
+ provider1, provider2 = aws_provider_pair
scan1, _, scan3 = scans_fixture
scan1.completed_at = datetime.now(UTC) - timedelta(hours=1)
@@ -2096,9 +2190,7 @@ def tenant_compliance_summary_fixture(tenants_fixture):
@pytest.fixture
-def finding_groups_fixture(
- tenants_fixture, providers_fixture, scans_fixture, resources_fixture
-):
+def finding_groups_fixture(tenants_fixture, scans_fixture, resources_fixture):
"""
Create a comprehensive set of findings for testing Finding Groups aggregation.
@@ -2117,7 +2209,6 @@ def finding_groups_fixture(
- Finding counts (pass, fail, muted, new, changed)
"""
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
scan1, scan2, *_ = scans_fixture
resource1, resource2, *_ = resources_fixture
@@ -2368,7 +2459,7 @@ def finding_groups_fixture(
@pytest.fixture
def finding_groups_title_variants_fixture(
- tenants_fixture, providers_fixture, scans_fixture, resources_fixture
+ tenants_fixture, scans_fixture, resources_fixture
):
"""
Two providers report the same check_id with different checktitle values.
@@ -2379,7 +2470,6 @@ def finding_groups_title_variants_fixture(
of which title variant matches the search term.
"""
tenant = tenants_fixture[0]
- provider1, provider2, *_ = providers_fixture
scan1, scan2, *_ = scans_fixture
resource1, resource2, *_ = resources_fixture
@@ -2453,8 +2543,27 @@ def pytest_collection_modifyitems(items):
"""Ensure test_rbac.py is executed first."""
items.sort(key=lambda item: 0 if "test_rbac.py" in item.nodeid else 1)
+ if any(item.get_closest_marker("requires_test_replica_alias") for item in items):
+ default_database = settings.DATABASES["default"]
+ if TEST_REPLICA_ALIAS not in settings.DATABASES:
+ settings.DATABASES[TEST_REPLICA_ALIAS] = {
+ **default_database,
+ "TEST": {
+ **default_database.get("TEST", {}),
+ "MIRROR": "default",
+ },
+ }
+ django_connections.databases[TEST_REPLICA_ALIAS] = settings.DATABASES[
+ TEST_REPLICA_ALIAS
+ ]
+
def pytest_configure(config):
+ config.addinivalue_line(
+ "markers",
+ "requires_test_replica_alias: creates a test-only replica alias mirrored "
+ "to default",
+ )
# Apply the mock before the test session starts. This is necessary to avoid admin error when running the
# 0004_rbac_missing_admin_roles migration
patch("api.db_router.MainRouter.admin_db", new="default").start()
diff --git a/api/src/backend/tasks/jobs/attack_paths/aws.py b/api/src/backend/tasks/jobs/attack_paths/aws.py
index 398c261ca4..4b2b96dd1b 100644
--- a/api/src/backend/tasks/jobs/attack_paths/aws.py
+++ b/api/src/backend/tasks/jobs/attack_paths/aws.py
@@ -6,7 +6,10 @@ from typing import Any
import aioboto3
import boto3
+import botocore
import neo4j
+import neo4j.exceptions
+from api.attack_paths.database import DATABASE_NOT_FOUND_CODE
from api.models import (
AttackPathsScan as ProwlerAPIAttackPathsScan,
)
@@ -73,13 +76,28 @@ def start_aws_ingestion(
# Adding an extra field
common_job_parameters["AWS_ID"] = prowler_api_provider.uid
- cartography_aws._autodiscover_accounts(
- neo4j_session,
- boto3_session,
- prowler_api_provider.uid,
- cartography_config.update_tag,
- common_job_parameters,
- )
+ # AWS Organizations account autodiscovery. Inlined from Cartography's removed
+ # `_autodiscover_accounts` (deleted in `0.137.0`), as `load_aws_accounts` is still public.
+ try:
+ org_client = boto3_session.client("organizations")
+ paginator = org_client.get_paginator("list_accounts")
+ discovered = []
+ for page in paginator.paginate():
+ discovered.extend(page["Accounts"])
+ active_accounts = {
+ a["Name"]: a["Id"] for a in discovered if a["Status"] == "ACTIVE"
+ }
+ cartography_aws.organizations.load_aws_accounts(
+ neo4j_session,
+ active_accounts,
+ cartography_config.update_tag,
+ common_job_parameters,
+ )
+ except botocore.exceptions.ClientError:
+ logger.warning(
+ f"Account {prowler_api_provider.uid} lacks permissions for AWS "
+ "Organizations autodiscovery."
+ )
db_utils.update_attack_paths_scan_progress(attack_paths_scan, 4)
failed_syncs = sync_aws_account(
@@ -277,7 +295,7 @@ def sync_aws_account(
sync_args: dict[str, Any],
attack_paths_scan: ProwlerAPIAttackPathsScan,
) -> dict[str, str]:
- current_progress = 4 # `cartography_aws._autodiscover_accounts`
+ current_progress = 4 # AWS Organizations account autodiscovery
max_progress = (
87 # `cartography_aws.RESOURCE_FUNCTIONS["permission_relationships"]` - 1
)
@@ -331,6 +349,12 @@ def sync_aws_account(
)
except Exception as e:
+ if (
+ isinstance(e, neo4j.exceptions.Neo4jError)
+ and e.code == DATABASE_NOT_FOUND_CODE
+ ):
+ raise
+
logger.info(
f"Synced function {func_name} for AWS account {prowler_api_provider.uid} in {time.perf_counter() - func_t0:.3f}s (FAILED)"
)
diff --git a/api/src/backend/tasks/jobs/attack_paths/cleanup.py b/api/src/backend/tasks/jobs/attack_paths/cleanup.py
index 9ac2733faf..11868b3fe0 100644
--- a/api/src/backend/tasks/jobs/attack_paths/cleanup.py
+++ b/api/src/backend/tasks/jobs/attack_paths/cleanup.py
@@ -1,40 +1,50 @@
from datetime import UTC, datetime, timedelta
+from functools import partial
from api.attack_paths import database as graph_database
from api.db_router import MainRouter
from api.db_utils import rls_transaction
from api.models import AttackPathsScan, StateChoices
-from celery import states
+from celery import current_app, states
from celery.utils.log import get_task_logger
-from config.django.base import ATTACK_PATHS_SCAN_STALE_THRESHOLD_MINUTES
+from config.django.base import (
+ ATTACK_PATHS_SCAN_INACTIVITY_THRESHOLD_MINUTES,
+ ATTACK_PATHS_SCAN_STALE_THRESHOLD_MINUTES,
+)
+from django.db import DatabaseError
+from django.db.transaction import on_commit
from tasks.jobs.attack_paths.db_utils import (
- _mark_scan_finished,
+ mark_scan_finished,
recover_graph_data_ready,
)
-from tasks.jobs.orphan_recovery import is_worker_alive as _is_worker_alive
from tasks.jobs.orphan_recovery import revoke_task as _revoke_task
logger = get_task_logger(__name__)
+WORKER_PING_BASE_TIMEOUT_SECONDS = 5
+WORKER_PING_MAX_ATTEMPTS = 3
+
def cleanup_stale_attack_paths_scans() -> dict:
"""
Mark stale `AttackPathsScan` rows as `FAILED`.
Covers two stuck-state scenarios:
- 1. `EXECUTING` scans whose workers are dead, or that have exceeded the
- stale threshold while alive.
- 2. `SCHEDULED` scans that never made it to a worker — parent scan
+ 1. `EXECUTING` scans whose workers are unresponsive and whose rows have
+ stopped receiving progress updates, or that exceeded the stale threshold.
+ 2. `SCHEDULED` scans that never made it to a worker - parent scan
crashed before dispatch, broker lost the message, etc. Detected by
age plus the parent `Scan` no longer being in flight.
"""
- threshold = timedelta(minutes=ATTACK_PATHS_SCAN_STALE_THRESHOLD_MINUTES)
now = datetime.now(tz=UTC)
- cutoff = now - threshold
+ stale_cutoff = now - timedelta(minutes=ATTACK_PATHS_SCAN_STALE_THRESHOLD_MINUTES)
+ inactivity_cutoff = now - timedelta(
+ minutes=ATTACK_PATHS_SCAN_INACTIVITY_THRESHOLD_MINUTES
+ )
cleaned_up: list[str] = []
- cleaned_up.extend(_cleanup_stale_executing_scans(cutoff))
- cleaned_up.extend(_cleanup_stale_scheduled_scans(cutoff))
+ cleaned_up.extend(_cleanup_stale_executing_scans(stale_cutoff, inactivity_cutoff))
+ cleaned_up.extend(_cleanup_stale_scheduled_scans(stale_cutoff))
logger.info(
f"Stale `AttackPathsScan` cleanup: {len(cleaned_up)} scan(s) cleaned up"
@@ -42,13 +52,57 @@ def cleanup_stale_attack_paths_scans() -> dict:
return {"cleaned_up_count": len(cleaned_up), "scan_ids": cleaned_up}
-def _cleanup_stale_executing_scans(cutoff: datetime) -> list[str]:
+def _ping_workers(workers: set[str]) -> tuple[set[str], set[str] | None]:
+ """Ping worker destinations in parallel and retry only missing workers.
+
+ The second tuple item is `None` when the final ping attempt raises. In that
+ case the pending workers have unknown liveness and their scans must be kept.
+ """
+ pending = set(workers)
+ responsive: set[str] = set()
+
+ for attempt in range(WORKER_PING_MAX_ATTEMPTS):
+ if not pending:
+ return responsive, set()
+
+ timeout = WORKER_PING_BASE_TIMEOUT_SECONDS * 2**attempt
+ try:
+ response = current_app.control.inspect(
+ destination=sorted(pending), timeout=timeout
+ ).ping()
+ except Exception:
+ attempts_remaining = WORKER_PING_MAX_ATTEMPTS - attempt - 1
+ if attempts_remaining:
+ logger.warning(
+ f"Attack Paths worker ping attempt {attempt + 1} failed; "
+ f"retrying pending workers with {attempts_remaining} "
+ "attempt(s) remaining",
+ exc_info=True,
+ )
+ continue
+
+ logger.exception(
+ "Attack Paths worker ping attempts exhausted; preserving scans "
+ "for workers with unknown liveness"
+ )
+ return responsive, None
+
+ responded = pending.intersection((response or {}).keys())
+ responsive.update(responded)
+ pending.difference_update(responded)
+
+ return responsive, pending
+
+
+def _cleanup_stale_executing_scans(
+ stale_cutoff: datetime, inactivity_cutoff: datetime
+) -> list[str]:
"""
Two-pass detection for `EXECUTING` scans:
- 1. If `TaskResult.worker` exists, ping the worker.
- - Dead worker: cleanup immediately (any age).
- - Alive + past threshold: revoke the task, then cleanup.
- - Alive + within threshold: skip.
+ 1. Ping all recorded workers in parallel with bounded retries.
+ - Responsive + past stale threshold: cleanup.
+ - Unresponsive + past inactivity threshold: cleanup.
+ - Unknown after a final ping exception: preserve.
2. If no worker field: fall back to time-based heuristic only.
"""
executing_scans = list(
@@ -57,14 +111,13 @@ def _cleanup_stale_executing_scans(cutoff: datetime) -> list[str]:
.select_related("task__task_runner_task")
)
- # Cache worker liveness so each worker is pinged at most once
workers = {
tr.worker
for scan in executing_scans
if (tr := getattr(scan.task, "task_runner_task", None) if scan.task else None)
and tr.worker
}
- worker_alive = {w: _is_worker_alive(w) for w in workers}
+ responsive_workers, unresponsive_workers = _ping_workers(workers)
cleaned_up: list[str] = []
@@ -75,27 +128,50 @@ def _cleanup_stale_executing_scans(cutoff: datetime) -> list[str]:
worker = task_result.worker if task_result else None
if worker:
- alive = worker_alive.get(worker, True)
-
- if alive:
- if scan.started_at and scan.started_at >= cutoff:
+ if worker in responsive_workers:
+ if scan.started_at is None or scan.started_at >= stale_cutoff:
continue
- # Alive but stale — revoke before cleanup
- _revoke_task(task_result)
- reason = "Scan exceeded stale threshold — cleaned up by periodic task"
+ reason = "Scan exceeded stale threshold - cleaned up by periodic task"
+ recheck_activity_cutoff = None
+ elif unresponsive_workers is None or worker not in unresponsive_workers:
+ logger.info(
+ f"Preserving scan {scan.id}: worker {worker} liveness is "
+ f"unknown (progress={scan.progress}, updated_at={scan.updated_at})"
+ )
+ continue
else:
- reason = "Worker dead — cleaned up by periodic task"
+ if scan.updated_at >= inactivity_cutoff:
+ logger.info(
+ f"Preserving scan {scan.id}: worker {worker} is unresponsive "
+ f"but activity is recent (progress={scan.progress}, "
+ f"updated_at={scan.updated_at})"
+ )
+ continue
+
+ reason = (
+ "Worker unresponsive and scan inactive for "
+ f"{ATTACK_PATHS_SCAN_INACTIVITY_THRESHOLD_MINUTES} minutes - "
+ "cleaned up by periodic task"
+ )
+ recheck_activity_cutoff = inactivity_cutoff
else:
- # No worker recorded — time-based heuristic only
- if scan.started_at and scan.started_at >= cutoff:
+ # No worker recorded, time-based heuristic only
+ if scan.started_at is None or scan.started_at >= stale_cutoff:
continue
reason = (
- "No worker recorded, scan exceeded stale threshold — "
+ "No worker recorded, scan exceeded stale threshold - "
"cleaned up by periodic task"
)
+ recheck_activity_cutoff = None
- if _cleanup_scan(scan, task_result, reason):
+ if _cleanup_scan(
+ scan,
+ task_result,
+ reason,
+ revoke=worker is not None,
+ inactivity_cutoff=recheck_activity_cutoff,
+ ):
cleaned_up.append(str(scan.id))
return cleaned_up
@@ -112,10 +188,9 @@ def _cleanup_stale_scheduled_scans(cutoff: datetime) -> list[str]:
avoids cleaning up rows whose parent Prowler scan is legitimately still
running.
- For each match: revoke the queued task (best-effort; harmless if already
- consumed), atomically flip to `FAILED`, and mark the `TaskResult`. The
- temp Neo4j database is never created while `SCHEDULED`, so no drop is
- needed.
+ For each match: lock and recheck the row, mark the scan and `TaskResult` as
+ failed, then revoke the queued task after the transaction commits. The temp
+ Neo4j database is never created while `SCHEDULED`, so no drop is needed.
"""
scheduled_scans = list(
AttackPathsScan.all_objects.using(MainRouter.admin_db)
@@ -141,42 +216,54 @@ def _cleanup_stale_scheduled_scans(cutoff: datetime) -> list[str]:
task_result = (
getattr(scan.task, "task_runner_task", None) if scan.task else None
)
- if task_result:
- _revoke_task(task_result, terminate=False)
-
- reason = "Scan never started — cleaned up by periodic task"
+ reason = "Scan never started - cleaned up by periodic task"
if _cleanup_scheduled_scan(scan, task_result, reason):
cleaned_up.append(str(scan.id))
return cleaned_up
-def _cleanup_scan(scan, task_result, reason: str) -> bool:
+def _cleanup_scan(
+ scan,
+ task_result,
+ reason: str,
+ *,
+ revoke: bool = False,
+ inactivity_cutoff: datetime | None = None,
+) -> bool:
"""
Clean up a single stale `AttackPathsScan`:
- drop temp DB, mark `FAILED`, update `TaskResult`, recover `graph_data_ready`.
+ lock and recheck, mark `FAILED`, revoke after commit, drop the temp DB, and
+ recover graph readiness.
Returns `True` if the scan was actually cleaned up, `False` if skipped.
"""
scan_id_str = str(scan.id)
- # 1. Drop temp Neo4j database
+ try:
+ fresh_scan = _finalize_failed_scan(
+ scan,
+ StateChoices.EXECUTING,
+ reason,
+ task_result=task_result,
+ revoke=revoke,
+ inactivity_cutoff=inactivity_cutoff,
+ )
+ except DatabaseError:
+ logger.exception(
+ f"Failed to mark stale Attack Paths scan {scan_id_str} as failed"
+ )
+ return False
+
+ if fresh_scan is None:
+ return False
+
tmp_db_name = graph_database.get_database_name(scan.id, temporary=True)
try:
graph_database.drop_database(tmp_db_name)
except Exception:
logger.exception(f"Failed to drop temp database {tmp_db_name}")
- fresh_scan = _finalize_failed_scan(scan, StateChoices.EXECUTING, reason)
- if fresh_scan is None:
- return False
-
- # Mark `TaskResult` as `FAILURE` (not RLS-protected, outside lock)
- if task_result:
- task_result.status = states.FAILURE
- task_result.date_done = datetime.now(tz=UTC)
- task_result.save(update_fields=["status", "date_done"])
-
recover_graph_data_ready(fresh_scan)
logger.info(f"Cleaned up stale scan {scan_id_str}: {reason}")
@@ -187,31 +274,49 @@ def _cleanup_scheduled_scan(scan, task_result, reason: str) -> bool:
"""
Clean up a `SCHEDULED` scan that never reached a worker.
- Skips the temp Neo4j drop — the database is only created once the worker
+ Skips the temp Neo4j drop - the database is only created once the worker
enters `EXECUTING`, so dropping it here just produces noisy log output.
Returns `True` if the scan was actually cleaned up, `False` if skipped.
"""
scan_id_str = str(scan.id)
- fresh_scan = _finalize_failed_scan(scan, StateChoices.SCHEDULED, reason)
- if fresh_scan is None:
+ try:
+ fresh_scan = _finalize_failed_scan(
+ scan,
+ StateChoices.SCHEDULED,
+ reason,
+ task_result=task_result,
+ revoke=task_result is not None,
+ terminate=False,
+ )
+ except DatabaseError:
+ logger.exception(
+ f"Failed to mark scheduled Attack Paths scan {scan_id_str} as failed"
+ )
return False
- if task_result:
- task_result.status = states.FAILURE
- task_result.date_done = datetime.now(tz=UTC)
- task_result.save(update_fields=["status", "date_done"])
+ if fresh_scan is None:
+ return False
logger.info(f"Cleaned up scheduled scan {scan_id_str}: {reason}")
return True
-def _finalize_failed_scan(scan, expected_state: str, reason: str):
+def _finalize_failed_scan(
+ scan,
+ expected_state: str,
+ reason: str,
+ *,
+ task_result=None,
+ revoke: bool = False,
+ terminate: bool = True,
+ inactivity_cutoff: datetime | None = None,
+):
"""
- Atomically lock the row, verify it's still in `expected_state`, and
- mark it `FAILED`. Returns the locked row on success, `None` if the
- row is gone or has already moved on.
+ Atomically lock the row, verify it's still eligible, and mark it `FAILED`.
+ If requested, register revocation after commit. Returns the locked row on
+ success, `None` if the row is gone or has already moved on.
"""
scan_id_str = str(scan.id)
with rls_transaction(str(scan.tenant_id)):
@@ -225,6 +330,23 @@ def _finalize_failed_scan(scan, expected_state: str, reason: str):
logger.info(f"Scan {scan_id_str} is now {fresh_scan.state}, skipping")
return None
- _mark_scan_finished(fresh_scan, StateChoices.FAILED, {"global_error": reason})
+ if inactivity_cutoff is not None and fresh_scan.updated_at >= inactivity_cutoff:
+ logger.info(
+ f"Scan {scan_id_str} received activity during worker checks, skipping"
+ )
+ return None
+
+ mark_scan_finished(fresh_scan, StateChoices.FAILED, {"global_error": reason})
+
+ if task_result:
+ task_result.status = states.FAILURE
+ task_result.date_done = datetime.now(tz=UTC)
+ task_result.save(update_fields=["status", "date_done"])
+
+ if revoke and task_result:
+ on_commit(
+ partial(_revoke_task, task_result, terminate=terminate),
+ using=fresh_scan._state.db,
+ )
return fresh_scan
diff --git a/api/src/backend/tasks/jobs/attack_paths/config.py b/api/src/backend/tasks/jobs/attack_paths/config.py
index 78ca7eb038..122fc8a9e0 100644
--- a/api/src/backend/tasks/jobs/attack_paths/config.py
+++ b/api/src/backend/tasks/jobs/attack_paths/config.py
@@ -1,17 +1,19 @@
from collections.abc import Callable
-from dataclasses import dataclass
from uuid import UUID
from config.env import env
-from tasks.jobs.attack_paths import aws
+from tasks.jobs.attack_paths import provider_config as _provider_config
-# Batch size for Neo4j write operations (resource labeling, cleanup)
-BATCH_SIZE = env.int("ATTACK_PATHS_BATCH_SIZE", 1000)
+# Re-export provider config objects so existing imports keep working.
+AWS_CONFIG = _provider_config.AWS_CONFIG
+NormalizedList = _provider_config.NormalizedList
+PROVIDER_CONFIGS = _provider_config.PROVIDER_CONFIGS
+ProviderConfig = _provider_config.ProviderConfig
+
+# Batch size for graph mutation operations (resource labeling and subgraph deletion)
+GRAPH_MUTATION_BATCH_SIZE = env.int("ATTACK_PATHS_GRAPH_MUTATION_BATCH_SIZE", 1000)
# Batch size for Postgres findings fetch (keyset pagination page size)
FINDINGS_BATCH_SIZE = env.int("ATTACK_PATHS_FINDINGS_BATCH_SIZE", 1000)
-# Batch size for temp-to-tenant graph sync (nodes and relationships per cursor page)
-SYNC_BATCH_SIZE = env.int("ATTACK_PATHS_SYNC_BATCH_SIZE", 1000)
-
# Neo4j internal labels (Prowler-specific, not provider-specific)
# - `Internet`: Singleton node representing external internet access for exposed-resource queries
# - `ProwlerFinding`: Label for finding nodes created by Prowler and linked to cloud resources
@@ -21,42 +23,12 @@ PROWLER_FINDING_LABEL = "ProwlerFinding"
PROVIDER_RESOURCE_LABEL = "_ProviderResource"
# Dynamic isolation labels that contain entity UUIDs and are added to every synced node during sync
-# Format: _Tenant_{uuid_no_hyphens}, _Provider_{uuid_no_hyphens}
+# Format: `_Tenant_{uuid_no_hyphens}`, `_Provider_{uuid_no_hyphens}`
TENANT_LABEL_PREFIX = "_Tenant_"
PROVIDER_LABEL_PREFIX = "_Provider_"
DYNAMIC_ISOLATION_PREFIXES = [TENANT_LABEL_PREFIX, PROVIDER_LABEL_PREFIX]
-@dataclass(frozen=True)
-class ProviderConfig:
- """Configuration for a cloud provider's Attack Paths integration."""
-
- name: str
- root_node_label: str # e.g., "AWSAccount"
- uid_field: str # e.g., "arn"
- # Label for resources connected to the account node, enabling indexed finding lookups.
- resource_label: str # e.g., "_AWSResource"
- ingestion_function: Callable
- # Maps a Postgres resource UID (e.g. full ARN) to the short-id form Cartography stores on some node types (e.g. `i-xxx` for EC2Instance).
- short_uid_extractor: Callable[[str], str]
-
-
-# Provider Configurations
-# -----------------------
-
-AWS_CONFIG = ProviderConfig(
- name="aws",
- root_node_label="AWSAccount",
- uid_field="arn",
- resource_label="_AWSResource",
- ingestion_function=aws.start_aws_ingestion,
- short_uid_extractor=aws.extract_short_uid,
-)
-
-PROVIDER_CONFIGS: dict[str, ProviderConfig] = {
- "aws": AWS_CONFIG,
-}
-
# Labels added by Prowler that should be filtered from API responses
# Derived from provider configs + common internal labels
INTERNAL_LABELS: list[str] = [
@@ -87,7 +59,6 @@ INTERNAL_PROPERTIES: list[str] = [
# Provider Config Accessors
-# -------------------------
def is_provider_available(provider_type: str) -> bool:
@@ -135,7 +106,6 @@ def get_short_uid_extractor(provider_type: str) -> Callable[[str], str]:
# Dynamic Isolation Label Helpers
-# --------------------------------
def _normalize_uuid(value: str | UUID) -> str:
diff --git a/api/src/backend/tasks/jobs/attack_paths/db_utils.py b/api/src/backend/tasks/jobs/attack_paths/db_utils.py
index f1bb4edef4..327d4463e2 100644
--- a/api/src/backend/tasks/jobs/attack_paths/db_utils.py
+++ b/api/src/backend/tasks/jobs/attack_paths/db_utils.py
@@ -8,6 +8,8 @@ from api.models import Provider as ProwlerAPIProvider
from api.models import StateChoices
from cartography.config import Config as CartographyConfig
from celery.utils.log import get_task_logger
+from django.conf import settings
+from django.db.models import Case, IntegerField, Value, When
from tasks.jobs.attack_paths.config import is_provider_available
logger = get_task_logger(__name__)
@@ -29,13 +31,33 @@ def create_attack_paths_scan(
return None
with rls_transaction(tenant_id):
- # Inherit graph_data_ready from the previous scan for this provider,
- # so queries remain available while the new scan runs.
- previous_data_ready = ProwlerAPIAttackPathsScan.objects.filter(
- tenant_id=tenant_id,
- provider_id=provider_id,
- graph_data_ready=True,
- ).exists()
+ # Inherit metadata from the previous ready scan for this provider so
+ # queries remain available while the new scan runs. The new row only
+ # flips to the target sink after its own graph sync succeeds.
+ active_sink_backend = settings.ATTACK_PATHS_SINK_DATABASE
+ previous_ready = (
+ ProwlerAPIAttackPathsScan.objects.filter(
+ tenant_id=tenant_id,
+ provider_id=provider_id,
+ graph_data_ready=True,
+ )
+ .annotate(
+ active_sink_rank=Case(
+ When(sink_backend=active_sink_backend, then=Value(0)),
+ default=Value(1),
+ output_field=IntegerField(),
+ )
+ )
+ .order_by("active_sink_rank", "-inserted_at")
+ .first()
+ )
+ previous_data_ready = previous_ready is not None
+ inherited_is_migrated = previous_ready.is_migrated if previous_ready else False
+ inherited_sink_backend = (
+ previous_ready.sink_backend
+ if previous_ready
+ else ProwlerAPIAttackPathsScan.SinkBackendChoices.NEO4J
+ )
attack_paths_scan = ProwlerAPIAttackPathsScan.objects.create(
tenant_id=tenant_id,
@@ -44,6 +66,8 @@ def create_attack_paths_scan(
state=StateChoices.SCHEDULED,
started_at=datetime.now(tz=UTC),
graph_data_ready=previous_data_ready,
+ is_migrated=inherited_is_migrated,
+ sink_backend=inherited_sink_backend,
)
attack_paths_scan.save()
@@ -102,19 +126,22 @@ def starting_attack_paths_scan(
if locked.state != StateChoices.SCHEDULED:
return False
+ now = datetime.now(tz=UTC)
locked.state = StateChoices.EXECUTING
- locked.started_at = datetime.now(tz=UTC)
+ locked.started_at = now
+ locked.updated_at = now
locked.update_tag = cartography_config.update_tag
- locked.save(update_fields=["state", "started_at", "update_tag"])
+ locked.save(update_fields=["state", "started_at", "updated_at", "update_tag"])
# Keep the in-memory object the caller is holding in sync.
attack_paths_scan.state = locked.state
attack_paths_scan.started_at = locked.started_at
+ attack_paths_scan.updated_at = locked.updated_at
attack_paths_scan.update_tag = locked.update_tag
return True
-def _mark_scan_finished(
+def mark_scan_finished(
attack_paths_scan: ProwlerAPIAttackPathsScan,
state: StateChoices,
ingestion_exceptions: dict[str, Any],
@@ -148,7 +175,7 @@ def finish_attack_paths_scan(
ingestion_exceptions: dict[str, Any],
) -> None:
with rls_transaction(attack_paths_scan.tenant_id):
- _mark_scan_finished(attack_paths_scan, state, ingestion_exceptions)
+ mark_scan_finished(attack_paths_scan, state, ingestion_exceptions)
def update_attack_paths_scan_progress(
@@ -157,7 +184,8 @@ def update_attack_paths_scan_progress(
) -> None:
with rls_transaction(attack_paths_scan.tenant_id):
attack_paths_scan.progress = progress
- attack_paths_scan.save(update_fields=["progress"])
+ attack_paths_scan.updated_at = datetime.now(tz=UTC)
+ attack_paths_scan.save(update_fields=["progress", "updated_at"])
def set_graph_data_ready(
@@ -169,19 +197,45 @@ def set_graph_data_ready(
attack_paths_scan.save(update_fields=["graph_data_ready"])
+def set_scan_migrated(
+ attack_paths_scan: ProwlerAPIAttackPathsScan,
+ migrated: bool,
+ sink_backend: str | None = None,
+) -> None:
+ """Mark the scan as written with the current (migrated) schema.
+
+ Called after a successful sync so the read catalog and sink backend only
+ switch once the new graph is actually live.
+
+ # TODO: drop after Neptune cutover
+ """
+ with rls_transaction(attack_paths_scan.tenant_id):
+ attack_paths_scan.is_migrated = migrated
+ update_fields = ["is_migrated"]
+ if sink_backend is not None:
+ attack_paths_scan.sink_backend = sink_backend
+ update_fields.append("sink_backend")
+ attack_paths_scan.save(update_fields=update_fields)
+
+
def set_provider_graph_data_ready(
attack_paths_scan: ProwlerAPIAttackPathsScan,
ready: bool,
+ sink_backend: str | None = None,
) -> None:
"""
- Set `graph_data_ready` for ALL scans of the same provider.
+ Set `graph_data_ready` for scans of the same provider in one sink.
- Used before drop/sync so that older scan IDs cannot bypass the query gate while the graph is being replaced.
+ Used before drop/sync so that older scan IDs in the target sink cannot
+ bypass the query gate while that sink's graph is being replaced. Scans
+ preserved in another sink stay queryable for rollback.
"""
+ target_sink_backend = sink_backend or attack_paths_scan.sink_backend
with rls_transaction(attack_paths_scan.tenant_id):
ProwlerAPIAttackPathsScan.objects.filter(
tenant_id=attack_paths_scan.tenant_id,
provider_id=attack_paths_scan.provider_id,
+ sink_backend=target_sink_backend,
).update(graph_data_ready=ready)
attack_paths_scan.refresh_from_db(fields=["graph_data_ready"])
@@ -202,10 +256,15 @@ def recover_graph_data_ready(
next successful scan) is a worse outcome for the user.
"""
try:
+ from api.attack_paths import sink as sink_module
+
tenant_db = graph_database.get_database_name(attack_paths_scan.tenant_id)
- if graph_database.has_provider_data(
- tenant_db, str(attack_paths_scan.provider_id)
- ):
+ # TODO: drop after Neptune cutover
+ # Check the backend that actually holds this scan's data, not the
+ # currently configured sink, a stale `EXECUTING` scan from before a
+ # backend switch must still be recoverable
+ backend = sink_module.get_backend_for_scan(attack_paths_scan)
+ if backend.has_provider_data(tenant_db, str(attack_paths_scan.provider_id)):
set_provider_graph_data_ready(attack_paths_scan, True)
logger.info(
f"Recovered `graph_data_ready` for provider {attack_paths_scan.provider_id}"
@@ -247,6 +306,6 @@ def fail_attack_paths_scan(
return
if fresh.state in (StateChoices.COMPLETED, StateChoices.FAILED):
return
- _mark_scan_finished(fresh, StateChoices.FAILED, {"global_error": error})
+ mark_scan_finished(fresh, StateChoices.FAILED, {"global_error": error})
recover_graph_data_ready(fresh)
diff --git a/api/src/backend/tasks/jobs/attack_paths/findings.py b/api/src/backend/tasks/jobs/attack_paths/findings.py
index a5bc4c1ad5..c47c9f1149 100644
--- a/api/src/backend/tasks/jobs/attack_paths/findings.py
+++ b/api/src/backend/tasks/jobs/attack_paths/findings.py
@@ -21,8 +21,8 @@ from cartography.config import Config as CartographyConfig
from celery.utils.log import get_task_logger
from prowler.config import config as ProwlerConfig
from tasks.jobs.attack_paths.config import (
- BATCH_SIZE,
FINDINGS_BATCH_SIZE,
+ GRAPH_MUTATION_BATCH_SIZE,
get_node_uid_field,
get_provider_resource_label,
get_root_node_label,
@@ -82,7 +82,6 @@ def _to_neo4j_dict(
# Public API
-# ----------
def analysis(
@@ -136,7 +135,7 @@ def add_resource_label(
while labeled_count > 0:
result = neo4j_session.run(
query,
- {"provider_uid": provider_uid, "batch_size": BATCH_SIZE},
+ {"provider_uid": provider_uid, "batch_size": GRAPH_MUTATION_BATCH_SIZE},
)
labeled_count = result.single().get("labeled_count", 0)
total_labeled += labeled_count
@@ -196,7 +195,6 @@ def load_findings(
# Findings Streaming (Generator-based)
-# -------------------------------------
def stream_findings_with_resources(
@@ -275,7 +273,6 @@ def _fetch_findings_batch(
# Batch Enrichment
-# -----------------
def _enrich_batch_with_resources(
diff --git a/api/src/backend/tasks/jobs/attack_paths/indexes.py b/api/src/backend/tasks/jobs/attack_paths/indexes.py
index c2b56197d4..50e8a12bcd 100644
--- a/api/src/backend/tasks/jobs/attack_paths/indexes.py
+++ b/api/src/backend/tasks/jobs/attack_paths/indexes.py
@@ -1,5 +1,6 @@
import neo4j
from cartography.client.core.tx import run_write_query
+from cartography.intel import create_indexes as cartography_create_indexes
from celery.utils.log import get_task_logger
from tasks.jobs.attack_paths.config import (
INTERNET_NODE_LABEL,
@@ -30,14 +31,34 @@ SYNC_INDEX_STATEMENTS = [
def create_findings_indexes(neo4j_session: neo4j.Session) -> None:
- """Create indexes for Prowler findings and resource lookups."""
+ """Create indexes for Prowler findings and resource lookups.
+
+ Runs `CREATE INDEX`, so the caller must only invoke this against a Neo4j
+ session (the temp ingest DB or a Neo4j sink). Neptune auto-manages indexes
+ and rejects `CREATE INDEX`, so callers skip it for the Neptune sink.
+ """
logger.info("Creating indexes for Prowler Findings node types")
for statement in FINDINGS_INDEX_STATEMENTS:
run_write_query(neo4j_session, statement)
+def create_cartography_indexes(neo4j_session: neo4j.Session, config) -> None:
+ """Create Cartography's standard indexes for the session's database.
+
+ Runs `CREATE INDEX`, so the caller must only invoke this against a Neo4j
+ session (the temp ingest DB or a Neo4j sink). Neptune auto-manages indexes
+ and rejects `CREATE INDEX`, so callers skip it for the Neptune sink.
+ """
+ cartography_create_indexes.run(neo4j_session, config)
+
+
def create_sync_indexes(neo4j_session: neo4j.Session) -> None:
- """Create indexes for provider resource sync operations."""
+ """Create indexes for provider resource sync operations.
+
+ Runs `CREATE INDEX`, so the caller must only invoke this against a Neo4j
+ session (the temp ingest DB or a Neo4j sink). Neptune auto-manages indexes
+ and rejects `CREATE INDEX`, so callers skip it for the Neptune sink.
+ """
logger.info("Ensuring ProviderResource indexes exist")
for statement in SYNC_INDEX_STATEMENTS:
neo4j_session.run(statement)
diff --git a/api/src/backend/tasks/jobs/attack_paths/provider_config.py b/api/src/backend/tasks/jobs/attack_paths/provider_config.py
new file mode 100644
index 0000000000..7d834e6aff
--- /dev/null
+++ b/api/src/backend/tasks/jobs/attack_paths/provider_config.py
@@ -0,0 +1,431 @@
+"""
+Provider-level Attack Paths configuration.
+
+Each `ProviderConfig` carries the cloud provider's ingestion entry point and
+the catalog of list-typed node properties (`normalized_lists`). The sync
+layer reads this catalog and materialises each list element as a child node
+connected to the parent by a typed edge, so queries traverse the graph
+instead of working on serialised list values. Both Neo4j and Neptune sinks
+write the same shape and queries are portable across them.
+"""
+
+from collections.abc import Callable
+from dataclasses import dataclass, field
+
+from tasks.jobs.attack_paths import aws
+
+
+@dataclass(frozen=True)
+class NormalizedList:
+ """Catalog entry for a list-typed node property.
+
+ Describes how the sync layer materialises a parent node's list-typed
+ property as a set of child item nodes connected by a typed edge.
+
+ Conventions (mechanical, do not invent):
+ - `child_label`: `Item`
+ e.g. AWSPolicyStatement.resource -> AWSPolicyStatementResourceItem
+ - `rel_type`: `HAS_`
+ e.g. resource -> HAS_RESOURCE
+ - child node property:
+ * `field_map = []` (scalar list, ~95% case) -> child stores `value: str`
+ * `field_map = [(src_key, child_field), ...]` (list of dicts, rare)
+ -> child stores those fields
+ """
+
+ source_label: str
+ source_property: str
+ child_label: str
+ rel_type: str
+ field_map: list[tuple[str, str]] = field(default_factory=list)
+
+ def __post_init__(self) -> None:
+ if self.field_map:
+ child_fields = [dst for _, dst in self.field_map]
+ if "value" in child_fields:
+ raise ValueError(
+ f"NormalizedList {self.source_label}.{self.source_property}: "
+ "`value` is reserved for scalar mode; do not map a source key to it"
+ )
+ src_keys = [src for src, _ in self.field_map]
+ if len(set(src_keys)) != len(src_keys):
+ raise ValueError(
+ f"NormalizedList {self.source_label}.{self.source_property}: "
+ "duplicate source key in field_map"
+ )
+ if len(set(child_fields)) != len(child_fields):
+ raise ValueError(
+ f"NormalizedList {self.source_label}.{self.source_property}: "
+ "duplicate child field in field_map"
+ )
+
+
+@dataclass(frozen=True)
+class ProviderConfig:
+ """Configuration for a cloud provider's Attack Paths integration."""
+
+ name: str
+ root_node_label: str # e.g., "AWSAccount"
+ uid_field: str # e.g., "arn"
+ # Label for resources connected to the account node, enabling indexed finding lookups
+ resource_label: str # e.g., "_AWSResource"
+ ingestion_function: Callable
+ # Maps a Postgres resource UID (e.g. full ARN) to the short-id form Cartography stores on some node types (e.g. `i-xxx` for EC2Instance)
+ short_uid_extractor: Callable[[str], str]
+ # List-typed properties to materialise as child nodes + edges at sync time.
+ # Mandatory (may be []). Without an entry here, a list-typed property falls
+ # back to comma-string flatten and emits a one-time warning.
+ normalized_lists: list[NormalizedList]
+
+
+# AWS list-typed property catalog.
+# One entry per Cartography node property whose runtime value is a list. The
+# sync layer materialises each element as a `` node and links it
+# to the parent with a `` edge; see the `NormalizedList` docstring
+# above for the naming conventions.
+AWS_NORMALIZED_LISTS: list[NormalizedList] = [
+ # AWSPolicyStatement - the hot path driving the 53-query perf fix.
+ NormalizedList(
+ "AWSPolicyStatement", "action", "AWSPolicyStatementActionItem", "HAS_ACTION"
+ ),
+ NormalizedList(
+ "AWSPolicyStatement",
+ "notaction",
+ "AWSPolicyStatementNotactionItem",
+ "HAS_NOTACTION",
+ ),
+ NormalizedList(
+ "AWSPolicyStatement",
+ "resource",
+ "AWSPolicyStatementResourceItem",
+ "HAS_RESOURCE",
+ ),
+ NormalizedList(
+ "AWSPolicyStatement",
+ "notresource",
+ "AWSPolicyStatementNotresourceItem",
+ "HAS_NOTRESOURCE",
+ ),
+ # S3PolicyStatement - same shape as IAM policies; AWS allows list or string.
+ NormalizedList(
+ "S3PolicyStatement", "action", "S3PolicyStatementActionItem", "HAS_ACTION"
+ ),
+ NormalizedList(
+ "S3PolicyStatement", "resource", "S3PolicyStatementResourceItem", "HAS_RESOURCE"
+ ),
+ # IAM / Cognito / KMS / Secrets
+ NormalizedList(
+ "CognitoIdentityPool", "roles", "CognitoIdentityPoolRolesItem", "HAS_ROLES"
+ ),
+ NormalizedList(
+ "KMSKey",
+ "encryption_algorithms",
+ "KMSKeyEncryptionAlgorithmsItem",
+ "HAS_ENCRYPTION_ALGORITHMS",
+ ),
+ NormalizedList(
+ "KMSKey",
+ "signing_algorithms",
+ "KMSKeySigningAlgorithmsItem",
+ "HAS_SIGNING_ALGORITHMS",
+ ),
+ NormalizedList(
+ "KMSKey",
+ "anonymous_actions",
+ "KMSKeyAnonymousActionsItem",
+ "HAS_ANONYMOUS_ACTIONS",
+ ),
+ NormalizedList(
+ "KMSGrant", "operations", "KMSGrantOperationsItem", "HAS_OPERATIONS"
+ ),
+ NormalizedList(
+ "SecretsManagerSecretVersion",
+ "version_stages",
+ "SecretsManagerSecretVersionVersionStagesItem",
+ "HAS_VERSION_STAGES",
+ ),
+ NormalizedList(
+ "SecretsManagerSecretVersion",
+ "kms_key_ids",
+ "SecretsManagerSecretVersionKmsKeyIdsItem",
+ "HAS_KMS_KEY_IDS",
+ ),
+ NormalizedList(
+ "SecretsManagerSecretVersion",
+ "tags",
+ "SecretsManagerSecretVersionTagsItem",
+ "HAS_TAGS",
+ field_map=[("Key", "key"), ("Value", "value_")],
+ # `value` is reserved for scalar mode; map `Value` to `value_` to keep dict shape.
+ ),
+ # Lambda / Compute
+ NormalizedList(
+ "AWSLambda", "architectures", "AWSLambdaArchitecturesItem", "HAS_ARCHITECTURES"
+ ),
+ NormalizedList(
+ "AWSLambda",
+ "anonymous_actions",
+ "AWSLambdaAnonymousActionsItem",
+ "HAS_ANONYMOUS_ACTIONS",
+ ),
+ NormalizedList(
+ "CodeBuildProject",
+ "environment_variables",
+ "CodeBuildProjectEnvironmentVariablesItem",
+ "HAS_ENVIRONMENT_VARIABLES",
+ ),
+ # ECS family
+ NormalizedList(
+ "ECSCluster",
+ "capacity_providers",
+ "ECSClusterCapacityProvidersItem",
+ "HAS_CAPACITY_PROVIDERS",
+ ),
+ NormalizedList(
+ "ECSTaskDefinition",
+ "compatibilities",
+ "ECSTaskDefinitionCompatibilitiesItem",
+ "HAS_COMPATIBILITIES",
+ ),
+ NormalizedList(
+ "ECSTaskDefinition",
+ "requires_compatibilities",
+ "ECSTaskDefinitionRequiresCompatibilitiesItem",
+ "HAS_REQUIRES_COMPATIBILITIES",
+ ),
+ NormalizedList(
+ "ECSContainerDefinition",
+ "links",
+ "ECSContainerDefinitionLinksItem",
+ "HAS_LINKS",
+ ),
+ NormalizedList(
+ "ECSContainerDefinition",
+ "entry_point",
+ "ECSContainerDefinitionEntryPointItem",
+ "HAS_ENTRY_POINT",
+ ),
+ NormalizedList(
+ "ECSContainerDefinition",
+ "command",
+ "ECSContainerDefinitionCommandItem",
+ "HAS_COMMAND",
+ ),
+ NormalizedList(
+ "ECSContainerDefinition",
+ "dns_servers",
+ "ECSContainerDefinitionDnsServersItem",
+ "HAS_DNS_SERVERS",
+ ),
+ NormalizedList(
+ "ECSContainerDefinition",
+ "dns_search_domains",
+ "ECSContainerDefinitionDnsSearchDomainsItem",
+ "HAS_DNS_SEARCH_DOMAINS",
+ ),
+ NormalizedList(
+ "ECSContainerDefinition",
+ "docker_security_options",
+ "ECSContainerDefinitionDockerSecurityOptionsItem",
+ "HAS_DOCKER_SECURITY_OPTIONS",
+ ),
+ NormalizedList("ECSContainer", "gpu_ids", "ECSContainerGpuIdsItem", "HAS_GPU_IDS"),
+ # ECR
+ NormalizedList(
+ "ECRImage", "layer_diff_ids", "ECRImageLayerDiffIdsItem", "HAS_LAYER_DIFF_IDS"
+ ),
+ NormalizedList(
+ "ECRImage",
+ "child_image_digests",
+ "ECRImageChildImageDigestsItem",
+ "HAS_CHILD_IMAGE_DIGESTS",
+ ),
+ # EC2 / Networking
+ NormalizedList(
+ "EC2Instance",
+ "exposed_internet_type",
+ "EC2InstanceExposedInternetTypeItem",
+ "HAS_EXPOSED_INTERNET_TYPE",
+ ),
+ NormalizedList(
+ "AutoScalingGroup",
+ "exposed_internet_type",
+ "AutoScalingGroupExposedInternetTypeItem",
+ "HAS_EXPOSED_INTERNET_TYPE",
+ ),
+ NormalizedList(
+ "LaunchConfiguration",
+ "security_groups",
+ "LaunchConfigurationSecurityGroupsItem",
+ "HAS_SECURITY_GROUPS",
+ ),
+ NormalizedList(
+ "LaunchTemplateVersion",
+ "security_group_ids",
+ "LaunchTemplateVersionSecurityGroupIdsItem",
+ "HAS_SECURITY_GROUP_IDS",
+ ),
+ NormalizedList(
+ "LaunchTemplateVersion",
+ "security_groups",
+ "LaunchTemplateVersionSecurityGroupsItem",
+ "HAS_SECURITY_GROUPS",
+ ),
+ NormalizedList(
+ "AWSVpcEndpoint",
+ "route_table_ids",
+ "AWSVpcEndpointRouteTableIdsItem",
+ "HAS_ROUTE_TABLE_IDS",
+ ),
+ NormalizedList(
+ "AWSVpcEndpoint",
+ "network_interface_ids",
+ "AWSVpcEndpointNetworkInterfaceIdsItem",
+ "HAS_NETWORK_INTERFACE_IDS",
+ ),
+ NormalizedList(
+ "AWSVpcEndpoint",
+ "subnet_ids",
+ "AWSVpcEndpointSubnetIdsItem",
+ "HAS_SUBNET_IDS",
+ ),
+ NormalizedList(
+ "ELBListener", "policy_names", "ELBListenerPolicyNamesItem", "HAS_POLICY_NAMES"
+ ),
+ # CloudFront / Route53 / CloudWatch / CloudTrail
+ NormalizedList(
+ "CloudFrontDistribution",
+ "aliases",
+ "CloudFrontDistributionAliasesItem",
+ "HAS_ALIASES",
+ ),
+ NormalizedList(
+ "CloudFrontDistribution",
+ "geo_restriction_locations",
+ "CloudFrontDistributionGeoRestrictionLocationsItem",
+ "HAS_GEO_RESTRICTION_LOCATIONS",
+ ),
+ NormalizedList(
+ "CloudWatchLogGroup",
+ "inherited_properties",
+ "CloudWatchLogGroupInheritedPropertiesItem",
+ "HAS_INHERITED_PROPERTIES",
+ ),
+ # RDS / Storage
+ NormalizedList(
+ "RDSCluster",
+ "availability_zones",
+ "RDSClusterAvailabilityZonesItem",
+ "HAS_AVAILABILITY_ZONES",
+ ),
+ NormalizedList(
+ "RDSEventSubscription",
+ "event_categories",
+ "RDSEventSubscriptionEventCategoriesItem",
+ "HAS_EVENT_CATEGORIES",
+ ),
+ NormalizedList(
+ "RDSEventSubscription",
+ "source_ids",
+ "RDSEventSubscriptionSourceIdsItem",
+ "HAS_SOURCE_IDS",
+ ),
+ NormalizedList(
+ "S3Bucket",
+ "anonymous_actions",
+ "S3BucketAnonymousActionsItem",
+ "HAS_ANONYMOUS_ACTIONS",
+ ),
+ # Inspector / Config / SSM / ACM / APIGateway / Glue / SageMaker / Bedrock
+ NormalizedList(
+ "AWSInspectorFinding",
+ "referenceurls",
+ "AWSInspectorFindingReferenceurlsItem",
+ "HAS_REFERENCEURLS",
+ ),
+ NormalizedList(
+ "AWSInspectorFinding",
+ "relatedvulnerabilities",
+ "AWSInspectorFindingRelatedvulnerabilitiesItem",
+ "HAS_RELATEDVULNERABILITIES",
+ ),
+ NormalizedList(
+ "AWSInspectorFinding",
+ "vulnerablepackageids",
+ "AWSInspectorFindingVulnerablepackageidsItem",
+ "HAS_VULNERABLEPACKAGEIDS",
+ ),
+ NormalizedList(
+ "AWSConfigurationRecorder",
+ "recording_group_resource_types",
+ "AWSConfigurationRecorderRecordingGroupResourceTypesItem",
+ "HAS_RECORDING_GROUP_RESOURCE_TYPES",
+ ),
+ NormalizedList(
+ "AWSConfigRule",
+ "scope_compliance_resource_types",
+ "AWSConfigRuleScopeComplianceResourceTypesItem",
+ "HAS_SCOPE_COMPLIANCE_RESOURCE_TYPES",
+ ),
+ NormalizedList(
+ "AWSConfigRule",
+ "source_details",
+ "AWSConfigRuleSourceDetailsItem",
+ "HAS_SOURCE_DETAILS",
+ ),
+ NormalizedList(
+ "SSMInstancePatch", "cve_ids", "SSMInstancePatchCveIdsItem", "HAS_CVE_IDS"
+ ),
+ NormalizedList(
+ "ACMCertificate", "in_use_by", "ACMCertificateInUseByItem", "HAS_IN_USE_BY"
+ ),
+ NormalizedList(
+ "APIGatewayRestAPI",
+ "anonymous_actions",
+ "APIGatewayRestAPIAnonymousActionsItem",
+ "HAS_ANONYMOUS_ACTIONS",
+ ),
+ NormalizedList(
+ "GlueJob", "connections", "GlueJobConnectionsItem", "HAS_CONNECTIONS"
+ ),
+ NormalizedList(
+ "AWSBedrockFoundationModel",
+ "input_modalities",
+ "AWSBedrockFoundationModelInputModalitiesItem",
+ "HAS_INPUT_MODALITIES",
+ ),
+ NormalizedList(
+ "AWSBedrockFoundationModel",
+ "output_modalities",
+ "AWSBedrockFoundationModelOutputModalitiesItem",
+ "HAS_OUTPUT_MODALITIES",
+ ),
+ NormalizedList(
+ "AWSBedrockFoundationModel",
+ "customizations_supported",
+ "AWSBedrockFoundationModelCustomizationsSupportedItem",
+ "HAS_CUSTOMIZATIONS_SUPPORTED",
+ ),
+ NormalizedList(
+ "AWSBedrockFoundationModel",
+ "inference_types_supported",
+ "AWSBedrockFoundationModelInferenceTypesSupportedItem",
+ "HAS_INFERENCE_TYPES_SUPPORTED",
+ ),
+]
+
+
+AWS_CONFIG = ProviderConfig(
+ name="aws",
+ root_node_label="AWSAccount",
+ uid_field="arn",
+ resource_label="_AWSResource",
+ ingestion_function=aws.start_aws_ingestion,
+ short_uid_extractor=aws.extract_short_uid,
+ normalized_lists=AWS_NORMALIZED_LISTS,
+)
+
+
+PROVIDER_CONFIGS: dict[str, ProviderConfig] = {
+ "aws": AWS_CONFIG,
+}
diff --git a/api/src/backend/tasks/jobs/attack_paths/queries.py b/api/src/backend/tasks/jobs/attack_paths/queries.py
index 277305f0e0..1166de17ed 100644
--- a/api/src/backend/tasks/jobs/attack_paths/queries.py
+++ b/api/src/backend/tasks/jobs/attack_paths/queries.py
@@ -1,8 +1,6 @@
# Cypher query templates for Attack Paths operations
from tasks.jobs.attack_paths.config import (
INTERNET_NODE_LABEL,
- PROVIDER_ELEMENT_ID_PROPERTY,
- PROVIDER_RESOURCE_LABEL,
PROWLER_FINDING_LABEL,
)
@@ -21,7 +19,6 @@ def render_cypher_template(template: str, replacements: dict[str, str]) -> str:
# Findings queries (used by findings.py)
-# ---------------------------------------
ADD_RESOURCE_LABEL_TEMPLATE = """
MATCH (account:__ROOT_LABEL__ {id: $provider_uid})-->(r)
@@ -88,7 +85,6 @@ INSERT_FINDING_TEMPLATE = f"""
"""
# Internet queries (used by internet.py)
-# ---------------------------------------
CREATE_INTERNET_NODE = f"""
MERGE (internet:{INTERNET_NODE_LABEL} {{id: 'Internet'}})
@@ -118,8 +114,8 @@ CREATE_CAN_ACCESS_RELATIONSHIPS_TEMPLATE = f"""
RETURN COUNT(r) AS relationships_merged
"""
-# Sync queries (used by sync.py)
-# -------------------------------
+# Sync queries (used by sync.py to fetch from the cartography temp Neo4j DB)
+# The write side of sync lives in each sink (`api/attack_paths/sink/`).
NODE_FETCH_QUERY = """
MATCH (n)
@@ -143,17 +139,3 @@ RELATIONSHIPS_FETCH_QUERY = """
ORDER BY internal_id
LIMIT $batch_size
"""
-
-NODE_SYNC_TEMPLATE = f"""
- UNWIND $rows AS row
- MERGE (n:__NODE_LABELS__ {{{PROVIDER_ELEMENT_ID_PROPERTY}: row.provider_element_id}})
- SET n += row.props
-"""
-
-RELATIONSHIP_SYNC_TEMPLATE = f"""
- UNWIND $rows AS row
- MATCH (s:{PROVIDER_RESOURCE_LABEL} {{{PROVIDER_ELEMENT_ID_PROPERTY}: row.start_element_id}})
- MATCH (t:{PROVIDER_RESOURCE_LABEL} {{{PROVIDER_ELEMENT_ID_PROPERTY}: row.end_element_id}})
- MERGE (s)-[r:__REL_TYPE__ {{{PROVIDER_ELEMENT_ID_PROPERTY}: row.provider_element_id}}]->(t)
- SET r += row.props
-"""
diff --git a/api/src/backend/tasks/jobs/attack_paths/scan.py b/api/src/backend/tasks/jobs/attack_paths/scan.py
index 0fb8d2b885..e161c9eb8d 100644
--- a/api/src/backend/tasks/jobs/attack_paths/scan.py
+++ b/api/src/backend/tasks/jobs/attack_paths/scan.py
@@ -39,8 +39,8 @@ Pipeline steps:
7. Sync the temp database into the tenant database:
- Drop the old provider subgraph (matched by dynamic _Provider_{uuid} label).
- graph_data_ready is set to False for all scans of this provider while
- the swap happens so the API doesn't serve partial data.
+ graph_data_ready is set to False for scans of this provider in the
+ target sink while the swap happens so the API doesn't serve partial data.
- Copy nodes and relationships in batches. Every synced node gets a
_ProviderResource label and dynamic _Tenant_{uuid} / _Provider_{uuid}
isolation labels, plus a _provider_element_id property for MERGE keys.
@@ -64,10 +64,17 @@ from api.models import StateChoices
from api.utils import initialize_prowler_provider
from cartography.config import Config as CartographyConfig
from cartography.intel import analysis as cartography_analysis
-from cartography.intel import create_indexes as cartography_create_indexes
from cartography.intel import ontology as cartography_ontology
from celery.utils.log import get_task_logger
-from tasks.jobs.attack_paths import db_utils, findings, indexes, internet, sync, utils
+from django.conf import settings
+from tasks.jobs.attack_paths import (
+ db_utils,
+ findings,
+ indexes,
+ internet,
+ sync,
+ utils,
+)
from tasks.jobs.attack_paths.config import get_cartography_ingestion_function
# Without this Celery goes crazy with Cartography logging
@@ -96,7 +103,7 @@ def run(tenant_id: str, scan_id: str, task_id: str) -> dict[str, Any]:
attack_paths_scan = db_utils.retrieve_attack_paths_scan(tenant_id, scan_id)
# Idempotency guard: cleanup may have flipped this row to a terminal state
- # while the message was still in flight. Bail out before touching state.
+ # while the message was still in flight. Bail out before touching state
if attack_paths_scan and attack_paths_scan.state in (
StateChoices.FAILED,
StateChoices.COMPLETED,
@@ -125,7 +132,7 @@ def run(tenant_id: str, scan_id: str, task_id: str) -> dict[str, Any]:
else:
if not attack_paths_scan:
- # Safety net for in-flight messages or direct task invocations; dispatcher normally pre-creates the row.
+ # Safety net for in-flight messages or direct task invocations; dispatcher normally pre-creates the row
logger.warning(
f"No Attack Paths Scan found for scan {scan_id} and tenant {tenant_id}, let's create it then"
)
@@ -143,10 +150,18 @@ def run(tenant_id: str, scan_id: str, task_id: str) -> dict[str, Any]:
tenant_database_name = graph_database.get_database_name(
prowler_api_provider.tenant_id
)
+ target_sink_backend = settings.ATTACK_PATHS_SINK_DATABASE
+ target_description = (
+ f"tenant Neo4j database {tenant_database_name}"
+ if target_sink_backend == "neo4j"
+ else f"{target_sink_backend} sink"
+ )
# While creating the Cartography configuration, attributes `neo4j_user` and `neo4j_password` are not really needed in this config object
tmp_cartography_config = CartographyConfig(
- neo4j_uri=graph_database.get_uri(),
+ # The temp ingest database is always Neo4j, so use the ingest URI here
+ # rather than the sink URI (which points at Neptune when configured).
+ neo4j_uri=graph_database.get_ingest_uri(),
neo4j_database=tmp_database_name,
update_tag=int(time.time()),
)
@@ -156,6 +171,8 @@ def run(tenant_id: str, scan_id: str, task_id: str) -> dict[str, Any]:
update_tag=tmp_cartography_config.update_tag,
)
+ graph_database.verify_scan_databases_available()
+
# Starting the Attack Paths scan
if not db_utils.starting_attack_paths_scan(
attack_paths_scan, tenant_cartography_config
@@ -168,7 +185,8 @@ def run(tenant_id: str, scan_id: str, task_id: str) -> dict[str, Any]:
scan_t0 = time.perf_counter()
logger.info(
f"Starting Attack Paths scan ({attack_paths_scan.id}) for "
- f"{prowler_api_provider.provider.upper()} provider {prowler_api_provider.id}"
+ f"{prowler_api_provider.provider.upper()} provider {prowler_api_provider.id} "
+ f"(staging=Neo4j database {tmp_database_name}, target={target_description})"
)
subgraph_dropped = False
@@ -177,7 +195,8 @@ def run(tenant_id: str, scan_id: str, task_id: str) -> dict[str, Any]:
try:
logger.info(
- f"Creating Neo4j database {tmp_cartography_config.neo4j_database} for tenant {prowler_api_provider.tenant_id}"
+ f"Creating staging Neo4j database {tmp_cartography_config.neo4j_database} "
+ f"for tenant {prowler_api_provider.tenant_id}"
)
graph_database.create_database(tmp_cartography_config.neo4j_database)
@@ -191,7 +210,9 @@ def run(tenant_id: str, scan_id: str, task_id: str) -> dict[str, Any]:
tmp_cartography_config.neo4j_database
) as tmp_neo4j_session:
# Indexes creation
- cartography_create_indexes.run(tmp_neo4j_session, tmp_cartography_config)
+ indexes.create_cartography_indexes(
+ tmp_neo4j_session, tmp_cartography_config
+ )
indexes.create_findings_indexes(tmp_neo4j_session)
db_utils.update_attack_paths_scan_progress(attack_paths_scan, 2)
@@ -223,7 +244,7 @@ def run(tenant_id: str, scan_id: str, task_id: str) -> dict[str, Any]:
cartography_analysis.run(tmp_neo4j_session, tmp_cartography_config)
db_utils.update_attack_paths_scan_progress(attack_paths_scan, 95)
- # Creating Internet node and CAN_ACCESS relationships
+ # Creating Internet node and `CAN_ACCESS` relationships
logger.info(
f"Creating Internet graph for AWS account {prowler_api_provider.uid}"
)
@@ -247,23 +268,41 @@ def run(tenant_id: str, scan_id: str, task_id: str) -> dict[str, Any]:
db_utils.update_attack_paths_scan_progress(attack_paths_scan, 97)
logger.info(
- f"Clearing Neo4j cache for database {tmp_cartography_config.neo4j_database}"
+ f"Clearing Neo4j cache for staging database {tmp_cartography_config.neo4j_database}"
)
graph_database.clear_cache(tmp_cartography_config.neo4j_database)
+ t0 = time.perf_counter()
logger.info(
- f"Ensuring tenant database {tenant_database_name}, and its indexes, exists for tenant {prowler_api_provider.tenant_id}"
+ f"Preparing target {target_description} for tenant {prowler_api_provider.tenant_id}"
)
graph_database.create_database(tenant_database_name)
- with graph_database.get_session(tenant_database_name) as tenant_neo4j_session:
- cartography_create_indexes.run(
- tenant_neo4j_session, tenant_cartography_config
- )
- indexes.create_findings_indexes(tenant_neo4j_session)
- indexes.create_sync_indexes(tenant_neo4j_session)
+ # Sink-side index creation: Neptune auto-manages indexes and rejects
+ # `CREATE INDEX`, so only run it when the sink is Neo4j
+ # The temp ingest DB is always Neo4j and is always indexed above
+ if target_sink_backend != "neptune":
+ logger.info(f"Ensuring indexes exist for {target_description}")
+ with graph_database.get_session(
+ tenant_database_name
+ ) as tenant_neo4j_session:
+ indexes.create_cartography_indexes(
+ tenant_neo4j_session, tenant_cartography_config
+ )
+ indexes.create_findings_indexes(tenant_neo4j_session)
+ indexes.create_sync_indexes(tenant_neo4j_session)
+ else:
+ logger.info("Skipping tenant database indexes for neptune sink")
+ logger.info(
+ f"Prepared target {target_description} in {time.perf_counter() - t0:.3f}s"
+ )
- logger.info(f"Deleting existing provider graph in {tenant_database_name}")
- db_utils.set_provider_graph_data_ready(attack_paths_scan, False)
+ logger.info(
+ f"Deleting existing provider graph from {target_description} "
+ f"(tenant={prowler_api_provider.tenant_id}, provider={prowler_api_provider.id})"
+ )
+ db_utils.set_provider_graph_data_ready(
+ attack_paths_scan, False, target_sink_backend
+ )
provider_gated = True
t0 = time.perf_counter()
@@ -272,14 +311,17 @@ def run(tenant_id: str, scan_id: str, task_id: str) -> dict[str, Any]:
provider_id=str(prowler_api_provider.id),
)
logger.info(
- f"Deleted existing provider graph in {time.perf_counter() - t0:.3f}s "
- f"(deleted_nodes={deleted_nodes})"
+ f"Deleted existing provider graph from {target_description} "
+ f"in {time.perf_counter() - t0:.3f}s (deleted_nodes={deleted_nodes})"
)
subgraph_dropped = True
db_utils.update_attack_paths_scan_progress(attack_paths_scan, 98)
logger.info(
- f"Syncing graph from {tmp_database_name} into {tenant_database_name}"
+ f"Syncing staging graph {tmp_database_name} into {target_description} "
+ f"for provider {prowler_api_provider.id} "
+ f"(tenant {prowler_api_provider.tenant_id}, "
+ f"type {prowler_api_provider.provider})"
)
t0 = time.perf_counter()
sync_result = sync.sync_graph(
@@ -287,17 +329,34 @@ def run(tenant_id: str, scan_id: str, task_id: str) -> dict[str, Any]:
target_database=tenant_database_name,
tenant_id=str(prowler_api_provider.tenant_id),
provider_id=str(prowler_api_provider.id),
+ provider_type=prowler_api_provider.provider,
)
+ elapsed = time.perf_counter() - t0
+ total_nodes = sync_result["nodes"] + sync_result["child_nodes"]
+ elements = total_nodes + sync_result["relationships"]
+ rate = elements / elapsed if elapsed else 0
logger.info(
- f"Synced graph in {time.perf_counter() - t0:.3f}s "
- f"(nodes={sync_result['nodes']}, relationships={sync_result['relationships']})"
+ f"Synced staging graph into {target_description} in {elapsed:.3f}s - "
+ f"nodes={total_nodes} (source={sync_result['nodes']}, "
+ f"items={sync_result['child_nodes']}), "
+ f"relationships={sync_result['relationships']} "
+ f"(structural={sync_result['structural_relationships']}, "
+ f"items={sync_result['item_relationships']}), "
+ f"~{rate:.0f} elem/s"
)
sync_completed = True
+ # Flip metadata only now: the new schema is live in the target sink, so
+ # reads can switch to the current catalog/backend. The target-sink gate
+ # is already closed, so the switch is atomic from the API's view.
+ db_utils.set_scan_migrated(attack_paths_scan, True, target_sink_backend)
db_utils.set_graph_data_ready(attack_paths_scan, True)
db_utils.update_attack_paths_scan_progress(attack_paths_scan, 99)
- logger.info(f"Clearing Neo4j cache for database {tenant_database_name}")
- graph_database.clear_cache(tenant_database_name)
+ if target_sink_backend == "neptune":
+ logger.info("Skipping cache clear for neptune sink")
+ else:
+ logger.info(f"Clearing Neo4j cache for target {target_description}")
+ graph_database.clear_cache(tenant_database_name)
logger.info(f"Dropping temporary Neo4j database {tmp_database_name}")
graph_database.drop_database(tmp_database_name)
@@ -313,32 +372,51 @@ def run(tenant_id: str, scan_id: str, task_id: str) -> dict[str, Any]:
except Exception as e:
exception_message = utils.stringify_exception(e, "Attack Paths scan failed")
- logger.exception(exception_message)
+ temporary_database_missing = (
+ isinstance(e, graph_database.GraphDatabaseQueryException)
+ and e.code == graph_database.DATABASE_NOT_FOUND_CODE
+ and tmp_database_name in str(e)
+ )
+ if temporary_database_missing:
+ logger.warning(exception_message)
+ else:
+ logger.exception(exception_message)
+ cleanup_log_level = (
+ logging.WARNING if temporary_database_missing else logging.ERROR
+ )
+ cleanup_exc_info = not temporary_database_missing
ingestion_exceptions["global_error"] = exception_message
- # Recover graph_data_ready based on how far the swap got.
- # Partial drop (mid-batch failure) may leave `subgraph_dropped=False`
- # with data partially deleted, so we prefer that over permanently blocked queries.
+ # Recover `graph_data_ready` based on how far the swap got
+ # Partial drop (mid-batch failure) may leave `subgraph_dropped=False` with data partially deleted,
+ # so we prefer that over permanently blocked queries
try:
if sync_completed:
db_utils.set_graph_data_ready(attack_paths_scan, True)
elif provider_gated and not subgraph_dropped:
- db_utils.set_provider_graph_data_ready(attack_paths_scan, True)
+ db_utils.set_provider_graph_data_ready(
+ attack_paths_scan, True, target_sink_backend
+ )
except Exception:
- logger.error(
- f"Failed to recover `graph_data_ready` for provider {attack_paths_scan.provider_id}",
- exc_info=True,
+ logger.log(
+ cleanup_log_level,
+ "Failed to recover `graph_data_ready` for provider "
+ f"{attack_paths_scan.provider_id}",
+ exc_info=cleanup_exc_info,
)
# Dropping the temporary database if it still exists
try:
graph_database.drop_database(tmp_cartography_config.neo4j_database)
- except Exception as e:
- logger.error(
- f"Failed to drop temporary Neo4j database `{tmp_cartography_config.neo4j_database}` during cleanup: {e}",
- exc_info=True,
+ except Exception as cleanup_error:
+ logger.log(
+ cleanup_log_level,
+ "Failed to drop temporary Neo4j database "
+ f"`{tmp_cartography_config.neo4j_database}` during cleanup: "
+ f"{cleanup_error}",
+ exc_info=cleanup_exc_info,
)
# Set Attack Paths scan state to FAILED
@@ -346,10 +424,12 @@ def run(tenant_id: str, scan_id: str, task_id: str) -> dict[str, Any]:
db_utils.finish_attack_paths_scan(
attack_paths_scan, StateChoices.FAILED, ingestion_exceptions
)
- except Exception as e:
- logger.error(
- f"Could not mark Attack Paths scan {attack_paths_scan.id} as `FAILED` (row may have been deleted): {e}",
- exc_info=True,
+ except Exception as cleanup_error:
+ logger.log(
+ cleanup_log_level,
+ f"Could not mark Attack Paths scan {attack_paths_scan.id} as `FAILED` "
+ f"(row may have been deleted): {cleanup_error}",
+ exc_info=cleanup_exc_info,
)
raise
diff --git a/api/src/backend/tasks/jobs/attack_paths/sync.py b/api/src/backend/tasks/jobs/attack_paths/sync.py
index 50f770deb5..98a52bd48b 100644
--- a/api/src/backend/tasks/jobs/attack_paths/sync.py
+++ b/api/src/backend/tasks/jobs/attack_paths/sync.py
@@ -1,40 +1,58 @@
"""
Graph sync operations for Attack Paths.
-This module handles syncing graph data from temporary scan databases
-to the tenant database, adding provider isolation labels and properties.
+Reads nodes and relationships out of the cartography temp database (always
+Neo4j) and hands them to the configured sink (Neo4j or Neptune) in batches.
+Backend-specific Cypher (MERGE shape, ID strategy, indexes) lives in each
+sink; this module owns the source read loop, per-batch grouping, and the
+list-property materialisation policy (see `NormalizedList`).
+
+Each list-typed node property that appears in the provider's
+`normalized_lists` catalog becomes a set of child item nodes connected to
+the parent by a typed edge. A list-typed property that is not in the
+catalog is serialised to a comma-delimited string and emits a one-time
+warning per (label, property), surfacing Cartography fields that should be
+added to the catalog.
"""
+import json
import time
from collections import defaultdict
+from collections.abc import Iterator
+from hashlib import sha256
from typing import Any
import neo4j
from api.attack_paths import database as graph_database
+from api.attack_paths import sink as sink_module
from celery.utils.log import get_task_logger
from tasks.jobs.attack_paths.config import (
+ PROVIDER_CONFIGS,
PROVIDER_ISOLATION_PROPERTIES,
PROVIDER_RESOURCE_LABEL,
- SYNC_BATCH_SIZE,
+ NormalizedList,
get_provider_label,
get_tenant_label,
)
from tasks.jobs.attack_paths.queries import (
NODE_FETCH_QUERY,
- NODE_SYNC_TEMPLATE,
- RELATIONSHIP_SYNC_TEMPLATE,
RELATIONSHIPS_FETCH_QUERY,
- render_cypher_template,
)
logger = get_task_logger(__name__)
+# (label, property) tuples for which we've already emitted the
+# "unnormalised list" warning. Module-level so the warning fires once per
+# process, not once per node.
+_WARNED_UNNORMALIZED: set[tuple[str, str]] = set()
+
def sync_graph(
source_database: str,
target_database: str,
tenant_id: str,
provider_id: str,
+ provider_type: str,
) -> dict[str, int]:
"""
Sync all nodes and relationships from source to target database.
@@ -44,25 +62,38 @@ def sync_graph(
`target_database`: The tenant database
`tenant_id`: The tenant ID for isolation
`provider_id`: The provider ID for isolation
+ `provider_type`: Provider type key (e.g. "aws"), used to resolve the
+ `NormalizedList` catalog from `PROVIDER_CONFIGS`.
Returns:
- Dict with counts of synced nodes and relationships
+ Dict with counts of synced nodes, child item nodes, and relationships.
"""
- nodes_synced = sync_nodes(
+ sink = sink_module.get_backend()
+ sink.ensure_sync_indexes(target_database)
+
+ normalized_lists = _resolve_normalized_lists(provider_type)
+
+ node_result = sync_nodes(
source_database,
target_database,
tenant_id,
provider_id,
+ sink,
+ normalized_lists,
)
relationships_synced = sync_relationships(
source_database,
target_database,
provider_id,
+ sink,
)
return {
- "nodes": nodes_synced,
- "relationships": relationships_synced,
+ "nodes": node_result["parents"],
+ "child_nodes": node_result["children"],
+ "relationships": relationships_synced + node_result["parent_child_rels"],
+ "structural_relationships": relationships_synced,
+ "item_relationships": node_result["parent_child_rels"],
}
@@ -71,84 +102,123 @@ def sync_nodes(
target_database: str,
tenant_id: str,
provider_id: str,
-) -> int:
+ sink: Any,
+ normalized_lists: list[NormalizedList],
+) -> dict[str, int]:
"""
- Sync nodes from source to target database.
+ Sync nodes from source to target database, exploding catalogued list
+ properties into child nodes + parent->child edges.
Adds `_ProviderResource` label and dynamic `_Tenant_{id}` and `_Provider_{id}`
- isolation labels to all nodes.
+ isolation labels to all nodes (parents and children alike).
Source and target sessions are opened sequentially per batch to avoid
holding two Bolt connections simultaneously for the entire sync duration.
"""
+ batch_size = sink.sync_batch_size
t0 = time.perf_counter()
last_id = -1
- total_synced = 0
+ parents_synced = 0
+ children_synced = 0
+ parent_child_rels = 0
+
+ catalog = _build_catalog_index(normalized_lists)
+ extra_labels = _build_extra_labels(tenant_id, provider_id)
while True:
- grouped: dict[tuple[str, ...], list[dict[str, Any]]] = defaultdict(list)
+ tb = time.perf_counter()
+ prev_children = children_synced
+ prev_rels = parent_child_rels
+ parent_groups: dict[tuple[str, ...], list[dict[str, Any]]] = defaultdict(list)
+ child_groups: dict[str, list[dict[str, Any]]] = defaultdict(list)
+ rel_groups: dict[str, list[dict[str, Any]]] = defaultdict(list)
batch_count = 0
with graph_database.get_session(source_database) as source_session:
result = source_session.run(
NODE_FETCH_QUERY,
- {"last_id": last_id, "batch_size": SYNC_BATCH_SIZE},
+ {"last_id": last_id, "batch_size": batch_size},
)
for record in result:
batch_count += 1
last_id = record["internal_id"]
- key, value = _node_to_sync_dict(record, provider_id)
- grouped[key].append(value)
+ key, parent_dict, children, rels = _node_to_sync_dict(
+ record, provider_id, catalog
+ )
+ parent_groups[key].append(parent_dict)
+ for child in children:
+ child_groups[child["_child_label"]].append(child["row"])
+ for rel in rels:
+ rel_groups[rel["rel_type"]].append(rel["row"])
if batch_count == 0:
break
- with graph_database.get_session(target_database) as target_session:
- for labels, batch in grouped.items():
- label_set = set(labels)
- label_set.add(PROVIDER_RESOURCE_LABEL)
- label_set.add(get_tenant_label(tenant_id))
- label_set.add(get_provider_label(provider_id))
- node_labels = ":".join(f"`{label}`" for label in sorted(label_set))
+ for labels, batch in parent_groups.items():
+ rendered_labels = _render_labels(labels, extra_labels)
+ for sink_batch in _iter_sink_batches(batch, batch_size):
+ sink.write_nodes(target_database, rendered_labels, sink_batch)
- query = render_cypher_template(
- NODE_SYNC_TEMPLATE, {"__NODE_LABELS__": node_labels}
+ for child_label, batch in child_groups.items():
+ rendered_labels = _render_labels((child_label,), extra_labels)
+ for sink_batch in _iter_sink_batches(batch, batch_size):
+ sink.write_nodes(target_database, rendered_labels, sink_batch)
+ children_synced += len(batch)
+
+ for rel_type, batch in rel_groups.items():
+ for sink_batch in _iter_sink_batches(batch, batch_size):
+ sink.write_relationships(
+ target_database, rel_type, provider_id, sink_batch
)
- target_session.run(query, {"rows": batch})
+ parent_child_rels += len(batch)
- total_synced += batch_count
+ parents_synced += batch_count
+ batch_dt = time.perf_counter() - tb
+ batch_elements = (
+ batch_count
+ + (children_synced - prev_children)
+ + (parent_child_rels - prev_rels)
+ )
+ rate = batch_elements / batch_dt if batch_dt else 0
logger.info(
- f"Synced {total_synced} nodes from {source_database} to {target_database} in {time.perf_counter() - t0:.3f}s"
+ f"[sync nodes] {parents_synced} source (+{children_synced} items, "
+ f"+{parent_child_rels} item rels) · batch {batch_dt:.1f}s · "
+ f"elapsed {time.perf_counter() - t0:.1f}s · ~{rate:.0f} elem/s"
)
- return total_synced
+ return {
+ "parents": parents_synced,
+ "children": children_synced,
+ "parent_child_rels": parent_child_rels,
+ }
def sync_relationships(
source_database: str,
target_database: str,
provider_id: str,
+ sink: Any,
) -> int:
"""
Sync relationships from source to target database.
- Matches source and target nodes by `_provider_element_id` in the tenant database.
-
Source and target sessions are opened sequentially per batch to avoid
holding two Bolt connections simultaneously for the entire sync duration.
"""
+ batch_size = sink.sync_batch_size
t0 = time.perf_counter()
last_id = -1
total_synced = 0
while True:
+ tb = time.perf_counter()
grouped: dict[str, list[dict[str, Any]]] = defaultdict(list)
batch_count = 0
with graph_database.get_session(source_database) as source_session:
result = source_session.run(
RELATIONSHIPS_FETCH_QUERY,
- {"last_id": last_id, "batch_size": SYNC_BATCH_SIZE},
+ {"last_id": last_id, "batch_size": batch_size},
)
for record in result:
batch_count += 1
@@ -159,32 +229,212 @@ def sync_relationships(
if batch_count == 0:
break
- with graph_database.get_session(target_database) as target_session:
- for rel_type, batch in grouped.items():
- query = render_cypher_template(
- RELATIONSHIP_SYNC_TEMPLATE, {"__REL_TYPE__": rel_type}
+ for rel_type, batch in grouped.items():
+ for sink_batch in _iter_sink_batches(batch, batch_size):
+ sink.write_relationships(
+ target_database, rel_type, provider_id, sink_batch
)
- target_session.run(query, {"rows": batch})
total_synced += batch_count
+ batch_dt = time.perf_counter() - tb
+ rate = batch_count / batch_dt if batch_dt else 0
logger.info(
- f"Synced {total_synced} relationships from {source_database} to {target_database} in {time.perf_counter() - t0:.3f}s"
+ f"[sync rels] {total_synced} structural · batch {batch_dt:.1f}s · "
+ f"elapsed {time.perf_counter() - t0:.1f}s · ~{rate:.0f}/s"
)
return total_synced
+def _iter_sink_batches(
+ rows: list[dict[str, Any]],
+ batch_size: int,
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield final sink write batches after source rows have been transformed."""
+ if batch_size <= 0:
+ raise ValueError("Sink batch size must be greater than zero")
+
+ for index in range(0, len(rows), batch_size):
+ yield rows[index : index + batch_size]
+
+
def _node_to_sync_dict(
- record: neo4j.Record, provider_id: str
-) -> tuple[tuple[str, ...], dict[str, Any]]:
- """Transform a source node record into a (grouping_key, sync_dict) pair."""
+ record: neo4j.Record,
+ provider_id: str,
+ catalog: dict[tuple[str, str], NormalizedList],
+) -> tuple[
+ tuple[str, ...],
+ dict[str, Any],
+ list[dict[str, Any]],
+ list[dict[str, Any]],
+]:
+ """Transform a source node record into a (grouping_key, sync_dict, children, rels) tuple.
+
+ Catalogued list properties are popped from `props` and emitted as child
+ nodes + parent->child relationships.
+ """
props = dict(record["props"] or {})
_strip_internal_properties(props)
labels = tuple(sorted(set(record["labels"] or [])))
- return labels, {
- "provider_element_id": f"{provider_id}:{record['element_id']}",
+ parent_element_id = f"{provider_id}:{record['element_id']}"
+
+ children, rels = _explode_catalogued_lists(
+ labels, props, catalog, provider_id, parent_element_id
+ )
+
+ _normalize_sink_properties(props, labels)
+
+ parent = {
+ "provider_element_id": parent_element_id,
"props": props,
}
+ return labels, parent, children, rels
+
+
+def _explode_catalogued_lists(
+ labels: tuple[str, ...],
+ props: dict[str, Any],
+ catalog: dict[tuple[str, str], NormalizedList],
+ provider_id: str,
+ parent_element_id: str,
+) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
+ """Pop catalogued list properties from `props` and produce child + rel emits.
+
+ A node may carry multiple labels (e.g. `AWSPolicyStatement` plus
+ `_AWSResource`); we check each label for catalog matches independently.
+ Returns:
+ - children: list of {"_child_label": str, "row": } dicts.
+ - rels: list of {"rel_type": str, "row": } dicts.
+ """
+ children: list[dict[str, Any]] = []
+ rels: list[dict[str, Any]] = []
+
+ for label in labels:
+ for key in list(props.keys()):
+ spec = catalog.get((label, key))
+ if spec is None:
+ continue
+ value = props.pop(key)
+ if value is None:
+ continue
+ if not isinstance(value, list):
+ # Catalogued but not actually a list this scan - fall back to
+ # the generic normaliser so we don't lose the value.
+ props[key] = value
+ continue
+ for item in value:
+ child_value_key, child_props = _build_child_props(spec, item)
+ if child_value_key is None:
+ continue
+ child_element_id = _build_child_id(
+ provider_id, spec.child_label, child_value_key
+ )
+ children.append(
+ {
+ "_child_label": spec.child_label,
+ "row": {
+ "provider_element_id": child_element_id,
+ "props": child_props,
+ },
+ }
+ )
+ rels.append(
+ {
+ "rel_type": spec.rel_type,
+ "row": {
+ "start_element_id": parent_element_id,
+ "end_element_id": child_element_id,
+ "provider_element_id": (
+ f"{parent_element_id}::{spec.rel_type}::"
+ f"{child_element_id}"
+ ),
+ "props": {},
+ },
+ }
+ )
+
+ return children, rels
+
+
+def _build_child_props(
+ spec: NormalizedList, item: Any
+) -> tuple[str | None, dict[str, Any]]:
+ """Translate one list element into a child node's prop dict.
+
+ Returns (dedup_key, props). The dedup_key is what makes two child nodes
+ equal within (tenant, provider) - used to build `_provider_element_id`.
+ For scalar mode, the dedup key is the value itself. For dict mode it is
+ a stable concatenation of the mapped fields in `field_map` order.
+ """
+ if not spec.field_map:
+ if isinstance(item, (dict, list)):
+ # Defensive: caller marked this list as scalar but elements are
+ # structured. Convert to a stable string so the value survives.
+ value_str = json.dumps(item, sort_keys=True, default=str)
+ else:
+ value_str = str(item)
+ return value_str, {"value": value_str}
+
+ if not isinstance(item, dict):
+ # Catalogued as dict-shape but got a scalar. Skip - caller will see
+ # the value go missing and can fix the field_map.
+ return None, {}
+
+ props: dict[str, Any] = {}
+ dedup_parts: list[str] = []
+ for src_key, child_field in spec.field_map:
+ raw = item.get(src_key)
+ value_str = _to_sink_property_value(raw) if raw is not None else ""
+ props[child_field] = value_str
+ dedup_parts.append(f"{child_field}={value_str}")
+ return "::".join(dedup_parts), props
+
+
+def _build_child_id(provider_id: str, child_label: str, value_key: str) -> str:
+ """Deterministic `_provider_element_id` for a list-item child node.
+
+ Hashing the value keeps the ID bounded while preserving deduplication within
+ each provider and child label.
+ """
+ value_digest = sha256(value_key.encode("utf-8")).hexdigest()
+ return f"{provider_id}::{child_label}::{value_digest}"
+
+
+def _build_catalog_index(
+ normalized_lists: list[NormalizedList],
+) -> dict[tuple[str, str], NormalizedList]:
+ """Index the catalog by (source_label, source_property) for O(1) lookup."""
+ return {
+ (spec.source_label, spec.source_property): spec for spec in normalized_lists
+ }
+
+
+def _build_extra_labels(tenant_id: str, provider_id: str) -> tuple[str, ...]:
+ return (
+ PROVIDER_RESOURCE_LABEL,
+ get_tenant_label(tenant_id),
+ get_provider_label(provider_id),
+ )
+
+
+def _render_labels(base_labels: tuple[str, ...], extra_labels: tuple[str, ...]) -> str:
+ """Render the Cypher label string for a node-write batch."""
+ label_set = set(base_labels) | set(extra_labels)
+ return ":".join(f"`{label}`" for label in sorted(label_set))
+
+
+def _resolve_normalized_lists(provider_type: str) -> list[NormalizedList]:
+ config = PROVIDER_CONFIGS.get(provider_type)
+ if config is None:
+ # Unknown provider: empty catalog. Any list-typed property will be
+ # serialised to a comma-delimited string with one warning per
+ # (label, property).
+ logger.warning(
+ "Provider type %s not in PROVIDER_CONFIGS; no normalized_lists active",
+ provider_type,
+ )
+ return []
+ return config.normalized_lists
def _rel_to_sync_dict(
@@ -193,7 +443,11 @@ def _rel_to_sync_dict(
"""Transform a source relationship record into a (grouping_key, sync_dict) pair."""
props = dict(record["props"] or {})
_strip_internal_properties(props)
+ # Relationship properties go through the same primitive coercion as
+ # nodes; catalog-driven materialisation applies to node properties only.
+ _normalize_sink_properties(props, labels=None)
rel_type = record["rel_type"]
+
return rel_type, {
"start_element_id": f"{provider_id}:{record['start_element_id']}",
"end_element_id": f"{provider_id}:{record['end_element_id']}",
@@ -206,3 +460,80 @@ def _strip_internal_properties(props: dict[str, Any]) -> None:
"""Remove provider isolation properties before the += spread in sync templates."""
for key in PROVIDER_ISOLATION_PROPERTIES:
props.pop(key, None)
+
+
+def _normalize_sink_properties(
+ props: dict[str, Any], labels: tuple[str, ...] | None
+) -> None:
+ """Normalize property values to primitive Cypher literals for either sink.
+
+ Attack-paths node and relationship properties are written as primitive
+ scalars regardless of the active sink (Neo4j or Neptune). The convention
+ is driven by Neptune's openCypher type restrictions, which reject list,
+ map, temporal and spatial property values, but it is applied uniformly
+ so that custom and predefined queries are portable across sinks without
+ runtime rewriting.
+
+ Concretely:
+ - Temporal values (neo4j.time.{DateTime,Date,Time,Duration}) become
+ their ISO-8601 string representation.
+ - Spatial values (neo4j.spatial.Point and subclasses) become their
+ WKT-style string representation.
+ - Maps / dicts become a JSON-encoded string, read back with `CONTAINS`
+ substring checks inside queries.
+ - Lists become a comma-delimited string. Catalogued list properties
+ are materialised as child item nodes upstream in
+ `_explode_catalogued_lists` and never reach this point; any list
+ seen here is uncatalogued, so we log a one-time warning per
+ (label, property) to surface Cartography fields that should be
+ added to the catalog.
+
+ `labels` is only used for the warning message; pass `None` for
+ relationship props (no label context).
+ """
+ for key, value in list(props.items()):
+ if isinstance(value, list) and labels is not None:
+ _warn_unnormalized_list(labels, key)
+ props[key] = _to_sink_property_value(value)
+
+
+def _warn_unnormalized_list(labels: tuple[str, ...], key: str) -> None:
+ """Warn once per (label, property), on the real label(s) only.
+
+ Every synced node also carries internal isolation labels (`_AWSResource`,
+ `_ProviderResource`, `_Tenant_*`, `_Provider_*`); warning on those just
+ doubles the noise, so skip them and point at the actionable Cartography
+ label. Falls back to all labels if only internal ones are present.
+ """
+ real_labels = [label for label in labels if not label.startswith("_")]
+ for label in real_labels or labels:
+ token = (label, key)
+ if token in _WARNED_UNNORMALIZED:
+ continue
+ _WARNED_UNNORMALIZED.add(token)
+ logger.warning(
+ "Unnormalized list property %s.%s reached sink as comma-string; "
+ "add a NormalizedList entry to the provider catalog to explode it",
+ label,
+ key,
+ )
+
+
+def _to_sink_property_value(value: Any) -> Any:
+ if hasattr(value, "iso_format") and callable(value.iso_format):
+ return value.iso_format()
+
+ if type(value).__module__.startswith("neo4j.spatial"):
+ return str(value)
+
+ if isinstance(value, dict):
+ # openCypher `SET` rejects map property values: encode as JSON so the structured payload
+ # survives the round-trip and is queryable with `CONTAINS` substring checks
+ return json.dumps(value, sort_keys=True, default=str)
+
+ if isinstance(value, list):
+ # openCypher `SET` rejects list/array property values: encode as a
+ # delimited string read back with split() inside queries
+ return ",".join(str(_to_sink_property_value(v)) for v in value)
+
+ return value
diff --git a/api/src/backend/tasks/jobs/deletion.py b/api/src/backend/tasks/jobs/deletion.py
index fadf98d464..91e64610f7 100644
--- a/api/src/backend/tasks/jobs/deletion.py
+++ b/api/src/backend/tasks/jobs/deletion.py
@@ -1,4 +1,5 @@
from api.attack_paths import database as graph_database
+from api.attack_paths import sink as sink_module
from api.db_router import MainRouter
from api.db_utils import batch_delete, rls_transaction
from api.models import (
@@ -76,6 +77,12 @@ def delete_provider(tenant_id: str, pk: str):
"id", flat=True
)
)
+ attack_paths_sink_backends = list(
+ AttackPathsScan.all_objects.filter(provider=instance)
+ .values_list("sink_backend", flat=True)
+ .distinct()
+ .order_by("sink_backend")
+ )
deletion_steps = [
("Scan Summaries", ScanSummary.all_objects.filter(scan__provider=instance)),
@@ -97,7 +104,13 @@ def delete_provider(tenant_id: str, pk: str):
# Delete the Attack Paths' graph data related to the provider from the tenant database
tenant_database_name = graph_database.get_database_name(tenant_id)
try:
- graph_database.drop_subgraph(tenant_database_name, str(pk))
+ if attack_paths_sink_backends:
+ for sink_backend in attack_paths_sink_backends:
+ sink_module.get_backend_for_name(sink_backend).drop_subgraph(
+ tenant_database_name, str(pk)
+ )
+ else:
+ graph_database.drop_subgraph(tenant_database_name, str(pk))
except graph_database.GraphDatabaseQueryException as gdb_error:
logger.error(f"Error deleting Provider graph data: {gdb_error}")
diff --git a/api/src/backend/tasks/jobs/integrations.py b/api/src/backend/tasks/jobs/integrations.py
index 25722686cc..c77ba22b7f 100644
--- a/api/src/backend/tasks/jobs/integrations.py
+++ b/api/src/backend/tasks/jobs/integrations.py
@@ -14,6 +14,7 @@ from prowler.lib.outputs.compliance.generic.generic import GenericCompliance
from prowler.lib.outputs.csv.csv import CSV
from prowler.lib.outputs.finding import Finding as FindingOutput
from prowler.lib.outputs.html.html import HTML
+from prowler.lib.outputs.jira.exceptions.exceptions import JiraBaseException
from prowler.lib.outputs.ocsf.ocsf import OCSF
from prowler.providers.aws.aws_provider import AwsProvider
from prowler.providers.aws.lib.s3.s3 import S3
@@ -26,6 +27,8 @@ from tasks.utils import batched
logger = get_task_logger(__name__)
+JIRA_GENERIC_SEND_ERROR = "Failed to create Jira issue."
+
def get_s3_client_from_integration(
integration: Integration,
@@ -483,6 +486,7 @@ def send_findings_to_jira(
jira_integration = initialize_prowler_integration(integration)
num_tickets_created = 0
+ error_messages = []
for finding_id in finding_ids:
with rls_transaction(tenant_id):
finding_instance = (
@@ -512,35 +516,54 @@ def send_findings_to_jira(
recommendation = remediation.get("recommendation", {})
remediation_code = remediation.get("code", {})
- # Send the individual finding to Jira
- result = jira_integration.send_finding(
- check_id=finding_instance.check_id,
- check_title=check_metadata.get("checktitle", ""),
- severity=finding_instance.severity,
- status=finding_instance.status,
- status_extended=finding_instance.status_extended or "",
- provider=finding_instance.scan.provider.provider,
- region=region,
- resource_uid=resource_uid,
- resource_name=resource_name,
- risk=check_metadata.get("risk", ""),
- recommendation_text=recommendation.get("text", ""),
- recommendation_url=recommendation.get("url", ""),
- remediation_code_native_iac=remediation_code.get("nativeiac", ""),
- remediation_code_terraform=remediation_code.get("terraform", ""),
- remediation_code_cli=remediation_code.get("cli", ""),
- remediation_code_other=remediation_code.get("other", ""),
- resource_tags=resource_tags,
- compliance=finding_instance.compliance or {},
- project_key=project_key,
- issue_type=issue_type,
- )
+ try:
+ # Send the individual finding to Jira
+ result = jira_integration.send_finding(
+ check_id=finding_instance.check_id,
+ check_title=check_metadata.get("checktitle", ""),
+ severity=finding_instance.severity,
+ status=finding_instance.status,
+ status_extended=finding_instance.status_extended or "",
+ provider=finding_instance.scan.provider.provider,
+ region=region,
+ resource_uid=resource_uid,
+ resource_name=resource_name,
+ risk=check_metadata.get("risk", ""),
+ recommendation_text=recommendation.get("text", ""),
+ recommendation_url=recommendation.get("url", ""),
+ remediation_code_native_iac=remediation_code.get("nativeiac", ""),
+ remediation_code_terraform=remediation_code.get("terraform", ""),
+ remediation_code_cli=remediation_code.get("cli", ""),
+ remediation_code_other=remediation_code.get("other", ""),
+ resource_tags=resource_tags,
+ compliance=finding_instance.compliance or {},
+ project_key=project_key,
+ issue_type=issue_type,
+ )
+ except JiraBaseException as error:
+ error_message = error.message or JIRA_GENERIC_SEND_ERROR
+ logger.exception(
+ "Failed to send finding %s to Jira: %s", finding_id, error_message
+ )
+ error_messages.append(error_message)
+ continue
+ except Exception:
+ logger.exception("Failed to send finding %s to Jira", finding_id)
+ error_messages.append(JIRA_GENERIC_SEND_ERROR)
+ continue
+
if result:
num_tickets_created += 1
else:
- logger.error(f"Failed to send finding {finding_id} to Jira")
+ error_message = JIRA_GENERIC_SEND_ERROR
+ logger.error(error_message)
+ error_messages.append(error_message)
- return {
+ result = {
"created_count": num_tickets_created,
"failed_count": len(finding_ids) - num_tickets_created,
}
+ if error_messages:
+ result["error"] = "; ".join(dict.fromkeys(error_messages))
+
+ return result
diff --git a/api/src/backend/tasks/jobs/lighthouse_providers.py b/api/src/backend/tasks/jobs/lighthouse_providers.py
index 0f28725e01..1eec1d3c6a 100644
--- a/api/src/backend/tasks/jobs/lighthouse_providers.py
+++ b/api/src/backend/tasks/jobs/lighthouse_providers.py
@@ -1,6 +1,15 @@
+import ssl
+from collections.abc import Iterable
+
import boto3
+import httpcore
+import httpx
import openai
from api.models import LighthouseProviderConfiguration, LighthouseProviderModels
+from api.validators import (
+ resolve_lighthouse_openai_compatible_host,
+ validate_lighthouse_openai_compatible_base_url,
+)
from botocore import UNSIGNED
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError
@@ -43,6 +52,90 @@ EXCLUDED_OPENAI_MODEL_SUBSTRINGS = (
"-instruct", # Legacy instruct models (gpt-3.5-turbo-instruct, etc.)
)
+OPENAI_COMPATIBLE_AUTHENTICATION_ERROR = "API key is invalid or missing"
+OPENAI_COMPATIBLE_CONNECTION_ERROR = "Provider connection failed"
+
+
+class _OpenAICompatibleProviderError(Exception):
+ """Sanitized OpenAI-compatible provider error safe for task results."""
+
+
+def _sanitize_openai_compatible_error(error: Exception) -> str:
+ status_code = getattr(error, "status_code", None)
+ if status_code is None:
+ response = getattr(error, "response", None)
+ status_code = getattr(response, "status_code", None)
+
+ if status_code == 401:
+ return OPENAI_COMPATIBLE_AUTHENTICATION_ERROR
+ return OPENAI_COMPATIBLE_CONNECTION_ERROR
+
+
+class _LighthouseOpenAICompatibleNetworkBackend(httpcore.SyncBackend):
+ """Validate and pin DNS results immediately before TCP connections."""
+
+ def connect_tcp(
+ self,
+ host: str,
+ port: int,
+ timeout: float | None = None,
+ local_address: str | None = None,
+ socket_options: Iterable[httpcore.SOCKET_OPTION] | None = None,
+ ) -> httpcore.NetworkStream:
+ resolved_addresses = resolve_lighthouse_openai_compatible_host(host, port)
+ last_error: httpcore.ConnectError | httpcore.ConnectTimeout | None = None
+
+ for address in resolved_addresses:
+ try:
+ return super().connect_tcp(
+ address,
+ port,
+ timeout=timeout,
+ local_address=local_address,
+ socket_options=socket_options,
+ )
+ except (httpcore.ConnectError, httpcore.ConnectTimeout) as error:
+ last_error = error
+
+ if last_error:
+ raise last_error
+ raise httpcore.ConnectError("No resolved addresses are available")
+
+
+class _LighthouseOpenAICompatibleHTTPTransport(httpx.HTTPTransport):
+ """HTTP transport that connects only to validated public IP addresses."""
+
+ def __init__(self) -> None:
+ self._pool = httpcore.ConnectionPool(
+ ssl_context=ssl.create_default_context(),
+ network_backend=_LighthouseOpenAICompatibleNetworkBackend(),
+ )
+
+
+def _create_openai_compatible_http_client() -> httpx.Client:
+ """Create the restricted HTTP client used for OpenAI-compatible providers."""
+ return httpx.Client(
+ follow_redirects=False,
+ trust_env=False,
+ transport=_LighthouseOpenAICompatibleHTTPTransport(),
+ )
+
+
+def _list_openai_compatible_models(base_url: str, api_key: str):
+ validate_lighthouse_openai_compatible_base_url(base_url)
+ try:
+ with _create_openai_compatible_http_client() as http_client:
+ client = openai.OpenAI(
+ api_key=api_key,
+ base_url=base_url,
+ http_client=http_client,
+ )
+ return client.models.list()
+ except Exception as error:
+ raise _OpenAICompatibleProviderError(
+ _sanitize_openai_compatible_error(error)
+ ) from error
+
def _extract_error_message(e: Exception) -> str:
"""
@@ -114,6 +207,7 @@ def _extract_openai_compatible_params(
return None
if not isinstance(base_url, str) or not base_url:
return None
+ validate_lighthouse_openai_compatible_base_url(base_url, resolve_dns=False)
return {"base_url": base_url, "api_key": api_key}
@@ -285,13 +379,7 @@ def check_lighthouse_provider_connection(provider_config_id: str) -> dict:
"error": "Base URL or API key is invalid or missing",
}
- # Test connection using OpenAI SDK with custom base_url
- # Note: base_url should include version (e.g., https://openrouter.ai/api/v1)
- client = openai.OpenAI(
- api_key=params["api_key"],
- base_url=params["base_url"],
- )
- _ = client.models.list()
+ _ = _list_openai_compatible_models(params["base_url"], params["api_key"])
else:
return {"connected": False, "error": "Unsupported provider type"}
@@ -361,8 +449,7 @@ def _fetch_openai_compatible_models(base_url: str, api_key: str) -> dict[str, st
Note: base_url should include version (e.g., https://openrouter.ai/api/v1)
"""
- client = openai.OpenAI(api_key=api_key, base_url=base_url)
- models = client.models.list()
+ models = _list_openai_compatible_models(base_url, api_key)
available_models: dict[str, str] = {}
for model in models.data:
diff --git a/api/src/backend/tasks/jobs/orphan_recovery.py b/api/src/backend/tasks/jobs/orphan_recovery.py
index 7211f1a1d5..05a2083dbe 100644
--- a/api/src/backend/tasks/jobs/orphan_recovery.py
+++ b/api/src/backend/tasks/jobs/orphan_recovery.py
@@ -172,11 +172,9 @@ def reconcile_orphans(
window_hours: int = 6,
dry_run: bool = False,
) -> dict:
- """Run the full orphan sweep under a single-flight advisory lock.
+ """Run the orphan task sweep under a single-flight advisory lock.
- Recovers any orphaned in-flight task and delegates attack-paths scans that
- never reached a worker to their existing stale-cleanup. Returns a summary;
- a no-op (lock not won) is reported too.
+ Returns a recovery summary. A no-op is reported when the lock is not acquired.
"""
with advisory_lock() as acquired:
if not acquired:
@@ -200,11 +198,6 @@ def reconcile_orphans(
logger.info("Orphan task recovery disabled by feature flag")
result = {"recovered": [], "failed": [], "skipped": [], "enabled": False}
- if not dry_run:
- from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
-
- result["attack_paths"] = cleanup_stale_attack_paths_scans()
-
return {"acquired": True, **result}
diff --git a/api/src/backend/tasks/jobs/report.py b/api/src/backend/tasks/jobs/report.py
index b40516dadf..c9d63a63ac 100644
--- a/api/src/backend/tasks/jobs/report.py
+++ b/api/src/backend/tasks/jobs/report.py
@@ -11,7 +11,6 @@ from uuid import UUID
from api.db_router import READ_REPLICA_ALIAS, MainRouter
from api.db_utils import rls_transaction
from api.models import Provider, Scan, ScanSummary, StateChoices, ThreatScoreSnapshot
-from api.utils import initialize_prowler_provider
from celery.utils.log import get_task_logger
from config.django.base import DJANGO_TMP_OUTPUT_DIRECTORY
from prowler.lib.check.compliance_models import (
@@ -27,6 +26,7 @@ from tasks.jobs.reports import (
ENSReportGenerator,
NIS2ReportGenerator,
ThreatScoreReportGenerator,
+ build_provider_metadata,
)
from tasks.jobs.threatscore import compute_threatscore_metrics
from tasks.jobs.threatscore_utils import (
@@ -841,24 +841,12 @@ def generate_compliance_reports(
tenant_id, scan_id
)
- # Initialize the Prowler provider once for the whole report batch. Each
- # generator used to re-init this in _load_compliance_data, paying the
- # boto3/Azure-SDK construction cost 5 times per scan. The instance is
- # only used by FindingOutput.transform_api_finding to enrich findings,
- # so a single shared instance is correct.
- logger.info("Initializing prowler_provider once for all reports (scan %s)", scan_id)
- try:
- with rls_transaction(tenant_id, using=READ_REPLICA_ALIAS):
- prowler_provider = initialize_prowler_provider(provider_obj)
- except Exception as init_error:
- # If init fails the generators will fall back to lazy init in
- # _load_compliance_data; we just log and continue.
- logger.warning(
- "Could not pre-initialize prowler_provider for scan %s: %s",
- scan_id,
- init_error,
- )
- prowler_provider = None
+ # Build a credential-free provider metadata stub once for the whole
+ # report batch. FindingOutput.transform_api_finding only reads static
+ # attributes (type plus a few identity fields), so reports never decrypt
+ # the ProviderSecret nor construct a cloud SDK session — generation keeps
+ # working after credentials are deleted or invalidated (PROWLER-2145).
+ prowler_provider = build_provider_metadata(provider_obj)
# Create shared findings cache up front so the eviction closure below
# can reference it. Defined BEFORE the closure to avoid the UnboundLocalError
diff --git a/api/src/backend/tasks/jobs/reports/__init__.py b/api/src/backend/tasks/jobs/reports/__init__.py
index a538416f59..94da8d6524 100644
--- a/api/src/backend/tasks/jobs/reports/__init__.py
+++ b/api/src/backend/tasks/jobs/reports/__init__.py
@@ -98,6 +98,7 @@ from .config import (
from .csa import CSAReportGenerator
from .ens import ENSReportGenerator
from .nis2 import NIS2ReportGenerator
+from .provider_metadata import build_provider_metadata
from .threatscore import ThreatScoreReportGenerator
__all__ = [
@@ -105,6 +106,7 @@ __all__ = [
"BaseComplianceReportGenerator",
"ComplianceData",
"RequirementData",
+ "build_provider_metadata",
"create_pdf_styles",
"get_requirement_metadata",
# Framework-specific generators
diff --git a/api/src/backend/tasks/jobs/reports/base.py b/api/src/backend/tasks/jobs/reports/base.py
index f51319a846..574609280a 100644
--- a/api/src/backend/tasks/jobs/reports/base.py
+++ b/api/src/backend/tasks/jobs/reports/base.py
@@ -11,7 +11,6 @@ from typing import Any
from api.db_router import READ_REPLICA_ALIAS
from api.db_utils import rls_transaction
from api.models import Provider, StatusChoices
-from api.utils import initialize_prowler_provider
from celery.utils.log import get_task_logger
from prowler.lib.check.compliance_models import (
Compliance,
@@ -52,6 +51,7 @@ from .config import (
PADDING_SMALL,
FrameworkConfig,
)
+from .provider_metadata import build_provider_metadata
logger = get_task_logger(__name__)
@@ -178,7 +178,8 @@ class ComplianceData:
attributes_by_requirement_id: Mapping of requirement IDs to their attributes
findings_by_check_id: Mapping of check IDs to their findings
provider_obj: Provider model object
- prowler_provider: Initialized Prowler provider
+ prowler_provider: Credential-free provider metadata stub (see
+ ``build_provider_metadata``)
"""
tenant_id: str
@@ -439,10 +440,10 @@ class BaseComplianceReportGenerator(ABC):
provider_obj: Optional pre-fetched Provider object
requirement_statistics: Optional pre-aggregated statistics
findings_cache: Optional pre-loaded findings cache
- prowler_provider: Optional pre-initialized Prowler provider. When
- generating multiple reports for the same scan the master
- function initializes this once and passes it in to avoid
- re-running boto3/Azure-SDK setup per framework.
+ prowler_provider: Optional provider metadata stub (see
+ ``build_provider_metadata``). When generating multiple
+ reports for the same scan the master function builds it
+ once and passes it in.
**kwargs: Additional framework-specific arguments
"""
framework = self.config.display_name
@@ -896,9 +897,9 @@ class BaseComplianceReportGenerator(ABC):
provider_obj: Optional pre-fetched Provider
requirement_statistics: Optional pre-aggregated statistics
findings_cache: Optional pre-loaded findings
- prowler_provider: Optional pre-initialized Prowler provider. When
- the master function initializes it once and passes it in,
- we skip the per-report ``initialize_prowler_provider`` call.
+ prowler_provider: Optional provider metadata stub. When the
+ master function builds it once and passes it in, we skip
+ the per-report ``build_provider_metadata`` call.
Returns:
Aggregated ComplianceData object
@@ -909,7 +910,7 @@ class BaseComplianceReportGenerator(ABC):
provider_obj = Provider.objects.get(id=provider_id)
if prowler_provider is None:
- prowler_provider = initialize_prowler_provider(provider_obj)
+ prowler_provider = build_provider_metadata(provider_obj)
provider_type = provider_obj.provider
# Load compliance framework — fall back to the universal loader
diff --git a/api/src/backend/tasks/jobs/reports/provider_metadata.py b/api/src/backend/tasks/jobs/reports/provider_metadata.py
new file mode 100644
index 0000000000..632f15c424
--- /dev/null
+++ b/api/src/backend/tasks/jobs/reports/provider_metadata.py
@@ -0,0 +1,124 @@
+from types import SimpleNamespace
+
+from prowler.providers.github.models import GithubIdentityInfo
+
+
+def build_provider_metadata(provider) -> SimpleNamespace:
+ """Build a credential-free stand-in for the Prowler SDK provider.
+
+ ``FindingOutput.transform_api_finding`` only reads static attributes
+ from the provider (``type`` plus a few identity/metadata fields used to
+ label accounts), so compliance reports never need the decrypted
+ ``ProviderSecret`` nor a live cloud SDK session. This builds an object
+ exposing exactly those attributes from the ``Provider`` DB row, which
+ keeps report generation working when the provider secret has been
+ deleted or its credentials are no longer valid (PROWLER-2145).
+
+ Args:
+ provider: The API ``Provider`` model instance (only ``provider``,
+ ``uid`` and ``alias`` are read).
+
+ Returns:
+ A ``SimpleNamespace`` mimicking the SDK provider attributes consumed
+ by ``FindingOutput.transform_api_finding`` / ``generate_output``.
+ """
+ provider_type = provider.provider
+ uid = provider.uid
+ display_name = provider.alias or uid
+
+ # Defaults cover every attribute read unconditionally in
+ # FindingOutput.generate_output (``provider.auth_method`` is accessed
+ # directly for several provider types); identity lookups go through
+ # get_nested_attribute/getattr, which tolerate missing attributes.
+ stub = SimpleNamespace(
+ type=provider_type,
+ auth_method="",
+ identity=SimpleNamespace(),
+ )
+
+ if provider_type == "aws":
+ stub.identity = SimpleNamespace(account=uid)
+ elif provider_type == "azure":
+ stub.identity = SimpleNamespace(
+ identity_type="",
+ identity_id="",
+ tenant_ids=[""],
+ tenant_domain="",
+ subscriptions={uid: display_name},
+ )
+ elif provider_type == "gcp":
+ stub.identity = SimpleNamespace(profile="")
+ stub.projects = {
+ uid: SimpleNamespace(
+ id=uid,
+ name=display_name,
+ labels={},
+ organization=None,
+ )
+ }
+ elif provider_type == "kubernetes":
+ stub.identity = SimpleNamespace(context=uid, cluster=uid)
+ elif provider_type == "m365":
+ stub.identity = SimpleNamespace(
+ identity_type="",
+ identity_id="",
+ tenant_domain=uid,
+ tenant_id="",
+ )
+ elif provider_type == "github":
+ # generate_output assigns account fields only inside
+ # isinstance(identity, Github*IdentityInfo) branches, so the stub
+ # must carry a real GithubIdentityInfo instance.
+ stub.identity = GithubIdentityInfo(
+ account_id=uid,
+ account_name=display_name,
+ account_url="",
+ )
+ elif provider_type == "mongodbatlas":
+ stub.identity = SimpleNamespace(
+ organization_id=uid,
+ organization_name=display_name,
+ )
+ elif provider_type == "iac":
+ stub.provider_uid = uid
+ elif provider_type == "oraclecloud":
+ stub.identity = SimpleNamespace(
+ tenancy_id=uid,
+ tenancy_name=display_name,
+ )
+ elif provider_type == "alibabacloud":
+ stub.identity = SimpleNamespace(
+ identity_arn="",
+ account_id=uid,
+ account_name=display_name,
+ )
+ elif provider_type == "cloudflare":
+ stub.identity = SimpleNamespace(
+ audited_accounts=[uid],
+ accounts=[],
+ )
+ elif provider_type == "openstack":
+ stub.identity = SimpleNamespace(
+ username="",
+ project_id=uid,
+ project_name=display_name,
+ )
+ elif provider_type == "googleworkspace":
+ stub.identity = SimpleNamespace(
+ delegated_user="",
+ customer_id=uid,
+ domain=display_name,
+ )
+ elif provider_type == "vercel":
+ stub.identity = SimpleNamespace(
+ team=None,
+ user_id=uid,
+ username=display_name,
+ )
+ elif provider_type == "okta":
+ stub.identity = SimpleNamespace(
+ org_domain=uid,
+ client_id="",
+ )
+
+ return stub
diff --git a/api/src/backend/tasks/jobs/scan.py b/api/src/backend/tasks/jobs/scan.py
index dcaacf6642..39db32abe4 100644
--- a/api/src/backend/tasks/jobs/scan.py
+++ b/api/src/backend/tasks/jobs/scan.py
@@ -1,6 +1,7 @@
import csv
import io
import json
+import random
import re
import time
import uuid
@@ -19,7 +20,7 @@ from api.db_utils import (
psycopg_connection,
rls_transaction,
)
-from api.exceptions import ProviderConnectionError
+from api.exceptions import ProviderConnectionError, ProviderDeletedException
from api.models import (
AttackSurfaceOverview,
ComplianceOverviewSummary,
@@ -48,7 +49,7 @@ from celery.utils.log import get_task_logger
from config.django.base import DJANGO_FINDINGS_BATCH_SIZE
from config.env import env
from config.settings.celery import CELERY_DEADLOCK_ATTEMPTS
-from django.db import IntegrityError, OperationalError
+from django.db import DatabaseError, IntegrityError, OperationalError, transaction
from django.db.models import (
Case,
Count,
@@ -117,6 +118,20 @@ ATTACK_SURFACE_PROVIDER_COMPATIBILITY = {
_ATTACK_SURFACE_MAPPING_CACHE: dict[str, dict] = {}
+def _save_scan_instance(
+ scan_instance: Scan, provider_id: str, update_fields: list[str]
+) -> None:
+ try:
+ with transaction.atomic(): # Savepoint for not killing the `rls_transaction`
+ scan_instance.save(update_fields=update_fields)
+ except DatabaseError:
+ if Scan.objects.filter(pk=scan_instance.id).exists():
+ raise
+ raise ProviderDeletedException(
+ f"Provider '{provider_id}' for scan '{scan_instance.id}' was deleted during the scan"
+ ) from None
+
+
def aggregate_category_counts(
categories: list[str],
severity: str,
@@ -292,6 +307,55 @@ def _store_resources(
return resource_instance, (resource_instance.uid, resource_instance.region)
+def _bulk_update_resource_failed_findings_counts(
+ tenant_id: str,
+ scan_id: str,
+ resources_to_update: list[Resource],
+) -> None:
+ """Persist failed finding counters with stable row locking and retry."""
+ if not resources_to_update:
+ return
+
+ sorted_resources = sorted(
+ resources_to_update, key=lambda resource: str(resource.id)
+ )
+ for start in range(0, len(sorted_resources), SCAN_DB_BATCH_SIZE):
+ chunk = sorted_resources[start : start + SCAN_DB_BATCH_SIZE]
+ chunk_ids = [resource.id for resource in chunk]
+
+ for attempt in range(CELERY_DEADLOCK_ATTEMPTS):
+ try:
+ with rls_transaction(tenant_id):
+ list(
+ Resource.objects.select_for_update()
+ .filter(id__in=chunk_ids)
+ .order_by("id")
+ .values_list("id", flat=True)
+ )
+ Resource.objects.bulk_update(
+ chunk,
+ ["failed_findings_count"],
+ batch_size=SCAN_DB_BATCH_SIZE,
+ )
+ break
+ except OperationalError:
+ if attempt < CELERY_DEADLOCK_ATTEMPTS - 1:
+ logger.warning(
+ "Resource failed findings count update hit a database "
+ "conflict on scan %s. Retrying chunk %s/%s "
+ "(attempt %s/%s).",
+ scan_id,
+ start // SCAN_DB_BATCH_SIZE + 1,
+ (len(sorted_resources) + SCAN_DB_BATCH_SIZE - 1)
+ // SCAN_DB_BATCH_SIZE,
+ attempt + 1,
+ CELERY_DEADLOCK_ATTEMPTS,
+ )
+ time.sleep((0.1 * (2**attempt)) + random.uniform(0, 0.1))
+ continue
+ raise
+
+
def _copy_compliance_requirement_rows(
tenant_id: str, rows: list[dict[str, Any]]
) -> None:
@@ -1029,13 +1093,18 @@ def perform_prowler_scan(
group_resources_cache: dict[str, set] = {}
start_time = time.time()
exc = None
+ skip_final_scan_update = False
with rls_transaction(tenant_id):
provider_instance = Provider.objects.get(pk=provider_id)
scan_instance = Scan.objects.get(pk=scan_id)
scan_instance.state = StateChoices.EXECUTING
scan_instance.started_at = datetime.now(tz=UTC)
- scan_instance.save(update_fields=["state", "started_at", "updated_at"])
+ _save_scan_instance(
+ scan_instance,
+ provider_id,
+ ["state", "started_at", "updated_at"],
+ )
# Find the mutelist processor if it exists
with rls_transaction(tenant_id, using=READ_REPLICA_ALIAS):
@@ -1101,7 +1170,7 @@ def perform_prowler_scan(
# Throttle scan_instance progress writes to avoid hammering the writer:
# only persist when progress moves by at least `PROGRESS_THROTTLE_DELTA`
- # OR `PROGRESS_THROTTLE_SECONDS` have elapsed. The final progress (1.0)
+ # OR `PROGRESS_THROTTLE_SECONDS` have elapsed. The final progress (100)
# always persists in the `finally` block below.
last_persisted_progress = -1.0
last_persisted_progress_at = 0.0
@@ -1143,7 +1212,11 @@ def perform_prowler_scan(
):
with rls_transaction(tenant_id):
scan_instance.progress = progress
- scan_instance.save(update_fields=["progress", "updated_at"])
+ _save_scan_instance(
+ scan_instance,
+ provider_id,
+ ["progress", "updated_at"],
+ )
last_persisted_progress = progress
last_persisted_progress_at = now
@@ -1159,37 +1232,45 @@ def perform_prowler_scan(
resources_to_update.append(resource_instance)
if resources_to_update:
- # Single rls_transaction wrapping the bulk_update (previously
- # `update_objects_in_batches` opened one rls_transaction per
- # chunk; for tenants with many resources this collapsed N
- # BEGINs/COMMITs into 1).
- with rls_transaction(tenant_id):
- Resource.objects.bulk_update(
- resources_to_update,
- ["failed_findings_count"],
- batch_size=SCAN_DB_BATCH_SIZE,
- )
+ _bulk_update_resource_failed_findings_counts(
+ tenant_id=tenant_id,
+ scan_id=scan_id,
+ resources_to_update=resources_to_update,
+ )
+ except ProviderDeletedException as e:
+ logger.warning(str(e))
+ exception = e
+ skip_final_scan_update = True
except Exception as e:
logger.error(f"Error performing scan {scan_id}: {e}")
exception = e
scan_instance.state = StateChoices.FAILED
finally:
- with rls_transaction(tenant_id):
- scan_instance.duration = time.time() - start_time
- scan_instance.completed_at = datetime.now(tz=UTC)
- scan_instance.unique_resource_count = len(unique_resources)
- scan_instance.save(
- update_fields=[
- "state",
- "duration",
- "completed_at",
- "unique_resource_count",
- "progress",
- "updated_at",
- ]
- )
+ if not skip_final_scan_update:
+ try:
+ with rls_transaction(tenant_id):
+ scan_instance.duration = time.time() - start_time
+ scan_instance.completed_at = datetime.now(tz=UTC)
+ scan_instance.unique_resource_count = len(unique_resources)
+ if exception is None:
+ scan_instance.progress = 100
+ _save_scan_instance(
+ scan_instance,
+ provider_id,
+ [
+ "state",
+ "duration",
+ "completed_at",
+ "unique_resource_count",
+ "progress",
+ "updated_at",
+ ],
+ )
+ except ProviderDeletedException as e:
+ logger.warning(str(e))
+ exception = e
if exception is not None:
raise exception
@@ -1383,7 +1464,7 @@ def aggregate_findings(tenant_id: str, scan_id: str):
)
with rls_transaction(tenant_id):
- scan_aggregations = {
+ scan_aggregations = [
ScanSummary(
tenant_id=tenant_id,
scan_id=scan_id,
@@ -1408,9 +1489,18 @@ def aggregate_findings(tenant_id: str, scan_id: str):
for agg in aggregation
if agg["resources__service"] is not None
and agg["resources__region"] is not None
- }
- # Upsert so re-runs (post-mute reaggregation) don't trip
- # `unique_scan_summary`; race-safe under concurrent writers.
+ ]
+ # Needed sort so concurrent upserts acquire locks consistently
+ scan_aggregations.sort(
+ key=lambda summary: (
+ summary.tenant_id,
+ summary.scan_id,
+ summary.check_id,
+ summary.service,
+ summary.severity,
+ summary.region,
+ )
+ )
ScanSummary.objects.bulk_create(
scan_aggregations,
batch_size=3000,
diff --git a/api/src/backend/tasks/jobs/threatscore_utils.py b/api/src/backend/tasks/jobs/threatscore_utils.py
index 2e2fb87ba5..2f968749dd 100644
--- a/api/src/backend/tasks/jobs/threatscore_utils.py
+++ b/api/src/backend/tasks/jobs/threatscore_utils.py
@@ -178,7 +178,9 @@ def _load_findings_for_requirement_checks(
tenant_id (str): The tenant ID for Row-Level Security context.
scan_id (str): The ID of the scan to retrieve findings for.
check_ids (list[str]): List of check IDs to load findings for.
- prowler_provider: The initialized Prowler provider instance.
+ prowler_provider: Credential-free provider metadata stub (see
+ ``tasks.jobs.reports.build_provider_metadata``) consumed by
+ ``FindingOutput.transform_api_finding``.
findings_cache (dict, optional): Cache of already loaded findings.
If provided, checks are first looked up in cache before querying database.
total_counts_out (dict, optional): If provided, populated with
diff --git a/api/src/backend/tasks/tasks.py b/api/src/backend/tasks/tasks.py
index e7bb0982cd..a91ff85c01 100644
--- a/api/src/backend/tasks/tasks.py
+++ b/api/src/backend/tasks/tasks.py
@@ -2,6 +2,7 @@ import os
from datetime import UTC, datetime, timedelta
from pathlib import Path
from shutil import rmtree
+from uuid import uuid4
from api.compliance import (
get_compliance_frameworks,
@@ -10,14 +11,25 @@ from api.compliance import (
from api.db_router import READ_REPLICA_ALIAS
from api.db_utils import delete_related_daily_task, rls_transaction
from api.decorators import handle_provider_deletion, set_tenant
-from api.models import Finding, Integration, Provider, Scan, ScanSummary, StateChoices
+from api.exceptions import ProviderDeletedException
+from api.models import (
+ Finding,
+ Integration,
+ Provider,
+ Scan,
+ ScanSummary,
+ StateChoices,
+ Task,
+)
from api.utils import initialize_prowler_provider
from api.v1.serializers import ScanTaskSerializer
-from celery import chain, group, shared_task
+from celery import chain, group, shared_task, states
from celery.utils.log import get_task_logger
from config.celery import RLSTask
from config.django.base import DJANGO_FINDINGS_BATCH_SIZE, DJANGO_TMP_OUTPUT_DIRECTORY
+from django.db import transaction
from django_celery_beat.models import PeriodicTask
+from django_celery_results.models import TaskResult
from prowler.lib.check.compliance_models import Compliance
from prowler.lib.outputs.compliance.compliance import (
process_universal_compliance_frameworks,
@@ -85,6 +97,220 @@ from tasks.utils import (
)
logger = get_task_logger(__name__)
+QUEUED_SCAN_TASK_STATE = "QUEUED"
+DISPATCHED_SCAN_TASK_STATES = (states.PENDING, states.STARTED, "PROGRESS")
+
+
+def _get_dispatched_provider_scan(tenant_id: str, provider_id: str):
+ """Return a scan that has already been dispatched for a provider."""
+ executing_scan = (
+ Scan.objects.select_for_update()
+ .filter(
+ tenant_id=tenant_id,
+ provider_id=provider_id,
+ state=StateChoices.EXECUTING,
+ )
+ .order_by("-inserted_at")
+ .first()
+ )
+ if executing_scan:
+ return executing_scan
+
+ return (
+ Scan.objects.select_for_update(of=("self",))
+ .select_related("task__task_runner_task")
+ .filter(
+ tenant_id=tenant_id,
+ provider_id=provider_id,
+ state__in=(StateChoices.AVAILABLE, StateChoices.SCHEDULED),
+ task__isnull=False,
+ task__task_runner_task__status__in=DISPATCHED_SCAN_TASK_STATES,
+ )
+ .order_by("-inserted_at")
+ .first()
+ )
+
+
+def _get_queued_provider_scan(tenant_id: str, provider_id: str):
+ """Return the next DB-queued scan for a provider."""
+ return (
+ Scan.objects.select_for_update(of=("self",))
+ .select_related("task__task_runner_task")
+ .filter(
+ tenant_id=tenant_id,
+ provider_id=provider_id,
+ state=StateChoices.AVAILABLE,
+ task__isnull=False,
+ task__task_runner_task__status=QUEUED_SCAN_TASK_STATE,
+ )
+ .order_by("inserted_at", "id")
+ .first()
+ )
+
+
+def get_active_provider_scan(tenant_id: str, provider_id: str):
+ """Return a dispatched or DB-queued scan for a provider."""
+ return _get_dispatched_provider_scan(
+ tenant_id, provider_id
+ ) or _get_queued_provider_scan(tenant_id, provider_id)
+
+
+def create_scan_task_record(
+ tenant_id: str,
+ task_id: str,
+ task_name: str = "scan-perform",
+ task_status: str | None = states.PENDING,
+) -> Task:
+ if task_status is None:
+ task_status = states.PENDING
+
+ task_result, _ = TaskResult.objects.update_or_create(
+ task_id=str(task_id),
+ defaults={"status": task_status, "task_name": task_name},
+ )
+ prowler_task, _ = Task.objects.update_or_create(
+ id=str(task_id),
+ tenant_id=tenant_id,
+ defaults={"task_runner_task": task_result},
+ )
+ return prowler_task
+
+
+def enqueue_scan_execution_on_commit(
+ tenant_id: str,
+ scan: Scan,
+ task_id: str,
+) -> None:
+ transaction.on_commit(
+ lambda: perform_scan_task.apply_async(
+ kwargs={
+ "tenant_id": str(tenant_id),
+ "scan_id": str(scan.id),
+ "provider_id": str(scan.provider_id),
+ },
+ task_id=str(task_id),
+ )
+ )
+
+
+def _get_queued_scheduled_scan(tenant_id: str, provider_id: str):
+ return (
+ Scan.objects.select_for_update(of=("self",))
+ .select_related("task__task_runner_task")
+ .filter(
+ tenant_id=tenant_id,
+ provider_id=provider_id,
+ trigger=Scan.TriggerChoices.SCHEDULED,
+ state=StateChoices.AVAILABLE,
+ task__isnull=False,
+ task__task_runner_task__status=QUEUED_SCAN_TASK_STATE,
+ )
+ .order_by("inserted_at", "id")
+ .first()
+ )
+
+
+def _get_or_create_queued_scheduled_scan(
+ tenant_id: str,
+ provider_id: str,
+ periodic_task_instance: PeriodicTask,
+ scheduled_at: datetime,
+) -> Scan:
+ queued_scan = _get_queued_scheduled_scan(tenant_id, provider_id)
+ if queued_scan:
+ return queued_scan
+
+ task_id = str(uuid4())
+ queued_task = create_scan_task_record(
+ tenant_id=tenant_id,
+ task_id=task_id,
+ task_status=QUEUED_SCAN_TASK_STATE,
+ )
+ return Scan.objects.create(
+ tenant_id=tenant_id,
+ name="Daily scheduled scan",
+ provider_id=provider_id,
+ trigger=Scan.TriggerChoices.SCHEDULED,
+ state=StateChoices.AVAILABLE,
+ scheduled_at=scheduled_at,
+ scheduler_task_id=periodic_task_instance.id,
+ task=queued_task,
+ )
+
+
+def _dispatch_next_queued_provider_scan(tenant_id: str, provider_id: str):
+ with rls_transaction(tenant_id):
+ if not Provider.objects.select_for_update().filter(pk=provider_id).exists():
+ return None
+
+ if _get_dispatched_provider_scan(tenant_id, provider_id):
+ return None
+
+ queued_scan = _get_queued_provider_scan(tenant_id, provider_id)
+ if not queued_scan or not queued_scan.task:
+ return None
+
+ task_result = queued_scan.task.task_runner_task
+ task_result.status = states.PENDING
+ task_result.task_name = "scan-perform"
+ task_result.save(update_fields=["status", "task_name"])
+ enqueue_scan_execution_on_commit(
+ tenant_id=tenant_id,
+ scan=queued_scan,
+ task_id=str(queued_scan.task_id),
+ )
+ return queued_scan
+
+
+def _dispatch_next_queued_provider_scan_best_effort(
+ tenant_id: str, provider_id: str
+) -> None:
+ try:
+ _dispatch_next_queued_provider_scan(tenant_id, provider_id)
+ except Exception:
+ logger.exception(
+ "Failed to dispatch next queued scan for provider %s", provider_id
+ )
+
+
+def _get_or_create_next_scheduled_scan(
+ tenant_id: str,
+ provider_id: str,
+ periodic_task_instance: PeriodicTask,
+ next_scan_datetime: datetime,
+) -> Scan:
+ interval = periodic_task_instance.interval
+ now = datetime.now(UTC)
+ while next_scan_datetime <= now:
+ next_scan_datetime += timedelta(**{interval.period: interval.every})
+
+ return _get_or_create_scheduled_scan(
+ tenant_id=tenant_id,
+ provider_id=provider_id,
+ scheduler_task_id=periodic_task_instance.id,
+ scheduled_at=next_scan_datetime,
+ update_state=True,
+ )
+
+
+def _ensure_next_scheduled_scan_best_effort(
+ tenant_id: str,
+ provider_id: str,
+ periodic_task_instance: PeriodicTask,
+ next_scan_datetime: datetime,
+) -> None:
+ try:
+ with rls_transaction(tenant_id):
+ _get_or_create_next_scheduled_scan(
+ tenant_id=tenant_id,
+ provider_id=provider_id,
+ periodic_task_instance=periodic_task_instance,
+ next_scan_datetime=next_scan_datetime,
+ )
+ except Exception:
+ logger.exception(
+ "Failed to ensure next scheduled scan for provider %s", provider_id
+ )
def _cleanup_orphan_scheduled_scans(
@@ -117,6 +343,7 @@ def _cleanup_orphan_scheduled_scans(
trigger=Scan.TriggerChoices.SCHEDULED,
state=StateChoices.AVAILABLE,
scheduler_task_id=scheduler_task_id,
+ task__isnull=True,
)
scheduled_scan_exists = Scan.objects.filter(
@@ -292,16 +519,17 @@ def perform_scan_task(
)
return None
- result = perform_prowler_scan(
- tenant_id=tenant_id,
- scan_id=scan_id,
- provider_id=provider_id,
- checks_to_execute=checks_to_execute,
- )
-
- _perform_scan_complete_tasks(tenant_id, scan_id, provider_id)
-
- return result
+ try:
+ result = perform_prowler_scan(
+ tenant_id=tenant_id,
+ scan_id=scan_id,
+ provider_id=provider_id,
+ checks_to_execute=checks_to_execute,
+ )
+ _perform_scan_complete_tasks(tenant_id, scan_id, provider_id)
+ return result
+ finally:
+ _dispatch_next_queued_provider_scan_best_effort(tenant_id, provider_id)
# acks_late=False: like scan-perform; a dropped run is re-fired by Beat on the next tick.
@@ -335,7 +563,7 @@ def perform_scheduled_scan_task(self, tenant_id: str, provider_id: str):
task_id = self.request.id
with rls_transaction(tenant_id):
- if not Provider.objects.filter(pk=provider_id).exists():
+ if not Provider.objects.select_for_update().filter(pk=provider_id).exists():
logger.warning(
"scheduled scan-perform skipped: provider %s no longer exists "
"(tenant=%s)",
@@ -348,22 +576,6 @@ def perform_scheduled_scan_task(self, tenant_id: str, provider_id: str):
periodic_task_instance = PeriodicTask.objects.get(
name=f"scan-perform-scheduled-{provider_id}"
)
- executing_scan = (
- Scan.objects.filter(
- tenant_id=tenant_id,
- provider_id=provider_id,
- trigger=Scan.TriggerChoices.SCHEDULED,
- state=StateChoices.EXECUTING,
- )
- .order_by("-started_at")
- .first()
- )
- if executing_scan:
- logger.warning(
- f"Scheduled scan already executing for provider {provider_id}. Skipping."
- )
- return ScanTaskSerializer(instance=executing_scan).data
-
executed_scan = Scan.objects.filter(
tenant_id=tenant_id,
provider_id=provider_id,
@@ -388,6 +600,26 @@ def perform_scheduled_scan_task(self, tenant_id: str, provider_id: str):
scheduler_task_id=periodic_task_instance.id,
)
+ active_scan = get_active_provider_scan(tenant_id, provider_id)
+ if active_scan:
+ logger.warning(
+ "Scan already queued or executing for provider %s. Queueing scheduled run.",
+ provider_id,
+ )
+ queued_scheduled_scan = _get_or_create_queued_scheduled_scan(
+ tenant_id=tenant_id,
+ provider_id=provider_id,
+ periodic_task_instance=periodic_task_instance,
+ scheduled_at=current_scan_datetime,
+ )
+ _get_or_create_next_scheduled_scan(
+ tenant_id=tenant_id,
+ provider_id=provider_id,
+ periodic_task_instance=periodic_task_instance,
+ next_scan_datetime=next_scan_datetime,
+ )
+ return ScanTaskSerializer(instance=queued_scheduled_scan).data
+
scan_instance = _get_or_create_scheduled_scan(
tenant_id=tenant_id,
provider_id=provider_id,
@@ -403,24 +635,16 @@ def perform_scheduled_scan_task(self, tenant_id: str, provider_id: str):
scan_id=str(scan_instance.id),
provider_id=provider_id,
)
+ _perform_scan_complete_tasks(tenant_id, str(scan_instance.id), provider_id)
+ return result
finally:
- with rls_transaction(tenant_id):
- now = datetime.now(UTC)
- if next_scan_datetime <= now:
- interval_delta = timedelta(**{interval.period: interval.every})
- while next_scan_datetime <= now:
- next_scan_datetime += interval_delta
- _get_or_create_scheduled_scan(
- tenant_id=tenant_id,
- provider_id=provider_id,
- scheduler_task_id=periodic_task_instance.id,
- scheduled_at=next_scan_datetime,
- update_state=True,
- )
-
- _perform_scan_complete_tasks(tenant_id, str(scan_instance.id), provider_id)
-
- return result
+ _ensure_next_scheduled_scan_best_effort(
+ tenant_id=tenant_id,
+ provider_id=provider_id,
+ periodic_task_instance=periodic_task_instance,
+ next_scan_datetime=next_scan_datetime,
+ )
+ _dispatch_next_queued_provider_scan_best_effort(tenant_id, provider_id)
@shared_task(name="scan-summary", queue="overview")
@@ -443,7 +667,13 @@ class AttackPathsScanRLSTask(RLSTask):
scan_id = kwargs.get("scan_id")
if tenant_id and scan_id:
- logger.error(f"Attack paths scan task {task_id} failed: {exc}")
+ if isinstance(exc, ProviderDeletedException):
+ logger.warning(
+ f"Attack paths scan task {task_id} stopped because its provider "
+ f"or tenant was deleted: {exc}"
+ )
+ else:
+ logger.error(f"Attack paths scan task {task_id} failed: {exc}")
attack_paths_db_utils.fail_attack_paths_scan(tenant_id, scan_id, str(exc))
diff --git a/api/src/backend/tasks/tests/report_test_helpers.py b/api/src/backend/tasks/tests/report_test_helpers.py
new file mode 100644
index 0000000000..18d7b0e2b6
--- /dev/null
+++ b/api/src/backend/tasks/tests/report_test_helpers.py
@@ -0,0 +1,62 @@
+import io
+import struct
+import zlib
+from types import ModuleType, SimpleNamespace
+from typing import Any
+
+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
+
+
+def _png_chunk(chunk_type: bytes, data: bytes) -> bytes:
+ checksum = zlib.crc32(chunk_type + data) & 0xFFFFFFFF
+ return (
+ struct.pack(">I", len(data)) + chunk_type + data + struct.pack(">I", checksum)
+ )
+
+
+def _build_tiny_png() -> bytes:
+ ihdr = struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0)
+ # Filter byte 0 plus one white RGB pixel.
+ idat = zlib.compress(b"\x00\xff\xff\xff")
+ return (
+ PNG_SIGNATURE
+ + _png_chunk(b"IHDR", ihdr)
+ + _png_chunk(b"IDAT", idat)
+ + _png_chunk(b"IEND", b"")
+ )
+
+
+_TINY_PNG_BYTES = _build_tiny_png()
+
+
+def fake_png_buffer() -> io.BytesIO:
+ return io.BytesIO(_TINY_PNG_BYTES)
+
+
+def patch_chart_helpers(
+ monkeypatch: Any, module: ModuleType, names: tuple[str, ...]
+) -> dict[str, list[dict[str, Any]]]:
+ calls: dict[str, list[dict[str, Any]]] = {name: [] for name in names}
+
+ def _build_fake_chart(name: str):
+ def _fake_chart(*args: Any, **kwargs: Any) -> io.BytesIO:
+ calls[name].append({"args": args, "kwargs": kwargs})
+ return fake_png_buffer()
+
+ return _fake_chart
+
+ for name in names:
+ monkeypatch.setattr(module, name, _build_fake_chart(name))
+
+ return calls
+
+
+def patch_report_gc(monkeypatch: Any) -> None:
+ from tasks.jobs import report as report_module
+ from tasks.jobs.reports import base as base_report_module
+ from tasks.jobs.reports import threatscore as threatscore_report_module
+
+ gc_stub = SimpleNamespace(collect=lambda: 0)
+ monkeypatch.setattr(report_module, "gc", gc_stub)
+ monkeypatch.setattr(base_report_module, "gc", gc_stub)
+ monkeypatch.setattr(threatscore_report_module, "gc", gc_stub)
diff --git a/api/src/backend/tasks/tests/test_attack_paths_aws.py b/api/src/backend/tasks/tests/test_attack_paths_aws.py
new file mode 100644
index 0000000000..dc2c59d614
--- /dev/null
+++ b/api/src/backend/tasks/tests/test_attack_paths_aws.py
@@ -0,0 +1,102 @@
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import neo4j.exceptions
+import pytest
+from tasks.jobs.attack_paths import aws
+
+DATABASE_NOT_FOUND_CODE = "Neo.ClientError.Database.DatabaseNotFound"
+
+
+def _make_neo4j_error(code: str) -> neo4j.exceptions.Neo4jError:
+ return neo4j.exceptions.Neo4jError._hydrate_neo4j(
+ code=code,
+ message="graph query failed",
+ )
+
+
+def _resource_functions(failing_sync, following_sync):
+ return {
+ "failing_sync": failing_sync,
+ "following_sync": following_sync,
+ "permission_relationships": MagicMock(),
+ "resourcegroupstaggingapi": MagicMock(),
+ }
+
+
+def test_sync_aws_account_reraises_database_not_found_immediately():
+ error = _make_neo4j_error(DATABASE_NOT_FOUND_CODE)
+ failing_sync = MagicMock(side_effect=error)
+ following_sync = MagicMock()
+
+ with (
+ patch.object(
+ aws.cartography_aws,
+ "RESOURCE_FUNCTIONS",
+ _resource_functions(failing_sync, following_sync),
+ ),
+ patch.object(aws.db_utils, "update_attack_paths_scan_progress"),
+ patch.object(aws.utils, "stringify_exception") as stringify_exception,
+ patch.object(aws.logger, "warning") as warning,
+ pytest.raises(neo4j.exceptions.Neo4jError) as exc_info,
+ ):
+ aws.sync_aws_account(
+ SimpleNamespace(uid="123456789012"),
+ [
+ "failing_sync",
+ "following_sync",
+ "permission_relationships",
+ "resourcegroupstaggingapi",
+ ],
+ {},
+ MagicMock(),
+ )
+
+ assert exc_info.value is error
+ following_sync.assert_not_called()
+ stringify_exception.assert_not_called()
+ warning.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "error",
+ [
+ _make_neo4j_error("Neo.ClientError.Statement.SyntaxError"),
+ RuntimeError("resource sync failed"),
+ ],
+ ids=["different-neo4j-error", "non-neo4j-error"],
+)
+def test_sync_aws_account_warns_and_continues_for_other_exceptions(error):
+ failing_sync = MagicMock(side_effect=error)
+ following_sync = MagicMock()
+
+ with (
+ patch.object(
+ aws.cartography_aws,
+ "RESOURCE_FUNCTIONS",
+ _resource_functions(failing_sync, following_sync),
+ ),
+ patch.object(aws.db_utils, "update_attack_paths_scan_progress"),
+ patch.object(
+ aws.utils,
+ "stringify_exception",
+ return_value="formatted failure",
+ ),
+ patch.object(aws.logger, "warning") as warning,
+ ):
+ failed_syncs = aws.sync_aws_account(
+ SimpleNamespace(uid="123456789012"),
+ [
+ "failing_sync",
+ "following_sync",
+ "permission_relationships",
+ "resourcegroupstaggingapi",
+ ],
+ {},
+ MagicMock(),
+ )
+
+ assert failed_syncs == {"failing_sync": "formatted failure"}
+ following_sync.assert_called_once_with()
+ warning.assert_called_once()
+ assert "Continuing to the next AWS sync function" in warning.call_args.args[0]
diff --git a/api/src/backend/tasks/tests/test_attack_paths_provider_config.py b/api/src/backend/tasks/tests/test_attack_paths_provider_config.py
new file mode 100644
index 0000000000..41ec2847d4
--- /dev/null
+++ b/api/src/backend/tasks/tests/test_attack_paths_provider_config.py
@@ -0,0 +1,30 @@
+from tasks.jobs.attack_paths.provider_config import AWS_NORMALIZED_LISTS
+from tasks.jobs.attack_paths.sync import _build_catalog_index, _node_to_sync_dict
+
+
+def test_aws_vpc_endpoint_id_lists_are_normalized():
+ catalog = _build_catalog_index(AWS_NORMALIZED_LISTS)
+ record = {
+ "element_id": "node-1",
+ "labels": ["AWSVpcEndpoint"],
+ "props": {
+ "id": "vpce-123",
+ "route_table_ids": ["rtb-1"],
+ "network_interface_ids": ["eni-1"],
+ "subnet_ids": ["subnet-1"],
+ },
+ }
+
+ _, parent, children, rels = _node_to_sync_dict(record, "provider-id", catalog)
+
+ assert parent["props"] == {"id": "vpce-123"}
+ assert {child["_child_label"] for child in children} == {
+ "AWSVpcEndpointRouteTableIdsItem",
+ "AWSVpcEndpointNetworkInterfaceIdsItem",
+ "AWSVpcEndpointSubnetIdsItem",
+ }
+ assert {rel["rel_type"] for rel in rels} == {
+ "HAS_ROUTE_TABLE_IDS",
+ "HAS_NETWORK_INTERFACE_IDS",
+ "HAS_SUBNET_IDS",
+ }
diff --git a/api/src/backend/tasks/tests/test_attack_paths_scan.py b/api/src/backend/tasks/tests/test_attack_paths_scan.py
index fef4894646..4409e5f19d 100644
--- a/api/src/backend/tasks/tests/test_attack_paths_scan.py
+++ b/api/src/backend/tasks/tests/test_attack_paths_scan.py
@@ -1,9 +1,14 @@
+import logging
from contextlib import nullcontext
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from unittest.mock import MagicMock, call, patch
+from uuid import uuid4
import pytest
+from api.attack_paths.database import GraphDatabaseQueryException
+from api.db_utils import rls_transaction
+from api.exceptions import ProviderDeletedException
from api.models import (
AttackPathsScan,
Finding,
@@ -15,6 +20,7 @@ from api.models import (
StatusChoices,
Task,
)
+from django.db import DEFAULT_DB_ALIAS, DatabaseError
from django_celery_results.models import TaskResult
from prowler.lib.check.models import Severity
from tasks.jobs.attack_paths import findings as findings_module
@@ -23,15 +29,31 @@ from tasks.jobs.attack_paths import internet as internet_module
from tasks.jobs.attack_paths import sync as sync_module
from tasks.jobs.attack_paths.scan import run as attack_paths_run
+SYNC_RESULT_EMPTY = {
+ "nodes": 0,
+ "child_nodes": 0,
+ "relationships": 0,
+ "structural_relationships": 0,
+ "item_relationships": 0,
+}
+
@pytest.mark.django_db
class TestAttackPathsRun:
+ @pytest.fixture(autouse=True)
+ def mock_graph_database_preflight(self):
+ with patch(
+ "tasks.jobs.attack_paths.scan.graph_database.verify_scan_databases_available"
+ ) as mock_preflight:
+ yield mock_preflight
+
# Patching with decorators as we got a `SyntaxError: too many statically nested blocks` error if we use context managers
@patch("tasks.jobs.attack_paths.scan.graph_database.drop_database")
@patch(
"tasks.jobs.attack_paths.scan.utils.call_within_event_loop",
side_effect=lambda fn, *a, **kw: fn(*a, **kw),
)
+ @patch("tasks.jobs.attack_paths.scan.db_utils.set_scan_migrated")
@patch("tasks.jobs.attack_paths.scan.db_utils.set_graph_data_ready")
@patch("tasks.jobs.attack_paths.scan.db_utils.set_provider_graph_data_ready")
@patch("tasks.jobs.attack_paths.scan.db_utils.finish_attack_paths_scan")
@@ -39,7 +61,7 @@ class TestAttackPathsRun:
@patch("tasks.jobs.attack_paths.scan.db_utils.starting_attack_paths_scan")
@patch(
"tasks.jobs.attack_paths.scan.sync.sync_graph",
- return_value={"nodes": 0, "relationships": 0},
+ return_value=SYNC_RESULT_EMPTY,
)
@patch("tasks.jobs.attack_paths.scan.graph_database.drop_subgraph", return_value=0)
@patch("tasks.jobs.attack_paths.scan.indexes.create_sync_indexes")
@@ -48,11 +70,11 @@ class TestAttackPathsRun:
@patch("tasks.jobs.attack_paths.scan.indexes.create_findings_indexes")
@patch("tasks.jobs.attack_paths.scan.cartography_ontology.run")
@patch("tasks.jobs.attack_paths.scan.cartography_analysis.run")
- @patch("tasks.jobs.attack_paths.scan.cartography_create_indexes.run")
+ @patch("tasks.jobs.attack_paths.indexes.cartography_create_indexes.run")
@patch("tasks.jobs.attack_paths.scan.graph_database.clear_cache")
@patch("tasks.jobs.attack_paths.scan.graph_database.create_database")
@patch(
- "tasks.jobs.attack_paths.scan.graph_database.get_uri",
+ "tasks.jobs.attack_paths.scan.graph_database.get_ingest_uri",
return_value="bolt://neo4j",
)
@patch(
@@ -66,7 +88,7 @@ class TestAttackPathsRun:
def test_run_success_flow(
self,
mock_init_provider,
- mock_get_uri,
+ mock_get_ingest_uri,
mock_create_db,
mock_clear_cache,
mock_cartography_indexes,
@@ -83,19 +105,16 @@ class TestAttackPathsRun:
mock_finish,
mock_set_provider_graph_data_ready,
mock_set_graph_data_ready,
+ mock_set_scan_migrated,
mock_event_loop,
mock_drop_db,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -159,6 +178,7 @@ class TestAttackPathsRun:
target_database="tenant-db",
tenant_id=str(provider.tenant_id),
provider_id=str(provider.id),
+ provider_type="aws",
)
mock_get_ingestion.assert_called_once_with(provider.provider)
mock_event_loop.assert_called_once()
@@ -172,10 +192,93 @@ class TestAttackPathsRun:
attack_paths_scan, StateChoices.COMPLETED, ingestion_result
)
mock_set_provider_graph_data_ready.assert_called_once_with(
- attack_paths_scan, False
+ attack_paths_scan, False, "neo4j"
)
mock_set_graph_data_ready.assert_called_once_with(attack_paths_scan, True)
+ # is_migrated is flipped to True only after the sync succeeds, so reads
+ # don't switch to the new catalog/sink before the graph is live.
+ mock_set_scan_migrated.assert_called_once_with(attack_paths_scan, True, "neo4j")
+ def test_run_preflight_failure_does_not_start_scan(
+ self,
+ mock_graph_database_preflight,
+ tenants_fixture,
+ aws_provider,
+ scans_fixture,
+ ):
+ tenant = tenants_fixture[0]
+ provider = aws_provider
+ scan = scans_fixture[0]
+
+ attack_paths_scan = AttackPathsScan.objects.create(
+ tenant_id=tenant.id,
+ provider=provider,
+ scan=scan,
+ state=StateChoices.SCHEDULED,
+ )
+ mock_graph_database_preflight.side_effect = RuntimeError("graph unavailable")
+
+ with (
+ patch(
+ "tasks.jobs.attack_paths.scan.rls_transaction",
+ new=lambda *args, **kwargs: nullcontext(),
+ ),
+ patch(
+ "tasks.jobs.attack_paths.scan.initialize_prowler_provider",
+ return_value=MagicMock(_enabled_regions=["us-east-1"]),
+ ),
+ patch(
+ "tasks.jobs.attack_paths.scan.graph_database.get_ingest_uri",
+ return_value="bolt://neo4j",
+ ),
+ patch(
+ "tasks.jobs.attack_paths.scan.db_utils.retrieve_attack_paths_scan",
+ return_value=attack_paths_scan,
+ ),
+ patch(
+ "tasks.jobs.attack_paths.scan.get_cartography_ingestion_function",
+ return_value=MagicMock(return_value={}),
+ ),
+ patch(
+ "tasks.jobs.attack_paths.scan.db_utils.starting_attack_paths_scan"
+ ) as mock_starting,
+ patch(
+ "tasks.jobs.attack_paths.scan.graph_database.create_database"
+ ) as mock_create_db,
+ ):
+ with pytest.raises(RuntimeError, match="graph unavailable"):
+ attack_paths_run(str(tenant.id), str(scan.id), "task-123")
+
+ mock_graph_database_preflight.assert_called_once_with()
+ mock_starting.assert_not_called()
+ mock_create_db.assert_not_called()
+
+ @pytest.mark.parametrize(
+ ("ingestion_error", "temporary_database_missing"),
+ [
+ (RuntimeError("ingestion boom"), False),
+ (
+ GraphDatabaseQueryException(
+ message="Graph not found: db-scan-id",
+ code="Neo.ClientError.Database.DatabaseNotFound",
+ ),
+ True,
+ ),
+ (
+ GraphDatabaseQueryException(
+ message="Graph not found: db-tenant-id",
+ code="Neo.ClientError.Database.DatabaseNotFound",
+ ),
+ False,
+ ),
+ ],
+ ids=[
+ "regular-error",
+ "temporary-database-missing",
+ "sink-database-missing",
+ ],
+ )
+ @patch("tasks.jobs.attack_paths.scan.logger")
@patch(
"tasks.jobs.attack_paths.scan.utils.stringify_exception",
return_value="Cartography failed: ingestion boom",
@@ -194,13 +297,13 @@ class TestAttackPathsRun:
@patch("tasks.jobs.attack_paths.scan.internet.analysis")
@patch("tasks.jobs.attack_paths.scan.indexes.create_findings_indexes")
@patch("tasks.jobs.attack_paths.scan.cartography_analysis.run")
- @patch("tasks.jobs.attack_paths.scan.cartography_create_indexes.run")
+ @patch("tasks.jobs.attack_paths.indexes.cartography_create_indexes.run")
@patch("tasks.jobs.attack_paths.scan.graph_database.create_database")
@patch(
"tasks.jobs.attack_paths.scan.graph_database.get_database_name",
return_value="db-scan-id",
)
- @patch("tasks.jobs.attack_paths.scan.graph_database.get_uri")
+ @patch("tasks.jobs.attack_paths.scan.graph_database.get_ingest_uri")
@patch(
"tasks.jobs.attack_paths.scan.initialize_prowler_provider",
return_value=MagicMock(_enabled_regions=["us-east-1"]),
@@ -212,7 +315,7 @@ class TestAttackPathsRun:
def test_run_failure_marks_scan_failed(
self,
mock_init_provider,
- mock_get_uri,
+ mock_get_ingest_uri,
mock_get_db_name,
mock_create_db,
mock_cartography_indexes,
@@ -228,17 +331,16 @@ class TestAttackPathsRun:
mock_drop_db,
mock_event_loop,
mock_stringify,
+ mock_logger,
+ ingestion_error,
+ temporary_database_missing,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -251,7 +353,11 @@ class TestAttackPathsRun:
session_ctx = MagicMock()
session_ctx.__enter__.return_value = mock_session
session_ctx.__exit__.return_value = False
- ingestion_fn = MagicMock(side_effect=RuntimeError("ingestion boom"))
+ ingestion_fn = MagicMock(side_effect=ingestion_error)
+ if temporary_database_missing:
+ mock_finish.side_effect = DatabaseError(
+ "Save with update_fields did not affect any rows"
+ )
with (
patch(
@@ -267,13 +373,28 @@ class TestAttackPathsRun:
return_value=ingestion_fn,
),
):
- with pytest.raises(RuntimeError, match="ingestion boom"):
+ with pytest.raises(type(ingestion_error)):
attack_paths_run(str(tenant.id), str(scan.id), "task-456")
failure_args = mock_finish.call_args[0]
assert failure_args[0] is attack_paths_scan
assert failure_args[1] == StateChoices.FAILED
assert failure_args[2] == {"global_error": "Cartography failed: ingestion boom"}
+ mock_drop_db.assert_called_once_with("db-scan-id")
+ if temporary_database_missing:
+ mock_logger.warning.assert_any_call("Cartography failed: ingestion boom")
+ mock_logger.exception.assert_not_called()
+ mock_logger.log.assert_called_once_with(
+ logging.WARNING,
+ f"Could not mark Attack Paths scan {attack_paths_scan.id} as `FAILED` "
+ "(row may have been deleted): Save with update_fields did not affect "
+ "any rows",
+ exc_info=False,
+ )
+ else:
+ mock_logger.exception.assert_called_once_with(
+ "Cartography failed: ingestion boom"
+ )
@patch(
"tasks.jobs.attack_paths.scan.utils.stringify_exception",
@@ -293,13 +414,13 @@ class TestAttackPathsRun:
@patch("tasks.jobs.attack_paths.scan.internet.analysis")
@patch("tasks.jobs.attack_paths.scan.indexes.create_findings_indexes")
@patch("tasks.jobs.attack_paths.scan.cartography_analysis.run")
- @patch("tasks.jobs.attack_paths.scan.cartography_create_indexes.run")
+ @patch("tasks.jobs.attack_paths.indexes.cartography_create_indexes.run")
@patch("tasks.jobs.attack_paths.scan.graph_database.create_database")
@patch(
"tasks.jobs.attack_paths.scan.graph_database.get_database_name",
return_value="db-scan-id",
)
- @patch("tasks.jobs.attack_paths.scan.graph_database.get_uri")
+ @patch("tasks.jobs.attack_paths.scan.graph_database.get_ingest_uri")
@patch(
"tasks.jobs.attack_paths.scan.initialize_prowler_provider",
return_value=MagicMock(_enabled_regions=["us-east-1"]),
@@ -311,7 +432,7 @@ class TestAttackPathsRun:
def test_failure_before_gate_does_not_flip_graph_data_ready_true(
self,
mock_init_provider,
- mock_get_uri,
+ mock_get_ingest_uri,
mock_get_db_name,
mock_create_db,
mock_cartography_indexes,
@@ -328,18 +449,14 @@ class TestAttackPathsRun:
mock_event_loop,
mock_stringify,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
):
"""Failure during ingestion (before set_provider_graph_data_ready(False))
must NOT flip graph_data_ready to True for providers that never had data."""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -396,13 +513,13 @@ class TestAttackPathsRun:
@patch("tasks.jobs.attack_paths.scan.internet.analysis")
@patch("tasks.jobs.attack_paths.scan.indexes.create_findings_indexes")
@patch("tasks.jobs.attack_paths.scan.cartography_analysis.run")
- @patch("tasks.jobs.attack_paths.scan.cartography_create_indexes.run")
+ @patch("tasks.jobs.attack_paths.indexes.cartography_create_indexes.run")
@patch("tasks.jobs.attack_paths.scan.graph_database.create_database")
@patch(
"tasks.jobs.attack_paths.scan.graph_database.get_database_name",
return_value="db-scan-id",
)
- @patch("tasks.jobs.attack_paths.scan.graph_database.get_uri")
+ @patch("tasks.jobs.attack_paths.scan.graph_database.get_ingest_uri")
@patch(
"tasks.jobs.attack_paths.scan.initialize_prowler_provider",
return_value=MagicMock(_enabled_regions=["us-east-1"]),
@@ -414,7 +531,7 @@ class TestAttackPathsRun:
def test_run_failure_marks_scan_failed_even_when_drop_database_fails(
self,
mock_init_provider,
- mock_get_uri,
+ mock_get_ingest_uri,
mock_get_db_name,
mock_create_db,
mock_cartography_indexes,
@@ -431,16 +548,12 @@ class TestAttackPathsRun:
mock_event_loop,
mock_stringify,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -493,7 +606,7 @@ class TestAttackPathsRun:
@patch("tasks.jobs.attack_paths.scan.db_utils.starting_attack_paths_scan")
@patch(
"tasks.jobs.attack_paths.scan.sync.sync_graph",
- return_value={"nodes": 0, "relationships": 0},
+ return_value=SYNC_RESULT_EMPTY,
)
@patch(
"tasks.jobs.attack_paths.scan.graph_database.drop_subgraph",
@@ -505,11 +618,11 @@ class TestAttackPathsRun:
@patch("tasks.jobs.attack_paths.scan.indexes.create_findings_indexes")
@patch("tasks.jobs.attack_paths.scan.cartography_ontology.run")
@patch("tasks.jobs.attack_paths.scan.cartography_analysis.run")
- @patch("tasks.jobs.attack_paths.scan.cartography_create_indexes.run")
+ @patch("tasks.jobs.attack_paths.indexes.cartography_create_indexes.run")
@patch("tasks.jobs.attack_paths.scan.graph_database.clear_cache")
@patch("tasks.jobs.attack_paths.scan.graph_database.create_database")
@patch(
- "tasks.jobs.attack_paths.scan.graph_database.get_uri",
+ "tasks.jobs.attack_paths.scan.graph_database.get_ingest_uri",
return_value="bolt://neo4j",
)
@patch(
@@ -523,7 +636,7 @@ class TestAttackPathsRun:
def test_failure_after_gate_before_drop_restores_graph_data_ready(
self,
mock_init_provider,
- mock_get_uri,
+ mock_get_ingest_uri,
mock_create_db,
mock_clear_cache,
mock_cartography_indexes,
@@ -544,16 +657,12 @@ class TestAttackPathsRun:
mock_event_loop,
mock_stringify,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -589,8 +698,8 @@ class TestAttackPathsRun:
attack_paths_run(str(tenant.id), str(scan.id), "task-456")
assert mock_set_provider_graph_data_ready.call_args_list == [
- call(attack_paths_scan, False),
- call(attack_paths_scan, True),
+ call(attack_paths_scan, False, "neo4j"),
+ call(attack_paths_scan, True, "neo4j"),
]
@patch(
@@ -618,11 +727,11 @@ class TestAttackPathsRun:
@patch("tasks.jobs.attack_paths.scan.indexes.create_findings_indexes")
@patch("tasks.jobs.attack_paths.scan.cartography_ontology.run")
@patch("tasks.jobs.attack_paths.scan.cartography_analysis.run")
- @patch("tasks.jobs.attack_paths.scan.cartography_create_indexes.run")
+ @patch("tasks.jobs.attack_paths.indexes.cartography_create_indexes.run")
@patch("tasks.jobs.attack_paths.scan.graph_database.clear_cache")
@patch("tasks.jobs.attack_paths.scan.graph_database.create_database")
@patch(
- "tasks.jobs.attack_paths.scan.graph_database.get_uri",
+ "tasks.jobs.attack_paths.scan.graph_database.get_ingest_uri",
return_value="bolt://neo4j",
)
@patch(
@@ -636,7 +745,7 @@ class TestAttackPathsRun:
def test_failure_after_drop_before_sync_leaves_graph_data_ready_false(
self,
mock_init_provider,
- mock_get_uri,
+ mock_get_ingest_uri,
mock_create_db,
mock_clear_cache,
mock_cartography_indexes,
@@ -657,16 +766,12 @@ class TestAttackPathsRun:
mock_event_loop,
mock_stringify,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -703,7 +808,7 @@ class TestAttackPathsRun:
# Only called with False (gate), never with True (no recovery for partial data)
mock_set_provider_graph_data_ready.assert_called_once_with(
- attack_paths_scan, False
+ attack_paths_scan, False, "neo4j"
)
@patch(
@@ -716,6 +821,7 @@ class TestAttackPathsRun:
)
@patch("tasks.jobs.attack_paths.scan.graph_database.drop_database")
@patch("tasks.jobs.attack_paths.scan.db_utils.finish_attack_paths_scan")
+ @patch("tasks.jobs.attack_paths.scan.db_utils.set_scan_migrated")
@patch(
"tasks.jobs.attack_paths.scan.db_utils.set_graph_data_ready",
side_effect=[RuntimeError("flag failed"), None],
@@ -725,7 +831,7 @@ class TestAttackPathsRun:
@patch("tasks.jobs.attack_paths.scan.db_utils.starting_attack_paths_scan")
@patch(
"tasks.jobs.attack_paths.scan.sync.sync_graph",
- return_value={"nodes": 0, "relationships": 0},
+ return_value=SYNC_RESULT_EMPTY,
)
@patch("tasks.jobs.attack_paths.scan.graph_database.drop_subgraph")
@patch("tasks.jobs.attack_paths.scan.indexes.create_sync_indexes")
@@ -734,11 +840,11 @@ class TestAttackPathsRun:
@patch("tasks.jobs.attack_paths.scan.indexes.create_findings_indexes")
@patch("tasks.jobs.attack_paths.scan.cartography_ontology.run")
@patch("tasks.jobs.attack_paths.scan.cartography_analysis.run")
- @patch("tasks.jobs.attack_paths.scan.cartography_create_indexes.run")
+ @patch("tasks.jobs.attack_paths.indexes.cartography_create_indexes.run")
@patch("tasks.jobs.attack_paths.scan.graph_database.clear_cache")
@patch("tasks.jobs.attack_paths.scan.graph_database.create_database")
@patch(
- "tasks.jobs.attack_paths.scan.graph_database.get_uri",
+ "tasks.jobs.attack_paths.scan.graph_database.get_ingest_uri",
return_value="bolt://neo4j",
)
@patch(
@@ -752,7 +858,7 @@ class TestAttackPathsRun:
def test_failure_after_sync_restores_graph_data_ready(
self,
mock_init_provider,
- mock_get_uri,
+ mock_get_ingest_uri,
mock_create_db,
mock_clear_cache,
mock_cartography_indexes,
@@ -768,21 +874,18 @@ class TestAttackPathsRun:
mock_update_progress,
mock_set_provider_graph_data_ready,
mock_set_graph_data_ready,
+ mock_set_scan_migrated,
mock_finish,
mock_drop_db,
mock_event_loop,
mock_stringify,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -824,8 +927,11 @@ class TestAttackPathsRun:
]
# set_provider_graph_data_ready only called once with False (the gate)
mock_set_provider_graph_data_ready.assert_called_once_with(
- attack_paths_scan, False
+ attack_paths_scan, False, "neo4j"
)
+ # is_migrated is flipped once after the sync and is not touched again by
+ # the failure-recovery branch
+ mock_set_scan_migrated.assert_called_once_with(attack_paths_scan, True, "neo4j")
@patch(
"tasks.jobs.attack_paths.scan.utils.stringify_exception",
@@ -843,7 +949,7 @@ class TestAttackPathsRun:
@patch("tasks.jobs.attack_paths.scan.db_utils.starting_attack_paths_scan")
@patch(
"tasks.jobs.attack_paths.scan.sync.sync_graph",
- return_value={"nodes": 0, "relationships": 0},
+ return_value=SYNC_RESULT_EMPTY,
)
@patch(
"tasks.jobs.attack_paths.scan.graph_database.drop_subgraph",
@@ -855,11 +961,11 @@ class TestAttackPathsRun:
@patch("tasks.jobs.attack_paths.scan.indexes.create_findings_indexes")
@patch("tasks.jobs.attack_paths.scan.cartography_ontology.run")
@patch("tasks.jobs.attack_paths.scan.cartography_analysis.run")
- @patch("tasks.jobs.attack_paths.scan.cartography_create_indexes.run")
+ @patch("tasks.jobs.attack_paths.indexes.cartography_create_indexes.run")
@patch("tasks.jobs.attack_paths.scan.graph_database.clear_cache")
@patch("tasks.jobs.attack_paths.scan.graph_database.create_database")
@patch(
- "tasks.jobs.attack_paths.scan.graph_database.get_uri",
+ "tasks.jobs.attack_paths.scan.graph_database.get_ingest_uri",
return_value="bolt://neo4j",
)
@patch(
@@ -873,7 +979,7 @@ class TestAttackPathsRun:
def test_recovery_failure_does_not_suppress_original_exception(
self,
mock_init_provider,
- mock_get_uri,
+ mock_get_ingest_uri,
mock_create_db,
mock_clear_cache,
mock_cartography_indexes,
@@ -894,16 +1000,12 @@ class TestAttackPathsRun:
mock_event_loop,
mock_stringify,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -991,17 +1093,13 @@ class TestAttackPathsRun:
@pytest.mark.django_db
class TestFailAttackPathsScan:
def test_marks_executing_scan_as_failed(
- self, tenants_fixture, providers_fixture, scans_fixture
+ self, tenants_fixture, aws_provider, scans_fixture
):
from tasks.jobs.attack_paths.db_utils import fail_attack_paths_scan
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -1033,17 +1131,13 @@ class TestFailAttackPathsScan:
}
def test_drops_temp_database_even_when_drop_fails(
- self, tenants_fixture, providers_fixture, scans_fixture
+ self, tenants_fixture, aws_provider, scans_fixture
):
from tasks.jobs.attack_paths.db_utils import fail_attack_paths_scan
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -1069,17 +1163,13 @@ class TestFailAttackPathsScan:
assert attack_paths_scan.state == StateChoices.FAILED
def test_skips_already_failed_scan(
- self, tenants_fixture, providers_fixture, scans_fixture
+ self, tenants_fixture, aws_provider, scans_fixture
):
from tasks.jobs.attack_paths.db_utils import fail_attack_paths_scan
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -1116,17 +1206,13 @@ class TestFailAttackPathsScan:
fail_attack_paths_scan(str(tenant.id), "nonexistent", "setup exploded")
def test_fail_recovers_graph_data_ready_when_data_exists(
- self, tenants_fixture, providers_fixture, scans_fixture
+ self, tenants_fixture, aws_provider, scans_fixture, sink_backend_stub
):
from tasks.jobs.attack_paths.db_utils import fail_attack_paths_scan
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -1135,16 +1221,18 @@ class TestFailAttackPathsScan:
state=StateChoices.EXECUTING,
)
+ # `recover_graph_data_ready` routes `has_provider_data` through
+ # `sink_module.get_backend_for_scan(scan)`. With `is_migrated=False`
+ # and the default `ATTACK_PATHS_SINK_DATABASE=neo4j`, the factory
+ # returns the active backend, which `sink_backend_stub` replaces.
+ sink_backend_stub.has_provider_data.return_value = True
+
with (
patch(
"tasks.jobs.attack_paths.db_utils.retrieve_attack_paths_scan",
return_value=attack_paths_scan,
),
patch("tasks.jobs.attack_paths.db_utils.graph_database.drop_database"),
- patch(
- "tasks.jobs.attack_paths.db_utils.graph_database.has_provider_data",
- return_value=True,
- ),
patch(
"tasks.jobs.attack_paths.db_utils.set_provider_graph_data_ready"
) as mock_set_ready,
@@ -1154,17 +1242,13 @@ class TestFailAttackPathsScan:
mock_set_ready.assert_called_once_with(attack_paths_scan, True)
def test_fail_leaves_graph_data_ready_false_when_no_data(
- self, tenants_fixture, providers_fixture, scans_fixture
+ self, tenants_fixture, aws_provider, scans_fixture, sink_backend_stub
):
from tasks.jobs.attack_paths.db_utils import fail_attack_paths_scan
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -1173,16 +1257,14 @@ class TestFailAttackPathsScan:
state=StateChoices.EXECUTING,
)
+ sink_backend_stub.has_provider_data.return_value = False
+
with (
patch(
"tasks.jobs.attack_paths.db_utils.retrieve_attack_paths_scan",
return_value=attack_paths_scan,
),
patch("tasks.jobs.attack_paths.db_utils.graph_database.drop_database"),
- patch(
- "tasks.jobs.attack_paths.db_utils.graph_database.has_provider_data",
- return_value=False,
- ),
patch(
"tasks.jobs.attack_paths.db_utils.set_provider_graph_data_ready"
) as mock_set_ready,
@@ -1192,17 +1274,13 @@ class TestFailAttackPathsScan:
mock_set_ready.assert_not_called()
def test_recover_graph_data_ready_never_raises(
- self, tenants_fixture, providers_fixture, scans_fixture
+ self, tenants_fixture, aws_provider, scans_fixture
):
from tasks.jobs.attack_paths.db_utils import recover_graph_data_ready
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -1238,6 +1316,33 @@ class TestAttackPathsScanRLSTaskOnFailure:
mock_fail.assert_called_once_with("t-1", "s-1", "boom")
+ def test_on_failure_logs_provider_deletion_as_warning(self):
+ from tasks.tasks import AttackPathsScanRLSTask
+
+ task = AttackPathsScanRLSTask()
+ error = ProviderDeletedException("provider deleted")
+
+ with (
+ patch("tasks.tasks.logger") as mock_logger,
+ patch(
+ "tasks.tasks.attack_paths_db_utils.fail_attack_paths_scan"
+ ) as mock_fail,
+ ):
+ task.on_failure(
+ exc=error,
+ task_id="task-abc",
+ args=(),
+ kwargs={"tenant_id": "t-1", "scan_id": "s-1"},
+ _einfo=None,
+ )
+
+ mock_logger.warning.assert_called_once_with(
+ "Attack paths scan task task-abc stopped because its provider or tenant "
+ "was deleted: provider deleted"
+ )
+ mock_logger.error.assert_not_called()
+ mock_fail.assert_called_once_with("t-1", "s-1", "provider deleted")
+
def test_on_failure_skips_when_missing_kwargs(self):
from tasks.tasks import AttackPathsScanRLSTask
@@ -1271,10 +1376,22 @@ class TestAttackPathsFindingsHelpers:
[call(mock_session, stmt) for stmt in FINDINGS_INDEX_STATEMENTS]
)
- def test_load_findings_batches_requests(self, providers_fixture):
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ def test_create_findings_indexes_runs_even_when_sink_is_neptune(self, settings):
+ # The index helpers run against the temp ingest DB, which is always
+ # Neo4j regardless of the configured sink. A Neptune sink must not
+ # suppress index creation on that DB (regression for the dropped
+ # in-helper sink gate).
+ settings.ATTACK_PATHS_SINK_DATABASE = "neptune"
+ mock_session = MagicMock()
+ with patch("tasks.jobs.attack_paths.indexes.run_write_query") as mock_run_write:
+ indexes_module.create_findings_indexes(mock_session)
+
+ from tasks.jobs.attack_paths.indexes import FINDINGS_INDEX_STATEMENTS
+
+ assert mock_run_write.call_count == len(FINDINGS_INDEX_STATEMENTS)
+
+ def test_load_findings_batches_requests(self, aws_provider):
+ provider = aws_provider
# Create a generator that yields two batches of dicts (pre-converted)
def findings_generator():
@@ -1322,12 +1439,10 @@ class TestAttackPathsFindingsHelpers:
def test_stream_findings_with_resources_returns_latest_scan_data(
self,
tenants_fixture,
- providers_fixture,
+ aws_provider,
):
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
resource = Resource.objects.create(
tenant_id=tenant.id,
@@ -1426,13 +1541,11 @@ class TestAttackPathsFindingsHelpers:
def test_enrich_batch_with_resources_single_resource(
self,
tenants_fixture,
- providers_fixture,
+ aws_provider,
):
"""One finding + one resource = one output dict"""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
resource = Resource.objects.create(
tenant_id=tenant.id,
@@ -1510,13 +1623,11 @@ class TestAttackPathsFindingsHelpers:
def test_enrich_batch_with_resources_multiple_resources(
self,
tenants_fixture,
- providers_fixture,
+ aws_provider,
):
"""One finding + three resources = three output dicts"""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
resources = []
for i in range(3):
@@ -1602,13 +1713,11 @@ class TestAttackPathsFindingsHelpers:
def test_enrich_batch_with_resources_no_resources_skips(
self,
tenants_fixture,
- providers_fixture,
+ aws_provider,
):
"""Finding without resources should be skipped"""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = Scan.objects.create(
name="Test Scan",
@@ -1667,11 +1776,9 @@ class TestAttackPathsFindingsHelpers:
assert len(result) == 0
mock_logger.warning.assert_not_called()
- def test_generator_is_lazy(self, providers_fixture):
+ def test_generator_is_lazy(self, aws_provider):
"""Generator should not execute queries until iterated"""
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan_id = "some-scan-id"
with patch("tasks.jobs.attack_paths.findings.rls_transaction") as mock_rls:
@@ -1681,11 +1788,9 @@ class TestAttackPathsFindingsHelpers:
# Nothing should be called yet
mock_rls.assert_not_called()
- def test_load_findings_empty_generator(self, providers_fixture):
+ def test_load_findings_empty_generator(self, aws_provider):
"""Empty generator should not call neo4j"""
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
mock_session = MagicMock()
config = SimpleNamespace(update_tag=12345)
@@ -1801,8 +1906,63 @@ def _make_session_ctx(session, call_order=None, name=None):
return ctx
+class TestBuildChildId:
+ def test_large_value_is_hashed_and_preserved_as_child_data(self):
+ value = "x" * 22_796
+ spec = sync_module.NormalizedList(
+ "SomeLabel",
+ "values",
+ "SomeLabelValuesItem",
+ "HAS_VALUES",
+ )
+ record = {
+ "element_id": "elem-1",
+ "labels": ["SomeLabel"],
+ "props": {"values": [value]},
+ }
+
+ _, parent, children, relationships = sync_module._node_to_sync_dict(
+ record,
+ "prov-1",
+ sync_module._build_catalog_index([spec]),
+ )
+
+ child = children[0]["row"]
+ child_id = child["provider_element_id"]
+ prefix = "prov-1::SomeLabelValuesItem::"
+ assert parent["provider_element_id"] == "prov-1:elem-1"
+ assert child["props"]["value"] == value
+ assert len(child_id) == len(prefix) + 64
+ assert value not in child_id
+ assert relationships[0]["row"]["end_element_id"] == child_id
+
+ @pytest.mark.parametrize(
+ ("provider_id", "child_label", "value_key"),
+ [
+ ("prov-2", "ChildLabel", "value"),
+ ("prov-1", "OtherChildLabel", "value"),
+ ("prov-1", "ChildLabel", "other-value"),
+ ],
+ )
+ def test_each_identity_component_changes_id(
+ self, provider_id, child_label, value_key
+ ):
+ child_id = sync_module._build_child_id("prov-1", "ChildLabel", "value")
+
+ assert sync_module._build_child_id("prov-1", "ChildLabel", "value") == child_id
+ assert (
+ sync_module._build_child_id(provider_id, child_label, value_key) != child_id
+ )
+
+
class TestSyncNodes:
- def test_sync_nodes_adds_private_label(self):
+ def test_iter_sink_batches_rejects_zero_batch_size(self):
+ with pytest.raises(
+ ValueError, match="Sink batch size must be greater than zero"
+ ):
+ list(sync_module._iter_sink_batches([], batch_size=0))
+
+ def test_sync_nodes_passes_isolation_labels_to_sink(self):
row = {
"internal_id": 1,
"element_id": "elem-1",
@@ -1812,29 +1972,32 @@ class TestSyncNodes:
mock_source_1 = MagicMock()
mock_source_1.run.return_value = [row]
- mock_target = MagicMock()
mock_source_2 = MagicMock()
mock_source_2.run.return_value = []
+ sink = MagicMock(sync_batch_size=1000)
with patch(
"tasks.jobs.attack_paths.sync.graph_database.get_session",
side_effect=[
_make_session_ctx(mock_source_1),
- _make_session_ctx(mock_target),
_make_session_ctx(mock_source_2),
],
):
- total = sync_module.sync_nodes(
- "source-db", "target-db", "tenant-1", "prov-1"
+ result = sync_module.sync_nodes(
+ "source-db", "target-db", "tenant-1", "prov-1", sink, []
)
- assert total == 1
- query = mock_target.run.call_args.args[0]
- assert "_ProviderResource" in query
- assert "_Tenant_tenant1" in query
- assert "_Provider_prov1" in query
+ assert result["parents"] == 1
+ sink.write_nodes.assert_called_once()
+ target_db, labels, batch = sink.write_nodes.call_args.args
+ assert target_db == "target-db"
+ assert "_ProviderResource" in labels
+ assert "_Tenant_tenant1" in labels
+ assert "_Provider_prov1" in labels
+ assert batch[0]["provider_element_id"] == "prov-1:elem-1"
+ assert batch[0]["props"] == {"key": "value"}
- def test_sync_nodes_source_closes_before_target_opens(self):
+ def test_sync_nodes_writes_after_source_session_closes(self):
row = {
"internal_id": 1,
"element_id": "elem-1",
@@ -1846,21 +2009,23 @@ class TestSyncNodes:
src_1 = MagicMock()
src_1.run.return_value = [row]
- tgt = MagicMock()
src_2 = MagicMock()
src_2.run.return_value = []
+ sink = MagicMock(sync_batch_size=1000)
+ sink.write_nodes.side_effect = lambda *_a, **_kw: call_order.append(
+ "sink:write"
+ )
with patch(
"tasks.jobs.attack_paths.sync.graph_database.get_session",
side_effect=[
_make_session_ctx(src_1, call_order, "source1"),
- _make_session_ctx(tgt, call_order, "target"),
_make_session_ctx(src_2, call_order, "source2"),
],
):
- sync_module.sync_nodes("src-db", "tgt-db", "t-1", "p-1")
+ sync_module.sync_nodes("src-db", "tgt-db", "t-1", "p-1", sink, [])
- assert call_order.index("source1:exit") < call_order.index("target:enter")
+ assert call_order.index("source1:exit") < call_order.index("sink:write")
def test_sync_nodes_pagination_with_batch_size_1(self):
row_a = {
@@ -1882,44 +2047,83 @@ class TestSyncNodes:
src_2.run.return_value = [row_b]
src_3 = MagicMock()
src_3.run.return_value = []
- tgt_1 = MagicMock()
- tgt_2 = MagicMock()
+ sink = MagicMock(sync_batch_size=1)
- with (
- patch(
- "tasks.jobs.attack_paths.sync.graph_database.get_session",
- side_effect=[
- _make_session_ctx(src_1),
- _make_session_ctx(tgt_1),
- _make_session_ctx(src_2),
- _make_session_ctx(tgt_2),
- _make_session_ctx(src_3),
- ],
- ),
- patch("tasks.jobs.attack_paths.sync.SYNC_BATCH_SIZE", 1),
+ with patch(
+ "tasks.jobs.attack_paths.sync.graph_database.get_session",
+ side_effect=[
+ _make_session_ctx(src_1),
+ _make_session_ctx(src_2),
+ _make_session_ctx(src_3),
+ ],
):
- total = sync_module.sync_nodes("src", "tgt", "t-1", "p-1")
+ result = sync_module.sync_nodes("src", "tgt", "t-1", "p-1", sink, [])
- assert total == 2
+ assert result["parents"] == 2
+ assert sink.write_nodes.call_count == 2
assert src_1.run.call_args.args[1]["last_id"] == -1
assert src_2.run.call_args.args[1]["last_id"] == 1
+ def test_sync_nodes_chunks_expanded_list_rows_before_sink_write(self):
+ row = {
+ "internal_id": 1,
+ "element_id": "elem-1",
+ "labels": ["SomeLabel"],
+ "props": {"values": ["a", "b", "c", "d", "e"]},
+ }
+ normalized_lists = [
+ sync_module.NormalizedList(
+ "SomeLabel",
+ "values",
+ "SomeLabelValuesItem",
+ "HAS_VALUES",
+ )
+ ]
+
+ src_1 = MagicMock()
+ src_1.run.return_value = [row]
+ src_2 = MagicMock()
+ src_2.run.return_value = []
+ sink = MagicMock(sync_batch_size=2)
+
+ with patch(
+ "tasks.jobs.attack_paths.sync.graph_database.get_session",
+ side_effect=[
+ _make_session_ctx(src_1),
+ _make_session_ctx(src_2),
+ ],
+ ):
+ result = sync_module.sync_nodes(
+ "src", "tgt", "t-1", "p-1", sink, normalized_lists
+ )
+
+ assert result == {"parents": 1, "children": 5, "parent_child_rels": 5}
+ assert [
+ len(call_args.args[2]) for call_args in sink.write_nodes.call_args_list[1:]
+ ] == [2, 2, 1]
+ assert [
+ len(call_args.args[3])
+ for call_args in sink.write_relationships.call_args_list
+ ] == [2, 2, 1]
+
def test_sync_nodes_empty_source_returns_zero(self):
src = MagicMock()
src.run.return_value = []
+ sink = MagicMock(sync_batch_size=1000)
with patch(
"tasks.jobs.attack_paths.sync.graph_database.get_session",
side_effect=[_make_session_ctx(src)],
) as mock_get_session:
- total = sync_module.sync_nodes("src", "tgt", "t-1", "p-1")
+ result = sync_module.sync_nodes("src", "tgt", "t-1", "p-1", sink, [])
- assert total == 0
+ assert result["parents"] == 0
assert mock_get_session.call_count == 1
+ sink.write_nodes.assert_not_called()
class TestSyncRelationships:
- def test_sync_relationships_source_closes_before_target_opens(self):
+ def test_sync_relationships_writes_after_source_session_closes(self):
row = {
"internal_id": 1,
"rel_type": "HAS",
@@ -1932,21 +2136,23 @@ class TestSyncRelationships:
src_1 = MagicMock()
src_1.run.return_value = [row]
- tgt = MagicMock()
src_2 = MagicMock()
src_2.run.return_value = []
+ sink = MagicMock(sync_batch_size=1000)
+ sink.write_relationships.side_effect = lambda *_a, **_kw: call_order.append(
+ "sink:write"
+ )
with patch(
"tasks.jobs.attack_paths.sync.graph_database.get_session",
side_effect=[
_make_session_ctx(src_1, call_order, "source1"),
- _make_session_ctx(tgt, call_order, "target"),
_make_session_ctx(src_2, call_order, "source2"),
],
):
- sync_module.sync_relationships("src", "tgt", "p-1")
+ sync_module.sync_relationships("src", "tgt", "p-1", sink)
- assert call_order.index("source1:exit") < call_order.index("target:enter")
+ assert call_order.index("source1:exit") < call_order.index("sink:write")
def test_sync_relationships_pagination_with_batch_size_1(self):
row_a = {
@@ -1970,40 +2176,70 @@ class TestSyncRelationships:
src_2.run.return_value = [row_b]
src_3 = MagicMock()
src_3.run.return_value = []
- tgt_1 = MagicMock()
- tgt_2 = MagicMock()
+ sink = MagicMock(sync_batch_size=1)
- with (
- patch(
- "tasks.jobs.attack_paths.sync.graph_database.get_session",
- side_effect=[
- _make_session_ctx(src_1),
- _make_session_ctx(tgt_1),
- _make_session_ctx(src_2),
- _make_session_ctx(tgt_2),
- _make_session_ctx(src_3),
- ],
- ),
- patch("tasks.jobs.attack_paths.sync.SYNC_BATCH_SIZE", 1),
+ with patch(
+ "tasks.jobs.attack_paths.sync.graph_database.get_session",
+ side_effect=[
+ _make_session_ctx(src_1),
+ _make_session_ctx(src_2),
+ _make_session_ctx(src_3),
+ ],
):
- total = sync_module.sync_relationships("src", "tgt", "p-1")
+ total = sync_module.sync_relationships("src", "tgt", "p-1", sink)
assert total == 2
+ assert sink.write_relationships.call_count == 2
assert src_1.run.call_args.args[1]["last_id"] == -1
assert src_2.run.call_args.args[1]["last_id"] == 1
+ def test_sync_relationships_chunks_grouped_rows_before_sink_write(self):
+ rows = [
+ {
+ "internal_id": idx,
+ "rel_type": "HAS",
+ "start_element_id": f"s-{idx}",
+ "end_element_id": f"e-{idx}",
+ "props": {},
+ }
+ for idx in range(1, 6)
+ ]
+
+ src_1 = MagicMock()
+ src_1.run.return_value = rows
+ src_2 = MagicMock()
+ src_2.run.return_value = []
+ sink = MagicMock(sync_batch_size=2)
+
+ with patch(
+ "tasks.jobs.attack_paths.sync.graph_database.get_session",
+ side_effect=[
+ _make_session_ctx(src_1),
+ _make_session_ctx(src_2),
+ ],
+ ):
+ total = sync_module.sync_relationships("src", "tgt", "p-1", sink)
+
+ assert total == 5
+ assert [
+ len(call_args.args[3])
+ for call_args in sink.write_relationships.call_args_list
+ ] == [2, 2, 1]
+
def test_sync_relationships_empty_source_returns_zero(self):
src = MagicMock()
src.run.return_value = []
+ sink = MagicMock(sync_batch_size=1000)
with patch(
"tasks.jobs.attack_paths.sync.graph_database.get_session",
side_effect=[_make_session_ctx(src)],
) as mock_get_session:
- total = sync_module.sync_relationships("src", "tgt", "p-1")
+ total = sync_module.sync_relationships("src", "tgt", "p-1", sink)
assert total == 0
assert mock_get_session.call_count == 1
+ sink.write_relationships.assert_not_called()
class TestInternetAnalysis:
@@ -2052,18 +2288,62 @@ class TestInternetAnalysis:
class TestAttackPathsDbUtilsGraphDataReady:
"""Tests for db_utils functions related to graph_data_ready lifecycle."""
+ def test_database_defaults_allow_legacy_insert_without_cutover_columns(
+ self, tenants_fixture, aws_provider, scans_fixture
+ ):
+ tenant = tenants_fixture[0]
+ provider = aws_provider
+ scan = scans_fixture[0]
+
+ attack_paths_scan_id = uuid4()
+ now = datetime.now(tz=UTC)
+
+ with rls_transaction(str(tenant.id), using=DEFAULT_DB_ALIAS) as cursor:
+ cursor.execute(
+ """
+ INSERT INTO attack_paths_scans (
+ id,
+ inserted_at,
+ updated_at,
+ state,
+ progress,
+ graph_data_ready,
+ started_at,
+ tenant_id,
+ provider_id,
+ scan_id
+ )
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
+ """,
+ [
+ attack_paths_scan_id,
+ now,
+ now,
+ StateChoices.SCHEDULED,
+ 0,
+ False,
+ now,
+ tenant.id,
+ provider.id,
+ scan.id,
+ ],
+ )
+
+ attack_paths_scan = AttackPathsScan.objects.get(id=attack_paths_scan_id)
+
+ assert attack_paths_scan.is_migrated is False
+ assert (
+ attack_paths_scan.sink_backend == AttackPathsScan.SinkBackendChoices.NEO4J
+ )
+
def test_create_attack_paths_scan_first_scan_defaults_to_false(
- self, tenants_fixture, providers_fixture, scans_fixture
+ self, tenants_fixture, aws_provider, scans_fixture
):
from tasks.jobs.attack_paths.db_utils import create_attack_paths_scan
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
with patch(
"tasks.jobs.attack_paths.db_utils.rls_transaction",
@@ -2075,19 +2355,17 @@ class TestAttackPathsDbUtilsGraphDataReady:
assert attack_paths_scan is not None
assert attack_paths_scan.graph_data_ready is False
+ assert attack_paths_scan.is_migrated is False
+ assert attack_paths_scan.sink_backend == "neo4j"
def test_create_attack_paths_scan_inherits_true_from_previous(
- self, tenants_fixture, providers_fixture, scans_fixture
+ self, tenants_fixture, aws_provider, scans_fixture
):
from tasks.jobs.attack_paths.db_utils import create_attack_paths_scan
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -2095,6 +2373,8 @@ class TestAttackPathsDbUtilsGraphDataReady:
scan=scan,
state=StateChoices.COMPLETED,
graph_data_ready=True,
+ is_migrated=True,
+ sink_backend="neptune",
)
new_scan = Scan.objects.create(
@@ -2115,19 +2395,110 @@ class TestAttackPathsDbUtilsGraphDataReady:
assert attack_paths_scan is not None
assert attack_paths_scan.graph_data_ready is True
+ # is_migrated tracks the data being served: inherited from the ready scan
+ assert attack_paths_scan.is_migrated is True
+ assert attack_paths_scan.sink_backend == "neptune"
- def test_create_attack_paths_scan_inherits_false_when_no_previous_ready(
- self, tenants_fixture, providers_fixture, scans_fixture
+ def test_create_attack_paths_scan_prefers_active_sink_ready_scan(
+ self, tenants_fixture, aws_provider, scans_fixture, settings
+ ):
+ from tasks.jobs.attack_paths.db_utils import create_attack_paths_scan
+
+ settings.ATTACK_PATHS_SINK_DATABASE = "neo4j"
+ tenant = tenants_fixture[0]
+ provider = aws_provider
+ scan = scans_fixture[0]
+
+ AttackPathsScan.objects.create(
+ tenant_id=tenant.id,
+ provider=provider,
+ scan=scan,
+ state=StateChoices.COMPLETED,
+ graph_data_ready=True,
+ is_migrated=False,
+ sink_backend="neo4j",
+ )
+ AttackPathsScan.objects.create(
+ tenant_id=tenant.id,
+ provider=provider,
+ scan=scan,
+ state=StateChoices.COMPLETED,
+ graph_data_ready=True,
+ is_migrated=True,
+ sink_backend="neptune",
+ )
+
+ new_scan = Scan.objects.create(
+ name="New Scan",
+ provider=provider,
+ trigger=Scan.TriggerChoices.MANUAL,
+ state=StateChoices.AVAILABLE,
+ tenant_id=tenant.id,
+ )
+
+ with patch(
+ "tasks.jobs.attack_paths.db_utils.rls_transaction",
+ new=lambda *args, **kwargs: nullcontext(),
+ ):
+ attack_paths_scan = create_attack_paths_scan(
+ str(tenant.id), str(new_scan.id), provider.id
+ )
+
+ assert attack_paths_scan is not None
+ assert attack_paths_scan.graph_data_ready is True
+ assert attack_paths_scan.is_migrated is False
+ assert attack_paths_scan.sink_backend == "neo4j"
+
+ def test_create_attack_paths_scan_inherits_is_migrated_false_from_legacy_ready(
+ self, tenants_fixture, aws_provider, scans_fixture
):
from tasks.jobs.attack_paths.db_utils import create_attack_paths_scan
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
+ scan = scans_fixture[0]
+
+ # Previous scan is ready but pre-cutover (legacy Neo4j graph shape)
+ AttackPathsScan.objects.create(
+ tenant_id=tenant.id,
+ provider=provider,
+ scan=scan,
+ state=StateChoices.COMPLETED,
+ graph_data_ready=True,
+ is_migrated=False,
+ sink_backend="neo4j",
+ )
+
+ new_scan = Scan.objects.create(
+ name="New Scan",
+ provider=provider,
+ trigger=Scan.TriggerChoices.MANUAL,
+ state=StateChoices.AVAILABLE,
+ tenant_id=tenant.id,
+ )
+
+ with patch(
+ "tasks.jobs.attack_paths.db_utils.rls_transaction",
+ new=lambda *args, **kwargs: nullcontext(),
+ ):
+ attack_paths_scan = create_attack_paths_scan(
+ str(tenant.id), str(new_scan.id), provider.id
+ )
+
+ assert attack_paths_scan is not None
+ assert attack_paths_scan.graph_data_ready is True
+ # Reads stay on the legacy catalog/backend until this scan's own sync
+ assert attack_paths_scan.is_migrated is False
+ assert attack_paths_scan.sink_backend == "neo4j"
+
+ def test_create_attack_paths_scan_inherits_false_when_no_previous_ready(
+ self, tenants_fixture, aws_provider, scans_fixture
+ ):
+ from tasks.jobs.attack_paths.db_utils import create_attack_paths_scan
+
+ tenant = tenants_fixture[0]
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -2135,6 +2506,7 @@ class TestAttackPathsDbUtilsGraphDataReady:
scan=scan,
state=StateChoices.FAILED,
graph_data_ready=False,
+ sink_backend="neptune",
)
new_scan = Scan.objects.create(
@@ -2155,19 +2527,17 @@ class TestAttackPathsDbUtilsGraphDataReady:
assert attack_paths_scan is not None
assert attack_paths_scan.graph_data_ready is False
+ assert attack_paths_scan.is_migrated is False
+ assert attack_paths_scan.sink_backend == "neo4j"
def test_set_graph_data_ready_updates_field(
- self, tenants_fixture, providers_fixture, scans_fixture
+ self, tenants_fixture, aws_provider, scans_fixture
):
from tasks.jobs.attack_paths.db_utils import set_graph_data_ready
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -2196,17 +2566,13 @@ class TestAttackPathsDbUtilsGraphDataReady:
assert attack_paths_scan.graph_data_ready is True
def test_finish_attack_paths_scan_does_not_modify_graph_data_ready(
- self, tenants_fixture, providers_fixture, scans_fixture
+ self, tenants_fixture, aws_provider, scans_fixture
):
from tasks.jobs.attack_paths.db_utils import finish_attack_paths_scan
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -2227,17 +2593,13 @@ class TestAttackPathsDbUtilsGraphDataReady:
assert attack_paths_scan.graph_data_ready is True
def test_finish_attack_paths_scan_preserves_graph_data_ready_on_failure(
- self, tenants_fixture, providers_fixture, scans_fixture
+ self, tenants_fixture, aws_provider, scans_fixture
):
from tasks.jobs.attack_paths.db_utils import finish_attack_paths_scan
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan = scans_fixture[0]
- scan.provider = provider
- scan.save()
attack_paths_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -2261,19 +2623,15 @@ class TestAttackPathsDbUtilsGraphDataReady:
assert attack_paths_scan.state == StateChoices.FAILED
assert attack_paths_scan.graph_data_ready is True
- def test_set_provider_graph_data_ready_updates_all_scans_for_provider(
- self, tenants_fixture, providers_fixture, scans_fixture
+ def test_set_provider_graph_data_ready_updates_all_scans_for_provider_sink(
+ self, tenants_fixture, aws_provider, scans_fixture
):
from tasks.jobs.attack_paths.db_utils import set_provider_graph_data_ready
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
scan_a = scans_fixture[0]
- scan_a.provider = provider
- scan_a.save()
scan_b = Scan.objects.create(
name="Second Scan",
@@ -2289,6 +2647,7 @@ class TestAttackPathsDbUtilsGraphDataReady:
scan=scan_a,
state=StateChoices.COMPLETED,
graph_data_ready=True,
+ sink_backend="neptune",
)
new_ap_scan = AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -2296,6 +2655,7 @@ class TestAttackPathsDbUtilsGraphDataReady:
scan=scan_b,
state=StateChoices.EXECUTING,
graph_data_ready=True,
+ sink_backend="neptune",
)
with patch(
@@ -2309,23 +2669,53 @@ class TestAttackPathsDbUtilsGraphDataReady:
assert old_ap_scan.graph_data_ready is False
assert new_ap_scan.graph_data_ready is False
- def test_set_provider_graph_data_ready_does_not_affect_other_providers(
- self, tenants_fixture, providers_fixture, scans_fixture
+ def test_set_provider_graph_data_ready_preserves_other_sink_scans(
+ self, tenants_fixture, aws_provider, scans_fixture
):
from tasks.jobs.attack_paths.db_utils import set_provider_graph_data_ready
tenant = tenants_fixture[0]
- provider_a = providers_fixture[0]
- provider_a.provider = Provider.ProviderChoices.AWS
- provider_a.save()
+ provider = aws_provider
- provider_b = providers_fixture[1]
- provider_b.provider = Provider.ProviderChoices.AWS
- provider_b.save()
+ scan = scans_fixture[0]
+
+ legacy_scan = AttackPathsScan.objects.create(
+ tenant_id=tenant.id,
+ provider=provider,
+ scan=scan,
+ state=StateChoices.COMPLETED,
+ graph_data_ready=True,
+ sink_backend="neo4j",
+ )
+ neptune_scan = AttackPathsScan.objects.create(
+ tenant_id=tenant.id,
+ provider=provider,
+ scan=scan,
+ state=StateChoices.EXECUTING,
+ graph_data_ready=True,
+ sink_backend="neptune",
+ )
+
+ with patch(
+ "tasks.jobs.attack_paths.db_utils.rls_transaction",
+ new=lambda *args, **kwargs: nullcontext(),
+ ):
+ set_provider_graph_data_ready(neptune_scan, False)
+
+ legacy_scan.refresh_from_db()
+ neptune_scan.refresh_from_db()
+ assert legacy_scan.graph_data_ready is True
+ assert neptune_scan.graph_data_ready is False
+
+ def test_set_provider_graph_data_ready_does_not_affect_other_providers(
+ self, tenants_fixture, aws_provider_pair, scans_fixture
+ ):
+ from tasks.jobs.attack_paths.db_utils import set_provider_graph_data_ready
+
+ tenant = tenants_fixture[0]
+ provider_a, provider_b = aws_provider_pair
scan_a = scans_fixture[0]
- scan_a.provider = provider_a
- scan_a.save()
scan_b = Scan.objects.create(
name="Scan for provider B",
@@ -2362,10 +2752,194 @@ class TestAttackPathsDbUtilsGraphDataReady:
assert ap_scan_b.graph_data_ready is True
+class TestAttackPathsWorkerPing:
+ @patch("tasks.jobs.attack_paths.cleanup.current_app")
+ def test_pings_workers_in_parallel_and_retries_only_missing(self, mock_app):
+ from tasks.jobs.attack_paths.cleanup import _ping_workers
+
+ first_ping = MagicMock(return_value={"worker-a@host": {"ok": "pong"}})
+ second_ping = MagicMock(return_value={"worker-b@host": {"ok": "pong"}})
+ third_ping = MagicMock(return_value={"worker-c@host": {"ok": "pong"}})
+ mock_app.control.inspect.side_effect = [
+ MagicMock(ping=first_ping),
+ MagicMock(ping=second_ping),
+ MagicMock(ping=third_ping),
+ ]
+
+ responsive, unresponsive = _ping_workers(
+ {"worker-c@host", "worker-a@host", "worker-b@host"}
+ )
+
+ assert responsive == {
+ "worker-a@host",
+ "worker-b@host",
+ "worker-c@host",
+ }
+ assert unresponsive == set()
+ assert mock_app.control.inspect.call_args_list == [
+ call(
+ destination=["worker-a@host", "worker-b@host", "worker-c@host"],
+ timeout=5,
+ ),
+ call(destination=["worker-b@host", "worker-c@host"], timeout=10),
+ call(destination=["worker-c@host"], timeout=20),
+ ]
+
+ @patch("tasks.jobs.attack_paths.cleanup.logger")
+ @patch("tasks.jobs.attack_paths.cleanup.current_app")
+ def test_retries_intermediate_ping_exceptions(self, mock_app, mock_logger):
+ from tasks.jobs.attack_paths.cleanup import _ping_workers
+
+ mock_app.control.inspect.side_effect = [
+ MagicMock(ping=MagicMock(side_effect=ConnectionError("first"))),
+ MagicMock(ping=MagicMock(side_effect=ConnectionError("second"))),
+ MagicMock(ping=MagicMock(return_value={})),
+ ]
+
+ responsive, unresponsive = _ping_workers({"worker@host"})
+
+ assert responsive == set()
+ assert unresponsive == {"worker@host"}
+ assert mock_logger.warning.call_count == 2
+ assert all(
+ warning.kwargs["exc_info"] is True
+ for warning in mock_logger.warning.call_args_list
+ )
+ mock_logger.exception.assert_not_called()
+
+ @patch("tasks.jobs.attack_paths.cleanup.logger")
+ @patch("tasks.jobs.attack_paths.cleanup.current_app")
+ def test_final_ping_exception_leaves_pending_workers_unknown(
+ self, mock_app, mock_logger
+ ):
+ from tasks.jobs.attack_paths.cleanup import _ping_workers
+
+ mock_app.control.inspect.side_effect = [
+ MagicMock(ping=MagicMock(return_value={"worker-a@host": {"ok": "pong"}})),
+ MagicMock(ping=MagicMock(return_value={})),
+ MagicMock(ping=MagicMock(side_effect=ConnectionError("final"))),
+ ]
+
+ responsive, unresponsive = _ping_workers({"worker-a@host", "worker-b@host"})
+
+ assert responsive == {"worker-a@host"}
+ assert unresponsive is None
+ mock_logger.exception.assert_called_once()
+
+ @patch("tasks.jobs.attack_paths.cleanup.logger")
+ @patch("tasks.jobs.attack_paths.cleanup.current_app")
+ def test_worker_can_respond_after_an_intermediate_exception(
+ self, mock_app, mock_logger
+ ):
+ from tasks.jobs.attack_paths.cleanup import _ping_workers
+
+ mock_app.control.inspect.side_effect = [
+ MagicMock(ping=MagicMock(side_effect=ConnectionError("first"))),
+ MagicMock(ping=MagicMock(side_effect=ConnectionError("second"))),
+ MagicMock(ping=MagicMock(return_value={"worker@host": {"ok": "pong"}})),
+ ]
+
+ responsive, unresponsive = _ping_workers({"worker@host"})
+
+ assert responsive == {"worker@host"}
+ assert unresponsive == set()
+ assert mock_logger.warning.call_count == 2
+ mock_logger.exception.assert_not_called()
+
+
+class TestAttackPathsCleanupTask:
+ @patch(
+ "tasks.tasks.cleanup_stale_attack_paths_scans",
+ return_value={"cleaned_up_count": 1, "scan_ids": ["scan-id"]},
+ )
+ def test_hourly_task_invokes_attack_paths_cleanup(self, mock_cleanup):
+ from tasks.tasks import cleanup_stale_attack_paths_scans_task
+
+ result = cleanup_stale_attack_paths_scans_task.run()
+
+ assert result == {"cleaned_up_count": 1, "scan_ids": ["scan-id"]}
+ mock_cleanup.assert_called_once_with()
+
+
+@pytest.mark.django_db
+class TestAttackPathsDbUtilsActivity:
+ @patch(
+ "tasks.jobs.attack_paths.db_utils.rls_transaction",
+ new=lambda *args, **kwargs: nullcontext(),
+ )
+ def test_starting_scan_refreshes_updated_at(
+ self, tenants_fixture, aws_provider, scans_fixture
+ ):
+ from tasks.jobs.attack_paths.db_utils import starting_attack_paths_scan
+
+ old_updated_at = datetime.now(tz=UTC) - timedelta(hours=1)
+ attack_paths_scan = AttackPathsScan.objects.create(
+ tenant_id=tenants_fixture[0].id,
+ provider=aws_provider,
+ scan=scans_fixture[0],
+ state=StateChoices.SCHEDULED,
+ )
+ AttackPathsScan.objects.filter(id=attack_paths_scan.id).update(
+ updated_at=old_updated_at
+ )
+ attack_paths_scan.refresh_from_db()
+
+ started = starting_attack_paths_scan(
+ attack_paths_scan, SimpleNamespace(update_tag=123)
+ )
+
+ assert attack_paths_scan.updated_at > old_updated_at
+ attack_paths_scan.refresh_from_db()
+ assert started is True
+ assert attack_paths_scan.updated_at > old_updated_at
+
+ @patch(
+ "tasks.jobs.attack_paths.db_utils.rls_transaction",
+ new=lambda *args, **kwargs: nullcontext(),
+ )
+ def test_progress_update_refreshes_updated_at(
+ self, tenants_fixture, aws_provider, scans_fixture
+ ):
+ from tasks.jobs.attack_paths.db_utils import update_attack_paths_scan_progress
+
+ old_updated_at = datetime.now(tz=UTC) - timedelta(hours=1)
+ attack_paths_scan = AttackPathsScan.objects.create(
+ tenant_id=tenants_fixture[0].id,
+ provider=aws_provider,
+ scan=scans_fixture[0],
+ state=StateChoices.EXECUTING,
+ )
+ AttackPathsScan.objects.filter(id=attack_paths_scan.id).update(
+ updated_at=old_updated_at
+ )
+ attack_paths_scan.refresh_from_db()
+
+ update_attack_paths_scan_progress(attack_paths_scan, 42)
+
+ assert attack_paths_scan.updated_at > old_updated_at
+ attack_paths_scan.refresh_from_db()
+ assert attack_paths_scan.progress == 42
+ assert attack_paths_scan.updated_at > old_updated_at
+
+
@pytest.mark.django_db
class TestCleanupStaleAttackPathsScans:
+ @pytest.fixture(autouse=True)
+ def execute_on_commit_callbacks(self):
+ with patch(
+ "tasks.jobs.attack_paths.cleanup.on_commit",
+ side_effect=lambda callback, **kwargs: callback(),
+ ):
+ yield
+
def _create_executing_scan(
- self, tenant, provider, scan=None, started_at=None, worker=None
+ self,
+ tenant,
+ provider,
+ scan=None,
+ started_at=None,
+ updated_at=None,
+ worker=None,
):
"""Helper to create an EXECUTING AttackPathsScan with optional Task+TaskResult."""
ap_scan = AttackPathsScan.objects.create(
@@ -2392,40 +2966,106 @@ class TestCleanupStaleAttackPathsScans:
ap_scan.task = task
ap_scan.save(update_fields=["task_id"])
+ if updated_at is not None:
+ AttackPathsScan.objects.filter(id=ap_scan.id).update(updated_at=updated_at)
+ ap_scan.updated_at = updated_at
+
return ap_scan, task_result
+ @patch(
+ "tasks.jobs.attack_paths.cleanup.rls_transaction",
+ new=lambda *args, **kwargs: nullcontext(),
+ )
+ @patch("tasks.jobs.attack_paths.cleanup._revoke_task")
+ def test_defers_revoke_until_scan_failure_is_persisted(
+ self,
+ mock_revoke,
+ tenants_fixture,
+ aws_provider,
+ ):
+ from tasks.jobs.attack_paths.cleanup import _finalize_failed_scan
+
+ ap_scan, task_result = self._create_executing_scan(
+ tenants_fixture[0],
+ aws_provider,
+ worker="unresponsive-worker@host",
+ )
+
+ with patch("tasks.jobs.attack_paths.cleanup.on_commit") as mock_on_commit:
+ finalized_scan = _finalize_failed_scan(
+ ap_scan,
+ StateChoices.EXECUTING,
+ "Cleanup reason",
+ task_result=task_result,
+ revoke=True,
+ )
+
+ assert finalized_scan is not None
+ ap_scan.refresh_from_db()
+ task_result.refresh_from_db()
+ assert ap_scan.state == StateChoices.FAILED
+ assert task_result.status == "FAILURE"
+ mock_revoke.assert_not_called()
+ mock_on_commit.assert_called_once()
+ assert mock_on_commit.call_args.kwargs == {"using": DEFAULT_DB_ALIAS}
+
+ callback = mock_on_commit.call_args.args[0]
+ callback()
+
+ mock_revoke.assert_called_once_with(task_result, terminate=True)
+
@patch("tasks.jobs.attack_paths.cleanup.recover_graph_data_ready")
@patch("tasks.jobs.attack_paths.cleanup.graph_database.drop_database")
@patch(
"tasks.jobs.attack_paths.cleanup.rls_transaction",
new=lambda *args, **kwargs: nullcontext(),
)
- @patch("tasks.jobs.attack_paths.cleanup._is_worker_alive", return_value=False)
- def test_cleans_up_scan_with_dead_worker(
+ @patch("tasks.jobs.attack_paths.cleanup._revoke_task")
+ @patch("tasks.jobs.attack_paths.cleanup._ping_workers")
+ def test_cleans_up_inactive_scan_with_unresponsive_worker(
self,
- mock_alive,
+ mock_ping,
+ mock_revoke,
mock_drop_db,
mock_recover,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
):
from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
+ from tasks.jobs.attack_paths.db_utils import mark_scan_finished
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
- # Recent scan — should still be cleaned up because worker is dead
+ updated_at = datetime.now(tz=UTC) - timedelta(minutes=31)
ap_scan, task_result = self._create_executing_scan(
- tenant, provider, worker="dead-worker@host"
+ tenant,
+ provider,
+ updated_at=updated_at,
+ worker="unresponsive-worker@host",
)
+ mock_ping.return_value = (set(), {"unresponsive-worker@host"})
- result = cleanup_stale_attack_paths_scans()
+ with patch(
+ "tasks.jobs.attack_paths.cleanup.mark_scan_finished",
+ wraps=mark_scan_finished,
+ ) as mock_mark_failed:
+ call_order = MagicMock()
+ call_order.attach_mock(mock_revoke, "revoke")
+ call_order.attach_mock(mock_mark_failed, "mark_failed")
+ call_order.attach_mock(mock_drop_db, "drop_database")
+
+ result = cleanup_stale_attack_paths_scans()
assert result["cleaned_up_count"] == 1
assert str(ap_scan.id) in result["scan_ids"]
+ assert [entry[0] for entry in call_order.mock_calls] == [
+ "mark_failed",
+ "revoke",
+ "drop_database",
+ ]
+ mock_revoke.assert_called_once_with(task_result, terminate=True)
mock_drop_db.assert_called_once()
mock_recover.assert_called_once()
@@ -2434,7 +3074,10 @@ class TestCleanupStaleAttackPathsScans:
assert ap_scan.progress == 100
assert ap_scan.completed_at is not None
assert ap_scan.ingestion_exceptions == {
- "global_error": "Worker dead — cleaned up by periodic task"
+ "global_error": (
+ "Worker unresponsive and scan inactive for 30 minutes - "
+ "cleaned up by periodic task"
+ )
}
task_result.refresh_from_db()
@@ -2448,63 +3091,115 @@ class TestCleanupStaleAttackPathsScans:
new=lambda *args, **kwargs: nullcontext(),
)
@patch("tasks.jobs.attack_paths.cleanup._revoke_task")
- @patch("tasks.jobs.attack_paths.cleanup._is_worker_alive", return_value=True)
- def test_revokes_and_cleans_scan_exceeding_threshold_on_live_worker(
+ @patch("tasks.jobs.attack_paths.cleanup._ping_workers")
+ def test_revokes_and_cleans_scan_exceeding_threshold_on_responsive_worker(
self,
- mock_alive,
+ mock_ping,
mock_revoke,
mock_drop_db,
mock_recover,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
):
from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
old_start = datetime.now(tz=UTC) - timedelta(hours=49)
ap_scan, task_result = self._create_executing_scan(
tenant, provider, started_at=old_start, worker="live-worker@host"
)
+ mock_ping.return_value = ({"live-worker@host"}, set())
result = cleanup_stale_attack_paths_scans()
assert result["cleaned_up_count"] == 1
- mock_revoke.assert_called_once_with(task_result)
+ mock_revoke.assert_called_once_with(task_result, terminate=True)
mock_recover.assert_called_once()
ap_scan.refresh_from_db()
assert ap_scan.state == StateChoices.FAILED
+ @pytest.mark.parametrize(
+ ("age_seconds", "should_clean"),
+ [
+ (960 * 60 - 1, False),
+ (960 * 60, False),
+ (960 * 60 + 1, True),
+ ],
+ )
+ @patch("tasks.jobs.attack_paths.cleanup.recover_graph_data_ready")
+ @patch("tasks.jobs.attack_paths.cleanup.graph_database.drop_database")
+ @patch(
+ "tasks.jobs.attack_paths.cleanup.rls_transaction",
+ new=lambda *args, **kwargs: nullcontext(),
+ )
+ @patch("tasks.jobs.attack_paths.cleanup._revoke_task")
+ @patch("tasks.jobs.attack_paths.cleanup._ping_workers")
+ def test_stale_threshold_boundary_is_strict(
+ self,
+ mock_ping,
+ mock_revoke,
+ mock_drop_db,
+ mock_recover,
+ age_seconds,
+ should_clean,
+ tenants_fixture,
+ aws_provider,
+ ):
+ from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
+
+ now = datetime.now(tz=UTC)
+ ap_scan, task_result = self._create_executing_scan(
+ tenants_fixture[0],
+ aws_provider,
+ started_at=now - timedelta(seconds=age_seconds),
+ worker="live-worker@host",
+ )
+ mock_ping.return_value = ({"live-worker@host"}, set())
+
+ with patch("tasks.jobs.attack_paths.cleanup.datetime") as mock_datetime:
+ mock_datetime.now.return_value = now
+ result = cleanup_stale_attack_paths_scans()
+
+ assert result["cleaned_up_count"] == int(should_clean)
+ ap_scan.refresh_from_db()
+ expected_state = StateChoices.FAILED if should_clean else StateChoices.EXECUTING
+ assert ap_scan.state == expected_state
+ if should_clean:
+ mock_revoke.assert_called_once_with(task_result, terminate=True)
+ mock_drop_db.assert_called_once()
+ mock_recover.assert_called_once()
+ else:
+ mock_revoke.assert_not_called()
+ mock_drop_db.assert_not_called()
+ mock_recover.assert_not_called()
+
@patch("tasks.jobs.attack_paths.cleanup.recover_graph_data_ready")
@patch("tasks.jobs.attack_paths.cleanup.graph_database.drop_database")
@patch(
"tasks.jobs.attack_paths.cleanup.rls_transaction",
new=lambda *args, **kwargs: nullcontext(),
)
- @patch("tasks.jobs.attack_paths.cleanup._is_worker_alive", return_value=True)
- def test_ignores_recent_executing_scans_on_live_worker(
+ @patch("tasks.jobs.attack_paths.cleanup._ping_workers")
+ def test_ignores_recent_executing_scans_on_responsive_worker(
self,
- mock_alive,
+ mock_ping,
mock_drop_db,
mock_recover,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
):
from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
- # Recent scan on live worker — should be skipped
self._create_executing_scan(tenant, provider, worker="live-worker@host")
+ mock_ping.return_value = ({"live-worker@host"}, set())
result = cleanup_stale_attack_paths_scans()
@@ -2512,6 +3207,130 @@ class TestCleanupStaleAttackPathsScans:
mock_drop_db.assert_not_called()
mock_recover.assert_not_called()
+ @patch("tasks.jobs.attack_paths.cleanup.recover_graph_data_ready")
+ @patch("tasks.jobs.attack_paths.cleanup.graph_database.drop_database")
+ @patch(
+ "tasks.jobs.attack_paths.cleanup.rls_transaction",
+ new=lambda *args, **kwargs: nullcontext(),
+ )
+ @patch("tasks.jobs.attack_paths.cleanup._revoke_task")
+ @patch("tasks.jobs.attack_paths.cleanup._ping_workers")
+ def test_preserves_recent_scan_on_unresponsive_worker(
+ self,
+ mock_ping,
+ mock_revoke,
+ mock_drop_db,
+ mock_recover,
+ tenants_fixture,
+ aws_provider,
+ scans_fixture,
+ ):
+ from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
+
+ self._create_executing_scan(
+ tenants_fixture[0],
+ aws_provider,
+ updated_at=datetime.now(tz=UTC) - timedelta(minutes=29),
+ worker="unresponsive-worker@host",
+ )
+ mock_ping.return_value = (set(), {"unresponsive-worker@host"})
+
+ result = cleanup_stale_attack_paths_scans()
+
+ assert result["cleaned_up_count"] == 0
+ mock_revoke.assert_not_called()
+ mock_drop_db.assert_not_called()
+ mock_recover.assert_not_called()
+
+ @patch("tasks.jobs.attack_paths.cleanup.recover_graph_data_ready")
+ @patch("tasks.jobs.attack_paths.cleanup.graph_database.drop_database")
+ @patch(
+ "tasks.jobs.attack_paths.cleanup.rls_transaction",
+ new=lambda *args, **kwargs: nullcontext(),
+ )
+ @patch("tasks.jobs.attack_paths.cleanup._revoke_task")
+ @patch("tasks.jobs.attack_paths.cleanup._ping_workers", return_value=(set(), None))
+ def test_final_ping_exception_preserves_pending_worker_scan(
+ self,
+ mock_ping,
+ mock_revoke,
+ mock_drop_db,
+ mock_recover,
+ tenants_fixture,
+ aws_provider,
+ scans_fixture,
+ ):
+ from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
+
+ ap_scan, _ = self._create_executing_scan(
+ tenants_fixture[0],
+ aws_provider,
+ updated_at=datetime.now(tz=UTC) - timedelta(hours=1),
+ worker="unknown-worker@host",
+ )
+
+ result = cleanup_stale_attack_paths_scans()
+
+ assert result["cleaned_up_count"] == 0
+ mock_ping.assert_called_once_with({"unknown-worker@host"})
+ ap_scan.refresh_from_db()
+ assert ap_scan.state == StateChoices.EXECUTING
+ mock_revoke.assert_not_called()
+ mock_drop_db.assert_not_called()
+ mock_recover.assert_not_called()
+
+ @pytest.mark.parametrize(
+ ("inactive_seconds", "should_clean"),
+ [(29 * 60 + 59, False), (30 * 60, False), (30 * 60 + 1, True)],
+ )
+ @patch("tasks.jobs.attack_paths.cleanup.recover_graph_data_ready")
+ @patch("tasks.jobs.attack_paths.cleanup.graph_database.drop_database")
+ @patch(
+ "tasks.jobs.attack_paths.cleanup.rls_transaction",
+ new=lambda *args, **kwargs: nullcontext(),
+ )
+ @patch("tasks.jobs.attack_paths.cleanup._revoke_task")
+ @patch("tasks.jobs.attack_paths.cleanup._ping_workers")
+ def test_inactivity_boundary_is_strict(
+ self,
+ mock_ping,
+ mock_revoke,
+ mock_drop_db,
+ mock_recover,
+ inactive_seconds,
+ should_clean,
+ tenants_fixture,
+ aws_provider,
+ scans_fixture,
+ ):
+ from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
+
+ now = datetime.now(tz=UTC)
+ ap_scan, task_result = self._create_executing_scan(
+ tenants_fixture[0],
+ aws_provider,
+ updated_at=now - timedelta(seconds=inactive_seconds),
+ worker="unresponsive-worker@host",
+ )
+ mock_ping.return_value = (set(), {"unresponsive-worker@host"})
+
+ with patch("tasks.jobs.attack_paths.cleanup.datetime") as mock_datetime:
+ mock_datetime.now.return_value = now
+ result = cleanup_stale_attack_paths_scans()
+
+ assert result["cleaned_up_count"] == int(should_clean)
+ ap_scan.refresh_from_db()
+ expected_state = StateChoices.FAILED if should_clean else StateChoices.EXECUTING
+ assert ap_scan.state == expected_state
+ if should_clean:
+ mock_revoke.assert_called_once_with(task_result, terminate=True)
+ mock_drop_db.assert_called_once()
+ mock_recover.assert_called_once()
+ else:
+ mock_revoke.assert_not_called()
+ mock_drop_db.assert_not_called()
+ mock_recover.assert_not_called()
+
@patch("tasks.jobs.attack_paths.cleanup.recover_graph_data_ready")
@patch("tasks.jobs.attack_paths.cleanup.graph_database.drop_database")
@patch(
@@ -2523,15 +3342,13 @@ class TestCleanupStaleAttackPathsScans:
mock_drop_db,
mock_recover,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
):
from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
AttackPathsScan.objects.create(
tenant_id=tenant.id,
@@ -2552,35 +3369,100 @@ class TestCleanupStaleAttackPathsScans:
@patch("tasks.jobs.attack_paths.cleanup.recover_graph_data_ready")
@patch(
"tasks.jobs.attack_paths.cleanup.graph_database.drop_database",
- side_effect=Exception("Neo4j unreachable"),
+ side_effect=[Exception("Neo4j unreachable"), None],
)
@patch(
"tasks.jobs.attack_paths.cleanup.rls_transaction",
new=lambda *args, **kwargs: nullcontext(),
)
- @patch("tasks.jobs.attack_paths.cleanup._is_worker_alive", return_value=False)
- def test_handles_drop_database_failure_gracefully(
+ @patch("tasks.jobs.attack_paths.cleanup._revoke_task")
+ @patch("tasks.jobs.attack_paths.cleanup._ping_workers")
+ @patch("tasks.jobs.attack_paths.cleanup.logger")
+ def test_neo4j_failure_leaves_scan_failed_and_continues(
self,
- mock_alive,
+ mock_logger,
+ mock_ping,
+ mock_revoke,
mock_drop_db,
mock_recover,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
):
from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
- self._create_executing_scan(tenant, provider, worker="dead-worker@host")
+ updated_at = datetime.now(tz=UTC) - timedelta(minutes=31)
+ ap_scan_1, _ = self._create_executing_scan(
+ tenant,
+ provider,
+ updated_at=updated_at,
+ worker="unresponsive-worker-1@host",
+ )
+ ap_scan_2, _ = self._create_executing_scan(
+ tenant,
+ provider,
+ updated_at=updated_at,
+ worker="unresponsive-worker-2@host",
+ )
+ mock_ping.return_value = (
+ set(),
+ {"unresponsive-worker-1@host", "unresponsive-worker-2@host"},
+ )
result = cleanup_stale_attack_paths_scans()
- assert result["cleaned_up_count"] == 1
- mock_drop_db.assert_called_once()
+ assert result["cleaned_up_count"] == 2
+ assert mock_revoke.call_count == 2
+ assert mock_drop_db.call_count == 2
+ mock_logger.exception.assert_called_once()
+ ap_scan_1.refresh_from_db()
+ ap_scan_2.refresh_from_db()
+ assert ap_scan_1.state == StateChoices.FAILED
+ assert ap_scan_2.state == StateChoices.FAILED
+
+ @patch("tasks.jobs.attack_paths.cleanup.graph_database.drop_database")
+ @patch("tasks.jobs.attack_paths.cleanup._revoke_task")
+ @patch("tasks.jobs.attack_paths.cleanup._ping_workers")
+ @patch(
+ "tasks.jobs.attack_paths.cleanup.rls_transaction",
+ new=lambda *args, **kwargs: nullcontext(),
+ )
+ @patch(
+ "tasks.jobs.attack_paths.cleanup.mark_scan_finished",
+ side_effect=DatabaseError("PostgreSQL unavailable"),
+ )
+ @patch("tasks.jobs.attack_paths.cleanup.logger")
+ def test_postgresql_failure_prevents_revoke_and_neo4j_deletion(
+ self,
+ mock_logger,
+ mock_mark_failed,
+ mock_ping,
+ mock_revoke,
+ mock_drop_db,
+ tenants_fixture,
+ aws_provider,
+ scans_fixture,
+ ):
+ from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
+
+ self._create_executing_scan(
+ tenants_fixture[0],
+ aws_provider,
+ updated_at=datetime.now(tz=UTC) - timedelta(minutes=31),
+ worker="unresponsive-worker@host",
+ )
+ mock_ping.return_value = (set(), {"unresponsive-worker@host"})
+
+ result = cleanup_stale_attack_paths_scans()
+
+ assert result["cleaned_up_count"] == 0
+ mock_mark_failed.assert_called_once()
+ mock_logger.exception.assert_called_once()
+ mock_revoke.assert_not_called()
+ mock_drop_db.assert_not_called()
@patch("tasks.jobs.attack_paths.cleanup.recover_graph_data_ready")
@patch("tasks.jobs.attack_paths.cleanup.graph_database.drop_database")
@@ -2588,22 +3470,22 @@ class TestCleanupStaleAttackPathsScans:
"tasks.jobs.attack_paths.cleanup.rls_transaction",
new=lambda *args, **kwargs: nullcontext(),
)
- @patch("tasks.jobs.attack_paths.cleanup._is_worker_alive", return_value=False)
+ @patch("tasks.jobs.attack_paths.cleanup._revoke_task")
+ @patch("tasks.jobs.attack_paths.cleanup._ping_workers")
def test_cross_tenant_cleanup(
self,
- mock_alive,
+ mock_ping,
+ mock_revoke,
mock_drop_db,
mock_recover,
tenants_fixture,
- providers_fixture,
+ aws_provider,
):
from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
tenant1 = tenants_fixture[0]
tenant2 = tenants_fixture[1]
- provider1 = providers_fixture[0]
- provider1.provider = Provider.ProviderChoices.AWS
- provider1.save()
+ provider1 = aws_provider
provider2 = Provider.objects.create(
provider="aws",
@@ -2612,16 +3494,28 @@ class TestCleanupStaleAttackPathsScans:
tenant_id=tenant2.id,
)
+ updated_at = datetime.now(tz=UTC) - timedelta(minutes=31)
ap_scan1, _ = self._create_executing_scan(
- tenant1, provider1, worker="dead-worker-1@host"
+ tenant1,
+ provider1,
+ updated_at=updated_at,
+ worker="unresponsive-worker-1@host",
)
ap_scan2, _ = self._create_executing_scan(
- tenant2, provider2, worker="dead-worker-2@host"
+ tenant2,
+ provider2,
+ updated_at=updated_at,
+ worker="unresponsive-worker-2@host",
+ )
+ mock_ping.return_value = (
+ set(),
+ {"unresponsive-worker-1@host", "unresponsive-worker-2@host"},
)
result = cleanup_stale_attack_paths_scans()
assert result["cleaned_up_count"] == 2
+ assert mock_revoke.call_count == 2
assert mock_recover.call_count == 2
ap_scan1.refresh_from_db()
@@ -2635,29 +3529,34 @@ class TestCleanupStaleAttackPathsScans:
"tasks.jobs.attack_paths.cleanup.rls_transaction",
new=lambda *args, **kwargs: nullcontext(),
)
- @patch("tasks.jobs.attack_paths.cleanup._is_worker_alive", return_value=False)
+ @patch("tasks.jobs.attack_paths.cleanup._revoke_task")
+ @patch("tasks.jobs.attack_paths.cleanup._ping_workers")
def test_recovers_graph_data_ready_for_stale_scan(
self,
- mock_alive,
+ mock_ping,
+ mock_revoke,
mock_drop_db,
mock_recover,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
):
from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
ap_scan, _ = self._create_executing_scan(
- tenant, provider, worker="dead-worker@host"
+ tenant,
+ provider,
+ updated_at=datetime.now(tz=UTC) - timedelta(minutes=31),
+ worker="unresponsive-worker@host",
)
+ mock_ping.return_value = (set(), {"unresponsive-worker@host"})
cleanup_stale_attack_paths_scans()
+ mock_revoke.assert_called_once()
mock_recover.assert_called_once()
recovered_scan = mock_recover.call_args[0][0]
assert recovered_scan.id == ap_scan.id
@@ -2673,15 +3572,13 @@ class TestCleanupStaleAttackPathsScans:
mock_drop_db,
mock_recover,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
):
from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
# Old scan with no Task/TaskResult
old_start = datetime.now(tz=UTC) - timedelta(hours=49)
@@ -2705,32 +3602,176 @@ class TestCleanupStaleAttackPathsScans:
"tasks.jobs.attack_paths.cleanup.rls_transaction",
new=lambda *args, **kwargs: nullcontext(),
)
- @patch("tasks.jobs.attack_paths.cleanup._is_worker_alive", return_value=False)
- def test_shared_worker_is_pinged_only_once(
+ @patch("tasks.jobs.attack_paths.cleanup._revoke_task")
+ @patch("tasks.jobs.attack_paths.cleanup._ping_workers")
+ def test_preserves_scans_without_a_started_at_timestamp(
self,
- mock_alive,
+ mock_ping,
+ mock_revoke,
mock_drop_db,
mock_recover,
tenants_fixture,
- providers_fixture,
+ aws_provider,
+ scans_fixture,
+ ):
+ from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
+
+ responsive_scan, _ = self._create_executing_scan(
+ tenants_fixture[0],
+ aws_provider,
+ worker="responsive-worker@host",
+ )
+ AttackPathsScan.objects.filter(id=responsive_scan.id).update(started_at=None)
+ no_worker_scan = AttackPathsScan.objects.create(
+ tenant_id=tenants_fixture[0].id,
+ provider=aws_provider,
+ state=StateChoices.EXECUTING,
+ started_at=None,
+ )
+ mock_ping.return_value = ({"responsive-worker@host"}, set())
+
+ result = cleanup_stale_attack_paths_scans()
+
+ assert result["cleaned_up_count"] == 0
+ responsive_scan.refresh_from_db()
+ no_worker_scan.refresh_from_db()
+ assert responsive_scan.state == StateChoices.EXECUTING
+ assert no_worker_scan.state == StateChoices.EXECUTING
+ mock_revoke.assert_not_called()
+ mock_drop_db.assert_not_called()
+ mock_recover.assert_not_called()
+
+ @patch("tasks.jobs.attack_paths.cleanup.recover_graph_data_ready")
+ @patch("tasks.jobs.attack_paths.cleanup.graph_database.drop_database")
+ @patch(
+ "tasks.jobs.attack_paths.cleanup.rls_transaction",
+ new=lambda *args, **kwargs: nullcontext(),
+ )
+ @patch("tasks.jobs.attack_paths.cleanup._revoke_task")
+ @patch("tasks.jobs.attack_paths.cleanup._ping_workers")
+ def test_shared_worker_is_collected_only_once(
+ self,
+ mock_ping,
+ mock_revoke,
+ mock_drop_db,
+ mock_recover,
+ tenants_fixture,
+ aws_provider,
scans_fixture,
):
from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
- # Two scans on the same dead worker
- self._create_executing_scan(tenant, provider, worker="shared-worker@host")
- self._create_executing_scan(tenant, provider, worker="shared-worker@host")
+ updated_at = datetime.now(tz=UTC) - timedelta(minutes=31)
+ self._create_executing_scan(
+ tenant,
+ provider,
+ updated_at=updated_at,
+ worker="shared-worker@host",
+ )
+ self._create_executing_scan(
+ tenant,
+ provider,
+ updated_at=updated_at,
+ worker="shared-worker@host",
+ )
+ mock_ping.return_value = (set(), {"shared-worker@host"})
result = cleanup_stale_attack_paths_scans()
assert result["cleaned_up_count"] == 2
- # Worker should be pinged exactly once — cache prevents second ping
- mock_alive.assert_called_once_with("shared-worker@host")
+ assert mock_revoke.call_count == 2
+ mock_ping.assert_called_once_with({"shared-worker@host"})
+
+ @patch("tasks.jobs.attack_paths.cleanup.recover_graph_data_ready")
+ @patch("tasks.jobs.attack_paths.cleanup.graph_database.drop_database")
+ @patch(
+ "tasks.jobs.attack_paths.cleanup.rls_transaction",
+ new=lambda *args, **kwargs: nullcontext(),
+ )
+ @patch("tasks.jobs.attack_paths.cleanup._revoke_task")
+ def test_locked_recheck_preserves_scan_with_new_activity(
+ self,
+ mock_revoke,
+ mock_drop_db,
+ mock_recover,
+ tenants_fixture,
+ aws_provider,
+ scans_fixture,
+ ):
+ from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
+
+ ap_scan, _ = self._create_executing_scan(
+ tenants_fixture[0],
+ aws_provider,
+ updated_at=datetime.now(tz=UTC) - timedelta(minutes=31),
+ worker="unresponsive-worker@host",
+ )
+
+ def record_activity(_workers):
+ AttackPathsScan.objects.filter(id=ap_scan.id).update(
+ updated_at=datetime.now(tz=UTC)
+ )
+ return set(), {"unresponsive-worker@host"}
+
+ with patch(
+ "tasks.jobs.attack_paths.cleanup._ping_workers",
+ side_effect=record_activity,
+ ):
+ result = cleanup_stale_attack_paths_scans()
+
+ assert result["cleaned_up_count"] == 0
+ ap_scan.refresh_from_db()
+ assert ap_scan.state == StateChoices.EXECUTING
+ mock_revoke.assert_not_called()
+ mock_drop_db.assert_not_called()
+ mock_recover.assert_not_called()
+
+ @patch("tasks.jobs.attack_paths.cleanup.recover_graph_data_ready")
+ @patch("tasks.jobs.attack_paths.cleanup.graph_database.drop_database")
+ @patch(
+ "tasks.jobs.attack_paths.cleanup.rls_transaction",
+ new=lambda *args, **kwargs: nullcontext(),
+ )
+ @patch("tasks.jobs.attack_paths.cleanup._revoke_task")
+ def test_locked_recheck_preserves_scan_that_changed_state(
+ self,
+ mock_revoke,
+ mock_drop_db,
+ mock_recover,
+ tenants_fixture,
+ aws_provider,
+ scans_fixture,
+ ):
+ from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
+
+ ap_scan, _ = self._create_executing_scan(
+ tenants_fixture[0],
+ aws_provider,
+ updated_at=datetime.now(tz=UTC) - timedelta(minutes=31),
+ worker="unresponsive-worker@host",
+ )
+
+ def complete_scan(_workers):
+ AttackPathsScan.objects.filter(id=ap_scan.id).update(
+ state=StateChoices.COMPLETED
+ )
+ return set(), {"unresponsive-worker@host"}
+
+ with patch(
+ "tasks.jobs.attack_paths.cleanup._ping_workers",
+ side_effect=complete_scan,
+ ):
+ result = cleanup_stale_attack_paths_scans()
+
+ assert result["cleaned_up_count"] == 0
+ ap_scan.refresh_from_db()
+ assert ap_scan.state == StateChoices.COMPLETED
+ mock_revoke.assert_not_called()
+ mock_drop_db.assert_not_called()
+ mock_recover.assert_not_called()
# `SCHEDULED` state cleanup
def _create_scheduled_scan(
@@ -2793,14 +3834,12 @@ class TestCleanupStaleAttackPathsScans:
mock_drop_db,
mock_recover,
tenants_fixture,
- providers_fixture,
+ aws_provider,
):
from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
ap_scan, task_result = self._create_scheduled_scan(
tenant,
@@ -2819,7 +3858,7 @@ class TestCleanupStaleAttackPathsScans:
assert ap_scan.progress == 100
assert ap_scan.completed_at is not None
assert ap_scan.ingestion_exceptions == {
- "global_error": "Scan never started — cleaned up by periodic task"
+ "global_error": "Scan never started - cleaned up by periodic task"
}
# SCHEDULED revoke must NOT terminate a running worker
@@ -2848,14 +3887,12 @@ class TestCleanupStaleAttackPathsScans:
mock_drop_db,
mock_recover,
tenants_fixture,
- providers_fixture,
+ aws_provider,
):
from tasks.jobs.attack_paths.cleanup import cleanup_stale_attack_paths_scans
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
- provider.provider = Provider.ProviderChoices.AWS
- provider.save()
+ provider = aws_provider
ap_scan, _ = self._create_scheduled_scan(
tenant,
@@ -2871,3 +3908,57 @@ class TestCleanupStaleAttackPathsScans:
ap_scan.refresh_from_db()
assert ap_scan.state == StateChoices.SCHEDULED
mock_revoke.assert_not_called()
+
+
+class TestNormalizeSinkProperties:
+ """Coerce Cartography-emitted property values into sink-portable primitives.
+
+ Lists become comma-strings, dicts become JSON strings, temporals become
+ ISO strings, spatials become their stringified form. The same coercion
+ runs regardless of the active sink so queries are portable.
+ """
+
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ (
+ {"a": "x", "b": 1, "c": 1.5, "d": True, "e": None},
+ {"a": "x", "b": 1, "c": 1.5, "d": True, "e": None},
+ ),
+ (
+ {"actions": ["s3:GetObject", "s3:PutObject"], "tags": []},
+ {"actions": "s3:GetObject,s3:PutObject", "tags": ""},
+ ),
+ (
+ {"condition": {"StringEquals": {"aws:SourceAccount": "123456789012"}}},
+ {
+ "condition": '{"StringEquals": {"aws:SourceAccount": "123456789012"}}'
+ },
+ ),
+ ],
+ )
+ def test_primitive_list_and_dict_branches(self, raw, expected):
+ sync_module._normalize_sink_properties(raw, labels=None)
+ assert raw == expected
+
+ def test_temporal_and_spatial_become_strings(self):
+ class FakeDateTime:
+ def iso_format(self) -> str:
+ return "2026-05-13T10:00:00+00:00"
+
+ class FakeSpatialPoint:
+ def __str__(self) -> str:
+ return "POINT(1.0 2.0)"
+
+ # The spatial branch is detected by module prefix, not by base class.
+ FakeSpatialPoint.__module__ = "neo4j.spatial.fake"
+
+ props = {
+ "created_at": FakeDateTime(),
+ "location": FakeSpatialPoint(),
+ }
+ sync_module._normalize_sink_properties(props, labels=None)
+ assert props == {
+ "created_at": "2026-05-13T10:00:00+00:00",
+ "location": "POINT(1.0 2.0)",
+ }
diff --git a/api/src/backend/tasks/tests/test_backfill.py b/api/src/backend/tasks/tests/test_backfill.py
index 8ae39905fc..7b01c46480 100644
--- a/api/src/backend/tasks/tests/test_backfill.py
+++ b/api/src/backend/tasks/tests/test_backfill.py
@@ -39,9 +39,9 @@ def resource_scan_summary_data(scans_fixture):
@pytest.fixture(scope="function")
-def get_not_completed_scans(providers_fixture):
- provider_id = providers_fixture[0].id
- tenant_id = providers_fixture[0].tenant_id
+def get_not_completed_scans(aws_provider):
+ provider_id = aws_provider.id
+ tenant_id = aws_provider.tenant_id
scan_1 = Scan.objects.create(
tenant_id=tenant_id,
trigger=Scan.TriggerChoices.MANUAL,
diff --git a/api/src/backend/tasks/tests/test_beat.py b/api/src/backend/tasks/tests/test_beat.py
index 8679872164..e3ce97a04a 100644
--- a/api/src/backend/tasks/tests/test_beat.py
+++ b/api/src/backend/tasks/tests/test_beat.py
@@ -10,8 +10,8 @@ from tasks.beat import schedule_provider_scan
@pytest.mark.django_db
class TestScheduleProviderScan:
- def test_schedule_provider_scan_success(self, providers_fixture):
- provider_instance, *_ = providers_fixture
+ def test_schedule_provider_scan_success(self, aws_provider):
+ provider_instance = aws_provider
with patch(
"tasks.tasks.perform_scheduled_scan_task.apply_async"
@@ -41,8 +41,8 @@ class TestScheduleProviderScan:
"provider_id": str(provider_instance.id),
}
- def test_schedule_provider_scan_already_exists(self, providers_fixture):
- provider_instance, *_ = providers_fixture
+ def test_schedule_provider_scan_already_exists(self, aws_provider):
+ provider_instance = aws_provider
# First, schedule the scan
with patch("tasks.tasks.perform_scheduled_scan_task.apply_async"):
@@ -56,8 +56,8 @@ class TestScheduleProviderScan:
exc_info.value
)
- def test_remove_periodic_task(self, providers_fixture):
- provider_instance = providers_fixture[0]
+ def test_remove_periodic_task(self, aws_provider):
+ provider_instance = aws_provider
assert Scan.objects.count() == 0
with patch("tasks.tasks.perform_scheduled_scan_task.apply_async"):
diff --git a/api/src/backend/tasks/tests/test_deletion.py b/api/src/backend/tasks/tests/test_deletion.py
index 1124334861..9a6c4acc7c 100644
--- a/api/src/backend/tasks/tests/test_deletion.py
+++ b/api/src/backend/tasks/tests/test_deletion.py
@@ -1,4 +1,4 @@
-from unittest.mock import call, patch
+from unittest.mock import MagicMock, call, patch
import pytest
from api.attack_paths import database as graph_database
@@ -9,7 +9,7 @@ from tasks.jobs.deletion import delete_provider, delete_tenant
@pytest.mark.django_db
class TestDeleteProvider:
- def test_delete_provider_success(self, providers_fixture):
+ def test_delete_provider_success(self, aws_provider):
with (
patch(
"tasks.jobs.deletion.graph_database.get_database_name",
@@ -19,7 +19,7 @@ class TestDeleteProvider:
"tasks.jobs.deletion.graph_database.drop_subgraph"
) as mock_drop_subgraph,
):
- instance = providers_fixture[0]
+ instance = aws_provider
tenant_id = str(instance.tenant_id)
result = delete_provider(tenant_id, instance.id)
@@ -53,17 +53,19 @@ class TestDeleteProvider:
mock_drop_subgraph.assert_not_called()
def test_delete_provider_drops_temp_attack_paths_databases(
- self, providers_fixture, create_attack_paths_scan
+ self, aws_provider, create_attack_paths_scan
):
- instance = providers_fixture[0]
+ instance = aws_provider
tenant_id = str(instance.tenant_id)
aps1 = create_attack_paths_scan(instance)
aps2 = create_attack_paths_scan(instance)
+ backend = MagicMock()
with (
patch(
- "tasks.jobs.deletion.graph_database.drop_subgraph",
+ "tasks.jobs.deletion.sink_module.get_backend_for_name",
+ return_value=backend,
),
patch(
"tasks.jobs.deletion.graph_database.drop_database",
@@ -72,23 +74,68 @@ class TestDeleteProvider:
result = delete_provider(tenant_id, instance.id)
assert result
+ backend.drop_subgraph.assert_called_once_with(
+ graph_database.get_database_name(tenant_id), str(instance.id)
+ )
expected_tmp_calls = [
call(f"db-tmp-scan-{str(aps1.id).lower()}"),
call(f"db-tmp-scan-{str(aps2.id).lower()}"),
]
mock_drop_database.assert_has_calls(expected_tmp_calls, any_order=True)
- def test_delete_provider_continues_when_temp_db_drop_fails(
- self, providers_fixture, create_attack_paths_scan
+ def test_delete_provider_drops_graph_data_from_all_recorded_sinks(
+ self, aws_provider, create_attack_paths_scan
):
- instance = providers_fixture[0]
+ instance = aws_provider
tenant_id = str(instance.tenant_id)
+ create_attack_paths_scan(instance, sink_backend="neo4j")
+ create_attack_paths_scan(instance, sink_backend="neptune")
+ neo4j_backend = MagicMock()
+ neptune_backend = MagicMock()
- create_attack_paths_scan(instance)
+ def get_backend_for_name(name):
+ return {
+ "neo4j": neo4j_backend,
+ "neptune": neptune_backend,
+ }[name]
with (
patch(
- "tasks.jobs.deletion.graph_database.drop_subgraph",
+ "tasks.jobs.deletion.graph_database.get_database_name",
+ return_value="tenant-db",
+ ),
+ patch(
+ "tasks.jobs.deletion.sink_module.get_backend_for_name",
+ side_effect=get_backend_for_name,
+ ) as mock_get_backend_for_name,
+ patch("tasks.jobs.deletion.graph_database.drop_database"),
+ ):
+ result = delete_provider(tenant_id, instance.id)
+
+ assert result
+ mock_get_backend_for_name.assert_has_calls(
+ [call("neo4j"), call("neptune")], any_order=True
+ )
+ neo4j_backend.drop_subgraph.assert_called_once_with(
+ "tenant-db", str(instance.id)
+ )
+ neptune_backend.drop_subgraph.assert_called_once_with(
+ "tenant-db", str(instance.id)
+ )
+
+ def test_delete_provider_continues_when_temp_db_drop_fails(
+ self, aws_provider, create_attack_paths_scan
+ ):
+ instance = aws_provider
+ tenant_id = str(instance.tenant_id)
+
+ create_attack_paths_scan(instance)
+ backend = MagicMock()
+
+ with (
+ patch(
+ "tasks.jobs.deletion.sink_module.get_backend_for_name",
+ return_value=backend,
),
patch(
"tasks.jobs.deletion.graph_database.drop_database",
@@ -104,10 +151,10 @@ class TestDeleteProvider:
def test_delete_provider_recalculates_tenant_compliance_summary(
self,
- providers_fixture,
+ aws_provider_pair,
provider_compliance_scores_fixture,
):
- instance = providers_fixture[0]
+ instance = aws_provider_pair[0]
tenant_id = instance.tenant_id
TenantComplianceSummary.objects.create(
@@ -152,7 +199,7 @@ class TestDeleteProvider:
@pytest.mark.django_db
class TestDeleteTenant:
- def test_delete_tenant_success(self, tenants_fixture, providers_fixture):
+ def test_delete_tenant_success(self, tenants_fixture, aws_provider):
"""
Test successful deletion of a tenant and its related data.
"""
diff --git a/api/src/backend/tasks/tests/test_integrations.py b/api/src/backend/tasks/tests/test_integrations.py
index 9cb727e8d0..bebb813feb 100644
--- a/api/src/backend/tasks/tests/test_integrations.py
+++ b/api/src/backend/tasks/tests/test_integrations.py
@@ -5,6 +5,10 @@ from api.db_router import READ_REPLICA_ALIAS, MainRouter
from api.models import Integration
from api.utils import prowler_integration_connection_test
from django.db import OperationalError
+from prowler.lib.outputs.jira.exceptions.exceptions import (
+ JiraRefreshTokenError,
+ JiraRequiredCustomFieldsError,
+)
from prowler.providers.aws.lib.security_hub.security_hub import SecurityHubConnection
from prowler.providers.common.models import Connection
from tasks.jobs.integrations import (
@@ -1830,10 +1834,213 @@ class TestJiraIntegration:
)
# Assertions
- assert result == {"created_count": 2, "failed_count": 1}
+ assert result == {
+ "created_count": 2,
+ "failed_count": 1,
+ "error": "Failed to create Jira issue.",
+ }
# Verify error was logged for the failed finding
- mock_logger.error.assert_called_with("Failed to send finding finding-2 to Jira")
+ mock_logger.error.assert_called_with("Failed to create Jira issue.")
+
+ @patch("tasks.jobs.integrations.rls_transaction")
+ @patch("tasks.jobs.integrations.Finding")
+ @patch("tasks.jobs.integrations.Integration")
+ @patch("tasks.jobs.integrations.initialize_prowler_integration")
+ @patch("tasks.jobs.integrations.logger")
+ def test_send_findings_to_jira_preserves_exception_message(
+ self,
+ mock_logger,
+ mock_initialize_integration,
+ mock_integration_model,
+ mock_finding_model,
+ mock_rls_transaction,
+ ):
+ """Test Jira send exceptions are returned for UI polling."""
+ tenant_id = "tenant-123"
+ integration_id = "integration-456"
+ project_key = "PROJ"
+ issue_type = "Task"
+ finding_ids = ["finding-1"]
+ error_message = "Jira project requires custom fields: Team is required"
+
+ mock_rls_transaction.return_value.__enter__ = MagicMock()
+ mock_rls_transaction.return_value.__exit__ = MagicMock()
+
+ integration = MagicMock()
+ mock_integration_model.objects.get.return_value = integration
+
+ mock_jira_integration = MagicMock()
+
+ mock_jira_integration.send_finding.side_effect = JiraRequiredCustomFieldsError(
+ message=error_message
+ )
+ mock_initialize_integration.return_value = mock_jira_integration
+
+ finding = MagicMock()
+ finding.id = "finding-1"
+ finding.check_id = "check_001"
+ finding.severity = "high"
+ finding.status = "FAIL"
+ finding.status_extended = "Resource is not compliant"
+ finding.compliance = {}
+ finding.resources.exists.return_value = False
+ finding.resources.first.return_value = None
+ finding.scan.provider.provider = "aws"
+ finding.check_metadata = {
+ "checktitle": "Check Title",
+ "risk": "High risk",
+ "remediation": {"recommendation": {}, "code": {}},
+ }
+ mock_select_related = mock_finding_model.all_objects.select_related.return_value
+ mock_finding_query = mock_select_related.prefetch_related.return_value
+ mock_finding_query.get.return_value = finding
+
+ result = send_findings_to_jira(
+ tenant_id, integration_id, project_key, issue_type, finding_ids
+ )
+
+ assert result == {
+ "created_count": 0,
+ "failed_count": 1,
+ "error": error_message,
+ }
+ mock_logger.exception.assert_called_with(
+ "Failed to send finding %s to Jira: %s",
+ "finding-1",
+ error_message,
+ )
+
+ @patch("tasks.jobs.integrations.rls_transaction")
+ @patch("tasks.jobs.integrations.Finding")
+ @patch("tasks.jobs.integrations.Integration")
+ @patch("tasks.jobs.integrations.initialize_prowler_integration")
+ @patch("tasks.jobs.integrations.logger")
+ def test_send_findings_to_jira_preserves_refresh_token_error_message(
+ self,
+ mock_logger,
+ mock_initialize_integration,
+ mock_integration_model,
+ mock_finding_model,
+ mock_rls_transaction,
+ ):
+ """Test Jira refresh token exceptions return their UI-friendly message."""
+ tenant_id = "tenant-123"
+ integration_id = "integration-456"
+ project_key = "PROJ"
+ issue_type = "Task"
+ finding_ids = ["finding-1"]
+ error_message = "Failed to refresh the access token"
+
+ mock_rls_transaction.return_value.__enter__ = MagicMock()
+ mock_rls_transaction.return_value.__exit__ = MagicMock()
+
+ integration = MagicMock()
+ mock_integration_model.objects.get.return_value = integration
+
+ mock_jira_integration = MagicMock()
+
+ mock_jira_integration.send_finding.side_effect = JiraRefreshTokenError(
+ message=error_message
+ )
+ mock_initialize_integration.return_value = mock_jira_integration
+
+ finding = MagicMock()
+ finding.id = "finding-1"
+ finding.check_id = "check_001"
+ finding.severity = "high"
+ finding.status = "FAIL"
+ finding.status_extended = "Resource is not compliant"
+ finding.compliance = {}
+ finding.resources.exists.return_value = False
+ finding.resources.first.return_value = None
+ finding.scan.provider.provider = "aws"
+ finding.check_metadata = {
+ "checktitle": "Check Title",
+ "risk": "High risk",
+ "remediation": {"recommendation": {}, "code": {}},
+ }
+ mock_select_related = mock_finding_model.all_objects.select_related.return_value
+ mock_finding_query = mock_select_related.prefetch_related.return_value
+ mock_finding_query.get.return_value = finding
+
+ result = send_findings_to_jira(
+ tenant_id, integration_id, project_key, issue_type, finding_ids
+ )
+
+ assert result == {
+ "created_count": 0,
+ "failed_count": 1,
+ "error": error_message,
+ }
+ mock_logger.exception.assert_called_with(
+ "Failed to send finding %s to Jira: %s",
+ "finding-1",
+ error_message,
+ )
+
+ @patch("tasks.jobs.integrations.rls_transaction")
+ @patch("tasks.jobs.integrations.Finding")
+ @patch("tasks.jobs.integrations.Integration")
+ @patch("tasks.jobs.integrations.initialize_prowler_integration")
+ @patch("tasks.jobs.integrations.logger")
+ def test_send_findings_to_jira_sanitizes_unexpected_exception_message(
+ self,
+ mock_logger,
+ mock_initialize_integration,
+ mock_integration_model,
+ mock_finding_model,
+ mock_rls_transaction,
+ ):
+ """Test unexpected Jira send exceptions do not leak raw details to UI."""
+ tenant_id = "tenant-123"
+ integration_id = "integration-456"
+ project_key = "PROJ"
+ issue_type = "Task"
+ finding_ids = ["finding-1"]
+
+ mock_rls_transaction.return_value.__enter__ = MagicMock()
+ mock_rls_transaction.return_value.__exit__ = MagicMock()
+
+ integration = MagicMock()
+ mock_integration_model.objects.get.return_value = integration
+
+ mock_jira_integration = MagicMock()
+ mock_jira_integration.send_finding.side_effect = Exception("token=secret-value")
+ mock_initialize_integration.return_value = mock_jira_integration
+
+ finding = MagicMock()
+ finding.id = "finding-1"
+ finding.check_id = "check_001"
+ finding.severity = "high"
+ finding.status = "FAIL"
+ finding.status_extended = "Resource is not compliant"
+ finding.compliance = {}
+ finding.resources.exists.return_value = False
+ finding.resources.first.return_value = None
+ finding.scan.provider.provider = "aws"
+ finding.check_metadata = {
+ "checktitle": "Check Title",
+ "risk": "High risk",
+ "remediation": {"recommendation": {}, "code": {}},
+ }
+ mock_select_related = mock_finding_model.all_objects.select_related.return_value
+ mock_finding_query = mock_select_related.prefetch_related.return_value
+ mock_finding_query.get.return_value = finding
+
+ result = send_findings_to_jira(
+ tenant_id, integration_id, project_key, issue_type, finding_ids
+ )
+
+ assert result == {
+ "created_count": 0,
+ "failed_count": 1,
+ "error": "Failed to create Jira issue.",
+ }
+ assert "secret-value" not in result["error"]
+ mock_logger.exception.assert_called_with(
+ "Failed to send finding %s to Jira", "finding-1"
+ )
@patch("tasks.jobs.integrations.rls_transaction")
@patch("tasks.jobs.integrations.Finding")
diff --git a/api/src/backend/tasks/tests/test_orphan_recovery.py b/api/src/backend/tasks/tests/test_orphan_recovery.py
index b78aca4e63..074e311b70 100644
--- a/api/src/backend/tasks/tests/test_orphan_recovery.py
+++ b/api/src/backend/tasks/tests/test_orphan_recovery.py
@@ -7,6 +7,7 @@ from celery import states
from django.test import override_settings
from django_celery_results.models import TaskResult
from tasks.jobs.orphan_recovery import (
+ _SKIP_RECOVERY,
_decode_celery_field,
_reconcile_task_results,
_recovery_attempt_count,
@@ -14,6 +15,7 @@ from tasks.jobs.orphan_recovery import (
is_worker_alive,
reconcile_orphans,
reenqueueable_tasks,
+ revoke_task,
)
@@ -180,10 +182,18 @@ class TestReconcileTaskResults:
assert tr.task_id in result["failed"]
mock_count.assert_not_called()
- def test_scan_task_is_skipped_entirely(self, tenants_fixture):
+ @pytest.mark.parametrize(
+ "task_name",
+ [
+ "scan-perform",
+ "attack-paths-scan-perform",
+ "attack-paths-cleanup-stale-scans",
+ ],
+ )
+ def test_scan_task_is_skipped_entirely(self, tenants_fixture, task_name):
"""Scan tasks are excluded from recovery: the watchdog never touches them."""
tr = _orphan_result(
- name="scan-perform",
+ name=task_name,
kwargs={
"tenant_id": str(tenants_fixture[0].id),
"scan_id": str(uuid4()),
@@ -339,6 +349,15 @@ class TestOrphanRecoveryHelpers:
):
assert is_worker_alive("w@h") is False
+ def test_revoke_task_terminates_with_sigterm_by_default(self):
+ task_result = MagicMock(task_id="task-id")
+ with patch(
+ "tasks.jobs.orphan_recovery.current_app.control.revoke"
+ ) as mock_revoke:
+ revoke_task(task_result)
+
+ mock_revoke.assert_called_once_with("task-id", terminate=True, signal="SIGTERM")
+
def test_recovery_attempt_count_increments(self):
# Unique signature so the Valkey counter starts fresh for this test.
kwargs_repr = repr({"probe": str(uuid4())})
@@ -350,6 +369,12 @@ class TestOrphanRecoveryHelpers:
class TestRecoveryFeatureFlags:
+ def test_attack_paths_tasks_are_excluded_from_generic_recovery(self):
+ assert {
+ "attack-paths-scan-perform",
+ "attack-paths-cleanup-stale-scans",
+ } <= _SKIP_RECOVERY
+
def test_all_groups_enabled_by_default(self):
tasks = reenqueueable_tasks()
assert "scan-summary" in tasks
@@ -374,33 +399,23 @@ class TestRecoveryFeatureFlags:
class TestRecoveryMasterFlag:
@override_settings(TASK_RECOVERY_ENABLED=False)
def test_master_flag_disables_task_recovery(self):
- with (
- patch(
- "tasks.jobs.orphan_recovery._reconcile_task_results"
- ) as mock_reconcile,
- patch(
- "tasks.jobs.attack_paths.cleanup.cleanup_stale_attack_paths_scans",
- return_value={},
- ),
- ):
+ with patch(
+ "tasks.jobs.orphan_recovery._reconcile_task_results"
+ ) as mock_reconcile:
result = reconcile_orphans(grace_minutes=2, max_attempts=3, dry_run=False)
mock_reconcile.assert_not_called()
assert result["acquired"] is True
assert result["enabled"] is False
+ assert "attack_paths" not in result
@override_settings(TASK_RECOVERY_ENABLED=True)
def test_master_flag_enabled_runs_task_recovery(self):
- with (
- patch(
- "tasks.jobs.orphan_recovery._reconcile_task_results",
- return_value={"recovered": [], "failed": [], "skipped": []},
- ) as mock_reconcile,
- patch(
- "tasks.jobs.attack_paths.cleanup.cleanup_stale_attack_paths_scans",
- return_value={},
- ),
- ):
- reconcile_orphans(grace_minutes=2, max_attempts=3, dry_run=False)
+ with patch(
+ "tasks.jobs.orphan_recovery._reconcile_task_results",
+ return_value={"recovered": [], "failed": [], "skipped": []},
+ ) as mock_reconcile:
+ result = reconcile_orphans(grace_minutes=2, max_attempts=3, dry_run=False)
mock_reconcile.assert_called_once()
+ assert "attack_paths" not in result
diff --git a/api/src/backend/tasks/tests/test_reports.py b/api/src/backend/tasks/tests/test_reports.py
index c290e6fe1d..626237922f 100644
--- a/api/src/backend/tasks/tests/test_reports.py
+++ b/api/src/backend/tasks/tests/test_reports.py
@@ -45,14 +45,48 @@ from tasks.jobs.reports import (
get_color_for_risk_level,
get_color_for_weight,
)
+from tasks.jobs.reports import cis as cis_report_module
+from tasks.jobs.reports import csa as csa_report_module
+from tasks.jobs.reports import ens as ens_report_module
+from tasks.jobs.reports import nis2 as nis2_report_module
+from tasks.jobs.reports import threatscore as threatscore_report_module
from tasks.jobs.threatscore_utils import (
_aggregate_requirement_statistics_from_database,
_load_findings_for_requirement_checks,
)
+from tasks.tests.report_test_helpers import patch_chart_helpers, patch_report_gc
matplotlib.use("Agg") # Use non-interactive backend for tests
+@pytest.fixture
+def patch_report_rendering(monkeypatch):
+ patch_report_gc(monkeypatch)
+ patch_chart_helpers(
+ monkeypatch,
+ cis_report_module,
+ (
+ "create_pie_chart",
+ "create_horizontal_bar_chart",
+ "create_stacked_bar_chart",
+ ),
+ )
+ patch_chart_helpers(
+ monkeypatch, csa_report_module, ("create_horizontal_bar_chart",)
+ )
+ patch_chart_helpers(
+ monkeypatch,
+ ens_report_module,
+ ("create_horizontal_bar_chart", "create_radar_chart"),
+ )
+ patch_chart_helpers(
+ monkeypatch, nis2_report_module, ("create_horizontal_bar_chart",)
+ )
+ patch_chart_helpers(
+ monkeypatch, threatscore_report_module, ("create_vertical_bar_chart",)
+ )
+
+
@pytest.mark.django_db
class TestAggregateRequirementStatistics:
"""Test suite for _aggregate_requirement_statistics_from_database function."""
@@ -355,7 +389,7 @@ class TestPDFStylesCreation:
class TestLoadFindingsForChecks:
"""Test suite for _load_findings_for_requirement_checks function."""
- def test_empty_check_ids_returns_empty(self, tenants_fixture, providers_fixture):
+ def test_empty_check_ids_returns_empty(self, tenants_fixture):
"""Test that empty check_ids list returns empty dict."""
tenant = tenants_fixture[0]
@@ -1041,23 +1075,24 @@ class TestStaleCleanupProtectionHelpers:
@pytest.mark.django_db
+@pytest.mark.usefixtures("patch_report_rendering")
class TestGenerateThreatscoreReportFunction:
"""Test suite for generate_threatscore_report function."""
- @patch("tasks.jobs.reports.base.initialize_prowler_provider")
+ @patch("tasks.jobs.reports.base.build_provider_metadata")
def test_generate_threatscore_report_exception_handling(
self,
- mock_initialize_provider,
+ mock_build_provider_metadata,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
"""Test that exceptions during report generation are properly handled."""
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
- mock_initialize_provider.side_effect = Exception("Test exception")
+ mock_build_provider_metadata.side_effect = Exception("Test exception")
with pytest.raises(Exception) as exc_info:
generate_threatscore_report(
@@ -1072,6 +1107,7 @@ class TestGenerateThreatscoreReportFunction:
@pytest.mark.django_db
+@pytest.mark.usefixtures("patch_report_rendering")
class TestGenerateComplianceReportsOptimized:
"""Test suite for generate_compliance_reports function."""
@@ -1087,12 +1123,12 @@ class TestGenerateComplianceReportsOptimized:
mock_upload,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
"""Test that function returns early when scan has no findings."""
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
result = generate_compliance_reports(
tenant_id=str(tenant.id),
@@ -1144,14 +1180,14 @@ class TestGenerateComplianceReportsOptimized:
mock_upload,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
"""Scan with no findings and ``generate_cis=True`` must yield a flat
``{"upload": False, "path": ""}`` entry, consistent with the other
frameworks (no nested dict, no sentinel keys)."""
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
result = generate_compliance_reports(
tenant_id=str(tenant.id),
@@ -1167,7 +1203,6 @@ class TestGenerateComplianceReportsOptimized:
assert result["cis"] == {"upload": False, "path": ""}
mock_cis.assert_not_called()
- @patch("api.utils.initialize_prowler_provider")
@patch("tasks.jobs.report.rmtree")
@patch("tasks.jobs.report._upload_to_s3")
@patch("tasks.jobs.report.generate_cis_report")
@@ -1194,7 +1229,6 @@ class TestGenerateComplianceReportsOptimized:
mock_cis,
mock_upload_to_s3,
mock_rmtree,
- mock_init_provider,
):
"""After each framework finishes, exclusive entries are evicted.
@@ -1223,7 +1257,6 @@ class TestGenerateComplianceReportsOptimized:
mock_aggregate_stats.return_value = {}
mock_generate_output_dir.return_value = "/tmp/tenant/scan/x/prowler-out"
mock_upload_to_s3.return_value = "s3://bucket/tenant/scan/x/report.pdf"
- mock_init_provider.return_value = Mock(name="prowler_provider")
# Seed the cache as if both frameworks had already loaded their
# findings. We mutate it indirectly: each generator wrapper is a
@@ -1266,7 +1299,7 @@ class TestGenerateComplianceReportsOptimized:
"shared must remain in cache because ENS still needs it"
)
- @patch("tasks.jobs.report.initialize_prowler_provider")
+ @patch("tasks.jobs.report.build_provider_metadata")
@patch("tasks.jobs.report.rmtree")
@patch("tasks.jobs.report._upload_to_s3")
@patch("tasks.jobs.report.generate_cis_report")
@@ -1279,7 +1312,7 @@ class TestGenerateComplianceReportsOptimized:
@patch("tasks.jobs.report.Compliance.get_bulk")
@patch("tasks.jobs.report.Provider.objects.get")
@patch("tasks.jobs.report.ScanSummary.objects.filter")
- def test_prowler_provider_initialized_once(
+ def test_provider_metadata_built_once(
self,
mock_scan_summary_filter,
mock_provider_get,
@@ -1293,11 +1326,11 @@ class TestGenerateComplianceReportsOptimized:
mock_cis,
mock_upload_to_s3,
mock_rmtree,
- mock_init_provider,
+ mock_build_metadata,
):
- """``initialize_prowler_provider`` must be called exactly once for
- the whole batch (PROWLER-1733). Previously each generator re-init'd
- the SDK provider in ``_load_compliance_data`` → 5 inits per scan.
+ """``build_provider_metadata`` must be called exactly once for the
+ whole batch and its result shared across all 5 reports
+ (PROWLER-1733 / PROWLER-2145).
"""
mock_scan_summary_filter.return_value.exists.return_value = True
mock_provider_get.return_value = Mock(uid="provider-uid", provider="aws")
@@ -1306,7 +1339,7 @@ class TestGenerateComplianceReportsOptimized:
mock_aggregate_stats.return_value = {}
mock_generate_output_dir.return_value = "/tmp/tenant/scan/x/prowler-out"
mock_upload_to_s3.return_value = "s3://bucket/tenant/scan/x/report.pdf"
- mock_init_provider.return_value = Mock(name="prowler_provider")
+ mock_build_metadata.return_value = Mock(name="prowler_provider")
generate_compliance_reports(
tenant_id=str(uuid.uuid4()),
@@ -1325,14 +1358,14 @@ class TestGenerateComplianceReportsOptimized:
mock_nis2.assert_called_once()
mock_csa.assert_called_once()
mock_cis.assert_called_once()
- # …but the SDK provider was initialized only once.
- assert mock_init_provider.call_count == 1, (
- f"expected 1 init, got {mock_init_provider.call_count} "
+ # …but the provider metadata stub was built only once.
+ assert mock_build_metadata.call_count == 1, (
+ f"expected 1 build, got {mock_build_metadata.call_count} "
f"(prowler_provider must be shared across reports)"
)
# The shared instance must reach every wrapper as kwargs.
- shared = mock_init_provider.return_value
+ shared = mock_build_metadata.return_value
for mock_wrapper in (
mock_threatscore,
mock_ens,
@@ -1442,6 +1475,7 @@ class TestGenerateComplianceReportsOptimized:
@pytest.mark.django_db
+@pytest.mark.usefixtures("patch_report_rendering")
class TestGenerateComplianceReportsCIS:
"""Test suite covering the CIS branch of generate_compliance_reports."""
@@ -1471,7 +1505,7 @@ class TestGenerateComplianceReportsCIS:
monkeypatch,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
"""CIS branch should generate a single PDF for the highest version.
@@ -1481,7 +1515,7 @@ class TestGenerateComplianceReportsCIS:
"""
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
self._force_scan_has_findings(monkeypatch)
@@ -1530,12 +1564,12 @@ class TestGenerateComplianceReportsCIS:
monkeypatch,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
"""A failure in the latest CIS variant must be surfaced in the flat results entry."""
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
self._force_scan_has_findings(monkeypatch)
@@ -1577,14 +1611,14 @@ class TestGenerateComplianceReportsCIS:
monkeypatch,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
"""When ``Compliance.get_bulk`` returns no CIS entry the CIS branch
must skip cleanly and record a flat ``{"upload": False, "path": ""}``
entry — no hard-coded provider whitelist is consulted."""
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
self._force_scan_has_findings(monkeypatch)
mock_stats.return_value = {}
@@ -1616,12 +1650,12 @@ class TestGenerateComplianceReportsCIS:
monkeypatch,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
"""CIS output dir errors must be captured in results (not raised)."""
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
self._force_scan_has_findings(monkeypatch)
mock_stats.return_value = {}
diff --git a/api/src/backend/tasks/tests/test_reports_base.py b/api/src/backend/tasks/tests/test_reports_base.py
index 6246654436..7577903bae 100644
--- a/api/src/backend/tasks/tests/test_reports_base.py
+++ b/api/src/backend/tasks/tests/test_reports_base.py
@@ -43,6 +43,7 @@ from tasks.jobs.reports import ( # Configuration; Colors; Components; Charts; B
get_framework_config,
get_status_color,
)
+from tasks.tests.report_test_helpers import PNG_SIGNATURE, fake_png_buffer
# =============================================================================
# Configuration Tests
@@ -452,174 +453,47 @@ class TestSectionHeader:
# =============================================================================
-class TestChartCreation:
- """Tests for chart creation functions."""
+class TestChartRenderingSmoke:
+ """Small real-render coverage for the chart helpers."""
- def test_create_vertical_bar_chart(self):
- """Test vertical bar chart creation."""
- buffer = create_vertical_bar_chart(
- labels=["A", "B", "C"],
- values=[80, 60, 40],
- )
- assert isinstance(buffer, io.BytesIO)
- assert buffer.getvalue() # Not empty
+ @pytest.mark.parametrize(
+ ("chart_helper", "kwargs"),
+ [
+ (
+ create_vertical_bar_chart,
+ {"labels": ["Section 1", "Section 2"], "values": [90, 70]},
+ ),
+ (
+ create_horizontal_bar_chart,
+ {"labels": ["Category 1", "Category 2"], "values": [85, 65]},
+ ),
+ (
+ create_radar_chart,
+ {"labels": ["A", "B", "C"], "values": [50, 60, 70]},
+ ),
+ (
+ create_pie_chart,
+ {"labels": ["Pass", "Fail"], "values": [80, 20]},
+ ),
+ (
+ create_stacked_bar_chart,
+ {
+ "labels": ["Section 1", "Section 2"],
+ "data_series": {"Pass": [8, 6], "Fail": [2, 4]},
+ },
+ ),
+ ],
+ )
+ def test_chart_helper_renders_valid_png(self, chart_helper, kwargs):
+ buffer = chart_helper(**kwargs)
+ image_bytes = buffer.getvalue()
- def test_create_vertical_bar_chart_with_options(self):
- """Test vertical bar chart with custom options."""
- buffer = create_vertical_bar_chart(
- labels=["Section 1", "Section 2"],
- values=[90, 70],
- ylabel="Compliance",
- title="Test Chart",
- figsize=(8, 6),
- )
assert isinstance(buffer, io.BytesIO)
+ assert image_bytes
+ assert image_bytes.startswith(PNG_SIGNATURE)
- def test_create_horizontal_bar_chart(self):
- """Test horizontal bar chart creation."""
- buffer = create_horizontal_bar_chart(
- labels=["Category 1", "Category 2", "Category 3"],
- values=[85, 65, 45],
- )
- assert isinstance(buffer, io.BytesIO)
- assert buffer.getvalue()
-
- def test_create_horizontal_bar_chart_with_options(self):
- """Test horizontal bar chart with custom options."""
- buffer = create_horizontal_bar_chart(
- labels=["A", "B"],
- values=[100, 50],
- xlabel="Percentage",
- title="Custom Chart",
- )
- assert isinstance(buffer, io.BytesIO)
-
- def test_create_radar_chart(self):
- """Test radar chart creation."""
- buffer = create_radar_chart(
- labels=["Dim 1", "Dim 2", "Dim 3", "Dim 4", "Dim 5"],
- values=[80, 70, 60, 90, 75],
- )
- assert isinstance(buffer, io.BytesIO)
- assert buffer.getvalue()
-
- def test_create_radar_chart_with_options(self):
- """Test radar chart with custom options."""
- buffer = create_radar_chart(
- labels=["A", "B", "C"],
- values=[50, 60, 70],
- color="#FF0000",
- fill_alpha=0.5,
- title="Custom Radar",
- )
- assert isinstance(buffer, io.BytesIO)
-
- def test_create_pie_chart(self):
- """Test pie chart creation."""
- buffer = create_pie_chart(
- labels=["Pass", "Fail"],
- values=[80, 20],
- )
- assert isinstance(buffer, io.BytesIO)
- assert buffer.getvalue()
-
- def test_create_pie_chart_with_options(self):
- """Test pie chart with custom options."""
- buffer = create_pie_chart(
- labels=["Pass", "Fail", "Manual"],
- values=[60, 30, 10],
- colors=["#4CAF50", "#F44336", "#9E9E9E"],
- title="Status Distribution",
- autopct="%1.0f%%",
- )
- assert isinstance(buffer, io.BytesIO)
-
- def test_create_stacked_bar_chart(self):
- """Test stacked bar chart creation."""
- buffer = create_stacked_bar_chart(
- labels=["Section 1", "Section 2", "Section 3"],
- data_series={
- "Pass": [8, 6, 4],
- "Fail": [2, 4, 6],
- },
- )
- assert isinstance(buffer, io.BytesIO)
- assert buffer.getvalue()
-
- def test_create_stacked_bar_chart_with_options(self):
- """Test stacked bar chart with custom options."""
- buffer = create_stacked_bar_chart(
- labels=["A", "B"],
- data_series={
- "Pass": [10, 5],
- "Fail": [2, 3],
- "Manual": [1, 2],
- },
- colors={
- "Pass": "#4CAF50",
- "Fail": "#F44336",
- "Manual": "#9E9E9E",
- },
- xlabel="Categories",
- ylabel="Requirements",
- title="Requirements by Status",
- )
- assert isinstance(buffer, io.BytesIO)
-
- def test_create_stacked_bar_chart_without_legend(self):
- """Test stacked bar chart without legend."""
- buffer = create_stacked_bar_chart(
- labels=["X", "Y"],
- data_series={"A": [1, 2]},
- show_legend=False,
- )
- assert isinstance(buffer, io.BytesIO)
-
- def test_create_vertical_bar_chart_without_labels(self):
- """Test vertical bar chart without value labels."""
- buffer = create_vertical_bar_chart(
- labels=["A", "B"],
- values=[50, 75],
- show_labels=False,
- )
- assert isinstance(buffer, io.BytesIO)
-
- def test_create_vertical_bar_chart_with_explicit_colors(self):
- """Test vertical bar chart with explicit color list."""
- buffer = create_vertical_bar_chart(
- labels=["Pass", "Fail"],
- values=[80, 20],
- colors=["#4CAF50", "#F44336"],
- )
- assert isinstance(buffer, io.BytesIO)
-
- def test_create_horizontal_bar_chart_auto_figsize(self):
- """Test horizontal bar chart auto-calculates figure size for many items."""
- labels = [f"Item {i}" for i in range(20)]
- values = [50 + i * 2 for i in range(20)]
- buffer = create_horizontal_bar_chart(
- labels=labels,
- values=values,
- )
- assert isinstance(buffer, io.BytesIO)
-
- def test_create_horizontal_bar_chart_with_explicit_colors(self):
- """Test horizontal bar chart with explicit colors."""
- buffer = create_horizontal_bar_chart(
- labels=["A", "B", "C"],
- values=[80, 60, 40],
- colors=["#4CAF50", "#FFEB3B", "#F44336"],
- )
- assert isinstance(buffer, io.BytesIO)
-
- def test_create_radar_chart_with_custom_ticks(self):
- """Test radar chart with custom y-axis ticks."""
- buffer = create_radar_chart(
- labels=["A", "B", "C", "D"],
- values=[25, 50, 75, 100],
- y_ticks=[0, 25, 50, 75, 100],
- )
- assert isinstance(buffer, io.BytesIO)
+ buffer.seek(0)
+ assert Image(buffer, width=1 * inch, height=1 * inch)
# =============================================================================
@@ -1056,10 +930,7 @@ class TestExampleReportGenerator:
]
def create_charts_section(self, data):
- chart_buffer = create_vertical_bar_chart(
- labels=["Pass", "Fail"],
- values=[80, 20],
- )
+ chart_buffer = fake_png_buffer()
return [Image(chart_buffer, width=6 * inch, height=4 * inch)]
def create_requirements_index(self, data):
@@ -1150,63 +1021,6 @@ class TestExampleReportGenerator:
# =============================================================================
-class TestChartEdgeCases:
- """Tests for chart edge cases."""
-
- def test_vertical_bar_chart_empty_data(self):
- """Test vertical bar chart with empty data."""
- buffer = create_vertical_bar_chart(labels=[], values=[])
- assert isinstance(buffer, io.BytesIO)
-
- def test_vertical_bar_chart_single_item(self):
- """Test vertical bar chart with single item."""
- buffer = create_vertical_bar_chart(labels=["Single"], values=[75.0])
- assert isinstance(buffer, io.BytesIO)
-
- def test_horizontal_bar_chart_empty_data(self):
- """Test horizontal bar chart with empty data."""
- buffer = create_horizontal_bar_chart(labels=[], values=[])
- assert isinstance(buffer, io.BytesIO)
-
- def test_horizontal_bar_chart_single_item(self):
- """Test horizontal bar chart with single item."""
- buffer = create_horizontal_bar_chart(labels=["Single"], values=[50.0])
- assert isinstance(buffer, io.BytesIO)
-
- def test_radar_chart_minimum_points(self):
- """Test radar chart with minimum number of points (3)."""
- buffer = create_radar_chart(
- labels=["A", "B", "C"],
- values=[30.0, 60.0, 90.0],
- )
- assert isinstance(buffer, io.BytesIO)
-
- def test_pie_chart_single_slice(self):
- """Test pie chart with single slice."""
- buffer = create_pie_chart(labels=["Only"], values=[100.0])
- assert isinstance(buffer, io.BytesIO)
-
- def test_pie_chart_many_slices(self):
- """Test pie chart with many slices."""
- labels = [f"Item {i}" for i in range(10)]
- values = [10.0] * 10
- buffer = create_pie_chart(labels=labels, values=values)
- assert isinstance(buffer, io.BytesIO)
-
- def test_stacked_bar_chart_single_series(self):
- """Test stacked bar chart with single series."""
- buffer = create_stacked_bar_chart(
- labels=["A", "B"],
- data_series={"Only": [10.0, 20.0]},
- )
- assert isinstance(buffer, io.BytesIO)
-
- def test_stacked_bar_chart_empty_data(self):
- """Test stacked bar chart with empty data."""
- buffer = create_stacked_bar_chart(labels=[], data_series={})
- assert isinstance(buffer, io.BytesIO)
-
-
class TestComponentEdgeCases:
"""Tests for component edge cases."""
diff --git a/api/src/backend/tasks/tests/test_reports_cis.py b/api/src/backend/tasks/tests/test_reports_cis.py
index 31e5a5495f..b57780b8a4 100644
--- a/api/src/backend/tasks/tests/test_reports_cis.py
+++ b/api/src/backend/tasks/tests/test_reports_cis.py
@@ -4,11 +4,13 @@ import pytest
from api.models import StatusChoices
from reportlab.platypus import Image, LongTable, Paragraph, Table
from tasks.jobs.reports import FRAMEWORK_REGISTRY, ComplianceData, RequirementData
+from tasks.jobs.reports import cis as cis_report_module
from tasks.jobs.reports.cis import (
CISReportGenerator,
_normalize_profile,
_profile_badge_text,
)
+from tasks.tests.report_test_helpers import patch_chart_helpers
# =============================================================================
# Fixtures
@@ -399,18 +401,69 @@ class TestCISExecutiveSummary:
class TestCISChartsSection:
- def test_charts_rendered(self, cis_generator, populated_cis_compliance_data):
- elements = cis_generator.create_charts_section(populated_cis_compliance_data)
- # At least 1 image for the pie + 1 for section bar + 1 for stacked
- images = [e for e in elements if isinstance(e, Image)]
- assert len(images) >= 1
+ def test_charts_rendered(
+ self, monkeypatch, cis_generator, populated_cis_compliance_data
+ ):
+ chart_calls = patch_chart_helpers(
+ monkeypatch,
+ cis_report_module,
+ (
+ "create_pie_chart",
+ "create_horizontal_bar_chart",
+ "create_stacked_bar_chart",
+ ),
+ )
- def test_charts_no_data_no_crash(self, cis_generator, basic_cis_compliance_data):
+ elements = cis_generator.create_charts_section(populated_cis_compliance_data)
+
+ images = [e for e in elements if isinstance(e, Image)]
+ assert len(images) == 3
+
+ pie_kwargs = chart_calls["create_pie_chart"][0]["kwargs"]
+ assert pie_kwargs["labels"] == ["Pass (2)", "Fail (2)", "Manual (1)"]
+ assert pie_kwargs["values"] == [2, 2, 1]
+ assert pie_kwargs["colors"]
+
+ bar_kwargs = chart_calls["create_horizontal_bar_chart"][0]["kwargs"]
+ assert set(bar_kwargs["labels"]) == {
+ "1 Identity and Access Management",
+ "2 Storage",
+ }
+ assert bar_kwargs["values"] == [50.0, 50.0]
+ assert bar_kwargs["xlabel"] == "Compliance (%)"
+ assert bar_kwargs["color_func"]
+ assert bar_kwargs["label_fontsize"] == 9
+
+ stacked_kwargs = chart_calls["create_stacked_bar_chart"][0]["kwargs"]
+ assert stacked_kwargs["labels"] == ["Level 1", "Level 2"]
+ assert stacked_kwargs["data_series"] == {
+ "Pass": [1, 1],
+ "Fail": [2, 0],
+ "Manual": [0, 1],
+ }
+ assert stacked_kwargs["xlabel"] == "Profile"
+ assert stacked_kwargs["ylabel"] == "Requirements"
+
+ def test_charts_no_data_no_crash(
+ self, monkeypatch, cis_generator, basic_cis_compliance_data
+ ):
+ chart_calls = patch_chart_helpers(
+ monkeypatch,
+ cis_report_module,
+ (
+ "create_pie_chart",
+ "create_horizontal_bar_chart",
+ "create_stacked_bar_chart",
+ ),
+ )
basic_cis_compliance_data.requirements = []
basic_cis_compliance_data.attributes_by_requirement_id = {}
elements = cis_generator.create_charts_section(basic_cis_compliance_data)
- # Must not raise; may or may not have any Image
+
assert isinstance(elements, list)
+ assert chart_calls["create_pie_chart"] == []
+ assert chart_calls["create_horizontal_bar_chart"] == []
+ assert chart_calls["create_stacked_bar_chart"] == []
# =============================================================================
diff --git a/api/src/backend/tasks/tests/test_reports_csa.py b/api/src/backend/tasks/tests/test_reports_csa.py
index 2e61e9ef84..7a97018f6c 100644
--- a/api/src/backend/tasks/tests/test_reports_csa.py
+++ b/api/src/backend/tasks/tests/test_reports_csa.py
@@ -2,9 +2,11 @@ import io
from unittest.mock import Mock
import pytest
-from reportlab.platypus import PageBreak, Paragraph, Table
+from reportlab.platypus import Image, PageBreak, Paragraph, Table
from tasks.jobs.reports import FRAMEWORK_REGISTRY, ComplianceData, RequirementData
+from tasks.jobs.reports import csa as csa_report_module
from tasks.jobs.reports.csa import CSAReportGenerator
+from tasks.tests.report_test_helpers import patch_chart_helpers
# Use string status values directly to avoid Django DB initialization
@@ -29,6 +31,13 @@ def csa_generator():
return CSAReportGenerator(config)
+@pytest.fixture
+def patched_csa_charts(monkeypatch):
+ return patch_chart_helpers(
+ monkeypatch, csa_report_module, ("create_horizontal_bar_chart",)
+ )
+
+
@pytest.fixture
def mock_csa_requirement_attribute_iam():
"""Create a mock CSA CCM requirement attribute for Identity & Access Management."""
@@ -320,7 +329,7 @@ class TestCSAChartsSection:
"""Test suite for CSA charts section generation."""
def test_charts_section_has_section_chart_title(
- self, csa_generator, basic_csa_compliance_data
+ self, csa_generator, basic_csa_compliance_data, patched_csa_charts
):
"""Test that charts section has section compliance title."""
basic_csa_compliance_data.requirements = []
@@ -331,9 +340,14 @@ class TestCSAChartsSection:
paragraphs = [e for e in elements if isinstance(e, Paragraph)]
content = " ".join(str(p.text) for p in paragraphs)
assert "Section" in content or "Compliance" in content
+ assert any(isinstance(e, Image) for e in elements)
+ chart_kwargs = patched_csa_charts["create_horizontal_bar_chart"][0]["kwargs"]
+ assert chart_kwargs["labels"] == []
+ assert chart_kwargs["values"] == []
+ assert chart_kwargs["xlabel"] == "Compliance (%)"
def test_charts_section_has_page_break(
- self, csa_generator, basic_csa_compliance_data
+ self, csa_generator, basic_csa_compliance_data, patched_csa_charts
):
"""Test that charts section has page breaks."""
basic_csa_compliance_data.requirements = []
@@ -343,12 +357,14 @@ class TestCSAChartsSection:
page_breaks = [e for e in elements if isinstance(e, PageBreak)]
assert len(page_breaks) >= 1
+ assert len(patched_csa_charts["create_horizontal_bar_chart"]) == 1
def test_charts_section_has_section_breakdown(
self,
csa_generator,
basic_csa_compliance_data,
mock_csa_requirement_attribute_iam,
+ patched_csa_charts,
):
"""Test that charts section includes section breakdown table."""
basic_csa_compliance_data.requirements = [
@@ -372,6 +388,11 @@ class TestCSAChartsSection:
paragraphs = [e for e in elements if isinstance(e, Paragraph)]
content = " ".join(str(p.text) for p in paragraphs)
assert "Section" in content or "Breakdown" in content
+ assert any(isinstance(e, Image) for e in elements)
+ chart_kwargs = patched_csa_charts["create_horizontal_bar_chart"][0]["kwargs"]
+ assert chart_kwargs["labels"] == ["Identity & Access Management"]
+ assert chart_kwargs["values"] == [100.0]
+ assert chart_kwargs["color_func"]
# =============================================================================
@@ -387,6 +408,7 @@ class TestCSASectionChart:
csa_generator,
basic_csa_compliance_data,
mock_csa_requirement_attribute_iam,
+ patched_csa_charts,
):
"""Test that section chart is created successfully."""
basic_csa_compliance_data.requirements = [
@@ -409,12 +431,17 @@ class TestCSASectionChart:
assert isinstance(chart_buffer, io.BytesIO)
assert chart_buffer.getvalue() # Not empty
+ chart_kwargs = patched_csa_charts["create_horizontal_bar_chart"][0]["kwargs"]
+ assert chart_kwargs["labels"] == ["Identity & Access Management"]
+ assert chart_kwargs["values"] == [100.0]
+ assert chart_kwargs["xlabel"] == "Compliance (%)"
def test_section_chart_excludes_manual(
self,
csa_generator,
basic_csa_compliance_data,
mock_csa_requirement_attribute_iam,
+ patched_csa_charts,
):
"""Test that manual requirements are excluded from section chart."""
basic_csa_compliance_data.requirements = [
@@ -447,6 +474,9 @@ class TestCSASectionChart:
# Should not raise any errors
chart_buffer = csa_generator._create_section_chart(basic_csa_compliance_data)
assert isinstance(chart_buffer, io.BytesIO)
+ chart_kwargs = patched_csa_charts["create_horizontal_bar_chart"][0]["kwargs"]
+ assert chart_kwargs["labels"] == ["Identity & Access Management"]
+ assert chart_kwargs["values"] == [100.0]
def test_section_chart_multiple_sections(
self,
@@ -455,6 +485,7 @@ class TestCSASectionChart:
mock_csa_requirement_attribute_iam,
mock_csa_requirement_attribute_logging,
mock_csa_requirement_attribute_crypto,
+ patched_csa_charts,
):
"""Test section chart with multiple sections."""
basic_csa_compliance_data.requirements = [
@@ -501,6 +532,13 @@ class TestCSASectionChart:
chart_buffer = csa_generator._create_section_chart(basic_csa_compliance_data)
assert isinstance(chart_buffer, io.BytesIO)
+ chart_kwargs = patched_csa_charts["create_horizontal_bar_chart"][0]["kwargs"]
+ assert chart_kwargs["labels"] == [
+ "Cryptography & Encryption",
+ "Identity & Access Management",
+ "Logging and Monitoring",
+ ]
+ assert chart_kwargs["values"] == [100.0, 100.0, 0.0]
# =============================================================================
diff --git a/api/src/backend/tasks/tests/test_reports_ens.py b/api/src/backend/tasks/tests/test_reports_ens.py
index 91eb6d6f3a..220c3e1427 100644
--- a/api/src/backend/tasks/tests/test_reports_ens.py
+++ b/api/src/backend/tasks/tests/test_reports_ens.py
@@ -2,9 +2,11 @@ import io
from unittest.mock import Mock, patch
import pytest
-from reportlab.platypus import PageBreak, Paragraph, Table
+from reportlab.platypus import Image, PageBreak, Paragraph, Table
from tasks.jobs.reports import FRAMEWORK_REGISTRY, ComplianceData, RequirementData
+from tasks.jobs.reports import ens as ens_report_module
from tasks.jobs.reports.ens import ENSReportGenerator
+from tasks.tests.report_test_helpers import patch_chart_helpers
# Use string status values directly to avoid Django DB initialization
@@ -29,6 +31,15 @@ def ens_generator():
return ENSReportGenerator(config)
+@pytest.fixture
+def patched_ens_charts(monkeypatch):
+ return patch_chart_helpers(
+ monkeypatch,
+ ens_report_module,
+ ("create_horizontal_bar_chart", "create_radar_chart"),
+ )
+
+
@pytest.fixture
def mock_ens_requirement_attribute():
"""Create a mock ENS requirement attribute with all fields."""
@@ -355,7 +366,7 @@ class TestENSChartsSection:
"""Test suite for ENS charts section generation."""
def test_charts_section_has_page_breaks(
- self, ens_generator, basic_ens_compliance_data
+ self, ens_generator, basic_ens_compliance_data, patched_ens_charts
):
"""Test that charts section has page breaks between charts."""
basic_ens_compliance_data.requirements = []
@@ -365,9 +376,25 @@ class TestENSChartsSection:
page_breaks = [e for e in elements if isinstance(e, PageBreak)]
assert len(page_breaks) >= 2 # At least 2 page breaks for different charts
+ assert any(isinstance(e, Image) for e in elements)
+ assert len(patched_ens_charts["create_horizontal_bar_chart"]) == 1
+ assert len(patched_ens_charts["create_radar_chart"]) == 1
+
+ marco_kwargs = patched_ens_charts["create_horizontal_bar_chart"][0]["kwargs"]
+ assert marco_kwargs["labels"] == []
+ assert marco_kwargs["values"] == []
+
+ radar_kwargs = patched_ens_charts["create_radar_chart"][0]["kwargs"]
+ assert radar_kwargs["labels"] == ens_report_module.DIMENSION_NAMES
+ assert radar_kwargs["values"] == [100, 100, 100, 100, 100]
+ assert radar_kwargs["color"] == "#2196F3"
def test_charts_section_has_marco_category_chart(
- self, ens_generator, basic_ens_compliance_data, mock_ens_requirement_attribute
+ self,
+ ens_generator,
+ basic_ens_compliance_data,
+ mock_ens_requirement_attribute,
+ patched_ens_charts,
):
"""Test that charts section contains Marco/Categoría chart."""
basic_ens_compliance_data.requirements = [
@@ -391,9 +418,18 @@ class TestENSChartsSection:
paragraphs = [e for e in elements if isinstance(e, Paragraph)]
content = " ".join(str(p.text) for p in paragraphs)
assert "Marco" in content or "Categoría" in content
+ assert any(isinstance(e, Image) for e in elements)
+ chart_kwargs = patched_ens_charts["create_horizontal_bar_chart"][0]["kwargs"]
+ assert chart_kwargs["labels"] == ["Operacional - Gestión de incidentes"]
+ assert chart_kwargs["values"] == [100.0]
+ assert chart_kwargs["xlabel"] == "Porcentaje de Cumplimiento (%)"
def test_charts_section_has_dimensions_radar(
- self, ens_generator, basic_ens_compliance_data, mock_ens_requirement_attribute
+ self,
+ ens_generator,
+ basic_ens_compliance_data,
+ mock_ens_requirement_attribute,
+ patched_ens_charts,
):
"""Test that charts section contains dimensions radar chart."""
basic_ens_compliance_data.requirements = [
@@ -417,9 +453,17 @@ class TestENSChartsSection:
paragraphs = [e for e in elements if isinstance(e, Paragraph)]
content = " ".join(str(p.text) for p in paragraphs)
assert "Dimensiones" in content or "dimensiones" in content.lower()
+ radar_kwargs = patched_ens_charts["create_radar_chart"][0]["kwargs"]
+ assert radar_kwargs["labels"] == ens_report_module.DIMENSION_NAMES
+ assert radar_kwargs["values"] == [100, 100, 100.0, 100.0, 100]
+ assert radar_kwargs["color"] == "#2196F3"
def test_charts_section_has_tipo_distribution(
- self, ens_generator, basic_ens_compliance_data, mock_ens_requirement_attribute
+ self,
+ ens_generator,
+ basic_ens_compliance_data,
+ mock_ens_requirement_attribute,
+ patched_ens_charts,
):
"""Test that charts section contains tipo distribution."""
basic_ens_compliance_data.requirements = [
@@ -443,6 +487,8 @@ class TestENSChartsSection:
paragraphs = [e for e in elements if isinstance(e, Paragraph)]
content = " ".join(str(p.text) for p in paragraphs)
assert "Tipo" in content or "tipo" in content.lower()
+ assert len(patched_ens_charts["create_horizontal_bar_chart"]) == 1
+ assert len(patched_ens_charts["create_radar_chart"]) == 1
# =============================================================================
@@ -829,7 +875,11 @@ class TestENSDimensionHandling:
"""Test suite for ENS security dimension handling."""
def test_dimensions_as_list(
- self, ens_generator, basic_ens_compliance_data, mock_ens_requirement_attribute
+ self,
+ ens_generator,
+ basic_ens_compliance_data,
+ mock_ens_requirement_attribute,
+ patched_ens_charts,
):
"""Test handling dimensions as a list."""
# mock_ens_requirement_attribute has Dimensiones as list
@@ -837,9 +887,9 @@ class TestENSDimensionHandling:
RequirementData(
id="REQ-001",
description="Test requirement",
- status=StatusChoices.PASS,
- passed_findings=10,
- failed_findings=0,
+ status=StatusChoices.FAIL,
+ passed_findings=0,
+ failed_findings=10,
total_findings=10,
),
]
@@ -854,12 +904,16 @@ class TestENSDimensionHandling:
basic_ens_compliance_data
)
assert isinstance(chart_buffer, io.BytesIO)
+ chart_kwargs = patched_ens_charts["create_radar_chart"][0]["kwargs"]
+ assert chart_kwargs["labels"] == ens_report_module.DIMENSION_NAMES
+ assert chart_kwargs["values"] == [100, 100, 0.0, 0.0, 100]
def test_dimensions_as_string(
self,
ens_generator,
basic_ens_compliance_data,
mock_ens_requirement_attribute_medio,
+ patched_ens_charts,
):
"""Test handling dimensions as comma-separated string."""
# mock_ens_requirement_attribute_medio has Dimensiones as string
@@ -867,9 +921,9 @@ class TestENSDimensionHandling:
RequirementData(
id="REQ-001",
description="Test requirement",
- status=StatusChoices.PASS,
- passed_findings=10,
- failed_findings=0,
+ status=StatusChoices.FAIL,
+ passed_findings=0,
+ failed_findings=10,
total_findings=10,
),
]
@@ -884,12 +938,16 @@ class TestENSDimensionHandling:
basic_ens_compliance_data
)
assert isinstance(chart_buffer, io.BytesIO)
+ chart_kwargs = patched_ens_charts["create_radar_chart"][0]["kwargs"]
+ assert chart_kwargs["labels"] == ens_report_module.DIMENSION_NAMES
+ assert chart_kwargs["values"] == [0.0, 0.0, 100, 100, 100]
def test_dimensions_empty(
self,
ens_generator,
basic_ens_compliance_data,
mock_ens_requirement_attribute_opcional,
+ patched_ens_charts,
):
"""Test handling empty dimensions."""
# mock_ens_requirement_attribute_opcional has empty Dimensiones
@@ -916,6 +974,9 @@ class TestENSDimensionHandling:
basic_ens_compliance_data
)
assert isinstance(chart_buffer, io.BytesIO)
+ chart_kwargs = patched_ens_charts["create_radar_chart"][0]["kwargs"]
+ assert chart_kwargs["labels"] == ens_report_module.DIMENSION_NAMES
+ assert chart_kwargs["values"] == [100, 100, 100, 100, 100]
# =============================================================================
@@ -1061,7 +1122,11 @@ class TestENSMarcoCategoryChart:
"""Test suite for ENS Marco/Categoría chart."""
def test_marco_category_chart_creation(
- self, ens_generator, basic_ens_compliance_data, mock_ens_requirement_attribute
+ self,
+ ens_generator,
+ basic_ens_compliance_data,
+ mock_ens_requirement_attribute,
+ patched_ens_charts,
):
"""Test that Marco/Categoría chart is created successfully."""
basic_ens_compliance_data.requirements = [
@@ -1086,9 +1151,17 @@ class TestENSMarcoCategoryChart:
assert isinstance(chart_buffer, io.BytesIO)
assert chart_buffer.getvalue() # Not empty
+ chart_kwargs = patched_ens_charts["create_horizontal_bar_chart"][0]["kwargs"]
+ assert chart_kwargs["labels"] == ["Operacional - Gestión de incidentes"]
+ assert chart_kwargs["values"] == [100.0]
+ assert chart_kwargs["xlabel"] == "Porcentaje de Cumplimiento (%)"
def test_marco_category_chart_excludes_manual(
- self, ens_generator, basic_ens_compliance_data, mock_ens_requirement_attribute
+ self,
+ ens_generator,
+ basic_ens_compliance_data,
+ mock_ens_requirement_attribute,
+ patched_ens_charts,
):
"""Test that manual requirements are excluded from chart."""
basic_ens_compliance_data.requirements = [
@@ -1123,6 +1196,9 @@ class TestENSMarcoCategoryChart:
basic_ens_compliance_data
)
assert isinstance(chart_buffer, io.BytesIO)
+ chart_kwargs = patched_ens_charts["create_horizontal_bar_chart"][0]["kwargs"]
+ assert chart_kwargs["labels"] == ["Operacional - Gestión de incidentes"]
+ assert chart_kwargs["values"] == [100.0]
# =============================================================================
diff --git a/api/src/backend/tasks/tests/test_reports_nis2.py b/api/src/backend/tasks/tests/test_reports_nis2.py
index 07e88ec7ca..ea6e06477d 100644
--- a/api/src/backend/tasks/tests/test_reports_nis2.py
+++ b/api/src/backend/tasks/tests/test_reports_nis2.py
@@ -2,9 +2,11 @@ import io
from unittest.mock import Mock, patch
import pytest
-from reportlab.platypus import PageBreak, Paragraph, Table
+from reportlab.platypus import Image, PageBreak, Paragraph, Table
from tasks.jobs.reports import FRAMEWORK_REGISTRY, ComplianceData, RequirementData
+from tasks.jobs.reports import nis2 as nis2_report_module
from tasks.jobs.reports.nis2 import NIS2ReportGenerator, _extract_section_number
+from tasks.tests.report_test_helpers import patch_chart_helpers
# Use string status values directly to avoid Django DB initialization
@@ -29,6 +31,13 @@ def nis2_generator():
return NIS2ReportGenerator(config)
+@pytest.fixture
+def patched_nis2_charts(monkeypatch):
+ return patch_chart_helpers(
+ monkeypatch, nis2_report_module, ("create_horizontal_bar_chart",)
+ )
+
+
@pytest.fixture
def mock_nis2_requirement_attribute_section1():
"""Create a mock NIS2 requirement attribute for Section 1."""
@@ -380,7 +389,7 @@ class TestNIS2ChartsSection:
"""Test suite for NIS2 charts section generation."""
def test_charts_section_has_section_chart_title(
- self, nis2_generator, basic_nis2_compliance_data
+ self, nis2_generator, basic_nis2_compliance_data, patched_nis2_charts
):
"""Test that charts section has section compliance title."""
basic_nis2_compliance_data.requirements = []
@@ -391,9 +400,14 @@ class TestNIS2ChartsSection:
paragraphs = [e for e in elements if isinstance(e, Paragraph)]
content = " ".join(str(p.text) for p in paragraphs)
assert "Section" in content or "Compliance" in content
+ assert any(isinstance(e, Image) for e in elements)
+ chart_kwargs = patched_nis2_charts["create_horizontal_bar_chart"][0]["kwargs"]
+ assert chart_kwargs["labels"] == []
+ assert chart_kwargs["values"] == []
+ assert chart_kwargs["xlabel"] == "Compliance (%)"
def test_charts_section_has_page_break(
- self, nis2_generator, basic_nis2_compliance_data
+ self, nis2_generator, basic_nis2_compliance_data, patched_nis2_charts
):
"""Test that charts section has page breaks."""
basic_nis2_compliance_data.requirements = []
@@ -403,12 +417,14 @@ class TestNIS2ChartsSection:
page_breaks = [e for e in elements if isinstance(e, PageBreak)]
assert len(page_breaks) >= 1
+ assert len(patched_nis2_charts["create_horizontal_bar_chart"]) == 1
def test_charts_section_has_subsection_breakdown(
self,
nis2_generator,
basic_nis2_compliance_data,
mock_nis2_requirement_attribute_section1,
+ patched_nis2_charts,
):
"""Test that charts section includes subsection breakdown table."""
basic_nis2_compliance_data.requirements = [
@@ -434,6 +450,11 @@ class TestNIS2ChartsSection:
paragraphs = [e for e in elements if isinstance(e, Paragraph)]
content = " ".join(str(p.text) for p in paragraphs)
assert "SubSection" in content or "Breakdown" in content
+ assert any(isinstance(e, Image) for e in elements)
+ chart_kwargs = patched_nis2_charts["create_horizontal_bar_chart"][0]["kwargs"]
+ assert chart_kwargs["labels"] == ["1. Policy on Security"]
+ assert chart_kwargs["values"] == [100.0]
+ assert chart_kwargs["color_func"]
# =============================================================================
@@ -449,6 +470,7 @@ class TestNIS2SectionChart:
nis2_generator,
basic_nis2_compliance_data,
mock_nis2_requirement_attribute_section1,
+ patched_nis2_charts,
):
"""Test that section chart is created successfully."""
basic_nis2_compliance_data.requirements = [
@@ -473,12 +495,17 @@ class TestNIS2SectionChart:
assert isinstance(chart_buffer, io.BytesIO)
assert chart_buffer.getvalue() # Not empty
+ chart_kwargs = patched_nis2_charts["create_horizontal_bar_chart"][0]["kwargs"]
+ assert chart_kwargs["labels"] == ["1. Policy on Security"]
+ assert chart_kwargs["values"] == [100.0]
+ assert chart_kwargs["xlabel"] == "Compliance (%)"
def test_section_chart_excludes_manual(
self,
nis2_generator,
basic_nis2_compliance_data,
mock_nis2_requirement_attribute_section1,
+ patched_nis2_charts,
):
"""Test that manual requirements are excluded from section chart."""
basic_nis2_compliance_data.requirements = [
@@ -515,6 +542,9 @@ class TestNIS2SectionChart:
# Should not raise any errors
chart_buffer = nis2_generator._create_section_chart(basic_nis2_compliance_data)
assert isinstance(chart_buffer, io.BytesIO)
+ chart_kwargs = patched_nis2_charts["create_horizontal_bar_chart"][0]["kwargs"]
+ assert chart_kwargs["labels"] == ["1. Policy on Security"]
+ assert chart_kwargs["values"] == [100.0]
def test_section_chart_multiple_sections(
self,
@@ -523,6 +553,7 @@ class TestNIS2SectionChart:
mock_nis2_requirement_attribute_section1,
mock_nis2_requirement_attribute_section2,
mock_nis2_requirement_attribute_section11,
+ patched_nis2_charts,
):
"""Test section chart with multiple sections."""
basic_nis2_compliance_data.requirements = [
@@ -571,6 +602,13 @@ class TestNIS2SectionChart:
chart_buffer = nis2_generator._create_section_chart(basic_nis2_compliance_data)
assert isinstance(chart_buffer, io.BytesIO)
+ chart_kwargs = patched_nis2_charts["create_horizontal_bar_chart"][0]["kwargs"]
+ assert chart_kwargs["labels"] == [
+ "1. Policy on Security",
+ "2. Risk Management",
+ "11. Access Control",
+ ]
+ assert chart_kwargs["values"] == [100.0, 0.0, 100.0]
# =============================================================================
diff --git a/api/src/backend/tasks/tests/test_reports_provider_metadata.py b/api/src/backend/tasks/tests/test_reports_provider_metadata.py
new file mode 100644
index 0000000000..6fe1c32255
--- /dev/null
+++ b/api/src/backend/tasks/tests/test_reports_provider_metadata.py
@@ -0,0 +1,193 @@
+"""Tests for the credential-free provider metadata stub (PROWLER-2145).
+
+Every provider object used here is a plain ``SimpleNamespace`` WITHOUT a
+``secret`` attribute: any code path trying to read ``provider.secret`` (the
+coupling these tests guard against) would raise ``AttributeError`` and fail
+the test. No database is required.
+"""
+
+from types import SimpleNamespace
+
+import pytest
+from api.models import Provider
+from prowler.lib.outputs.finding import Finding as FindingOutput
+from prowler.providers.github.models import GithubIdentityInfo
+from tasks.jobs.reports import build_provider_metadata
+
+PROVIDER_UID = "provider-uid-123"
+PROVIDER_ALIAS = "my-provider-alias"
+
+
+def _provider_row(provider_type: str, alias: str | None = PROVIDER_ALIAS):
+ """Mimic the Provider DB row attributes read by build_provider_metadata."""
+ return SimpleNamespace(provider=provider_type, uid=PROVIDER_UID, alias=alias)
+
+
+class TestBuildProviderMetadata:
+ @pytest.mark.parametrize("provider_type", Provider.ProviderChoices.values)
+ def test_every_provider_type_gets_safe_defaults(self, provider_type):
+ stub = build_provider_metadata(_provider_row(provider_type))
+
+ assert stub.type == provider_type
+ assert isinstance(stub.auth_method, str)
+ assert hasattr(stub, "identity")
+
+ def test_aws_identity_account_is_uid(self):
+ stub = build_provider_metadata(_provider_row("aws"))
+ assert stub.identity.account == PROVIDER_UID
+
+ def test_azure_identity_covers_generate_output_accesses(self):
+ stub = build_provider_metadata(_provider_row("azure"))
+
+ # generate_output indexes tenant_ids[0] and reads these directly.
+ assert stub.identity.tenant_ids
+ assert stub.identity.identity_type == ""
+ assert stub.identity.identity_id == ""
+ assert stub.identity.subscriptions == {PROVIDER_UID: PROVIDER_ALIAS}
+
+ def test_gcp_projects_keyed_by_uid(self):
+ stub = build_provider_metadata(_provider_row("gcp"))
+
+ project = stub.projects[PROVIDER_UID]
+ assert project.id == PROVIDER_UID
+ assert project.name == PROVIDER_ALIAS
+ assert project.labels == {}
+ # generate_output calls getattr(project, "organization") without a
+ # default, so the attribute must exist (None skips the org branch).
+ assert project.organization is None
+
+ def test_kubernetes_identity_context_and_cluster(self):
+ stub = build_provider_metadata(_provider_row("kubernetes"))
+ assert stub.identity.context == PROVIDER_UID
+ assert stub.identity.cluster == PROVIDER_UID
+
+ def test_github_identity_is_real_identity_info(self):
+ # generate_output only assigns account fields inside
+ # isinstance(identity, Github*IdentityInfo) branches.
+ stub = build_provider_metadata(_provider_row("github"))
+ assert isinstance(stub.identity, GithubIdentityInfo)
+ assert stub.identity.account_id == PROVIDER_UID
+ assert stub.identity.account_name == PROVIDER_ALIAS
+
+ def test_iac_provider_uid(self):
+ stub = build_provider_metadata(_provider_row("iac"))
+ assert stub.provider_uid == PROVIDER_UID
+
+ def test_alias_falls_back_to_uid(self):
+ stub = build_provider_metadata(_provider_row("azure", alias=None))
+ assert stub.identity.subscriptions == {PROVIDER_UID: PROVIDER_UID}
+
+
+def _check_metadata_dict(provider_type: str, check_id: str) -> dict:
+ return {
+ "provider": provider_type,
+ "checkid": check_id,
+ "checktitle": "Test check title",
+ "checktype": [],
+ # CheckMetadata validates ServiceName == check_id.split("_")[0]
+ "servicename": check_id.split("_")[0],
+ "subservicename": "",
+ "severity": "high",
+ "resourcetype": "resource-type",
+ "description": "",
+ "risk": "",
+ "relatedurl": "",
+ "remediation": {
+ "recommendation": {"text": "", "url": ""},
+ "code": {"nativeiac": "", "terraform": "", "cli": "", "other": ""},
+ },
+ "resourceidtemplate": "",
+ "categories": [],
+ "dependson": [],
+ "relatedto": [],
+ "notes": "",
+ }
+
+
+class _FakeFinding:
+ """Attribute-faithful Finding stand-in.
+
+ A plain object instead of ``Mock``: only the attributes the Django model
+ exposes exist, so any new provider-attribute read in generate_output
+ (e.g. cloudflare's ``getattr(finding, "account_id", ...)``) hits the
+ same missing-attribute path it would hit in production instead of being
+ masked by Mock auto-created attributes.
+ """
+
+
+def _finding_model(provider_type: str, check_id: str, region: str):
+ """Mimic the Django Finding row attributes read by transform_api_finding."""
+ resource = SimpleNamespace(
+ uid="resource-uid",
+ name="resource-name",
+ metadata="{}",
+ details="",
+ region=region,
+ tags=SimpleNamespace(all=lambda: []),
+ )
+ finding = _FakeFinding()
+ finding.resources = SimpleNamespace(first=lambda: resource)
+ finding.check_metadata = _check_metadata_dict(provider_type, check_id)
+ finding.status = "FAIL"
+ finding.status_extended = "failed for testing"
+ finding.muted = False
+ return finding
+
+
+_FINDING_REGION = "region-x"
+
+# Expected (account_uid, region) of the transformed finding per provider
+# type, with resource.region = _FINDING_REGION. Keyed by every
+# Provider.ProviderChoices value so that adding a new provider type without
+# extending build_provider_metadata (and this table) fails the test below
+# instead of breaking PDF generation at runtime.
+_EXPECTED_TRANSFORM = {
+ "aws": (PROVIDER_UID, _FINDING_REGION),
+ "azure": (PROVIDER_UID, _FINDING_REGION),
+ "gcp": (PROVIDER_UID, _FINDING_REGION),
+ # transform_api_finding strips the "namespace: " prefix and
+ # generate_output re-adds it.
+ "kubernetes": (PROVIDER_UID, f"namespace: {_FINDING_REGION}"),
+ "m365": (PROVIDER_UID, _FINDING_REGION),
+ # For GitHub the owner comes from resource.region.
+ "github": (_FINDING_REGION, _FINDING_REGION),
+ "mongodbatlas": (PROVIDER_UID, _FINDING_REGION),
+ "iac": (PROVIDER_UID, _FINDING_REGION),
+ "oraclecloud": (PROVIDER_UID, _FINDING_REGION),
+ "alibabacloud": (PROVIDER_UID, _FINDING_REGION),
+ # Cloudflare uses the zone name (falls back to resource.name) as region.
+ "cloudflare": (PROVIDER_UID, "resource-name"),
+ "openstack": (PROVIDER_UID, _FINDING_REGION),
+ "image": ("image", _FINDING_REGION),
+ "googleworkspace": (PROVIDER_UID, _FINDING_REGION),
+ "vercel": (PROVIDER_UID, "global"),
+ "okta": (PROVIDER_UID, "global"),
+}
+
+
+class TestTransformApiFindingWithMetadataStub:
+ """transform_api_finding must work end-to-end with the stub — i.e.
+ without a credentialed SDK provider — for EVERY API provider type."""
+
+ @pytest.mark.parametrize("provider_type", Provider.ProviderChoices.values)
+ def test_transform_with_stub(self, provider_type):
+ assert provider_type in _EXPECTED_TRANSFORM, (
+ f"New provider type {provider_type!r}: add a branch to "
+ f"build_provider_metadata covering the attributes read by "
+ f"FindingOutput.generate_output, then add its expected "
+ f"(account_uid, region) here."
+ )
+ expected_account_uid, expected_region = _EXPECTED_TRANSFORM[provider_type]
+
+ stub = build_provider_metadata(_provider_row(provider_type))
+ check_id = f"{provider_type}_test_check"
+ finding_model = _finding_model(provider_type, check_id, _FINDING_REGION)
+
+ output = FindingOutput.transform_api_finding(finding_model, stub)
+
+ assert output.check_id == check_id
+ assert output.status == "FAIL"
+ assert output.account_uid == expected_account_uid
+ assert output.region == expected_region
+ assert output.resource_name
+ assert output.resource_uid
diff --git a/api/src/backend/tasks/tests/test_reports_threatscore.py b/api/src/backend/tasks/tests/test_reports_threatscore.py
index 07dd654a05..570a437eb3 100644
--- a/api/src/backend/tasks/tests/test_reports_threatscore.py
+++ b/api/src/backend/tasks/tests/test_reports_threatscore.py
@@ -10,6 +10,8 @@ from tasks.jobs.reports import (
RequirementData,
ThreatScoreReportGenerator,
)
+from tasks.jobs.reports import threatscore as threatscore_report_module
+from tasks.tests.report_test_helpers import patch_chart_helpers
# =============================================================================
# Fixtures
@@ -23,6 +25,13 @@ def threatscore_generator():
return ThreatScoreReportGenerator(config)
+@pytest.fixture
+def patched_threatscore_charts(monkeypatch):
+ return patch_chart_helpers(
+ monkeypatch, threatscore_report_module, ("create_vertical_bar_chart",)
+ )
+
+
@pytest.fixture
def mock_requirement_attribute():
"""Create a mock requirement attribute with numeric values."""
@@ -677,7 +686,7 @@ class TestSectionScoreChart:
"""Test suite for section score chart generation."""
def test_create_section_chart_empty_data(
- self, threatscore_generator, basic_compliance_data
+ self, threatscore_generator, basic_compliance_data, patched_threatscore_charts
):
"""Test chart creation with no requirements."""
basic_compliance_data.requirements = []
@@ -689,9 +698,22 @@ class TestSectionScoreChart:
assert isinstance(result, io.BytesIO)
assert result.getvalue() # Should have content
+ chart_kwargs = patched_threatscore_charts["create_vertical_bar_chart"][0][
+ "kwargs"
+ ]
+ assert chart_kwargs["labels"] == []
+ assert chart_kwargs["values"] == []
+ assert chart_kwargs["ylabel"] == "Compliance Score (%)"
+ assert chart_kwargs["xlabel"] == ""
+ assert chart_kwargs["color_func"]
+ assert chart_kwargs["rotation"] == 0
def test_create_section_chart_single_section(
- self, threatscore_generator, basic_compliance_data, mock_requirement_attribute
+ self,
+ threatscore_generator,
+ basic_compliance_data,
+ mock_requirement_attribute,
+ patched_threatscore_charts,
):
"""Test chart creation with a single section."""
basic_compliance_data.requirements = [
@@ -713,9 +735,14 @@ class TestSectionScoreChart:
)
assert isinstance(result, io.BytesIO)
+ chart_kwargs = patched_threatscore_charts["create_vertical_bar_chart"][0][
+ "kwargs"
+ ]
+ assert chart_kwargs["labels"] == ["1. IAM"]
+ assert chart_kwargs["values"] == [100.0]
def test_create_section_chart_multiple_sections(
- self, threatscore_generator, basic_compliance_data
+ self, threatscore_generator, basic_compliance_data, patched_threatscore_charts
):
"""Test chart creation with multiple sections."""
mock_attr_1 = Mock()
@@ -756,9 +783,14 @@ class TestSectionScoreChart:
)
assert isinstance(result, io.BytesIO)
+ chart_kwargs = patched_threatscore_charts["create_vertical_bar_chart"][0][
+ "kwargs"
+ ]
+ assert chart_kwargs["labels"] == ["1. IAM", "2. Attack Surface"]
+ assert chart_kwargs["values"] == [100.0, 50.0]
def test_create_section_chart_no_findings_section_gets_100(
- self, threatscore_generator, basic_compliance_data
+ self, threatscore_generator, basic_compliance_data, patched_threatscore_charts
):
"""Test that sections without findings get 100% score."""
mock_attr = Mock()
@@ -786,6 +818,11 @@ class TestSectionScoreChart:
)
assert isinstance(result, io.BytesIO)
+ chart_kwargs = patched_threatscore_charts["create_vertical_bar_chart"][0][
+ "kwargs"
+ ]
+ assert chart_kwargs["labels"] == ["1. IAM"]
+ assert chart_kwargs["values"] == [100.0]
# =============================================================================
@@ -797,7 +834,11 @@ class TestExecutiveSummary:
"""Test suite for executive summary generation."""
def test_executive_summary_contains_chart(
- self, threatscore_generator, basic_compliance_data, mock_requirement_attribute
+ self,
+ threatscore_generator,
+ basic_compliance_data,
+ mock_requirement_attribute,
+ patched_threatscore_charts,
):
"""Test that executive summary contains a chart."""
basic_compliance_data.requirements = [
@@ -818,9 +859,18 @@ class TestExecutiveSummary:
assert len(elements) > 0
assert any(isinstance(e, Image) for e in elements)
+ chart_kwargs = patched_threatscore_charts["create_vertical_bar_chart"][0][
+ "kwargs"
+ ]
+ assert chart_kwargs["labels"] == ["1. IAM"]
+ assert chart_kwargs["values"] == [100.0]
def test_executive_summary_contains_score_table(
- self, threatscore_generator, basic_compliance_data, mock_requirement_attribute
+ self,
+ threatscore_generator,
+ basic_compliance_data,
+ mock_requirement_attribute,
+ patched_threatscore_charts,
):
"""Test that executive summary contains a score table."""
basic_compliance_data.requirements = [
diff --git a/api/src/backend/tasks/tests/test_scan.py b/api/src/backend/tasks/tests/test_scan.py
index 17b3b65fc4..2a66985276 100644
--- a/api/src/backend/tasks/tests/test_scan.py
+++ b/api/src/backend/tasks/tests/test_scan.py
@@ -9,7 +9,7 @@ from unittest.mock import MagicMock, patch
import pytest
from api.db_router import MainRouter
-from api.exceptions import ProviderConnectionError
+from api.exceptions import ProviderConnectionError, ProviderDeletedException
from api.models import (
Finding,
MuteRule,
@@ -21,11 +21,13 @@ from api.models import (
StateChoices,
StatusChoices,
)
+from django.db import IntegrityError, OperationalError
from prowler.lib.check.models import Severity
from prowler.lib.outputs.finding import Status
from tasks.jobs.scan import (
_ATTACK_SURFACE_MAPPING_CACHE,
_aggregate_findings_by_region,
+ _bulk_update_resource_failed_findings_counts,
_copy_compliance_requirement_rows,
_create_compliance_summaries,
_create_finding_delta,
@@ -74,7 +76,7 @@ class TestPerformScan:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
with (
patch("api.db_utils.rls_transaction"),
@@ -132,7 +134,7 @@ class TestPerformScan:
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
# Ensure the provider type is 'aws' to match our mocks
provider.provider = Provider.ProviderChoices.AWS
@@ -241,11 +243,11 @@ class TestPerformScan:
mock_prowler_scan_class,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
tenant_id = str(tenant.id)
scan_id = str(scan.id)
@@ -262,6 +264,75 @@ class TestPerformScan:
assert provider.connected is False
assert isinstance(provider.connection_last_checked_at, datetime)
+ def test_perform_prowler_scan_provider_deleted_during_progress_update(
+ self,
+ tenants_fixture,
+ scans_fixture,
+ aws_provider,
+ ):
+ tenant = tenants_fixture[0]
+ scan = scans_fixture[0]
+ provider = aws_provider
+
+ tenant_id = str(tenant.id)
+ scan_id = str(scan.id)
+ provider_id = str(provider.id)
+
+ def scan_results():
+ Provider.objects.filter(pk=provider_id).delete()
+ yield 50, []
+
+ with (
+ patch(
+ "tasks.jobs.scan.initialize_prowler_provider",
+ return_value=MagicMock(),
+ ),
+ patch("tasks.jobs.scan.ProwlerScan") as mock_prowler_scan_class,
+ patch("tasks.jobs.scan.logger.error") as mock_logger_error,
+ ):
+ mock_prowler_scan_instance = MagicMock()
+ mock_prowler_scan_instance.scan.return_value = scan_results()
+ mock_prowler_scan_class.return_value = mock_prowler_scan_instance
+
+ with pytest.raises(ProviderDeletedException):
+ perform_prowler_scan(tenant_id, scan_id, provider_id, [])
+
+ mock_logger_error.assert_not_called()
+ assert not Scan.objects.filter(pk=scan_id).exists()
+
+ def test_perform_prowler_scan_sets_final_progress_when_progress_updates_are_throttled(
+ self,
+ tenants_fixture,
+ scans_fixture,
+ aws_provider,
+ ):
+ tenant = tenants_fixture[0]
+ scan = scans_fixture[0]
+ provider = aws_provider
+
+ tenant_id = str(tenant.id)
+ scan_id = str(scan.id)
+ provider_id = str(provider.id)
+
+ with (
+ patch(
+ "tasks.jobs.scan.initialize_prowler_provider",
+ return_value=MagicMock(),
+ ),
+ patch("tasks.jobs.scan.ProwlerScan") as mock_prowler_scan_class,
+ patch("tasks.jobs.scan.PROGRESS_THROTTLE_DELTA", 200),
+ patch("tasks.jobs.scan.PROGRESS_THROTTLE_SECONDS", 3600),
+ ):
+ mock_prowler_scan_instance = MagicMock()
+ mock_prowler_scan_instance.scan.return_value = [(99, []), (100, [])]
+ mock_prowler_scan_class.return_value = mock_prowler_scan_instance
+
+ perform_prowler_scan(tenant_id, scan_id, provider_id, [])
+
+ scan.refresh_from_db()
+ assert scan.state == StateChoices.COMPLETED
+ assert scan.progress == 100
+
@pytest.mark.parametrize(
"last_status, new_status, expected_delta",
[
@@ -440,7 +511,7 @@ class TestPerformScan:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
"""Test that failed findings increment the failed_findings_count"""
with (
@@ -461,7 +532,7 @@ class TestPerformScan:
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
# Ensure the provider type is 'aws'
provider.provider = Provider.ProviderChoices.AWS
@@ -518,7 +589,7 @@ class TestPerformScan:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
"""Test that multiple FAIL findings on the same resource increment the counter correctly"""
with (
@@ -535,7 +606,7 @@ class TestPerformScan:
):
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
provider.provider = Provider.ProviderChoices.AWS
provider.save()
@@ -635,7 +706,7 @@ class TestPerformScan:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
"""Test that muted FAIL findings do not increment the failed_findings_count"""
with (
@@ -652,7 +723,7 @@ class TestPerformScan:
):
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
provider.provider = Provider.ProviderChoices.AWS
provider.save()
@@ -706,13 +777,13 @@ class TestPerformScan:
def test_perform_prowler_scan_reset_failed_findings_count(
self,
tenants_fixture,
- providers_fixture,
+ aws_provider,
resources_fixture,
):
"""Test that failed_findings_count is reset to 0 at the beginning of each scan"""
# Use existing resource from fixture and set initial failed_findings_count
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
resource = resources_fixture[0]
# Set a non-zero failed_findings_count initially
@@ -789,11 +860,103 @@ class TestPerformScan:
# Assert that failed_findings_count was reset to 0 during the scan
assert resource.failed_findings_count == 0
+ def test_failed_findings_count_update_retries_deadlock_in_stable_order(
+ self, resources_fixture, monkeypatch
+ ):
+ resource1, resource2, _ = resources_fixture
+ tenant_id = str(resource1.tenant_id)
+ resource1.failed_findings_count = 2
+ resource2.failed_findings_count = 3
+ resources_to_update = [resource2, resource1]
+ expected_order = [
+ str(resource.id)
+ for resource in sorted(resources_to_update, key=lambda item: str(item.id))
+ ]
+ original_bulk_update = Resource.objects.bulk_update
+ bulk_update_calls = []
+
+ def flaky_bulk_update(objects, fields, batch_size=None):
+ bulk_update_calls.append([str(obj.id) for obj in objects])
+ if len(bulk_update_calls) == 1:
+ raise OperationalError("deadlock detected")
+ return original_bulk_update(objects, fields, batch_size=batch_size)
+
+ monkeypatch.setattr("tasks.jobs.scan.SCAN_DB_BATCH_SIZE", 10)
+ monkeypatch.setattr(Resource.objects, "bulk_update", flaky_bulk_update)
+
+ _bulk_update_resource_failed_findings_counts(
+ tenant_id=tenant_id,
+ scan_id="scan-id",
+ resources_to_update=resources_to_update,
+ )
+
+ resource1.refresh_from_db()
+ resource2.refresh_from_db()
+ assert resource1.failed_findings_count == 2
+ assert resource2.failed_findings_count == 3
+ assert bulk_update_calls == [expected_order, expected_order]
+
+ def test_failed_findings_count_update_does_not_retry_integrity_error(
+ self, resources_fixture, monkeypatch
+ ):
+ resource, *_ = resources_fixture
+ resource.failed_findings_count = 2
+ bulk_update_calls = []
+ sleep_calls = []
+
+ def failing_bulk_update(objects, fields, batch_size=None):
+ bulk_update_calls.append([str(obj.id) for obj in objects])
+ raise IntegrityError("constraint violation")
+
+ monkeypatch.setattr(Resource.objects, "bulk_update", failing_bulk_update)
+ monkeypatch.setattr("tasks.jobs.scan.time.sleep", sleep_calls.append)
+
+ with pytest.raises(IntegrityError, match="constraint violation"):
+ _bulk_update_resource_failed_findings_counts(
+ tenant_id=str(resource.tenant_id),
+ scan_id="scan-id",
+ resources_to_update=[resource],
+ )
+
+ assert len(bulk_update_calls) == 1
+ assert sleep_calls == []
+
+ def test_failed_findings_count_update_adds_jitter_to_retry_backoff(
+ self, resources_fixture, monkeypatch
+ ):
+ from tasks.jobs import scan as scan_jobs
+
+ resource, *_ = resources_fixture
+ resource.failed_findings_count = 2
+ bulk_update_calls = []
+ sleep_calls = []
+ original_bulk_update = Resource.objects.bulk_update
+
+ def flaky_bulk_update(objects, fields, batch_size=None):
+ bulk_update_calls.append([str(obj.id) for obj in objects])
+ if len(bulk_update_calls) == 1:
+ raise OperationalError("deadlock detected")
+ return original_bulk_update(objects, fields, batch_size=batch_size)
+
+ monkeypatch.setattr(Resource.objects, "bulk_update", flaky_bulk_update)
+ monkeypatch.setattr(scan_jobs, "random", MagicMock())
+ scan_jobs.random.uniform.return_value = 0.037
+ monkeypatch.setattr("tasks.jobs.scan.time.sleep", sleep_calls.append)
+
+ _bulk_update_resource_failed_findings_counts(
+ tenant_id=str(resource.tenant_id),
+ scan_id="scan-id",
+ resources_to_update=[resource],
+ )
+
+ scan_jobs.random.uniform.assert_called_once_with(0, 0.1)
+ assert sleep_calls == [0.137]
+
def test_perform_prowler_scan_with_active_mute_rules(
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
"""Test active MuteRule mutes findings with correct reason"""
with (
@@ -810,7 +973,7 @@ class TestPerformScan:
):
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
provider.provider = Provider.ProviderChoices.AWS
provider.save()
@@ -910,7 +1073,7 @@ class TestPerformScan:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
"""Test inactive MuteRule does not mute findings"""
with (
@@ -927,7 +1090,7 @@ class TestPerformScan:
):
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
provider.provider = Provider.ProviderChoices.AWS
provider.save()
@@ -996,7 +1159,7 @@ class TestPerformScan:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
"""Test mutelist processor takes precedence over MuteRule"""
with (
@@ -1013,7 +1176,7 @@ class TestPerformScan:
):
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
provider.provider = Provider.ProviderChoices.AWS
provider.save()
@@ -1082,7 +1245,7 @@ class TestPerformScan:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
"""Test MuteRule with multiple finding UIDs mutes all findings"""
with (
@@ -1099,7 +1262,7 @@ class TestPerformScan:
):
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
provider.provider = Provider.ProviderChoices.AWS
provider.save()
@@ -1181,7 +1344,7 @@ class TestPerformScan:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
"""Test scan continues when MuteRule loading fails"""
with (
@@ -1199,7 +1362,7 @@ class TestPerformScan:
):
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
provider.provider = Provider.ProviderChoices.AWS
provider.save()
@@ -1264,7 +1427,7 @@ class TestPerformScan:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
):
"""Test muted_at timestamp is set correctly for muted findings"""
with (
@@ -1281,7 +1444,7 @@ class TestPerformScan:
):
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
provider.provider = Provider.ProviderChoices.AWS
provider.save()
@@ -1868,7 +2031,7 @@ class TestCreateComplianceRequirements:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
findings_fixture,
resources_fixture,
):
@@ -1919,7 +2082,7 @@ class TestCreateComplianceRequirements:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
findings_fixture,
):
with patch(
@@ -1957,7 +2120,7 @@ class TestCreateComplianceRequirements:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
findings_fixture,
):
"""Re-running compliance materialization must not raise nor duplicate rows.
@@ -2012,7 +2175,7 @@ class TestCreateComplianceRequirements:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
findings_fixture,
):
with patch(
@@ -2020,7 +2183,7 @@ class TestCreateComplianceRequirements:
) as mock_compliance_template:
tenant = tenants_fixture[0]
scan = scans_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
provider.provider = Provider.ProviderChoices.KUBERNETES
provider.save()
@@ -2058,7 +2221,7 @@ class TestCreateComplianceRequirements:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
findings_fixture,
):
with patch(
@@ -2077,7 +2240,7 @@ class TestCreateComplianceRequirements:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
findings_fixture,
):
with patch("tasks.jobs.scan.return_prowler_provider") as mock_prowler_provider:
@@ -2161,7 +2324,7 @@ class TestCreateComplianceRequirements:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
findings_fixture,
):
with patch(
@@ -2199,7 +2362,7 @@ class TestCreateComplianceRequirements:
self,
tenants_fixture,
scans_fixture,
- providers_fixture,
+ aws_provider,
findings_fixture,
):
with patch(
@@ -3489,6 +3652,95 @@ class TestAggregateFindings:
regions = {s.region for s in summaries}
assert regions == {"us-east-1", "us-west-2"}
+ @patch("tasks.jobs.scan.Finding.objects.filter")
+ @patch("tasks.jobs.scan.ScanSummary.objects.bulk_create")
+ @patch("tasks.jobs.scan.rls_transaction")
+ def test_aggregate_findings_orders_upserts_by_conflict_key(
+ self, mock_rls_transaction, mock_bulk_create, mock_findings_filter
+ ):
+ """Scan summaries must use a stable lock order for concurrent upserts."""
+ tenant_id = str(uuid.uuid4())
+ scan_id = str(uuid.uuid4())
+ counts = {
+ "fail": 1,
+ "_pass": 0,
+ "muted_count": 0,
+ "total": 1,
+ "new": 1,
+ "changed": 0,
+ "unchanged": 0,
+ "fail_new": 1,
+ "fail_changed": 0,
+ "pass_new": 0,
+ "pass_changed": 0,
+ "muted_new": 0,
+ "muted_changed": 0,
+ }
+
+ mock_queryset = MagicMock()
+ mock_queryset.values.return_value = mock_queryset
+ mock_queryset.annotate.return_value = [
+ {
+ "check_id": "check-b",
+ "resources__service": "s3",
+ "severity": "high",
+ "resources__region": "us-east-1",
+ **counts,
+ },
+ {
+ "check_id": "check-a",
+ "resources__service": "sqs",
+ "severity": "high",
+ "resources__region": "us-east-1",
+ **counts,
+ },
+ {
+ "check_id": "check-a",
+ "resources__service": "s3",
+ "severity": "medium",
+ "resources__region": "us-east-1",
+ **counts,
+ },
+ {
+ "check_id": "check-a",
+ "resources__service": "s3",
+ "severity": "high",
+ "resources__region": "us-west-2",
+ **counts,
+ },
+ {
+ "check_id": "check-a",
+ "resources__service": "s3",
+ "severity": "high",
+ "resources__region": "us-east-1",
+ **counts,
+ },
+ ]
+
+ ctx = MagicMock()
+ ctx.__enter__.return_value = None
+ ctx.__exit__.return_value = False
+ mock_rls_transaction.return_value = ctx
+ mock_findings_filter.return_value = mock_queryset
+
+ aggregate_findings(tenant_id, scan_id)
+
+ summaries = mock_bulk_create.call_args.args[0]
+ assert isinstance(summaries, list)
+ conflict_keys = [
+ (
+ str(summary.tenant_id),
+ str(summary.scan_id),
+ summary.check_id,
+ summary.service,
+ summary.severity,
+ summary.region,
+ )
+ for summary in summaries
+ ]
+ assert len(conflict_keys) == 5
+ assert conflict_keys == sorted(conflict_keys)
+
@patch("tasks.jobs.scan.Finding.objects.filter")
@patch("tasks.jobs.scan.ScanSummary.objects.bulk_create")
@patch("tasks.jobs.scan.rls_transaction")
@@ -4526,7 +4778,7 @@ class TestUpdateProviderComplianceScores:
self,
mock_psycopg_connection,
tenants_fixture,
- providers_fixture,
+ aws_provider,
scans_fixture,
settings,
):
@@ -4634,7 +4886,7 @@ class TestResetEphemeralResourceFindingsCount:
)
def test_resets_only_resources_missing_from_full_scope_scan(
- self, tenants_fixture, scans_fixture, providers_fixture, resources_fixture
+ self, tenants_fixture, scans_fixture, aws_provider, resources_fixture
):
tenant, *_ = tenants_fixture
scan1, scan2, *_ = scans_fixture
@@ -4714,7 +4966,7 @@ class TestResetEphemeralResourceFindingsCount:
assert result["reason"] == "scan not found"
def test_skips_when_newer_scan_completed_for_same_provider(
- self, tenants_fixture, scans_fixture, providers_fixture, resources_fixture
+ self, tenants_fixture, scans_fixture, aws_provider, resources_fixture
):
# If a newer completed scan exists for the same provider, our
# ResourceScanSummary set is stale relative to the resources' current
@@ -4723,7 +4975,7 @@ class TestResetEphemeralResourceFindingsCount:
tenant, *_ = tenants_fixture
scan1, *_ = scans_fixture
- provider, *_ = providers_fixture
+ provider = aws_provider
_, resource2, _ = resources_fixture
Resource.objects.filter(id=resource2.id).update(failed_findings_count=5)
@@ -4753,7 +5005,7 @@ class TestResetEphemeralResourceFindingsCount:
assert resource2.failed_findings_count == 5
def test_does_not_touch_other_providers_resources(
- self, tenants_fixture, scans_fixture, providers_fixture, resources_fixture
+ self, tenants_fixture, scans_fixture, aws_provider, resources_fixture
):
tenant, *_ = tenants_fixture
scan1, *_ = scans_fixture
@@ -4819,14 +5071,14 @@ class TestResetEphemeralResourceFindingsCount:
assert resource2.failed_findings_count == 5
def test_ignores_sibling_scan_with_null_completed_at(
- self, tenants_fixture, scans_fixture, providers_fixture, resources_fixture
+ self, tenants_fixture, scans_fixture, aws_provider, resources_fixture
):
# Postgres orders NULL first in DESC; a sibling COMPLETED scan with a
# missing completed_at must not be treated as the latest scan and
# cause us to incorrectly skip the reset.
tenant, *_ = tenants_fixture
scan1, *_ = scans_fixture
- provider, *_ = providers_fixture
+ provider = aws_provider
resource1, resource2, _ = resources_fixture
Resource.objects.filter(id=resource2.id).update(failed_findings_count=5)
diff --git a/api/src/backend/tasks/tests/test_tasks.py b/api/src/backend/tasks/tests/test_tasks.py
index 95634e8a95..476444cb00 100644
--- a/api/src/backend/tasks/tests/test_tasks.py
+++ b/api/src/backend/tasks/tests/test_tasks.py
@@ -3,6 +3,7 @@ from contextlib import contextmanager
from datetime import UTC, datetime, timedelta
from unittest.mock import MagicMock, patch
+import httpx
import openai
import pytest
from api.models import (
@@ -14,11 +15,13 @@ from api.models import (
Task,
)
from botocore.exceptions import ClientError
+from celery import states
from django_celery_beat.models import IntervalSchedule, PeriodicTask
from django_celery_results.models import TaskResult
from tasks.jobs.lighthouse_providers import (
_create_bedrock_client,
_extract_bedrock_credentials,
+ _LighthouseOpenAICompatibleNetworkBackend,
)
from tasks.tasks import (
DJANGO_TMP_OUTPUT_DIRECTORY,
@@ -1565,7 +1568,7 @@ class TestCheckLighthouseProviderConnectionTask:
(
LighthouseProviderConfiguration.LLMProviderChoices.OPENAI_COMPATIBLE,
{"api_key": "sk-test123"},
- "https://openrouter.ai/api/v1",
+ "https://93.184.216.34/api/v1",
{"connected": True, "error": None},
),
(
@@ -1640,7 +1643,7 @@ class TestCheckLighthouseProviderConnectionTask:
(
LighthouseProviderConfiguration.LLMProviderChoices.OPENAI_COMPATIBLE,
{"api_key": "sk-invalid"},
- "https://openrouter.ai/api/v1",
+ "https://93.184.216.34/api/v1",
openai.APIConnectionError(request=MagicMock()),
),
(
@@ -1754,6 +1757,166 @@ class TestCheckLighthouseProviderConnectionTask:
provider_cfg.refresh_from_db()
assert provider_cfg.is_active is False
+ def test_openai_compatible_connection_rejects_metadata_base_url_without_request(
+ self, tenants_fixture
+ ):
+ provider_cfg = LighthouseProviderConfiguration(
+ tenant_id=tenants_fixture[0].id,
+ provider_type=LighthouseProviderConfiguration.LLMProviderChoices.OPENAI_COMPATIBLE,
+ base_url="https://169.254.169.254/latest/meta-data",
+ is_active=True,
+ )
+ provider_cfg.credentials_decoded = {"api_key": "compatible-key"}
+ provider_cfg.save()
+
+ with patch("tasks.jobs.lighthouse_providers.openai.OpenAI") as mock_openai:
+ eager_result = check_lighthouse_provider_connection_task.apply(
+ kwargs={
+ "provider_config_id": str(provider_cfg.id),
+ "tenant_id": str(tenants_fixture[0].id),
+ }
+ )
+
+ assert eager_result.successful()
+ result = eager_result.result
+ assert result["connected"] is False
+ assert "base url" in result["error"].lower()
+ mock_openai.assert_not_called()
+ provider_cfg.refresh_from_db()
+ assert provider_cfg.is_active is False
+
+ def test_openai_compatible_connection_disables_redirects(self, tenants_fixture):
+ provider_cfg = LighthouseProviderConfiguration(
+ tenant_id=tenants_fixture[0].id,
+ provider_type=LighthouseProviderConfiguration.LLMProviderChoices.OPENAI_COMPATIBLE,
+ base_url="https://93.184.216.34/api/v1",
+ is_active=False,
+ )
+ provider_cfg.credentials_decoded = {"api_key": "compatible-key"}
+ provider_cfg.save()
+
+ with patch("tasks.jobs.lighthouse_providers.openai.OpenAI") as mock_openai:
+ mock_client = MagicMock()
+ mock_client.models.list.return_value = MagicMock()
+ mock_openai.return_value = mock_client
+
+ eager_result = check_lighthouse_provider_connection_task.apply(
+ kwargs={
+ "provider_config_id": str(provider_cfg.id),
+ "tenant_id": str(tenants_fixture[0].id),
+ }
+ )
+
+ assert eager_result.successful()
+ result = eager_result.result
+ assert result == {"connected": True, "error": None}
+ http_client = mock_openai.call_args.kwargs["http_client"]
+ assert http_client.follow_redirects is False
+ assert http_client.trust_env is False
+
+ def test_openai_compatible_connection_masks_remote_http_error(
+ self, tenants_fixture
+ ):
+ provider_cfg = LighthouseProviderConfiguration(
+ tenant_id=tenants_fixture[0].id,
+ provider_type=LighthouseProviderConfiguration.LLMProviderChoices.OPENAI_COMPATIBLE,
+ base_url="https://93.184.216.34/api/v1",
+ is_active=True,
+ )
+ provider_cfg.credentials_decoded = {"api_key": "compatible-key"}
+ provider_cfg.save()
+ remote_body = "
"
+ response = httpx.Response(
+ 404,
+ request=httpx.Request("GET", "https://provider.example/v1/models"),
+ )
+
+ with patch("tasks.jobs.lighthouse_providers.openai.OpenAI") as mock_openai:
+ mock_client = MagicMock()
+ mock_client.models.list.side_effect = openai.NotFoundError(
+ remote_body,
+ response=response,
+ body=remote_body,
+ )
+ mock_openai.return_value = mock_client
+
+ eager_result = refresh_lighthouse_provider_models_task.apply(
+ kwargs={
+ "provider_config_id": str(provider_cfg.id),
+ "tenant_id": str(tenants_fixture[0].id),
+ }
+ )
+
+ assert eager_result.successful()
+ result = eager_result.result
+ assert result["created"] == 0
+ assert result["updated"] == 0
+ assert result["deleted"] == 0
+ assert result["error"] == "Provider connection failed"
+ assert remote_body not in result["error"]
+
def test_refresh_models_mixed_operations(self, tenants_fixture):
"""Test mixed create, update, and delete operations."""
# Create provider configuration
@@ -1963,11 +2226,11 @@ class TestCleanupOrphanScheduledScans:
)
def test_cleanup_deletes_orphan_when_both_available_and_scheduled_exist(
- self, tenants_fixture, providers_fixture
+ self, tenants_fixture, aws_provider
):
"""Test that AVAILABLE scan is deleted when SCHEDULED also exists."""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
periodic_task = self._create_periodic_task(provider.id, tenant.id)
# Create orphan AVAILABLE scan
@@ -2003,11 +2266,11 @@ class TestCleanupOrphanScheduledScans:
assert Scan.objects.filter(id=scheduled_scan.id).exists()
def test_cleanup_does_not_delete_when_only_available_exists(
- self, tenants_fixture, providers_fixture
+ self, tenants_fixture, aws_provider
):
"""Test that AVAILABLE scan is NOT deleted when no SCHEDULED exists."""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
periodic_task = self._create_periodic_task(provider.id, tenant.id)
# Create only AVAILABLE scan (normal first scan scenario)
@@ -2032,11 +2295,11 @@ class TestCleanupOrphanScheduledScans:
assert Scan.objects.filter(id=available_scan.id).exists()
def test_cleanup_does_not_delete_when_only_scheduled_exists(
- self, tenants_fixture, providers_fixture
+ self, tenants_fixture, aws_provider
):
"""Test that nothing is deleted when only SCHEDULED exists."""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
periodic_task = self._create_periodic_task(provider.id, tenant.id)
# Create only SCHEDULED scan (normal subsequent scan scenario)
@@ -2061,11 +2324,11 @@ class TestCleanupOrphanScheduledScans:
assert Scan.objects.filter(id=scheduled_scan.id).exists()
def test_cleanup_returns_zero_when_no_scans_exist(
- self, tenants_fixture, providers_fixture
+ self, tenants_fixture, aws_provider
):
"""Test that cleanup returns 0 when no scans exist."""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
periodic_task = self._create_periodic_task(provider.id, tenant.id)
# Execute cleanup with no scans
@@ -2078,11 +2341,11 @@ class TestCleanupOrphanScheduledScans:
assert deleted_count == 0
def test_cleanup_deletes_multiple_orphan_available_scans(
- self, tenants_fixture, providers_fixture
+ self, tenants_fixture, aws_provider
):
"""Test that multiple AVAILABLE orphan scans are all deleted."""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
periodic_task = self._create_periodic_task(provider.id, tenant.id)
# Create multiple orphan AVAILABLE scans
@@ -2127,12 +2390,11 @@ class TestCleanupOrphanScheduledScans:
assert Scan.objects.filter(id=scheduled_scan.id).exists()
def test_cleanup_does_not_affect_different_provider(
- self, tenants_fixture, providers_fixture
+ self, tenants_fixture, aws_provider_pair
):
"""Test that cleanup only affects scans for the specified provider."""
tenant = tenants_fixture[0]
- provider1 = providers_fixture[0]
- provider2 = providers_fixture[1]
+ provider1, provider2 = aws_provider_pair
periodic_task1 = self._create_periodic_task(provider1.id, tenant.id)
periodic_task2 = self._create_periodic_task(provider2.id, tenant.id)
@@ -2177,12 +2439,10 @@ class TestCleanupOrphanScheduledScans:
assert Scan.objects.filter(id=scheduled_scan_p1.id).exists()
assert Scan.objects.filter(id=available_scan_p2.id).exists()
- def test_cleanup_does_not_affect_manual_scans(
- self, tenants_fixture, providers_fixture
- ):
+ def test_cleanup_does_not_affect_manual_scans(self, tenants_fixture, aws_provider):
"""Test that cleanup only affects SCHEDULED trigger scans, not MANUAL."""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
periodic_task = self._create_periodic_task(provider.id, tenant.id)
# Create orphan AVAILABLE scheduled scan
@@ -2228,11 +2488,11 @@ class TestCleanupOrphanScheduledScans:
assert Scan.objects.filter(id=manual_scan.id).exists()
def test_cleanup_does_not_affect_different_scheduler_task(
- self, tenants_fixture, providers_fixture
+ self, tenants_fixture, aws_provider
):
"""Test that cleanup only affects scans with the specified scheduler_task_id."""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
periodic_task1 = self._create_periodic_task(provider.id, tenant.id)
# Create another periodic task
@@ -2286,6 +2546,51 @@ class TestCleanupOrphanScheduledScans:
assert Scan.objects.filter(id=scheduled_scan.id).exists()
assert Scan.objects.filter(id=available_scan_other_task.id).exists()
+ def test_cleanup_keeps_db_queued_scheduled_scans(
+ self, tenants_fixture, aws_provider
+ ):
+ """DB-queued scheduled scans have a task and must not be deleted as orphans."""
+ tenant = tenants_fixture[0]
+ provider = aws_provider
+ periodic_task = self._create_periodic_task(provider.id, tenant.id)
+ task_result = TaskResult.objects.create(
+ task_id=str(uuid.uuid4()),
+ task_name="scan-perform",
+ status="QUEUED",
+ )
+ queued_task = Task.objects.create(
+ id=task_result.task_id,
+ task_runner_task=task_result,
+ tenant_id=tenant.id,
+ )
+ queued_scan = Scan.objects.create(
+ tenant_id=tenant.id,
+ provider=provider,
+ name="Queued scheduled scan",
+ trigger=Scan.TriggerChoices.SCHEDULED,
+ state=StateChoices.AVAILABLE,
+ scheduler_task_id=periodic_task.id,
+ task=queued_task,
+ )
+ scheduled_scan = Scan.objects.create(
+ tenant_id=tenant.id,
+ provider=provider,
+ name="Daily scheduled scan",
+ trigger=Scan.TriggerChoices.SCHEDULED,
+ state=StateChoices.SCHEDULED,
+ scheduler_task_id=periodic_task.id,
+ )
+
+ deleted_count = _cleanup_orphan_scheduled_scans(
+ tenant_id=str(tenant.id),
+ provider_id=str(provider.id),
+ scheduler_task_id=periodic_task.id,
+ )
+
+ assert deleted_count == 0
+ assert Scan.objects.filter(id=queued_scan.id).exists()
+ assert Scan.objects.filter(id=scheduled_scan.id).exists()
+
@pytest.mark.django_db
class TestPerformScheduledScanTask:
@@ -2334,12 +2639,12 @@ class TestPerformScheduledScanTask:
)
return task_result
- def test_skip_when_scheduled_scan_executing(
- self, tenants_fixture, providers_fixture
+ def test_queues_scheduled_scan_when_scheduled_scan_is_executing(
+ self, tenants_fixture, aws_provider
):
- """Skip a scheduled run when another scheduled scan is already executing."""
+ """Queue a scheduled run when another scheduled scan is executing."""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
periodic_task = self._create_periodic_task(provider.id, tenant.id)
task_id = str(uuid.uuid4())
self._create_task_result(tenant.id, task_id)
@@ -2364,8 +2669,16 @@ class TestPerformScheduledScanTask:
mock_scan.assert_not_called()
mock_complete_tasks.assert_not_called()
- assert result["id"] == str(executing_scan.id)
- assert result["state"] == StateChoices.EXECUTING
+ assert result["id"] != str(executing_scan.id)
+ assert result["state"] == StateChoices.AVAILABLE
+ queued_scheduled_scan = Scan.objects.get(
+ tenant_id=tenant.id,
+ provider=provider,
+ trigger=Scan.TriggerChoices.SCHEDULED,
+ state=StateChoices.AVAILABLE,
+ )
+ assert result["id"] == str(queued_scheduled_scan.id)
+ assert queued_scheduled_scan.task.task_runner_task.status == "QUEUED"
assert (
Scan.objects.filter(
tenant_id=tenant.id,
@@ -2373,15 +2686,141 @@ class TestPerformScheduledScanTask:
trigger=Scan.TriggerChoices.SCHEDULED,
state=StateChoices.SCHEDULED,
).count()
- == 0
+ == 1
+ )
+
+ def test_queues_scheduled_scan_when_manual_scan_is_pending(
+ self, tenants_fixture, aws_provider
+ ):
+ """Queue one scheduled run when a manual scan is already dispatched."""
+ tenant = tenants_fixture[0]
+ provider = aws_provider
+ self._create_periodic_task(provider.id, tenant.id)
+ task_id = str(uuid.uuid4())
+ self._create_task_result(tenant.id, task_id)
+ manual_task_result = TaskResult.objects.create(
+ task_id=str(uuid.uuid4()),
+ task_name="scan-perform",
+ status=states.PENDING,
+ )
+ manual_task = Task.objects.create(
+ id=manual_task_result.task_id,
+ task_runner_task=manual_task_result,
+ tenant_id=tenant.id,
+ )
+ manual_scan = Scan.objects.create(
+ tenant_id=tenant.id,
+ provider=provider,
+ name="Manual scan",
+ trigger=Scan.TriggerChoices.MANUAL,
+ state=StateChoices.AVAILABLE,
+ task=manual_task,
+ )
+
+ with (
+ patch("tasks.tasks.perform_prowler_scan") as mock_scan,
+ patch("tasks.tasks._perform_scan_complete_tasks") as mock_complete_tasks,
+ self._override_task_request(perform_scheduled_scan_task, id=task_id),
+ ):
+ result = perform_scheduled_scan_task.run(
+ tenant_id=str(tenant.id), provider_id=str(provider.id)
+ )
+
+ mock_scan.assert_not_called()
+ mock_complete_tasks.assert_not_called()
+ assert result["id"] != str(manual_scan.id)
+ assert result["state"] == StateChoices.AVAILABLE
+ queued_scheduled_scan = Scan.objects.get(
+ tenant_id=tenant.id,
+ provider=provider,
+ trigger=Scan.TriggerChoices.SCHEDULED,
+ state=StateChoices.AVAILABLE,
+ )
+ assert result["id"] == str(queued_scheduled_scan.id)
+ assert queued_scheduled_scan.task.task_runner_task.status == "QUEUED"
+ scheduled_scan = Scan.objects.get(
+ tenant_id=tenant.id,
+ provider=provider,
+ trigger=Scan.TriggerChoices.SCHEDULED,
+ state=StateChoices.SCHEDULED,
+ )
+ assert scheduled_scan.scheduled_at > datetime.now(UTC)
+
+ def test_coalesces_scheduled_scan_when_one_is_already_queued(
+ self, tenants_fixture, aws_provider
+ ):
+ """Reuse the existing queued scheduled scan instead of adding another."""
+ tenant = tenants_fixture[0]
+ provider = aws_provider
+ periodic_task = self._create_periodic_task(provider.id, tenant.id)
+ task_id = str(uuid.uuid4())
+ self._create_task_result(tenant.id, task_id)
+ manual_task_result = TaskResult.objects.create(
+ task_id=str(uuid.uuid4()),
+ task_name="scan-perform",
+ status=states.PENDING,
+ )
+ manual_task = Task.objects.create(
+ id=manual_task_result.task_id,
+ task_runner_task=manual_task_result,
+ tenant_id=tenant.id,
+ )
+ Scan.objects.create(
+ tenant_id=tenant.id,
+ provider=provider,
+ name="Manual scan",
+ trigger=Scan.TriggerChoices.MANUAL,
+ state=StateChoices.AVAILABLE,
+ task=manual_task,
+ )
+ queued_task_result = TaskResult.objects.create(
+ task_id=str(uuid.uuid4()),
+ task_name="scan-perform",
+ status="QUEUED",
+ )
+ queued_task = Task.objects.create(
+ id=queued_task_result.task_id,
+ task_runner_task=queued_task_result,
+ tenant_id=tenant.id,
+ )
+ queued_scheduled_scan = Scan.objects.create(
+ tenant_id=tenant.id,
+ provider=provider,
+ name="Daily scheduled scan",
+ trigger=Scan.TriggerChoices.SCHEDULED,
+ state=StateChoices.AVAILABLE,
+ scheduler_task_id=periodic_task.id,
+ task=queued_task,
+ )
+
+ with (
+ patch("tasks.tasks.perform_prowler_scan") as mock_scan,
+ patch("tasks.tasks._perform_scan_complete_tasks") as mock_complete_tasks,
+ self._override_task_request(perform_scheduled_scan_task, id=task_id),
+ ):
+ result = perform_scheduled_scan_task.run(
+ tenant_id=str(tenant.id), provider_id=str(provider.id)
+ )
+
+ mock_scan.assert_not_called()
+ mock_complete_tasks.assert_not_called()
+ assert result["id"] == str(queued_scheduled_scan.id)
+ assert (
+ Scan.objects.filter(
+ tenant_id=tenant.id,
+ provider=provider,
+ trigger=Scan.TriggerChoices.SCHEDULED,
+ state=StateChoices.AVAILABLE,
+ ).count()
+ == 1
)
def test_creates_next_scheduled_scan_after_completion(
- self, tenants_fixture, providers_fixture
+ self, tenants_fixture, aws_provider
):
"""Create a next scheduled scan after a successful run completes."""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
self._create_periodic_task(provider.id, tenant.id)
task_id = str(uuid.uuid4())
self._create_task_result(tenant.id, task_id)
@@ -2435,12 +2874,47 @@ class TestPerformScheduledScanTask:
== 1
)
+ def test_next_scheduled_scan_failure_does_not_mask_completed_scan(
+ self, tenants_fixture, aws_provider, caplog
+ ):
+ """Keep scheduled scan success when next-run creation fails."""
+ tenant = tenants_fixture[0]
+ provider = aws_provider
+ self._create_periodic_task(provider.id, tenant.id)
+ task_id = str(uuid.uuid4())
+ self._create_task_result(tenant.id, task_id)
+
+ def _complete_scan(tenant_id, scan_id, provider_id):
+ scan_instance = Scan.objects.get(id=scan_id)
+ scan_instance.state = StateChoices.COMPLETED
+ scan_instance.save()
+ return {"status": "ok"}
+
+ with (
+ patch("tasks.tasks.perform_prowler_scan", side_effect=_complete_scan),
+ patch("tasks.tasks._perform_scan_complete_tasks"),
+ patch(
+ "tasks.tasks._get_or_create_next_scheduled_scan",
+ side_effect=RuntimeError("scheduler unavailable"),
+ ),
+ patch("tasks.tasks._dispatch_next_queued_provider_scan") as mock_dispatch,
+ self._override_task_request(perform_scheduled_scan_task, id=task_id),
+ caplog.at_level("ERROR"),
+ ):
+ result = perform_scheduled_scan_task.run(
+ tenant_id=str(tenant.id), provider_id=str(provider.id)
+ )
+
+ assert result == {"status": "ok"}
+ mock_dispatch.assert_called_once_with(str(tenant.id), str(provider.id))
+ assert "Failed to ensure next scheduled scan" in caplog.text
+
def test_dedupes_multiple_scheduled_scans_before_run(
- self, tenants_fixture, providers_fixture
+ self, tenants_fixture, aws_provider
):
"""Ensure duplicated scheduled scans are removed before executing."""
tenant = tenants_fixture[0]
- provider = providers_fixture[0]
+ provider = aws_provider
periodic_task = self._create_periodic_task(provider.id, tenant.id)
task_id = str(uuid.uuid4())
self._create_task_result(tenant.id, task_id)
@@ -2549,6 +3023,104 @@ class TestPerformScanTask:
mock_scan.assert_not_called()
mock_complete_tasks.assert_not_called()
+ def test_dispatches_next_queued_scan_after_completion(
+ self,
+ tenants_fixture,
+ aws_provider,
+ django_capture_on_commit_callbacks,
+ ):
+ """Dispatch the next queued scan for the provider after completion."""
+ tenant = tenants_fixture[0]
+ provider = aws_provider
+ current_scan = Scan.objects.create(
+ tenant_id=tenant.id,
+ provider=provider,
+ name="Running scan",
+ trigger=Scan.TriggerChoices.MANUAL,
+ state=StateChoices.AVAILABLE,
+ )
+ queued_task_result = TaskResult.objects.create(
+ task_id=str(uuid.uuid4()),
+ task_name="scan-perform",
+ status="QUEUED",
+ )
+ queued_task = Task.objects.create(
+ id=queued_task_result.task_id,
+ task_runner_task=queued_task_result,
+ tenant_id=tenant.id,
+ )
+ queued_scan = Scan.objects.create(
+ tenant_id=tenant.id,
+ provider=provider,
+ name="Queued scan",
+ trigger=Scan.TriggerChoices.MANUAL,
+ state=StateChoices.AVAILABLE,
+ task=queued_task,
+ )
+
+ def _complete_scan(tenant_id, scan_id, provider_id, checks_to_execute=None):
+ scan_instance = Scan.objects.get(id=scan_id)
+ scan_instance.state = StateChoices.COMPLETED
+ scan_instance.save()
+ return {"status": "ok"}
+
+ with (
+ patch("tasks.tasks.perform_prowler_scan", side_effect=_complete_scan),
+ patch("tasks.tasks._perform_scan_complete_tasks"),
+ patch("tasks.tasks.perform_scan_task.apply_async") as mock_apply_async,
+ ):
+ with django_capture_on_commit_callbacks(execute=True):
+ result = perform_scan_task.run(
+ tenant_id=str(tenant.id),
+ scan_id=str(current_scan.id),
+ provider_id=str(provider.id),
+ )
+
+ queued_task_result.refresh_from_db()
+ assert result == {"status": "ok"}
+ assert queued_task_result.status == states.PENDING
+ mock_apply_async.assert_called_once_with(
+ kwargs={
+ "tenant_id": str(tenant.id),
+ "scan_id": str(queued_scan.id),
+ "provider_id": str(provider.id),
+ },
+ task_id=str(queued_task.id),
+ )
+
+ def test_dispatch_failure_does_not_mask_completed_scan(
+ self, tenants_fixture, aws_provider, caplog
+ ):
+ """Keep scan success when queued dispatch fails after completion."""
+ tenant = tenants_fixture[0]
+ provider = aws_provider
+ current_scan = Scan.objects.create(
+ tenant_id=tenant.id,
+ provider=provider,
+ name="Running scan",
+ trigger=Scan.TriggerChoices.MANUAL,
+ state=StateChoices.AVAILABLE,
+ )
+
+ with (
+ patch("tasks.tasks.perform_prowler_scan", return_value={"status": "ok"}),
+ patch("tasks.tasks._perform_scan_complete_tasks"),
+ patch(
+ "tasks.tasks._dispatch_next_queued_provider_scan",
+ side_effect=RuntimeError("dispatch unavailable"),
+ ) as mock_dispatch,
+ caplog.at_level("ERROR"),
+ ):
+ result = perform_scan_task.run(
+ tenant_id=str(tenant.id),
+ scan_id=str(current_scan.id),
+ provider_id=str(provider.id),
+ )
+
+ assert result == {"status": "ok"}
+ mock_dispatch.assert_called_once_with(str(tenant.id), str(provider.id))
+ assert "Failed to dispatch next queued scan" in caplog.text
+
@pytest.mark.django_db
class TestReaggregateAllFindingGroupSummaries:
@@ -2732,6 +3304,7 @@ class TestTaskTimeLimits:
for name in (
"scan-perform",
"scan-perform-scheduled",
+ "attack-paths-scan-perform",
"provider-deletion",
"tenant-deletion",
):
diff --git a/api/src/backend/tasks/utils.py b/api/src/backend/tasks/utils.py
index 26bc031d7b..cac9a10f0d 100644
--- a/api/src/backend/tasks/utils.py
+++ b/api/src/backend/tasks/utils.py
@@ -103,6 +103,7 @@ def _get_or_create_scheduled_scan(
trigger=Scan.TriggerChoices.SCHEDULED,
state__in=(StateChoices.SCHEDULED, StateChoices.AVAILABLE),
scheduler_task_id=scheduler_task_id,
+ task__isnull=True,
).order_by("scheduled_at", "inserted_at")
)
diff --git a/api/towncrier.toml b/api/towncrier.toml
new file mode 100644
index 0000000000..528e6129ec
--- /dev/null
+++ b/api/towncrier.toml
@@ -0,0 +1,39 @@
+[tool.towncrier]
+directory = "changelog.d"
+filename = "CHANGELOG.md"
+start_string = "\n"
+title_format = "## [{version}] ({name})"
+issue_format = "[(#{issue})](https://github.com/prowler-cloud/prowler/pull/{issue})"
+template = "../.github/towncrier/template.md.jinja"
+underlines = ["", "", ""]
+ignore = [".gitkeep", "README.md"]
+
+[[tool.towncrier.type]]
+directory = "added"
+name = "🚀 Added"
+showcontent = true
+
+[[tool.towncrier.type]]
+directory = "changed"
+name = "🔄 Changed"
+showcontent = true
+
+[[tool.towncrier.type]]
+directory = "deprecated"
+name = "⚠️ Deprecated"
+showcontent = true
+
+[[tool.towncrier.type]]
+directory = "removed"
+name = "❌ Removed"
+showcontent = true
+
+[[tool.towncrier.type]]
+directory = "fixed"
+name = "🐞 Fixed"
+showcontent = true
+
+[[tool.towncrier.type]]
+directory = "security"
+name = "🔐 Security"
+showcontent = true
diff --git a/api/uv.lock b/api/uv.lock
index 06b1968c9a..de878d9dc9 100644
--- a/api/uv.lock
+++ b/api/uv.lock
@@ -110,7 +110,7 @@ constraints = [
{ name = "blinker", specifier = "==1.9.0" },
{ name = "boto3", specifier = "==1.40.61" },
{ name = "botocore", specifier = "==1.40.61" },
- { name = "cartography", specifier = "==0.135.0" },
+ { name = "cartography", specifier = "==0.138.1" },
{ name = "celery", specifier = "==5.6.2" },
{ name = "certifi", specifier = "==2026.1.4" },
{ name = "cffi", specifier = "==2.0.0" },
@@ -135,7 +135,6 @@ constraints = [
{ name = "debugpy", specifier = "==1.8.20" },
{ name = "decorator", specifier = "==5.2.1" },
{ name = "defusedxml", specifier = "==0.7.1" },
- { name = "detect-secrets", specifier = "==1.5.0" },
{ name = "dill", specifier = "==0.4.1" },
{ name = "distro", specifier = "==1.9.0" },
{ name = "dj-rest-auth", specifier = "==7.0.1" },
@@ -218,6 +217,7 @@ constraints = [
{ name = "jsonschema", specifier = "==4.23.0" },
{ name = "jsonschema-specifications", specifier = "==2025.9.1" },
{ name = "keystoneauth1", specifier = "==5.13.0" },
+ { name = "kingfisher-bin", specifier = "==1.104.0" },
{ name = "kiwisolver", specifier = "==1.4.9" },
{ name = "knack", specifier = "==0.11.0" },
{ name = "kombu", specifier = "==5.6.2" },
@@ -364,7 +364,7 @@ constraints = [
{ name = "wcwidth", specifier = "==0.5.3" },
{ name = "websocket-client", specifier = "==1.9.0" },
{ name = "werkzeug", specifier = "==3.1.7" },
- { name = "workos", specifier = "==6.0.4" },
+ { name = "workos", specifier = "==6.0.8" },
{ name = "wrapt", specifier = "==1.17.3" },
{ name = "xlsxwriter", specifier = "==3.2.9" },
{ name = "xmlsec", specifier = "==1.3.17" },
@@ -376,6 +376,7 @@ constraints = [
{ name = "zstd", specifier = "==1.5.7.3" },
]
overrides = [
+ { name = "azure-mgmt-containerservice", specifier = "==34.1.0" },
{ name = "dulwich", specifier = "==1.2.5" },
{ name = "microsoft-kiota-abstractions", specifier = "==1.9.9" },
{ name = "okta", specifier = "==3.4.2" },
@@ -1407,6 +1408,20 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/3d/66/0d8ae9ca4d75e57746026a1f9a10a7e25029511c128cf20166fce516bda9/azure_mgmt_logic-10.0.0-py3-none-any.whl", hash = "sha256:525c78afedf3edb35eb0a16152c8beba89769ee1bc6af01bcdc42842a551e443", size = 235433, upload-time = "2022-06-13T01:38:27.333Z" },
]
+[[package]]
+name = "azure-mgmt-managementgroups"
+version = "1.1.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "azure-mgmt-core" },
+ { name = "isodate" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/fd/73/ac5e064ed7343e1b3172f32f09be3efca906087218d3046b5038f2f394ed/azure_mgmt_managementgroups-1.1.0.tar.gz", hash = "sha256:e6199baf118890ba2bda35dda83a88861c0b1bbef126311b20ec12eed9681951", size = 60101, upload-time = "2026-02-13T03:45:45.439Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/92/bc/993158de03cc0a49f2cf8192615ffedbc508c417cb3522e88f6652b714cc/azure_mgmt_managementgroups-1.1.0-py3-none-any.whl", hash = "sha256:140934589559ef6afcac6f1d24f995588a1965aaa89d47851c1cc639fafb1942", size = 83586, upload-time = "2026-02-13T03:45:46.836Z" },
+]
+
[[package]]
name = "azure-mgmt-monitor"
version = "6.0.2"
@@ -1726,7 +1741,7 @@ wheels = [
[[package]]
name = "cartography"
-version = "0.135.0"
+version = "0.138.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "adal" },
@@ -1746,6 +1761,7 @@ dependencies = [
{ name = "azure-mgmt-eventhub" },
{ name = "azure-mgmt-keyvault" },
{ name = "azure-mgmt-logic" },
+ { name = "azure-mgmt-managementgroups" },
{ name = "azure-mgmt-monitor" },
{ name = "azure-mgmt-network" },
{ name = "azure-mgmt-resource" },
@@ -1754,6 +1770,7 @@ dependencies = [
{ name = "azure-mgmt-storage" },
{ name = "azure-mgmt-synapse" },
{ name = "azure-mgmt-web" },
+ { name = "azure-storage-blob" },
{ name = "azure-synapse-artifacts" },
{ name = "backoff" },
{ name = "boto3" },
@@ -1765,8 +1782,12 @@ dependencies = [
{ name = "duo-client" },
{ name = "google-api-python-client" },
{ name = "google-auth" },
+ { name = "google-cloud-aiplatform" },
+ { name = "google-cloud-artifact-registry" },
{ name = "google-cloud-asset" },
{ name = "google-cloud-resource-manager" },
+ { name = "google-cloud-run" },
+ { name = "google-cloud-storage" },
{ name = "httpx" },
{ name = "kubernetes" },
{ name = "marshmallow" },
@@ -1792,9 +1813,9 @@ dependencies = [
{ name = "workos" },
{ name = "xmltodict" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/39/47/606851d2403a983b63813b9e95427a5dd896e49bc5a501868c041262e9a5/cartography-0.135.0.tar.gz", hash = "sha256:3f500cd22c3b392d00e8b49f62acc95fd4dcd559ce514aafe2eb8101133c7a49", size = 9106458, upload-time = "2026-04-10T16:25:34.898Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/51/cd/0eb6a5a3c89cc179801d902ade9719af1a583c516c00f50d72b8207db1eb/cartography-0.138.1.tar.gz", hash = "sha256:356e946a0bcac899cba293d57803c71bd35fdeabe623f5f67d9405d7a643af9f", size = 9756966, upload-time = "2026-06-19T22:11:32.411Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/b1/e1/99a26b3e662202be77961aba73338e1448623490710b81783e53a4bbef15/cartography-0.135.0-py3-none-any.whl", hash = "sha256:c62c32a6917b8f23a8b98fe2b6c7c4a918b50f55918482966c4dae1cf5f538e1", size = 1590545, upload-time = "2026-04-10T16:25:37.669Z" },
+ { url = "https://files.pythonhosted.org/packages/a8/15/4447ec968825b2a19cba26ecb74964208aa3f941d9181a7782572e30b43d/cartography-0.138.1-py3-none-any.whl", hash = "sha256:88ec0898ea1a1b3f4653be9a3e7e61144f5cee20384b9040e92039617d39f029", size = 2014725, upload-time = "2026-06-19T22:11:29.886Z" },
]
[[package]]
@@ -2224,16 +2245,15 @@ wheels = [
]
[[package]]
-name = "detect-secrets"
-version = "1.5.0"
+name = "deprecated"
+version = "1.3.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "pyyaml" },
- { name = "requests" },
+ { name = "wrapt" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/69/67/382a863fff94eae5a0cf05542179169a1c49a4c8784a9480621e2066ca7d/detect_secrets-1.5.0.tar.gz", hash = "sha256:6bb46dcc553c10df51475641bb30fd69d25645cc12339e46c824c1e0c388898a", size = 97351, upload-time = "2024-05-06T17:46:19.721Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/49/85/12f0a49a7c4ffb70572b6c2ef13c90c88fd190debda93b23f026b25f9634/deprecated-1.3.1.tar.gz", hash = "sha256:b1b50e0ff0c1fddaa5708a2c6b0a6588bb09b892825ab2b214ac9ea9d92a5223", size = 2932523, upload-time = "2025-10-30T08:19:02.757Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/4e/5e/4f5fe4b89fde1dc3ed0eb51bd4ce4c0bca406246673d370ea2ad0c58d747/detect_secrets-1.5.0-py3-none-any.whl", hash = "sha256:e24e7b9b5a35048c313e983f76c4bd09dad89f045ff059e354f9943bf45aa060", size = 120341, upload-time = "2024-05-06T17:46:16.628Z" },
+ { url = "https://files.pythonhosted.org/packages/84/d0/205d54408c08b13550c733c4b85429e7ead111c7f0014309637425520a9a/deprecated-1.3.1-py2.py3-none-any.whl", hash = "sha256:597bfef186b6f60181535a29fbe44865ce137a5079f295b479886c82729d5f3f", size = 11298, upload-time = "2025-10-30T08:19:00.758Z" },
]
[[package]]
@@ -2511,6 +2531,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e3/26/57c6fb270950d476074c087527a558ccb6f4436657314bfb6cdf484114c4/docker-7.1.0-py3-none-any.whl", hash = "sha256:c96b93b7f0a746f9e77d325bcfb87422a3d8bd4f03136ae8a85b37f1898d5fc0", size = 147774, upload-time = "2024-05-23T11:13:55.01Z" },
]
+[[package]]
+name = "docstring-parser"
+version = "0.18.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e0/4d/f332313098c1de1b2d2ff91cf2674415cc7cddab2ca1b01ae29774bd5fdf/docstring_parser-0.18.0.tar.gz", hash = "sha256:292510982205c12b1248696f44959db3cdd1740237a968ea1e2e7a900eeb2015", size = 29341, upload-time = "2026-04-14T04:09:19.867Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a7/5f/ed01f9a3cdffbd5a008556fc7b2a08ddb1cc6ace7effa7340604b1d16699/docstring_parser-0.18.0-py3-none-any.whl", hash = "sha256:b3fcbed555c47d8479be0796ef7e19c2670d428d72e96da63f3a40122860374b", size = 22484, upload-time = "2026-04-14T04:09:18.638Z" },
+]
+
[[package]]
name = "dogpile-cache"
version = "1.5.0"
@@ -2851,6 +2880,11 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/83/1d/d6466de3a5249d35e832a52834115ca9d1d0de6abc22065f049707516d47/google_auth-2.48.0-py3-none-any.whl", hash = "sha256:2e2a537873d449434252a9632c28bfc268b0adb1e53f9fb62afc5333a975903f", size = 236499, upload-time = "2026-01-26T19:22:45.099Z" },
]
+[package.optional-dependencies]
+requests = [
+ { name = "requests" },
+]
+
[[package]]
name = "google-auth-httplib2"
version = "0.2.0"
@@ -2877,6 +2911,46 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/ca/94/24b010493660dd55e2d9769ae7ef44164aebd7e1f4a9266cf9459affd687/google_cloud_access_context_manager-0.3.0-py3-none-any.whl", hash = "sha256:5d15ad51547f06c281e35f16b4ffcb3e98bb2d898b01470f88b94edfb2eeb0a3", size = 58852, upload-time = "2025-10-17T02:30:33.768Z" },
]
+[[package]]
+name = "google-cloud-aiplatform"
+version = "1.153.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "docstring-parser" },
+ { name = "google-api-core", extra = ["grpc"] },
+ { name = "google-auth" },
+ { name = "google-cloud-bigquery" },
+ { name = "google-cloud-resource-manager" },
+ { name = "google-cloud-storage" },
+ { name = "google-genai" },
+ { name = "packaging" },
+ { name = "proto-plus" },
+ { name = "protobuf" },
+ { name = "pydantic" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/d5/97/1779e66ab845550bc602364311ea093ba156cb805a1c31b7c4d6f25b5863/google_cloud_aiplatform-1.153.1.tar.gz", hash = "sha256:445b6c683d5c630f174d81ae1f69f7da9e27e4d4ec5b70c5fe96de5c1247cfbc", size = 11011349, upload-time = "2026-05-15T06:34:14.851Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/16/01/8a1900e7a742ed480e6037ac4f6541466cb981d81bd4cbd34a9d46204ea1/google_cloud_aiplatform-1.153.1-py2.py3-none-any.whl", hash = "sha256:033fa1595a7e8ed1d97066e261e630f38fbc60e10c98c6487cf228fe9c7ec151", size = 9170782, upload-time = "2026-05-15T06:34:10.887Z" },
+]
+
+[[package]]
+name = "google-cloud-artifact-registry"
+version = "1.21.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "google-api-core", extra = ["grpc"] },
+ { name = "google-auth" },
+ { name = "grpc-google-iam-v1" },
+ { name = "grpcio" },
+ { name = "proto-plus" },
+ { name = "protobuf" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/13/2b/24e6956789bc1244efb18143aa4f124e03d870228e5bfd065c04d38a4d6b/google_cloud_artifact_registry-1.21.0.tar.gz", hash = "sha256:546e51eb5d463a6e5c668be6727d14f8ec82bc798031398006b2213d703e184c", size = 315219, upload-time = "2026-03-30T22:50:38.875Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e1/8c/a5c68031728f38d3306bad5ac10c0ca670cbdf414db308ddefa2c47f2b34/google_cloud_artifact_registry-1.21.0-py3-none-any.whl", hash = "sha256:a07079035438fd0f2e7264d4318b388650495f011db575405c18c9881449025c", size = 250544, upload-time = "2026-03-30T22:48:49.345Z" },
+]
+
[[package]]
name = "google-cloud-asset"
version = "4.2.0"
@@ -2897,6 +2971,37 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/05/88/9a43fae1d2fed94d7f5f46b6f4c44bd15e5ea0e8657632108b5ec5f53d9d/google_cloud_asset-4.2.0-py3-none-any.whl", hash = "sha256:fd7ea04c64948a4779790343204cd5b41d4772d6ab1d05a9125e28a637ac0862", size = 282707, upload-time = "2026-01-09T14:53:03.081Z" },
]
+[[package]]
+name = "google-cloud-bigquery"
+version = "3.41.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "google-api-core", extra = ["grpc"] },
+ { name = "google-auth" },
+ { name = "google-cloud-core" },
+ { name = "google-resumable-media" },
+ { name = "packaging" },
+ { name = "python-dateutil" },
+ { name = "requests" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ce/13/6515c7aab55a4a0cf708ffd309fb9af5bab54c13e32dc22c5acd6497193c/google_cloud_bigquery-3.41.0.tar.gz", hash = "sha256:2217e488b47ed576360c9b2cc07d59d883a54b83167c0ef37f915c26b01a06fe", size = 513434, upload-time = "2026-03-30T22:50:55.347Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/40/33/1d3902efadef9194566d499d61507e1f038454e0b55499d2d7f8ab2a4fee/google_cloud_bigquery-3.41.0-py3-none-any.whl", hash = "sha256:2a5b5a737b401cbd824a6e5eac7554100b878668d908e6548836b5d8aaa4dcaa", size = 262343, upload-time = "2026-03-30T22:48:45.444Z" },
+]
+
+[[package]]
+name = "google-cloud-core"
+version = "2.6.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "google-api-core" },
+ { name = "google-auth" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/a8/dd/1eef226e470369b26824a505c34482c0b493bc35fe8e0c6b003b5feca21a/google_cloud_core-2.6.0.tar.gz", hash = "sha256:e76149739f90fac1fc6757c09f47eaccb3145b54adbd7759b0f7c4b235f46c83", size = 36001, upload-time = "2026-05-07T08:04:04.124Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/84/4a/98da8930ab109c73d9a5d13782a9ebb81ea8c111f6d534a567b71d23e52b/google_cloud_core-2.6.0-py3-none-any.whl", hash = "sha256:6d63ac8e5eca6d9e4319d0a1e2265fadcd7f1049904378caecfa01cf52dd869e", size = 29390, upload-time = "2026-05-07T08:02:34.672Z" },
+]
+
[[package]]
name = "google-cloud-org-policy"
version = "1.16.0"
@@ -2946,6 +3051,93 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/94/ff/4b28bcc791d9d7e4ac8fea00fbd90ccb236afda56746a3b4564d2ae45df3/google_cloud_resource_manager-1.16.0-py3-none-any.whl", hash = "sha256:fb9a2ad2b5053c508e1c407ac31abfd1a22e91c32876c1892830724195819a28", size = 400218, upload-time = "2026-01-15T13:02:47.378Z" },
]
+[[package]]
+name = "google-cloud-run"
+version = "0.16.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "google-api-core", extra = ["grpc"] },
+ { name = "google-auth" },
+ { name = "grpc-google-iam-v1" },
+ { name = "grpcio" },
+ { name = "proto-plus" },
+ { name = "protobuf" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b7/89/dcaf0dc97e39b41e446456ceb60657ab025de79cfccd39cbd739d1a9849e/google_cloud_run-0.16.0.tar.gz", hash = "sha256:d52cf4e6ad3702ae48caccf6abcab543afee6f61c2a6ec753cc62a31e5b629f1", size = 514452, upload-time = "2026-03-26T22:17:05.589Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fa/c7/46153dc13713b5e4276d86f28ff4563332f9e4bae5ebc83abc5bfd994801/google_cloud_run-0.16.0-py3-none-any.whl", hash = "sha256:d7d2dd7307130fde2a0ce27e96d580dd23b7b2d973b6484b94d902e6b2618860", size = 459112, upload-time = "2026-03-26T22:16:00.018Z" },
+]
+
+[[package]]
+name = "google-cloud-storage"
+version = "3.10.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "google-api-core" },
+ { name = "google-auth" },
+ { name = "google-cloud-core" },
+ { name = "google-crc32c" },
+ { name = "google-resumable-media" },
+ { name = "requests" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/4c/47/205eb8e9a1739b5345843e5a425775cbdc472cc38e7eda082ba5b8d02450/google_cloud_storage-3.10.1.tar.gz", hash = "sha256:97db9aa4460727982040edd2bd13ff3d5e2260b5331ad22895802da1fc2a5286", size = 17309950, upload-time = "2026-03-23T09:35:23.409Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ad/ff/ca9ab2417fa913d75aae38bf40bf856bb2749a604b2e0f701b37cfcd23cc/google_cloud_storage-3.10.1-py3-none-any.whl", hash = "sha256:a72f656759b7b99bda700f901adcb3425a828d4a29f911bc26b3ea79c5b1217f", size = 324453, upload-time = "2026-03-23T09:35:21.368Z" },
+]
+
+[[package]]
+name = "google-crc32c"
+version = "1.8.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/03/41/4b9c02f99e4c5fb477122cd5437403b552873f014616ac1d19ac8221a58d/google_crc32c-1.8.0.tar.gz", hash = "sha256:a428e25fb7691024de47fecfbff7ff957214da51eddded0da0ae0e0f03a2cf79", size = 14192, upload-time = "2025-12-16T00:35:25.142Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5d/ef/21ccfaab3d5078d41efe8612e0ed0bfc9ce22475de074162a91a25f7980d/google_crc32c-1.8.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:014a7e68d623e9a4222d663931febc3033c5c7c9730785727de2a81f87d5bab8", size = 31298, upload-time = "2025-12-16T00:20:32.241Z" },
+ { url = "https://files.pythonhosted.org/packages/c5/b8/f8413d3f4b676136e965e764ceedec904fe38ae8de0cdc52a12d8eb1096e/google_crc32c-1.8.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:86cfc00fe45a0ac7359e5214a1704e51a99e757d0272554874f419f79838c5f7", size = 30872, upload-time = "2025-12-16T00:33:58.785Z" },
+ { url = "https://files.pythonhosted.org/packages/f6/fd/33aa4ec62b290477181c55bb1c9302c9698c58c0ce9a6ab4874abc8b0d60/google_crc32c-1.8.0-cp311-cp311-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:19b40d637a54cb71e0829179f6cb41835f0fbd9e8eb60552152a8b52c36cbe15", size = 33243, upload-time = "2025-12-16T00:40:21.46Z" },
+ { url = "https://files.pythonhosted.org/packages/71/03/4820b3bd99c9653d1a5210cb32f9ba4da9681619b4d35b6a052432df4773/google_crc32c-1.8.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:17446feb05abddc187e5441a45971b8394ea4c1b6efd88ab0af393fd9e0a156a", size = 33608, upload-time = "2025-12-16T00:40:22.204Z" },
+ { url = "https://files.pythonhosted.org/packages/7c/43/acf61476a11437bf9733fb2f70599b1ced11ec7ed9ea760fdd9a77d0c619/google_crc32c-1.8.0-cp311-cp311-win_amd64.whl", hash = "sha256:71734788a88f551fbd6a97be9668a0020698e07b2bf5b3aa26a36c10cdfb27b2", size = 34439, upload-time = "2025-12-16T00:35:20.458Z" },
+ { url = "https://files.pythonhosted.org/packages/e9/5f/7307325b1198b59324c0fa9807cafb551afb65e831699f2ce211ad5c8240/google_crc32c-1.8.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:4b8286b659c1335172e39563ab0a768b8015e88e08329fa5321f774275fc3113", size = 31300, upload-time = "2025-12-16T00:21:56.723Z" },
+ { url = "https://files.pythonhosted.org/packages/21/8e/58c0d5d86e2220e6a37befe7e6a94dd2f6006044b1a33edf1ff6d9f7e319/google_crc32c-1.8.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:2a3dc3318507de089c5384cc74d54318401410f82aa65b2d9cdde9d297aca7cb", size = 30867, upload-time = "2025-12-16T00:38:31.302Z" },
+ { url = "https://files.pythonhosted.org/packages/ce/a9/a780cc66f86335a6019f557a8aaca8fbb970728f0efd2430d15ff1beae0e/google_crc32c-1.8.0-cp312-cp312-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:14f87e04d613dfa218d6135e81b78272c3b904e2a7053b841481b38a7d901411", size = 33364, upload-time = "2025-12-16T00:40:22.96Z" },
+ { url = "https://files.pythonhosted.org/packages/21/3f/3457ea803db0198c9aaca2dd373750972ce28a26f00544b6b85088811939/google_crc32c-1.8.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cb5c869c2923d56cb0c8e6bcdd73c009c36ae39b652dbe46a05eb4ef0ad01454", size = 33740, upload-time = "2025-12-16T00:40:23.96Z" },
+ { url = "https://files.pythonhosted.org/packages/df/c0/87c2073e0c72515bb8733d4eef7b21548e8d189f094b5dad20b0ecaf64f6/google_crc32c-1.8.0-cp312-cp312-win_amd64.whl", hash = "sha256:3cc0c8912038065eafa603b238abf252e204accab2a704c63b9e14837a854962", size = 34437, upload-time = "2025-12-16T00:35:21.395Z" },
+ { url = "https://files.pythonhosted.org/packages/52/c5/c171e4d8c44fec1422d801a6d2e5d7ddabd733eeda505c79730ee9607f07/google_crc32c-1.8.0-pp311-pypy311_pp73-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:87fa445064e7db928226b2e6f0d5304ab4cd0339e664a4e9a25029f384d9bb93", size = 28615, upload-time = "2025-12-16T00:40:29.298Z" },
+ { url = "https://files.pythonhosted.org/packages/9c/97/7d75fe37a7a6ed171a2cf17117177e7aab7e6e0d115858741b41e9dd4254/google_crc32c-1.8.0-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f639065ea2042d5c034bf258a9f085eaa7af0cd250667c0635a3118e8f92c69c", size = 28800, upload-time = "2025-12-16T00:40:30.322Z" },
+]
+
+[[package]]
+name = "google-genai"
+version = "1.68.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio" },
+ { name = "distro" },
+ { name = "google-auth", extra = ["requests"] },
+ { name = "httpx" },
+ { name = "pydantic" },
+ { name = "requests" },
+ { name = "sniffio" },
+ { name = "tenacity" },
+ { name = "typing-extensions" },
+ { name = "websockets" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/9c/2c/f059982dbcb658cc535c81bbcbe7e2c040d675f4b563b03cdb01018a4bc3/google_genai-1.68.0.tar.gz", hash = "sha256:ac30c0b8bc630f9372993a97e4a11dae0e36f2e10d7c55eacdca95a9fa14ca96", size = 511285, upload-time = "2026-03-18T01:03:18.243Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/84/de/7d3ee9c94b74c3578ea4f88d45e8de9405902f857932334d81e89bce3dfa/google_genai-1.68.0-py3-none-any.whl", hash = "sha256:a1bc9919c0e2ea2907d1e319b65471d3d6d58c54822039a249fe1323e4178d15", size = 750912, upload-time = "2026-03-18T01:03:15.983Z" },
+]
+
+[[package]]
+name = "google-resumable-media"
+version = "2.9.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "google-crc32c" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/00/4b/0b235beccc310d0a48adbc7246b719d173cca6c88c572dfa4b090e39143c/google_resumable_media-2.9.0.tar.gz", hash = "sha256:f7cfb224846a9dd444d125115dfbe8ef02a2b893e78f087762fe716a255a734b", size = 2164534, upload-time = "2026-05-07T08:04:44.236Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/07/73/3518e63deb1667c5409a4579e28daf5e84479a87a72c547e0487f7883dcd/google_resumable_media-2.9.0-py3-none-any.whl", hash = "sha256:c8901e88e389af8bed64d9696c74d8bad961865eb2236e13e0bfca9bb0a65ca3", size = 81507, upload-time = "2026-05-07T08:03:23.809Z" },
+]
+
[[package]]
name = "googleapis-common-protos"
version = "1.72.0"
@@ -3420,6 +3612,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/dd/99/76476a1057b349c860bae72e45d6ef438feb877c84ee7d565faf464e54c3/keystoneauth1-5.13.0-py3-none-any.whl", hash = "sha256:5ab81412eb0923ceb9c602cc3decce514b399523cb83d16b409ed3b0f9b03d41", size = 343585, upload-time = "2026-01-19T10:47:00.762Z" },
]
+[[package]]
+name = "kingfisher-bin"
+version = "1.104.0"
+source = { registry = "https://pypi.org/simple" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/1e/2b/324212f1baf482a7d4b66a2edf33073336735b67bb6b04a38d18fd9e67fb/kingfisher_bin-1.104.0-py3-none-macosx_10_9_x86_64.whl", hash = "sha256:8e3840e67004a971fef80aba240ee5c3c5f7a3a343a6d1083a2751aaf866d5d3", size = 14057606, upload-time = "2026-06-22T03:03:01.419Z" },
+ { url = "https://files.pythonhosted.org/packages/21/0a/cbf964da5102657cb9be4a59db7c9f7807ef88f9419673b7486daba785d3/kingfisher_bin-1.104.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:b838313411fa2166a318a45aec2cfcc238e2f30f5292e309ca1129a73180c851", size = 12468386, upload-time = "2026-06-22T03:03:03.951Z" },
+ { url = "https://files.pythonhosted.org/packages/0b/a0/cc7ef0ac28f147cdfc9d80e4239fff11c1329831c6f57510c929e848753c/kingfisher_bin-1.104.0-py3-none-manylinux_2_17_aarch64.musllinux_1_2_aarch64.whl", hash = "sha256:0a94abbf2154ef8a3b4845cc0240e2321cdc19e0f5c7f585ea5252e76b242f68", size = 13943188, upload-time = "2026-06-22T03:03:06.378Z" },
+ { url = "https://files.pythonhosted.org/packages/17/79/827cfd7787885798a00b5ab905bdc866ef6f8deeff0f708679b06bc9baaa/kingfisher_bin-1.104.0-py3-none-manylinux_2_17_x86_64.musllinux_1_2_x86_64.whl", hash = "sha256:f381274b946f7f68ed72911770fff72024f2192c6e2e2158f2a7fbfda8c482fb", size = 14757594, upload-time = "2026-06-22T03:03:08.66Z" },
+ { url = "https://files.pythonhosted.org/packages/da/93/b0061fc69cd10382f647f9266823f213fd0b3f168f8b5bd9151a2370abb1/kingfisher_bin-1.104.0-py3-none-win_amd64.whl", hash = "sha256:f228d0dd61a738673b1c536e965a5661a83b1ee6ca64186a46ba6ea81ab4fd0b", size = 27697957, upload-time = "2026-06-22T03:03:11.268Z" },
+ { url = "https://files.pythonhosted.org/packages/a5/fb/f062665b4eb3f77e799cb6335e56bc2945aea83787888a6c1ab329858d0a/kingfisher_bin-1.104.0-py3-none-win_arm64.whl", hash = "sha256:a7774d9d11815ca946bd80b8c9df0f1d39c36cb5a21def3323b99d148dc63065", size = 26063704, upload-time = "2026-06-22T03:03:14.08Z" },
+]
+
[[package]]
name = "kiwisolver"
version = "1.4.9"
@@ -3513,6 +3718,20 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/08/10/9f8af3e6f569685ce3af7faab51c8dd9d93b9c38eba339ca31c746119447/kubernetes-32.0.1-py2.py3-none-any.whl", hash = "sha256:35282ab8493b938b08ab5526c7ce66588232df00ef5e1dbe88a419107dc10998", size = 1988070, upload-time = "2025-02-18T21:06:31.391Z" },
]
+[[package]]
+name = "linode-api4"
+version = "5.45.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "deprecated" },
+ { name = "polling" },
+ { name = "requests" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b2/b5/fce03d9b81008dcc0fe4961ce10e140ac3ae5ab17f2cdd659763e4964c0d/linode_api4-5.45.0.tar.gz", hash = "sha256:af8a0a5638345ad467447112dcf5d58ec47e7dd192b89ce0c8537a1e5c435d04", size = 283375, upload-time = "2026-06-11T18:05:13.671Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/18/38/19e3c8f7b7a9dbeea2aa5af61f70162bff5131b3d39acbe73e8d0dd12972/linode_api4-5.45.0-py3-none-any.whl", hash = "sha256:3cc2650b13d8d3bc7735fa8e92a639669618f320471dc8e519db778c6020eacd", size = 158336, upload-time = "2026-06-11T18:05:11.799Z" },
+]
+
[[package]]
name = "lxml"
version = "6.1.0"
@@ -4332,6 +4551,12 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/41/f5/65b66420c275e9b26513fdd6d84687403d11ac8be4650b67d1e5572b8f48/policyuniverse-1.5.1.20231109-py2.py3-none-any.whl", hash = "sha256:0b0ece0ee8285af31fc39ce09c82a551ca62e62bc2842e23952503bccb973321", size = 484251, upload-time = "2023-11-30T19:12:43.463Z" },
]
+[[package]]
+name = "polling"
+version = "0.3.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/8f/c5/4249317962180d97ec7a60fe38aa91f86216533bd478a427a5468945c5c9/polling-0.3.2.tar.gz", hash = "sha256:3afd62320c99b725c70f379964bf548b302fc7f04d4604e6c315d9012309cc9a", size = 5189, upload-time = "2021-05-22T19:48:41.466Z" }
+
[[package]]
name = "portalocker"
version = "2.10.1"
@@ -4448,8 +4673,8 @@ wheels = [
[[package]]
name = "prowler"
-version = "5.31.0"
-source = { git = "https://github.com/prowler-cloud/prowler.git?rev=master#b5bb85c9564f6ca6a7f66c851bb56bde719205ee" }
+version = "5.35.0"
+source = { git = "https://github.com/prowler-cloud/prowler.git?rev=master#f5ea116763aeffede9f399c8934fc280eaccd315" }
dependencies = [
{ name = "alibabacloud-actiontrail20200706" },
{ name = "alibabacloud-credentials" },
@@ -4500,13 +4725,14 @@ dependencies = [
{ name = "dash" },
{ name = "dash-bootstrap-components" },
{ name = "defusedxml" },
- { name = "detect-secrets" },
{ name = "dulwich" },
{ name = "google-api-python-client" },
{ name = "google-auth-httplib2" },
{ name = "h2" },
{ name = "jsonschema" },
+ { name = "kingfisher-bin" },
{ name = "kubernetes" },
+ { name = "linode-api4" },
{ name = "markdown" },
{ name = "microsoft-kiota-abstractions" },
{ name = "msgraph-sdk" },
@@ -4536,7 +4762,7 @@ dependencies = [
[[package]]
name = "prowler-api"
-version = "1.33.0"
+version = "1.37.0"
source = { virtual = "." }
dependencies = [
{ name = "cartography" },
@@ -4606,7 +4832,7 @@ dev = [
[package.metadata]
requires-dist = [
- { name = "cartography", specifier = "==0.135.0" },
+ { name = "cartography", specifier = "==0.138.1" },
{ name = "celery", specifier = "==5.6.2" },
{ name = "defusedxml", specifier = "==0.7.1" },
{ name = "dj-rest-auth", extras = ["with-social", "jwt"], specifier = "==7.0.1" },
@@ -5931,6 +6157,38 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/34/db/b10e48aa8fff7407e67470363eac595018441cf32d5e1001567a7aeba5d2/websocket_client-1.9.0-py3-none-any.whl", hash = "sha256:af248a825037ef591efbf6ed20cc5faa03d3b47b9e5a2230a529eeee1c1fc3ef", size = 82616, upload-time = "2025-10-07T21:16:34.951Z" },
]
+[[package]]
+name = "websockets"
+version = "16.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/04/24/4b2031d72e840ce4c1ccb255f693b15c334757fc50023e4db9537080b8c4/websockets-16.0.tar.gz", hash = "sha256:5f6261a5e56e8d5c42a4497b364ea24d94d9563e8fbd44e78ac40879c60179b5", size = 179346, upload-time = "2026-01-10T09:23:47.181Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f2/db/de907251b4ff46ae804ad0409809504153b3f30984daf82a1d84a9875830/websockets-16.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:31a52addea25187bde0797a97d6fc3d2f92b6f72a9370792d65a6e84615ac8a8", size = 177340, upload-time = "2026-01-10T09:22:34.539Z" },
+ { url = "https://files.pythonhosted.org/packages/f3/fa/abe89019d8d8815c8781e90d697dec52523fb8ebe308bf11664e8de1877e/websockets-16.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:417b28978cdccab24f46400586d128366313e8a96312e4b9362a4af504f3bbad", size = 175022, upload-time = "2026-01-10T09:22:36.332Z" },
+ { url = "https://files.pythonhosted.org/packages/58/5d/88ea17ed1ded2079358b40d31d48abe90a73c9e5819dbcde1606e991e2ad/websockets-16.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:af80d74d4edfa3cb9ed973a0a5ba2b2a549371f8a741e0800cb07becdd20f23d", size = 175319, upload-time = "2026-01-10T09:22:37.602Z" },
+ { url = "https://files.pythonhosted.org/packages/d2/ae/0ee92b33087a33632f37a635e11e1d99d429d3d323329675a6022312aac2/websockets-16.0-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:08d7af67b64d29823fed316505a89b86705f2b7981c07848fb5e3ea3020c1abe", size = 184631, upload-time = "2026-01-10T09:22:38.789Z" },
+ { url = "https://files.pythonhosted.org/packages/c8/c5/27178df583b6c5b31b29f526ba2da5e2f864ecc79c99dae630a85d68c304/websockets-16.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7be95cfb0a4dae143eaed2bcba8ac23f4892d8971311f1b06f3c6b78952ee70b", size = 185870, upload-time = "2026-01-10T09:22:39.893Z" },
+ { url = "https://files.pythonhosted.org/packages/87/05/536652aa84ddc1c018dbb7e2c4cbcd0db884580bf8e95aece7593fde526f/websockets-16.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d6297ce39ce5c2e6feb13c1a996a2ded3b6832155fcfc920265c76f24c7cceb5", size = 185361, upload-time = "2026-01-10T09:22:41.016Z" },
+ { url = "https://files.pythonhosted.org/packages/6d/e2/d5332c90da12b1e01f06fb1b85c50cfc489783076547415bf9f0a659ec19/websockets-16.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:1c1b30e4f497b0b354057f3467f56244c603a79c0d1dafce1d16c283c25f6e64", size = 184615, upload-time = "2026-01-10T09:22:42.442Z" },
+ { url = "https://files.pythonhosted.org/packages/77/fb/d3f9576691cae9253b51555f841bc6600bf0a983a461c79500ace5a5b364/websockets-16.0-cp311-cp311-win32.whl", hash = "sha256:5f451484aeb5cafee1ccf789b1b66f535409d038c56966d6101740c1614b86c6", size = 178246, upload-time = "2026-01-10T09:22:43.654Z" },
+ { url = "https://files.pythonhosted.org/packages/54/67/eaff76b3dbaf18dcddabc3b8c1dba50b483761cccff67793897945b37408/websockets-16.0-cp311-cp311-win_amd64.whl", hash = "sha256:8d7f0659570eefb578dacde98e24fb60af35350193e4f56e11190787bee77dac", size = 178684, upload-time = "2026-01-10T09:22:44.941Z" },
+ { url = "https://files.pythonhosted.org/packages/84/7b/bac442e6b96c9d25092695578dda82403c77936104b5682307bd4deb1ad4/websockets-16.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:71c989cbf3254fbd5e84d3bff31e4da39c43f884e64f2551d14bb3c186230f00", size = 177365, upload-time = "2026-01-10T09:22:46.787Z" },
+ { url = "https://files.pythonhosted.org/packages/b0/fe/136ccece61bd690d9c1f715baaeefd953bb2360134de73519d5df19d29ca/websockets-16.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:8b6e209ffee39ff1b6d0fa7bfef6de950c60dfb91b8fcead17da4ee539121a79", size = 175038, upload-time = "2026-01-10T09:22:47.999Z" },
+ { url = "https://files.pythonhosted.org/packages/40/1e/9771421ac2286eaab95b8575b0cb701ae3663abf8b5e1f64f1fd90d0a673/websockets-16.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:86890e837d61574c92a97496d590968b23c2ef0aeb8a9bc9421d174cd378ae39", size = 175328, upload-time = "2026-01-10T09:22:49.809Z" },
+ { url = "https://files.pythonhosted.org/packages/18/29/71729b4671f21e1eaa5d6573031ab810ad2936c8175f03f97f3ff164c802/websockets-16.0-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:9b5aca38b67492ef518a8ab76851862488a478602229112c4b0d58d63a7a4d5c", size = 184915, upload-time = "2026-01-10T09:22:51.071Z" },
+ { url = "https://files.pythonhosted.org/packages/97/bb/21c36b7dbbafc85d2d480cd65df02a1dc93bf76d97147605a8e27ff9409d/websockets-16.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e0334872c0a37b606418ac52f6ab9cfd17317ac26365f7f65e203e2d0d0d359f", size = 186152, upload-time = "2026-01-10T09:22:52.224Z" },
+ { url = "https://files.pythonhosted.org/packages/4a/34/9bf8df0c0cf88fa7bfe36678dc7b02970c9a7d5e065a3099292db87b1be2/websockets-16.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a0b31e0b424cc6b5a04b8838bbaec1688834b2383256688cf47eb97412531da1", size = 185583, upload-time = "2026-01-10T09:22:53.443Z" },
+ { url = "https://files.pythonhosted.org/packages/47/88/4dd516068e1a3d6ab3c7c183288404cd424a9a02d585efbac226cb61ff2d/websockets-16.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:485c49116d0af10ac698623c513c1cc01c9446c058a4e61e3bf6c19dff7335a2", size = 184880, upload-time = "2026-01-10T09:22:55.033Z" },
+ { url = "https://files.pythonhosted.org/packages/91/d6/7d4553ad4bf1c0421e1ebd4b18de5d9098383b5caa1d937b63df8d04b565/websockets-16.0-cp312-cp312-win32.whl", hash = "sha256:eaded469f5e5b7294e2bdca0ab06becb6756ea86894a47806456089298813c89", size = 178261, upload-time = "2026-01-10T09:22:56.251Z" },
+ { url = "https://files.pythonhosted.org/packages/c3/f0/f3a17365441ed1c27f850a80b2bc680a0fa9505d733fe152fdf5e98c1c0b/websockets-16.0-cp312-cp312-win_amd64.whl", hash = "sha256:5569417dc80977fc8c2d43a86f78e0a5a22fee17565d78621b6bb264a115d4ea", size = 178693, upload-time = "2026-01-10T09:22:57.478Z" },
+ { url = "https://files.pythonhosted.org/packages/72/07/c98a68571dcf256e74f1f816b8cc5eae6eb2d3d5cfa44d37f801619d9166/websockets-16.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:349f83cd6c9a415428ee1005cadb5c2c56f4389bc06a9af16103c3bc3dcc8b7d", size = 174947, upload-time = "2026-01-10T09:23:36.166Z" },
+ { url = "https://files.pythonhosted.org/packages/7e/52/93e166a81e0305b33fe416338be92ae863563fe7bce446b0f687b9df5aea/websockets-16.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:4a1aba3340a8dca8db6eb5a7986157f52eb9e436b74813764241981ca4888f03", size = 175260, upload-time = "2026-01-10T09:23:37.409Z" },
+ { url = "https://files.pythonhosted.org/packages/56/0c/2dbf513bafd24889d33de2ff0368190a0e69f37bcfa19009ef819fe4d507/websockets-16.0-pp311-pypy311_pp73-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:f4a32d1bd841d4bcbffdcb3d2ce50c09c3909fbead375ab28d0181af89fd04da", size = 176071, upload-time = "2026-01-10T09:23:39.158Z" },
+ { url = "https://files.pythonhosted.org/packages/a5/8f/aea9c71cc92bf9b6cc0f7f70df8f0b420636b6c96ef4feee1e16f80f75dd/websockets-16.0-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0298d07ee155e2e9fda5be8a9042200dd2e3bb0b8a38482156576f863a9d457c", size = 176968, upload-time = "2026-01-10T09:23:41.031Z" },
+ { url = "https://files.pythonhosted.org/packages/9a/3f/f70e03f40ffc9a30d817eef7da1be72ee4956ba8d7255c399a01b135902a/websockets-16.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:a653aea902e0324b52f1613332ddf50b00c06fdaf7e92624fbf8c77c78fa5767", size = 178735, upload-time = "2026-01-10T09:23:42.259Z" },
+ { url = "https://files.pythonhosted.org/packages/6f/28/258ebab549c2bf3e64d2b0217b973467394a9cea8c42f70418ca2c5d0d2e/websockets-16.0-py3-none-any.whl", hash = "sha256:1637db62fad1dc833276dded54215f2c7fa46912301a24bd94d45d46a011ceec", size = 171598, upload-time = "2026-01-10T09:23:45.395Z" },
+]
+
[[package]]
name = "werkzeug"
version = "3.1.7"
@@ -5945,16 +6203,16 @@ wheels = [
[[package]]
name = "workos"
-version = "6.0.4"
+version = "6.0.8"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "cryptography" },
{ name = "httpx" },
{ name = "pyjwt", extra = ["crypto"] },
]
-sdist = { url = "https://files.pythonhosted.org/packages/3c/2f/99fb8718274116c5c146c745755620fd5c5943f78ca52ca9b17e94348286/workos-6.0.4.tar.gz", hash = "sha256:b0bfe8fd212b8567422c4ea3732eb33608794033eb3a69900c6b04db183c32d6", size = 172217, upload-time = "2026-04-16T03:09:28.583Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/ca/0d/0a7f78912657f99412c788932ea1f3f4089916e77bdef7d2463842febe08/workos-6.0.8.tar.gz", hash = "sha256:43aa3f1992a0a4ca8933d9b6e5ada846dd3b1fe0ee10e64c876ee2000fc6090d", size = 178137, upload-time = "2026-04-24T18:48:03.203Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/fa/f1/d2ab661e6dc2828a4c73e38f12630c3b109cfe2bc664ab70631c04f0db4b/workos-6.0.4-py3-none-any.whl", hash = "sha256:548668b3702673536f853ba72a7b5bbbc269e467aaf9ac4f477b6e0177df5e21", size = 511418, upload-time = "2026-04-16T03:09:27.098Z" },
+ { url = "https://files.pythonhosted.org/packages/b2/3f/3d96da80d650b2f97d58af626053354584f619dbb769051e118bd9cd1ca5/workos-6.0.8-py3-none-any.whl", hash = "sha256:a00dd4930333aded2babbba824f8032eea05c5ca8c44d04a3fa068cf6be6e21a", size = 524505, upload-time = "2026-04-24T18:48:01.389Z" },
]
[[package]]
diff --git a/claude_plugins/prowler/.claude-plugin/plugin.json b/claude_plugins/prowler/.claude-plugin/plugin.json
index 7bf822e2e7..c77187c3b0 100644
--- a/claude_plugins/prowler/.claude-plugin/plugin.json
+++ b/claude_plugins/prowler/.claude-plugin/plugin.json
@@ -22,7 +22,7 @@
"api_key": {
"type": "string",
"title": "Prowler API key",
- "description": "API key token used to authenticate with Prowler Cloud / Prowler App via the Prowler MCP server. Create one at https://cloud.prowler.com.",
+ "description": "API key token used to authenticate with Prowler (Prowler Cloud, Prowler Private Cloud, or Prowler Local Server) via the Prowler MCP server. Create one at https://cloud.prowler.com.",
"sensitive": true,
"required": true
}
diff --git a/claude_plugins/prowler/skills/framework-compliance-triage/SKILL.md b/claude_plugins/prowler/skills/framework-compliance-triage/SKILL.md
index 1af29f82b9..f8a9ded0c6 100644
--- a/claude_plugins/prowler/skills/framework-compliance-triage/SKILL.md
+++ b/claude_plugins/prowler/skills/framework-compliance-triage/SKILL.md
@@ -38,12 +38,12 @@ If the framework is not supported, tell the user, suggest they request it or con
### 1.1 Connect to Prowler Cloud
-Verify the Prowler MCP connection by calling `prowler_app_search_providers` — a successful response returns the list of providers. If the call fails, walk the user through troubleshooting: internet connectivity, Prowler Cloud credentials, and permissions on the Prowler Cloud account.
+Verify the Prowler MCP connection by calling `prowler_search_providers` — a successful response returns the list of providers. If the call fails, walk the user through troubleshooting: internet connectivity, Prowler Cloud credentials, and permissions on the Prowler Cloud account.
For getting accurate information about configurations use `prowler_docs_search` to pull relevant instructions from the Prowler documentation.
### 1.2 Verify the provider is configured (or configure it)
-Call `prowler_app_search_providers` to check whether the target provider (AWS account, Azure Subscription, GitHub Account...) exists in the user's Prowler Cloud account. Handle the result based on what's found:
+Call `prowler_search_providers` to check whether the target provider (AWS account, Azure Subscription, GitHub Account...) exists in the user's Prowler Cloud account. Handle the result based on what's found:
- **Provider not present.** Guide the user through adding and configuring it. Retrieve the relevant connection, credential, and permission instructions with `prowler_docs_search`.
- **Provider present but misconfigured** (missing credentials, insufficient permissions, etc.). Walk the user through fixing the configuration, pulling the relevant guidance with `prowler_docs_search`.
@@ -57,15 +57,15 @@ Call `prowler_app_search_providers` to check whether the target provider (AWS ac
The flow needs at least one completed scan with a compliance report available.
-Look for a completed scan first: call `prowler_app_list_scans` with the selected `provider_id` and `state: ["completed"]`, then call `prowler_app_get_compliance_overview` with each `scan_id` to find one whose compliance report is available. If one is found, continue to the next section.
+Look for a completed scan first: call `prowler_list_scans` with the selected `provider_id` and `state: ["completed"]`, then call `prowler_get_compliance_overview` with each `scan_id` to find one whose compliance report is available. If one is found, continue to the next section.
-If no completed scan has a report, call `prowler_app_list_scans` again with `state: ["available", "executing"]` to detect a scan in progress.
+If no completed scan has a report, call `prowler_list_scans` again with `state: ["available", "executing"]` to detect a scan in progress.
> **Checkpoint — Scan-in-progress decision** *(conditional: an in-progress scan was detected)*
>
> Tell the user a scan is already running and ask whether to wait for it to complete or start a fresh one. Wait for the answer.
-If no scan is running (or the user chose to start a fresh one), trigger a new scan with `prowler_app_trigger_scan` and the `provider_id`. The link `https://cloud.prowler.com/scans?filter%5Bprovider_uid__in%5D={provider_id}` lets the user monitor progress.
+If no scan is running (or the user chose to start a fresh one), trigger a new scan with `prowler_trigger_scan` and the `provider_id`. The link `https://cloud.prowler.com/scans?filter%5Bprovider_uid__in%5D={provider_id}` lets the user monitor progress.
When a scan is in progress (either pre-existing and elected to wait, or just triggered), stop the flow and ask the user to return when it's completed — restart this section to re-check the results.
@@ -85,7 +85,7 @@ Status taxonomy for failed requirements and their findings:
### Report template
-A fresh report is rendered like this (substituting values from the `prowler_app_get_compliance_framework_state_details` Prowler MCP tool response):
+A fresh report is rendered like this (substituting values from the `prowler_get_compliance_framework_state_details` Prowler MCP tool response):
````markdown
# Compliance report:
@@ -120,7 +120,7 @@ A fresh report is rendered like this (substituting values from the `prowler_app_
Resolve the report path for the current `compliance_id` and provider account.
-If the file does not exist, call `prowler_app_get_compliance_framework_state_details` for the target scan, render the template above, and write the file with one initialization entry in the activity log.
+If the file does not exist, call `prowler_get_compliance_framework_state_details` for the target scan, render the template above, and write the file with one initialization entry in the activity log.
If the file exists, read it and compare its `Scan ID` to the target scan from section 1.3. When the scan matches, reuse the file and summarize remaining `[FAIL]` and `[IN PROGRESS]` items in chat.
@@ -128,7 +128,7 @@ If the file exists, read it and compare its `Scan ID` to the target scan from se
>
> Tell the user the report on disk was generated from a different scan and ask whether to refresh it from the new scan. Wait for the answer.
-On confirmation, regenerate the failed-requirements section from the new `prowler_app_get_compliance_framework_state_details` response, carry forward the **Global remediation approach** block and the full activity log, and append an activity-log entry noting the scan change.
+On confirmation, regenerate the failed-requirements section from the new `prowler_get_compliance_framework_state_details` response, carry forward the **Global remediation approach** block and the full activity log, and append an activity-log entry noting the scan change.
Once the file is current, surface the top failing requirements in chat: sort by finding count descending, show the top 5 with their codes and counts, and point to the file path for the full list.
@@ -174,7 +174,7 @@ Once approved, the loop proceeds through the batch without further prompts unles
Pick the first `[FAIL]` requirement at the top of the failed-requirements section. Move its status and every finding under it to `[IN PROGRESS]`, and add a `**Fix plan**:` sub-bullet describing what will be done.
-Call `prowler_app_get_finding_details` for each `finding_id` to retrieve the failing resource and the Prowler Hub's remediation guidance for that check using the tool `prowler_hub_get_check_details` with the `check_id` from the finding details. Summarize the guidance in chat, and append it to the `**Fix plan**` note for each finding.
+Call `prowler_get_finding_details` for each `finding_id` to retrieve the failing resource and the Prowler Hub's remediation guidance for that check using the tool `prowler_hub_get_check_details` with the `check_id` from the finding details. Summarize the guidance in chat, and append it to the `**Fix plan**` note for each finding.
If a finding does not apply to the target resource (Organization-only check on a User account, paid-tier feature, missing resource type, etc.), set the requirement status to `[SKIPPED]` with the reason, log it in the activity log, and move on without attempting the fix — even if it was missed during §3.2.
@@ -194,6 +194,6 @@ Move to the next `[FAIL]` requirement and repeat from section 3.3.
> **Checkpoint — Rescan trigger** *(conditional: no `[FAIL]` requirements remain; all are `[FIXED-UNVERIFIED]` or `[SKIPPED]`)*
>
-> Summarize what was applied, list any `[SKIPPED]` items with reasons, and ask whether to trigger a fresh scan with `prowler_app_trigger_scan` to verify the fixes end-to-end. Wait for the answer.
+> Summarize what was applied, list any `[SKIPPED]` items with reasons, and ask whether to trigger a fresh scan with `prowler_trigger_scan` to verify the fixes end-to-end. Wait for the answer.
On confirmation, trigger the rescan. When it completes, restart section 2.1 with the carry-forward path — requirements no longer in the new FAIL list move to `[PASS]`, anything still failing reverts to `[FAIL]` with the previous fix attempt visible in the activity log.
diff --git a/contrib/aws/multi-account-securityhub/Dockerfile b/contrib/aws/multi-account-securityhub/Dockerfile
index de5c57ba7b..7e5e7f5182 100644
--- a/contrib/aws/multi-account-securityhub/Dockerfile
+++ b/contrib/aws/multi-account-securityhub/Dockerfile
@@ -1,7 +1,7 @@
# Build command
# docker build --platform=linux/amd64 --no-cache -t prowler:latest .
-ARG PROWLER_VERSION=latest@sha256:4b796c6df40a3350c7947747b59bdda230d0da6222287500e13b0a8e1574aad4
+ARG PROWLER_VERSION=latest@sha256:ebb4ab999f10cb7e7c256226c2873de9b3bf2f3d855f385e0164bcf34104bfba
FROM toniblyx/prowler:${PROWLER_VERSION}
diff --git a/contrib/k8s/helm/prowler-app/templates/api/configmap.yaml b/contrib/k8s/helm/prowler-app/templates/api/configmap.yaml
index 8e219a9271..a76982d403 100644
--- a/contrib/k8s/helm/prowler-app/templates/api/configmap.yaml
+++ b/contrib/k8s/helm/prowler-app/templates/api/configmap.yaml
@@ -7,4 +7,4 @@ metadata:
data:
{{- range $key, $value := .Values.api.djangoConfig }}
{{ $key }}: {{ $value | quote }}
- {{- end }}
\ No newline at end of file
+ {{- end }}
diff --git a/contrib/k8s/helm/prowler-app/templates/api/role.yaml b/contrib/k8s/helm/prowler-app/templates/api/role.yaml
index 172b035076..f55d3c7dc9 100644
--- a/contrib/k8s/helm/prowler-app/templates/api/role.yaml
+++ b/contrib/k8s/helm/prowler-app/templates/api/role.yaml
@@ -26,4 +26,4 @@ roleRef:
subjects:
- kind: ServiceAccount
name: {{ include "prowler.api.serviceAccountName" . }}
- namespace: {{ .Release.Namespace }}
\ No newline at end of file
+ namespace: {{ .Release.Namespace }}
diff --git a/contrib/reverse-proxy/docker-compose.reverse-proxy.yml b/contrib/reverse-proxy/docker-compose.reverse-proxy.yml
index b8f8edec30..cb6bd9c3a2 100644
--- a/contrib/reverse-proxy/docker-compose.reverse-proxy.yml
+++ b/contrib/reverse-proxy/docker-compose.reverse-proxy.yml
@@ -16,7 +16,7 @@
services:
nginx:
- image: nginx:alpine@sha256:8b1e78743a03dbb2c95171cc58639fef29abc8816598e27fb910ed2e621e589a
+ image: nginx:alpine@sha256:54f2a904c251d5a34adf545a72d32515a15e08418dae0266e23be2e18c66fefa
container_name: prowler-nginx
restart: unless-stopped
ports:
diff --git a/dashboard/__main__.py b/dashboard/__main__.py
index 664ce3bfa5..6a36bda7ed 100644
--- a/dashboard/__main__.py
+++ b/dashboard/__main__.py
@@ -20,7 +20,7 @@ print_banner()
print(
f"{Fore.GREEN}Loading all CSV files from the folder {folder_path_overview} ...\n{Style.RESET_ALL}"
)
-cli.show_server_banner = lambda *x: click.echo(
+cli.show_server_banner = lambda *_: click.echo(
f"{Fore.YELLOW}NOTE:{Style.RESET_ALL} If you are using {Fore.GREEN}{Style.BRIGHT}Prowler Cloud{Style.RESET_ALL} with the S3 integration or that integration \nfrom {Fore.CYAN}{Style.BRIGHT}Prowler CLI{Style.RESET_ALL} and you want to use your data from your S3 bucket,\nrun: `{orange_color}aws s3 cp s3:///output/csv ./output --recursive{Style.RESET_ALL}`\nand then run `prowler dashboard` again to load the new files."
)
@@ -33,148 +33,187 @@ dashboard = dash.Dash(
title="Prowler Dashboard",
)
-# Logo
-prowler_logo = html.Img(
- src="https://cdn.prod.website-files.com/68c4ec3f9fb7b154fbcb6e36/68ffb46d40ed7faa37a592a5_prowler-logo.png",
- alt="Prowler Logo",
+# ``use_pages`` above already imported dashboard/pages/cloud.py and registered
+# every /cloud/* route. Import its metadata now (after app instantiation) so
+# the sidebar and the gated pages share a single source of truth.
+from dashboard.pages.cloud import CLOUD_FEATURES_BY_SLUG # noqa: E402
+
+ICON_DIR = "/assets/images/icons/cloud"
+
+# Official marketing "PROWLER / LOCAL DASHBOARD" lockup (white wordmark + teal
+# gradient sublabel) shown in the expanded sidebar. Vector SVG so it stays crisp
+# at any DPI. The sublabel is right-anchored (text-anchor="end"), so a font
+# fallback widens it leftward rather than clipping at the edge.
+prowler_lockup = html.Img(
+ src=f"{ICON_DIR}/prowler-lockup.svg",
+ alt="Prowler Local Dashboard",
+ className="pc-brand-lockup",
)
-menu_icons = {
- "overview": "/assets/images/icons/overview.svg",
- "compliance": "/assets/images/icons/compliance.svg",
-}
+# Compact brand mark shown only when the sidebar collapses to its icon rail.
+prowler_mark = html.Img(
+ src=f"{ICON_DIR}/prowler-mark.svg",
+ alt="Prowler",
+ className="pc-brand-mark",
+)
+
+# Locally functional destinations (Overview + Compliance).
+DASHBOARD_ITEMS = [
+ {"label": "Overview", "route": "/", "icon": f"{ICON_DIR}/overview.svg"},
+ {
+ "label": "Compliance",
+ "route": "/compliance",
+ "icon": f"{ICON_DIR}/compliance.svg",
+ },
+]
+
+# Gated navigation groups reference the shared feature metadata by slug so the
+# sidebar and the informational pages never drift apart.
+GATED_GROUPS = [
+ ("Upgrade to Prowler Cloud", ["lighthouse-ai", "attack-paths", "findings"]),
+ ("Configuration", ["alerts", "mutelist", "integrations"]),
+ ("Workspace", ["organization"]),
+]
+
+HELP_LINKS = [
+ {
+ "title": "Help",
+ "url": "https://github.com/prowler-cloud/prowler/issues",
+ "icon": f"{ICON_DIR}/help.svg",
+ },
+ {
+ "title": "Docs",
+ "url": "https://docs.prowler.com",
+ "icon": f"{ICON_DIR}/docs.svg",
+ },
+]
-# Function to generate navigation links
-def generate_nav_links(current_path):
- nav_links = []
- for page in dash.page_registry.values():
- # Gets the icon URL based on the page name
- icon_url = menu_icons.get(page["name"].lower())
- is_active = (
- " bg-prowler-stone-950 border-r-4 border-solid border-prowler-lime"
- if current_path == page["relative_path"]
- else ""
- )
- link_class = f"block hover:bg-prowler-stone-950 hover:border-r-4 hover:border-solid hover:border-prowler-lime{is_active}"
+def _mask_style(icon_url):
+ """Inline style rendering a recolorable mask icon from a local asset."""
+ return {
+ "WebkitMaskImage": f"url({icon_url})",
+ "maskImage": f"url({icon_url})",
+ }
- link_content = html.Span(
+
+def _nav_icon(icon_url):
+ return html.Span(className="pc-ico", style=_mask_style(icon_url))
+
+
+def _nav_item(label, route, icon_url, current_path, gated=False):
+ is_active = current_path == route
+ class_name = "pc-nav-item pc-active" if is_active else "pc-nav-item"
+
+ content = [
+ _nav_icon(icon_url),
+ html.Span(label, className="pc-nav-label"),
+ ]
+ if gated:
+ content.append(html.Span("Prowler Cloud", className="pc-pill"))
+
+ return dcc.Link(content, href=route, className=class_name)
+
+
+def _section_label(title):
+ return html.Div(title, className="pc-section")
+
+
+def generate_sidebar(current_path):
+ children = [
+ # Brand lockup: full wordmark when expanded, compact mark when collapsed.
+ html.Div(
+ [prowler_lockup, prowler_mark],
+ className="pc-brand",
+ ),
+ # Dashboards section — the only locally functional destinations.
+ _section_label("Dashboards"),
+ html.Nav(
[
- html.Img(src=icon_url, className="w-5"),
- html.Span(
- page["name"], className="font-medium text-base leading-6 text-white"
- ),
+ _nav_item(item["label"], item["route"], item["icon"], current_path)
+ for item in DASHBOARD_ITEMS
],
- className="flex justify-center lg:justify-normal items-center gap-x-3 py-2 px-3",
- )
-
- nav_link = html.Li(
- dcc.Link(link_content, href=page["relative_path"], className=link_class)
- )
- nav_links.append(nav_link)
- return nav_links
-
-
-def generate_help_menu():
- help_links = [
- {
- "title": "Help",
- "url": "https://github.com/prowler-cloud/prowler/issues",
- "icon": "/assets/images/icons/help.png",
- },
- {
- "title": "Docs",
- "url": "https://docs.prowler.com",
- "icon": "/assets/images/icons/docs.png",
- },
+ className="pc-nav",
+ ),
]
- link_class = "block hover:bg-prowler-stone-950 hover:border-r-4 hover:border-solid hover:border-prowler-lime"
-
- menu_items = []
- for link in help_links:
- menu_item = html.Li(
- html.A(
- html.Span(
- [
- html.Img(src=link["icon"], className="w-5"),
- html.Span(
- link["title"],
- className="font-medium text-base leading-6 text-white",
- ),
- ],
- className="flex items-center gap-x-3 py-2 px-3",
- ),
- href=link["url"],
- target="_blank",
- className=link_class,
+ # Gated groups (Prowler Cloud only).
+ for section_title, slugs in GATED_GROUPS:
+ children.append(_section_label(section_title))
+ children.append(
+ html.Nav(
+ [
+ _nav_item(
+ CLOUD_FEATURES_BY_SLUG[slug]["nav_label"],
+ CLOUD_FEATURES_BY_SLUG[slug]["route"],
+ CLOUD_FEATURES_BY_SLUG[slug]["icon"],
+ current_path,
+ gated=True,
+ )
+ for slug in slugs
+ ],
+ className="pc-nav",
)
)
- menu_items.append(menu_item)
- return menu_items
+ # Help and Docs pinned to the bottom, separated by a neutral top border.
+ children.append(
+ html.Nav(
+ [
+ html.A(
+ [
+ _nav_icon(link["icon"]),
+ html.Span(link["title"], className="pc-nav-label"),
+ ],
+ href=link["url"],
+ target="_blank",
+ rel="noopener noreferrer",
+ className="pc-nav-item",
+ )
+ for link in HELP_LINKS
+ ],
+ className="pc-nav pc-footer",
+ )
+ )
+
+ return html.Div(children, className="pc-sidebar pc-font")
# Layout
dashboard.layout = html.Div(
[
- dcc.Location(id="url", refresh=False),
html.Link(rel="icon", href="assets/favicon.ico"),
- # Placeholder for dynamic navigation bar
html.Div(
[
+ # Dynamic sidebar (rebuilt on navigation for active state).
+ html.Div(id="navigation-bar"),
+ # Main pane hosting the routed page content.
html.Div(
- id="navigation-bar", className="bg-prowler-stone-900 min-w-36 z-10"
- ),
- html.Div(
- [
+ html.Div(
dash.page_container,
- ],
+ className="pc-main-inner",
+ ),
id="content_select",
- className="bg-prowler-white w-full col-span-11 h-screen mx-auto overflow-y-scroll no-scrollbar px-10 py-7",
+ className="pc-main pc-font no-scrollbar",
),
],
- className="grid custom-grid 2xl:custom-grid-large h-screen",
+ className="pc-shell",
),
],
className="h-screen mx-auto",
)
-# Callback to update navigation bar
-@dashboard.callback(Output("navigation-bar", "children"), [Input("url", "pathname")])
+# Callback to update navigation bar.
+#
+# Triggered off Dash Pages' own location (``_pages_location``) rather than a
+# separate ``dcc.Location``. A standalone ``dcc.Location(id="url")`` stops
+# emitting ``pathname`` when navigating between two pages that render an
+# identical component tree — every ``/cloud/*`` gated page shares the same
+# ``build_cloud_layout`` structure — which left the active highlight stuck on
+# the first gated page visited. ``_pages_location`` fires on every route change.
+@dashboard.callback(
+ Output("navigation-bar", "children"), [Input("_pages_location", "pathname")]
+)
def update_nav_bar(pathname):
- return html.Div(
- [
- html.Div([prowler_logo], className="mb-8 px-3"),
- html.H6(
- "Dashboards",
- className="px-3 text-prowler-stone-500 text-sm opacity-90 font-regular mb-2",
- ),
- html.Nav(
- [html.Ul(generate_nav_links(pathname), className="")],
- className="flex flex-col gap-y-6",
- ),
- html.Nav(
- [
- html.A(
- [
- html.Span(
- [
- html.Img(src="assets/favicon.ico", className="w-5"),
- "Subscribe to Prowler Cloud",
- ],
- className="flex items-center gap-x-3 text-white",
- ),
- ],
- href="https://prowler.com/",
- target="_blank",
- className="block p-3 uppercase text-xs hover:bg-prowler-stone-950 hover:border-r-4 hover:border-solid hover:border-prowler-lime",
- ),
- html.Ul(generate_help_menu(), className=""),
- ],
- className="flex flex-col gap-y-6 mt-auto",
- ),
- ],
- className="flex flex-col bg-prowler-stone-900 py-7 h-full",
- )
+ return generate_sidebar(pathname)
diff --git a/dashboard/assets/cloud-pages.css b/dashboard/assets/cloud-pages.css
new file mode 100644
index 0000000000..53052eabda
--- /dev/null
+++ b/dashboard/assets/cloud-pages.css
@@ -0,0 +1,389 @@
+/*
+ * Prowler Local Dashboard — Cloud upsell chrome & gated pages.
+ * These styles are self-contained (not dependent on the precompiled Tailwind
+ * bundle) so pixel specs from the PRD render reliably without a rebuild.
+ */
+
+@import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap");
+
+:root {
+ --pc-btn: #6ee7b7;
+ --pc-btn-hover: #99f6e4;
+ --pc-btn-press: #34d399;
+ --pc-grad-start: #2ee59b;
+ --pc-grad-end: #62dff0;
+ --pc-text: #020617;
+ --pc-text-2: #27272a;
+ --pc-sidebar-bg: #27272a;
+ --pc-pane-bg: #fdfdfd;
+ --pc-border: #e5e5e5;
+ --pc-teal-accent: #2ee59b;
+ --pc-sidebar-w: 264px;
+ --pc-sidebar-w-collapsed: 82px;
+}
+
+.pc-font {
+ font-family: "Inter", system-ui, -apple-system, "Segoe UI", Roboto,
+ Helvetica, Arial, sans-serif;
+}
+
+/* ----------------------------------------------------------------- Shell */
+
+.pc-shell {
+ display: flex;
+ height: 100vh;
+ width: 100%;
+ overflow: hidden;
+}
+
+.pc-main {
+ flex: 1 1 auto;
+ height: 100vh;
+ overflow-y: auto;
+ background: var(--pc-pane-bg);
+}
+
+.pc-main-inner {
+ padding: 28px 40px 64px;
+}
+
+/* --------------------------------------------------------------- Sidebar */
+
+.pc-sidebar {
+ flex: 0 0 var(--pc-sidebar-w);
+ width: var(--pc-sidebar-w);
+ background: var(--pc-sidebar-bg);
+ height: 100vh;
+ display: flex;
+ flex-direction: column;
+ padding: 22px 0 16px;
+ overflow-y: auto;
+ overflow-x: hidden;
+}
+
+.pc-sidebar::-webkit-scrollbar {
+ display: none;
+}
+
+.pc-brand {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 0 18px;
+ margin-bottom: 22px;
+}
+
+.pc-brand-lockup {
+ width: 190px;
+ height: auto;
+ display: block;
+}
+
+/* Compact mark is only revealed on the collapsed icon rail (see media query). */
+.pc-brand-mark {
+ width: 30px;
+ height: 30px;
+ flex: 0 0 auto;
+ display: none;
+}
+
+.pc-section {
+ color: #8a8a90;
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.07em;
+ text-transform: uppercase;
+ padding: 0 18px;
+ margin: 18px 0 8px;
+}
+
+.pc-nav {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.pc-nav-item {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 9px 12px;
+ margin: 0 8px;
+ color: #ffffff;
+ font-size: 14px;
+ font-weight: 500;
+ text-decoration: none;
+ border-radius: 8px;
+ border-left: 3px solid transparent;
+ overflow: hidden;
+ transition: background 0.15s ease;
+}
+
+.pc-nav-item:hover {
+ background: rgba(255, 255, 255, 0.07);
+}
+
+.pc-nav-item.pc-active {
+ background: rgba(255, 255, 255, 0.09);
+ border-left-color: var(--pc-teal-accent);
+}
+
+.pc-nav-label {
+ flex: 0 1 auto;
+ min-width: 0;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+/* Icon rendered as a recolorable mask so one asset serves any color. */
+.pc-ico {
+ width: 20px;
+ height: 20px;
+ flex: 0 0 auto;
+ display: inline-block;
+ background-color: currentColor;
+ -webkit-mask-repeat: no-repeat;
+ mask-repeat: no-repeat;
+ -webkit-mask-position: center;
+ mask-position: center;
+ -webkit-mask-size: contain;
+ mask-size: contain;
+}
+
+.pc-pill {
+ flex: 0 0 auto;
+ margin-left: auto;
+ display: inline-flex;
+ align-items: center;
+ background: linear-gradient(
+ 112deg,
+ var(--pc-grad-start) 3.5%,
+ var(--pc-grad-end) 98.8%
+ );
+ color: var(--pc-text);
+ font-size: 10px;
+ font-weight: 700;
+ letter-spacing: 0.02em;
+ line-height: 1;
+ padding: 3px 8px;
+ border-radius: 9999px;
+ white-space: nowrap;
+}
+
+.pc-footer {
+ margin-top: auto;
+ padding-top: 12px;
+ border-top: 1px solid rgba(255, 255, 255, 0.1);
+}
+
+/* -------------------------------------------------------- Gated page body */
+
+.pc-page {
+ max-width: 1120px;
+ margin: 0 auto;
+}
+
+.pc-page-header {
+ border-bottom: 1px solid var(--pc-border);
+ padding-bottom: 18px;
+ margin-bottom: 28px;
+}
+
+.pc-page-title-row {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+
+/* In the page header the badge sits right next to the title (not pushed to the
+ far right like the sidebar pills) and is uppercased for emphasis. */
+.pc-page-title-row .pc-pill {
+ margin-left: 0;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+}
+
+.pc-page-title {
+ font-size: 24px;
+ font-weight: 700;
+ color: var(--pc-text);
+ margin: 0;
+}
+
+.pc-page-subtitle {
+ font-size: 15px;
+ line-height: 24px;
+ color: #52525b;
+ margin: 8px 0 0;
+}
+
+/* ----------------------------------------------------------- Upgrade card */
+
+.pc-card {
+ position: relative;
+ background: #ffffff;
+ border: 1px solid var(--pc-border);
+ border-radius: 18px;
+ padding: 56px 40px;
+ overflow: hidden;
+}
+
+.pc-card-glow {
+ position: absolute;
+ top: 0;
+ left: 50%;
+ transform: translateX(-50%);
+ width: 560px;
+ height: 240px;
+ background: radial-gradient(
+ ellipse at top,
+ rgba(46, 229, 155, 0.2),
+ rgba(98, 223, 240, 0.06) 45%,
+ transparent 72%
+ );
+ pointer-events: none;
+}
+
+.pc-card-body {
+ position: relative;
+ z-index: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ text-align: center;
+}
+
+.pc-feature-icon {
+ width: 64px;
+ height: 64px;
+ border-radius: 16px;
+ background: linear-gradient(
+ 135deg,
+ rgba(46, 229, 155, 0.16),
+ rgba(98, 223, 240, 0.14)
+ );
+ border: 1px solid rgba(46, 229, 155, 0.3);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--pc-text);
+ margin-bottom: 22px;
+}
+
+.pc-feature-icon .pc-ico {
+ width: 30px;
+ height: 30px;
+}
+
+.pc-avail {
+ color: #0e9f6e;
+ font-size: 12px;
+ font-weight: 700;
+ letter-spacing: 0.09em;
+ text-transform: uppercase;
+ margin-bottom: 8px;
+}
+
+.pc-card-title {
+ font-size: 24px;
+ font-weight: 700;
+ color: var(--pc-text);
+ margin: 0 0 14px;
+}
+
+.pc-card-desc {
+ font-size: 15px;
+ line-height: 24px;
+ color: var(--pc-text-2);
+ max-width: 560px;
+ margin: 0 0 26px;
+}
+
+.pc-benefits {
+ list-style: none;
+ padding: 0;
+ margin: 0 0 30px;
+ text-align: left;
+}
+
+.pc-benefit {
+ display: flex;
+ align-items: flex-start;
+ gap: 10px;
+ padding: 7px 0;
+ font-size: 15px;
+ line-height: 22px;
+ color: var(--pc-text-2);
+}
+
+.pc-benefit-check {
+ flex: 0 0 auto;
+ width: 18px;
+ height: 18px;
+ margin-top: 2px;
+ color: var(--pc-btn-press);
+}
+
+.pc-cta {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background: var(--pc-btn);
+ color: var(--pc-text);
+ font-size: 15px;
+ font-weight: 700;
+ padding: 12px 24px;
+ border-radius: 12px;
+ border: 1px solid var(--pc-btn-press);
+ text-decoration: none;
+ cursor: pointer;
+ transition: background 0.15s ease;
+}
+
+.pc-cta:hover {
+ background: var(--pc-btn-hover);
+ color: var(--pc-text);
+}
+
+.pc-cta:active {
+ background: var(--pc-btn-press);
+}
+
+/* --------------------------------------------------- Responsive collapse */
+
+@media (max-width: 900px) {
+ .pc-sidebar {
+ flex-basis: var(--pc-sidebar-w-collapsed);
+ width: var(--pc-sidebar-w-collapsed);
+ }
+
+ .pc-brand {
+ justify-content: center;
+ padding: 0 8px;
+ }
+
+ .pc-brand-lockup {
+ display: none;
+ }
+
+ .pc-brand-mark {
+ display: block;
+ }
+
+ .pc-section,
+ .pc-nav-label,
+ .pc-pill {
+ display: none;
+ }
+
+ .pc-nav-item {
+ justify-content: center;
+ margin: 0 6px;
+ padding: 10px 0;
+ }
+
+ .pc-main-inner {
+ padding: 20px 18px 48px;
+ }
+}
diff --git a/dashboard/assets/images/icons/cloud/alerts.svg b/dashboard/assets/images/icons/cloud/alerts.svg
new file mode 100644
index 0000000000..6109e378ab
--- /dev/null
+++ b/dashboard/assets/images/icons/cloud/alerts.svg
@@ -0,0 +1 @@
+
diff --git a/dashboard/assets/images/icons/cloud/attack-paths.svg b/dashboard/assets/images/icons/cloud/attack-paths.svg
new file mode 100644
index 0000000000..b856c6ea2f
--- /dev/null
+++ b/dashboard/assets/images/icons/cloud/attack-paths.svg
@@ -0,0 +1 @@
+
diff --git a/dashboard/assets/images/icons/cloud/check.svg b/dashboard/assets/images/icons/cloud/check.svg
new file mode 100644
index 0000000000..a5f8ed0c8a
--- /dev/null
+++ b/dashboard/assets/images/icons/cloud/check.svg
@@ -0,0 +1 @@
+
diff --git a/dashboard/assets/images/icons/cloud/compliance.svg b/dashboard/assets/images/icons/cloud/compliance.svg
new file mode 100644
index 0000000000..e70ebda28c
--- /dev/null
+++ b/dashboard/assets/images/icons/cloud/compliance.svg
@@ -0,0 +1,4 @@
+
diff --git a/dashboard/assets/images/icons/cloud/docs.svg b/dashboard/assets/images/icons/cloud/docs.svg
new file mode 100644
index 0000000000..efc3dfc61b
--- /dev/null
+++ b/dashboard/assets/images/icons/cloud/docs.svg
@@ -0,0 +1 @@
+
diff --git a/dashboard/assets/images/icons/cloud/findings.svg b/dashboard/assets/images/icons/cloud/findings.svg
new file mode 100644
index 0000000000..93fc42a516
--- /dev/null
+++ b/dashboard/assets/images/icons/cloud/findings.svg
@@ -0,0 +1 @@
+
diff --git a/dashboard/assets/images/icons/cloud/help.svg b/dashboard/assets/images/icons/cloud/help.svg
new file mode 100644
index 0000000000..2b3f1024e8
--- /dev/null
+++ b/dashboard/assets/images/icons/cloud/help.svg
@@ -0,0 +1 @@
+
diff --git a/dashboard/assets/images/icons/cloud/integrations.svg b/dashboard/assets/images/icons/cloud/integrations.svg
new file mode 100644
index 0000000000..e7a2d07603
--- /dev/null
+++ b/dashboard/assets/images/icons/cloud/integrations.svg
@@ -0,0 +1 @@
+
diff --git a/dashboard/assets/images/icons/cloud/lighthouse-ai.svg b/dashboard/assets/images/icons/cloud/lighthouse-ai.svg
new file mode 100644
index 0000000000..1c510ac1fc
--- /dev/null
+++ b/dashboard/assets/images/icons/cloud/lighthouse-ai.svg
@@ -0,0 +1 @@
+
diff --git a/dashboard/assets/images/icons/cloud/mutelist.svg b/dashboard/assets/images/icons/cloud/mutelist.svg
new file mode 100644
index 0000000000..1d498fa9e3
--- /dev/null
+++ b/dashboard/assets/images/icons/cloud/mutelist.svg
@@ -0,0 +1 @@
+
diff --git a/dashboard/assets/images/icons/cloud/organization.svg b/dashboard/assets/images/icons/cloud/organization.svg
new file mode 100644
index 0000000000..1f3d1da9f5
--- /dev/null
+++ b/dashboard/assets/images/icons/cloud/organization.svg
@@ -0,0 +1 @@
+
diff --git a/dashboard/assets/images/icons/cloud/overview.svg b/dashboard/assets/images/icons/cloud/overview.svg
new file mode 100644
index 0000000000..809e63d945
--- /dev/null
+++ b/dashboard/assets/images/icons/cloud/overview.svg
@@ -0,0 +1,4 @@
+
diff --git a/dashboard/assets/images/icons/cloud/prowler-lockup.svg b/dashboard/assets/images/icons/cloud/prowler-lockup.svg
new file mode 100644
index 0000000000..9daee36463
--- /dev/null
+++ b/dashboard/assets/images/icons/cloud/prowler-lockup.svg
@@ -0,0 +1 @@
+
diff --git a/dashboard/assets/images/icons/cloud/prowler-mark.svg b/dashboard/assets/images/icons/cloud/prowler-mark.svg
new file mode 100644
index 0000000000..eb30d44be8
--- /dev/null
+++ b/dashboard/assets/images/icons/cloud/prowler-mark.svg
@@ -0,0 +1 @@
+
diff --git a/dashboard/compliance/cis_2_0_1_kubernetes.py b/dashboard/compliance/cis_2_0_1_kubernetes.py
new file mode 100644
index 0000000000..94558f33ad
--- /dev/null
+++ b/dashboard/compliance/cis_2_0_1_kubernetes.py
@@ -0,0 +1,24 @@
+import warnings
+
+from dashboard.common_methods import get_section_containers_cis
+
+warnings.filterwarnings("ignore")
+
+
+def get_table(data):
+ aux = data[
+ [
+ "REQUIREMENTS_ID",
+ "REQUIREMENTS_DESCRIPTION",
+ "REQUIREMENTS_ATTRIBUTES_SECTION",
+ "CHECKID",
+ "STATUS",
+ "REGION",
+ "ACCOUNTID",
+ "RESOURCEID",
+ ]
+ ].copy()
+
+ return get_section_containers_cis(
+ aux, "REQUIREMENTS_ID", "REQUIREMENTS_ATTRIBUTES_SECTION"
+ )
diff --git a/dashboard/compliance/cis_5_0_gcp.py b/dashboard/compliance/cis_5_0_gcp.py
new file mode 100644
index 0000000000..94558f33ad
--- /dev/null
+++ b/dashboard/compliance/cis_5_0_gcp.py
@@ -0,0 +1,24 @@
+import warnings
+
+from dashboard.common_methods import get_section_containers_cis
+
+warnings.filterwarnings("ignore")
+
+
+def get_table(data):
+ aux = data[
+ [
+ "REQUIREMENTS_ID",
+ "REQUIREMENTS_DESCRIPTION",
+ "REQUIREMENTS_ATTRIBUTES_SECTION",
+ "CHECKID",
+ "STATUS",
+ "REGION",
+ "ACCOUNTID",
+ "RESOURCEID",
+ ]
+ ].copy()
+
+ return get_section_containers_cis(
+ aux, "REQUIREMENTS_ID", "REQUIREMENTS_ATTRIBUTES_SECTION"
+ )
diff --git a/dashboard/compliance/cis_6_0_azure.py b/dashboard/compliance/cis_6_0_azure.py
new file mode 100644
index 0000000000..9d33cc67a8
--- /dev/null
+++ b/dashboard/compliance/cis_6_0_azure.py
@@ -0,0 +1,25 @@
+import warnings
+
+from dashboard.common_methods import get_section_containers_cis
+
+warnings.filterwarnings("ignore")
+
+
+def get_table(data):
+
+ aux = data[
+ [
+ "REQUIREMENTS_ID",
+ "REQUIREMENTS_DESCRIPTION",
+ "REQUIREMENTS_ATTRIBUTES_SECTION",
+ "CHECKID",
+ "STATUS",
+ "REGION",
+ "ACCOUNTID",
+ "RESOURCEID",
+ ]
+ ].copy()
+
+ return get_section_containers_cis(
+ aux, "REQUIREMENTS_ID", "REQUIREMENTS_ATTRIBUTES_SECTION"
+ )
diff --git a/dashboard/compliance/cis_7_0_aws.py b/dashboard/compliance/cis_7_0_aws.py
new file mode 100644
index 0000000000..94558f33ad
--- /dev/null
+++ b/dashboard/compliance/cis_7_0_aws.py
@@ -0,0 +1,24 @@
+import warnings
+
+from dashboard.common_methods import get_section_containers_cis
+
+warnings.filterwarnings("ignore")
+
+
+def get_table(data):
+ aux = data[
+ [
+ "REQUIREMENTS_ID",
+ "REQUIREMENTS_DESCRIPTION",
+ "REQUIREMENTS_ATTRIBUTES_SECTION",
+ "CHECKID",
+ "STATUS",
+ "REGION",
+ "ACCOUNTID",
+ "RESOURCEID",
+ ]
+ ].copy()
+
+ return get_section_containers_cis(
+ aux, "REQUIREMENTS_ID", "REQUIREMENTS_ATTRIBUTES_SECTION"
+ )
diff --git a/dashboard/compliance/cis_7_0_m365.py b/dashboard/compliance/cis_7_0_m365.py
new file mode 100644
index 0000000000..94558f33ad
--- /dev/null
+++ b/dashboard/compliance/cis_7_0_m365.py
@@ -0,0 +1,24 @@
+import warnings
+
+from dashboard.common_methods import get_section_containers_cis
+
+warnings.filterwarnings("ignore")
+
+
+def get_table(data):
+ aux = data[
+ [
+ "REQUIREMENTS_ID",
+ "REQUIREMENTS_DESCRIPTION",
+ "REQUIREMENTS_ATTRIBUTES_SECTION",
+ "CHECKID",
+ "STATUS",
+ "REGION",
+ "ACCOUNTID",
+ "RESOURCEID",
+ ]
+ ].copy()
+
+ return get_section_containers_cis(
+ aux, "REQUIREMENTS_ID", "REQUIREMENTS_ATTRIBUTES_SECTION"
+ )
diff --git a/dashboard/lib/layouts.py b/dashboard/lib/layouts.py
index 3fb230f314..6d1e7947fa 100644
--- a/dashboard/lib/layouts.py
+++ b/dashboard/lib/layouts.py
@@ -156,7 +156,7 @@ def create_layout_compliance(
html.Img(src="assets/favicon.ico", className="w-5 mr-3"),
html.Span("Subscribe to Prowler Cloud"),
],
- href="https://cloud.prowler.com/",
+ href="https://cloud.prowler.com/sign-up?utm_source=prowler-local-dashboard&utm_content=compliance",
target="_blank",
className="text-prowler-stone-900 inline-flex px-4 py-2 text-xs font-bold uppercase transition-all rounded-lg text-gray-900 hover:bg-prowler-stone-900/10 border-solid border-1 hover:border-prowler-stone-900/10 hover:border-solid hover:border-1 border-prowler-stone-900/10",
),
diff --git a/dashboard/pages/cloud.py b/dashboard/pages/cloud.py
new file mode 100644
index 0000000000..49778f8e26
--- /dev/null
+++ b/dashboard/pages/cloud.py
@@ -0,0 +1,265 @@
+"""Prowler Cloud upsell (gated) informational pages.
+
+These routes live inside the Local Dashboard but do NOT reproduce any Prowler
+Cloud functionality. Each renders the same reusable upgrade template with a
+feature-specific name, icon, description, benefit bullets and UTM-tagged CTA.
+All copy in ``CLOUD_FEATURES`` is normative — do not change wording,
+capitalization or punctuation without Product approval.
+"""
+
+import dash
+from dash import html
+
+# Shared subtitle used across every gated page header.
+CLOUD_SUBTITLE = "Discover more ways to protect and operate your cloud."
+
+# Base Prowler Cloud URL; the UTM content value identifies the feature.
+CLOUD_CTA_BASE = (
+ "https://cloud.prowler.com/sign-up?utm_source=prowler-local-dashboard&utm_content="
+)
+
+# Path to the recolorable checkmark mask used for benefit bullets.
+CHECK_ICON = "/assets/images/icons/cloud/check.svg"
+
+
+# Normative feature definitions. ``icon`` points to a local mask asset so no
+# external requests are needed and the glyph recolors per context.
+CLOUD_FEATURES = [
+ {
+ "slug": "lighthouse-ai",
+ "route": "/cloud/lighthouse-ai",
+ "nav_label": "Lighthouse AI",
+ "page_title": "Lighthouse AI",
+ "card_title": "Unlock Lighthouse AI",
+ "description": (
+ "Work with an AI security analyst that understands your cloud "
+ "posture and helps turn risk into action."
+ ),
+ "benefits": [
+ "Ask questions about your security posture in plain language",
+ "Investigate findings with context from your connected providers",
+ "Move from insight to remediation faster",
+ ],
+ "utm_content": "lighthouse-ai",
+ "icon": "/assets/images/icons/cloud/lighthouse-ai.svg",
+ },
+ {
+ "slug": "attack-paths",
+ "route": "/cloud/attack-paths",
+ "nav_label": "Attack Paths",
+ "page_title": "Attack Paths",
+ "card_title": "Unlock Attack Paths",
+ "description": (
+ "Visualize the paths an attacker could take through connected "
+ "resources before risk becomes compromise."
+ ),
+ "benefits": [
+ "See exploitable relationships across your AWS environment",
+ "Focus remediation on the paths with the greatest impact",
+ "Explore each scan as a point-in-time security graph",
+ ],
+ "utm_content": "attack-paths",
+ "icon": "/assets/images/icons/cloud/attack-paths.svg",
+ },
+ {
+ "slug": "findings",
+ "route": "/cloud/findings",
+ "nav_label": "Findings",
+ "page_title": "Findings",
+ "card_title": "Unlock Findings",
+ "description": (
+ "Filter, investigate, and prioritize security findings across "
+ "providers and scans from one workspace."
+ ),
+ "benefits": [
+ "Search and filter findings across all connected accounts",
+ "Track status, severity, ownership, and remediation context",
+ "Triage findings and share a consistent source of truth with your security team",
+ ],
+ "utm_content": "findings",
+ "icon": "/assets/images/icons/cloud/findings.svg",
+ },
+ {
+ "slug": "alerts",
+ "route": "/cloud/alerts",
+ "nav_label": "Alerts",
+ "page_title": "Alerts",
+ "card_title": "Unlock Alerts",
+ "description": (
+ "Create alert rules and stay informed when scan results reveal "
+ "the risks your team cares about."
+ ),
+ "benefits": [
+ "Define alerts around the findings that matter most",
+ "Route security signals to the right responders",
+ "Reduce the time between detection and action",
+ ],
+ "utm_content": "alerts",
+ "icon": "/assets/images/icons/cloud/alerts.svg",
+ },
+ {
+ "slug": "mutelist",
+ "route": "/cloud/mutelist",
+ "nav_label": "Mutelist",
+ "page_title": "Mutelist",
+ "card_title": "Unlock Mutelist",
+ "description": (
+ "Quiet expected findings, document accepted risk, and keep your "
+ "team focused on actionable work."
+ ),
+ "benefits": [
+ "Create reusable rules for known exceptions",
+ "Keep muted findings available for audit and review",
+ "Cut noise without losing security context",
+ ],
+ "utm_content": "mutelist",
+ "icon": "/assets/images/icons/cloud/mutelist.svg",
+ },
+ {
+ "slug": "integrations",
+ "route": "/cloud/integrations",
+ "nav_label": "Integrations",
+ "page_title": "Integrations",
+ "card_title": "Unlock Integrations",
+ "description": (
+ "Connect Prowler to your security workflow so findings and scan "
+ "data reach the tools your team already uses."
+ ),
+ "benefits": [
+ "Connect ticketing, notification, and cloud security services",
+ "Automate the handoff from detection to response",
+ "Keep teams aligned without manual exports",
+ ],
+ "utm_content": "integrations",
+ "icon": "/assets/images/icons/cloud/integrations.svg",
+ },
+ {
+ "slug": "organization",
+ "route": "/cloud/organization",
+ "nav_label": "Organization",
+ "page_title": "Organization",
+ "card_title": "Unlock Organization",
+ "description": (
+ "Manage users, roles, and invitations while organizing cloud "
+ "security work across your team."
+ ),
+ "benefits": [
+ "Invite teammates into a shared security workspace",
+ "Control access with role-based permissions",
+ "Coordinate security operations across accounts and teams",
+ ],
+ "utm_content": "organization",
+ "icon": "/assets/images/icons/cloud/organization.svg",
+ },
+]
+
+# Convenience lookup for the navigation builder in ``__main__``.
+CLOUD_FEATURES_BY_SLUG = {feature["slug"]: feature for feature in CLOUD_FEATURES}
+
+
+def _mask_style(icon_url):
+ """Return the inline style that renders a recolorable mask icon."""
+ return {
+ "WebkitMaskImage": f"url({icon_url})",
+ "maskImage": f"url({icon_url})",
+ }
+
+
+def _benefit_item(text):
+ return html.Li(
+ [
+ html.Span(
+ className="pc-ico pc-benefit-check",
+ style=_mask_style(CHECK_ICON),
+ ),
+ html.Span(text),
+ ],
+ className="pc-benefit",
+ )
+
+
+def build_cloud_layout(feature):
+ """Build the reusable gated informational page for a single feature."""
+ cta_url = f"{CLOUD_CTA_BASE}{feature['utm_content']}"
+
+ return html.Div(
+ html.Div(
+ [
+ # Page header: title + Prowler Cloud badge + shared subtitle.
+ html.Div(
+ [
+ html.Div(
+ [
+ html.H1(
+ feature["page_title"],
+ className="pc-page-title",
+ ),
+ html.Span("Prowler Cloud", className="pc-pill"),
+ ],
+ className="pc-page-title-row",
+ ),
+ html.P(CLOUD_SUBTITLE, className="pc-page-subtitle"),
+ ],
+ className="pc-page-header",
+ ),
+ # Centered upgrade card.
+ html.Div(
+ [
+ html.Div(className="pc-card-glow"),
+ html.Div(
+ [
+ html.Div(
+ html.Span(
+ className="pc-ico",
+ style=_mask_style(feature["icon"]),
+ ),
+ className="pc-feature-icon",
+ ),
+ html.Div(
+ "Available in Prowler Cloud",
+ className="pc-avail",
+ ),
+ html.H2(
+ feature["card_title"],
+ className="pc-card-title",
+ ),
+ html.P(
+ feature["description"],
+ className="pc-card-desc",
+ ),
+ html.Ul(
+ [
+ _benefit_item(benefit)
+ for benefit in feature["benefits"]
+ ],
+ className="pc-benefits",
+ ),
+ html.A(
+ "Upgrade to Prowler Cloud",
+ href=cta_url,
+ target="_blank",
+ rel="noopener noreferrer",
+ className="pc-cta",
+ ),
+ ],
+ className="pc-card-body",
+ ),
+ ],
+ className="pc-card",
+ ),
+ ],
+ className="pc-page pc-font",
+ ),
+ )
+
+
+# Register one page per gated feature. A distinct module key keeps each entry
+# unique in Dash's page registry while sharing the same template.
+for _feature in CLOUD_FEATURES:
+ dash.register_page(
+ f"cloud_{_feature['slug'].replace('-', '_')}",
+ path=_feature["route"],
+ name=_feature["nav_label"],
+ title=f"Prowler Dashboard - {_feature['page_title']}",
+ layout=build_cloud_layout(_feature),
+ )
diff --git a/dashboard/pages/overview.py b/dashboard/pages/overview.py
index e705f15e9f..8f786412d9 100644
--- a/dashboard/pages/overview.py
+++ b/dashboard/pages/overview.py
@@ -1538,7 +1538,7 @@ def filter_data(
html.Img(src="assets/favicon.ico", className="w-5 mr-3"),
html.Span("Subscribe to Prowler Cloud"),
],
- href="https://cloud.prowler.com/",
+ href="https://cloud.prowler.com/sign-up?utm_source=prowler-local-dashboard&utm_content=overview",
target="_blank",
className="text-prowler-stone-900 inline-flex px-4 py-2 text-xs font-bold uppercase transition-all rounded-lg text-gray-900 hover:bg-prowler-stone-900/10 border-solid border-1 hover:border-prowler-stone-900/10 hover:border-solid hover:border-1 border-prowler-stone-900/10",
),
diff --git a/docs/AGENTS.md b/docs/AGENTS.md
index 8278a7f88a..45bd3f04fa 100644
--- a/docs/AGENTS.md
+++ b/docs/AGENTS.md
@@ -78,11 +78,25 @@ b. National security is of the utmost concern nowadays.
Prowler Features are considered proper nouns. They are to be referenced without articles in all pieces of writing.
-This is a list of Prowler Features:
+Prowler ships two product families. Use these names exactly; the former names Prowler App (now Prowler Local Server) and Prowler Enterprise (now Prowler Private Cloud) must not appear in new writing. The only allowed former-name notes are on the Prowler Product Families page (`getting-started/products/index.mdx`) and in the site-wide banner, which document the mapping.
+
+Prowler Products:
+
+* **Prowler Cloud**
+* **Prowler Private Cloud** (formerly Prowler Enterprise)
+* **Prowler Hub**
+* **Prowler Lighthouse AI**
+* **Prowler MCP**
+
+Open Source projects:
-* **Prowler App**
* **Prowler CLI**
+* **Prowler Local Server** (formerly Prowler App)
+* **Prowler Local Dashboard** (the Prowler CLI dashboard)
* **Prowler SDK**
+
+Other Prowler Features:
+
* **Built-in Compliance Checks**
* **Multi-cloud Security Scanning**
* **Autonomous Cloud Security Analyst (AI)**
@@ -97,8 +111,6 @@ This is a list of Prowler Features:
* **AI-Generated Detections & Remediations**
* **Prowler Studio**
* **Custom Security Policies**
-* **Prowler Cloud**
-* **Prowler Registry**
* **Open Source & Full APIs**
---
@@ -137,10 +149,10 @@ Explicit use of second-person pronouns (you) and possessives (your) should be mi
### Example of Improvement Through Avoiding Second Person Pronouns
**Original:**
-Prowler App can be installed in different ways, depending on your environment:
+Prowler Local Server can be installed in different ways, depending on your environment:
**Improved Version:**
-Prowler App offers flexible installation methods tailored to various environments:
+Prowler Local Server offers flexible installation methods tailored to various environments:
---
@@ -262,7 +274,7 @@ There are several options for punctuating bullet points. Regardless of the style
* **No punctuation (minimalistic):** This strategy is suitable when no verbs are involved and is best used to highlight products or features in isolation. For example:
- Prowler App is composed of three key components:
+ Prowler Local Server is composed of three key components:
* Prowler UI
* Prowler API
* Prowler SDK
@@ -271,7 +283,7 @@ There are several options for punctuating bullet points. Regardless of the style
* **Periods for full sentences:** This approach works best when each bullet point forms a full sentence or includes verbs. For example:
- Prowler App is composed of three key components:
+ Prowler Local Server is composed of three key components:
* Prowler UI, a web-based interface, built with Next.js, providing a user-friendly experience for executing Prowler scans and visualizing results.
* Prowler API, a backend service, developed with Django REST Framework, responsible for running Prowler scans and storing the generated results.
* Prowler SDK, a Python SDK designed to extend the functionality of the Prowler CLI for advanced capabilities.
@@ -539,6 +551,43 @@ Tag-Based Scanning allows filtering resources by AWS tags during security assess
---
+## AppliesTo Banner for Product Scope
+
+The AppliesTo component states which products a guide covers and links to the product families page. It is located at `docs/snippets/applies-to.mdx`.
+
+### When to Use the AppliesTo Banner
+
+Use it on web UI tutorial pages that apply to more than one product (for example, a guide written for Prowler Cloud whose steps also work on Prowler Local Server). Do not combine it with the SubscriptionBanner: pages carrying the SubscriptionBanner already state their availability.
+
+### How to Use the AppliesTo Banner
+
+```mdx
+import { AppliesTo } from "/snippets/applies-to.mdx"
+
+
+```
+
+The default covers Prowler Cloud, Prowler Private Cloud, and Prowler Local Server. Pass the `products` prop to narrow the scope:
+
+```mdx
+
+```
+
+Place it on its own line below the Version Badge when one is present, otherwise directly after the imports.
+
+### Cloud Marker for Subscription Content
+
+The custom green cloud glyph (`docs/images/icons/cloud-bold.svg`) marks content that requires a Prowler Cloud or Prowler Private Cloud subscription. It renders as a trailing `::after` element through the "Cloud marker" rules in `docs/style.css`, so sidebar labels stay left-aligned.
+
+* Pages: add a `li[id=""] a span::after` selector to the Cloud marker rule in `docs/style.css` for every page whose content is subscription-gated. The `li` id equals the page URL path. Pages where only one section is gated (for example the Support page, where only the Support Desk carries the SubscriptionBanner) get no marker.
+* Navigation groups: add a selector only when every page in the group is subscription-gated. One sanctioned exception: the Prowler MCP group is marked because the hosted server at `mcp.prowler.com` includes tools for Prowler Cloud-specific features, and its overview page explains the free local alternative. Nested groups render as `li[data-title=""]` with a button toggle, so use `li[data-title=""] > button span:first-child::after`. Top-level groups render as `h3` headings without `data-title`, which means name collisions with top-level groups resolve themselves; a gated top-level group (always expanded) is selected through its sibling list with `:has()`, like the Security tab group. Do not use `:has()` on child links of nested groups: collapsed groups do not render their children.
+
+Do not use the `icon` field for this marker (icons render before the label and misalign the sidebar), and do not use `"tag"` on navigation groups (group-level tags crash `mint broken-links` with a stack overflow, verified with mint 4.2.689). The SVG stroke uses the fixed brand green `#10B981` on purpose: it must be visible on both themes without `currentColor` support.
+
+The marker meaning is explained on the Prowler Product Families page at `getting-started/products/index.mdx`: keep that note in place.
+
+---
+
## Avoid Assumptions Regarding Audience’s Expertise
### Understand Your Audience’s Expertise
diff --git a/docs/README.md b/docs/README.md
index 595f79bc5a..7934972c9b 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -5,7 +5,7 @@ This repository contains the Prowler Open Source documentation powered by [Mintl
## Documentation Structure
- **Getting Started**: Overview, installation, and basic usage guides
-- **User Guide**: Comprehensive guides for Prowler App, CLI, providers, and compliance
+- **User Guide**: Comprehensive guides for Prowler Cloud, Prowler Local Server, Prowler CLI, providers, and compliance
- **Developer Guide**: Technical documentation for developers contributing to Prowler
## Local Development
@@ -13,7 +13,7 @@ This repository contains the Prowler Open Source documentation powered by [Mintl
Install a reviewed version of the [Mintlify CLI](https://www.npmjs.com/package/mint) to preview documentation changes locally:
```bash
-npm install --global mint@4.2.560
+npm install --global mint@4.2.689
```
Run the following command at the root of your documentation (where `mint.json` is located):
diff --git a/docs/developer-guide/checks.mdx b/docs/developer-guide/checks.mdx
index 2f0f45cd96..5334799d36 100644
--- a/docs/developer-guide/checks.mdx
+++ b/docs/developer-guide/checks.mdx
@@ -445,3 +445,5 @@ The metadata structure is enforced in code using a Pydantic model. For reference
## Specific Check Patterns
Details for specific providers can be found in documentation pages named using the pattern `-details`.
+
+Checks that scan resources for plaintext secrets follow a dedicated batched structure. Refer to [Secret-Scanning Checks](/developer-guide/secret-scanning-checks) before creating or updating one.
diff --git a/docs/developer-guide/configurable-checks.mdx b/docs/developer-guide/configurable-checks.mdx
index 760dc80f58..f550ff4f52 100644
--- a/docs/developer-guide/configurable-checks.mdx
+++ b/docs/developer-guide/configurable-checks.mdx
@@ -42,10 +42,14 @@ When adding a new configurable check to Prowler, update the following files:
```
- **Provider Schema:** Add the typed field to the provider's Pydantic schema in `prowler/config/schema/.py`. This is required: the loader validates user configs against these schemas and the shipped `config.yaml` must round-trip with zero warnings. See [Adding a Parameter to the Provider Schema](#adding-a-parameter-to-the-provider-schema) below.
- **Test Fixtures:** If tests depend on this configuration, add the variable to `tests/config/fixtures/config.yaml`.
-- **Documentation:** Document the new variable in the list of configurable checks in `docs/tutorials/configuration_file.md`.
+- **Documentation:** Document the new variable in the list of configurable checks in [Configuration File](/user-guide/cli/tutorials/configuration_file) (`docs/user-guide/cli/tutorials/configuration_file.mdx`).
For a complete list of checks that already support configuration, see the [Configuration File Tutorial](/user-guide/cli/tutorials/configuration_file).
+
+Because a configurable check's verdict depends on the `audit_config` value it reads, a compliance requirement can lose meaning if the scan ran with a looser threshold than the control demands. Compliance frameworks can guard against this with **configuration guardrails**: a requirement declares the strictest configuration it tolerates and is forced to FAIL when the scan's config falls short. See [Configuration Guardrails for Requirements](/developer-guide/security-compliance-framework#configuration-guardrails-for-requirements).
+
+
## Adding a Parameter to the Provider Schema
Most providers have a typed Pydantic schema in `prowler/config/schema/`, registered in `prowler/config/schema/registry.py`. When a config is loaded and the provider has a registered schema, `validate_provider_config` checks each user-supplied key against it, logs a warning, and drops any field that fails validation. The consumer's `.get(key, default)` then falls back to the built-in default. Providers without a registered schema are passed through unchanged.
@@ -149,7 +153,6 @@ Only fields with a numeric range, a fixed value set, or a length cap are listed.
| `max_days_secret_unused` | `7..365` days | |
| `max_days_secret_unrotated` | `1..180` days | NIST IA-5: rotate quarterly; CIS ≤90 |
| `min_kinesis_stream_retention_hours` | `24..8760` h | 1 day .. 1 year |
-| `detect_secrets_plugins[].limit` | `0.0..10.0` | Shannon entropy threshold |
| `shodan_api_key` | ≤512 chars | |
### Azure
diff --git a/docs/developer-guide/documentation.mdx b/docs/developer-guide/documentation.mdx
index d0fb808af2..fd045a1751 100644
--- a/docs/developer-guide/documentation.mdx
+++ b/docs/developer-guide/documentation.mdx
@@ -8,9 +8,9 @@ Prowler documentation is built using [Mintlify](https://www.mintlify.com/docs),
The Prowler documentation is organized into several sections. The main ones are:
-- **Getting Started**: Provides an overview of the Prowler platform and its different solutions, including Prowler Cloud/App, Prowler CLI, Prowler MCP Server, Prowler Hub, and Prowler Lighthouse AI. This section helps new users understand which Prowler solution best fits their needs and includes product comparisons.
+- **Getting Started**: Provides an overview of the Prowler platform and its two product families, Prowler Products (Prowler Cloud, Prowler Hub, Prowler MCP, Prowler Lighthouse AI) and Open Source (Prowler CLI, Prowler Local Server). This section helps new users understand which Prowler solution best fits their needs and includes product comparisons.
-- **Guides**: Contains practical tutorials and how-to guides organized by product (Prowler Cloud/App, CLI) and provider (AWS, Azure, GCP, Kubernetes, Microsoft 365, GitHub, etc.). This section covers authentication, integrations, compliance, and advanced usage scenarios.
+- **Guides**: Contains practical tutorials and how-to guides organized by product (Prowler Cloud, CLI) and provider (AWS, Azure, GCP, Kubernetes, Microsoft 365, GitHub, etc.). This section covers authentication, integrations, compliance, and advanced usage scenarios.
- **Developer Guide**: Documentation for contributors looking to extend Prowler functionality. This includes guides on creating providers, services, checks, output formats, integrations, and compliance frameworks. Provider-specific implementation details and testing strategies are also covered here.
diff --git a/docs/developer-guide/end2end-testing.mdx b/docs/developer-guide/end2end-testing.mdx
index 9013a32245..df99de6fee 100644
--- a/docs/developer-guide/end2end-testing.mdx
+++ b/docs/developer-guide/end2end-testing.mdx
@@ -1,12 +1,12 @@
---
-title: 'End-2-End Tests for Prowler App'
+title: 'End-2-End Tests for Prowler Local Server'
---
-End-to-end (E2E) tests validate complete user flows in Prowler App (UI + API). These tests are implemented with [Playwright](https://playwright.dev/) under the `ui/tests` folder and are designed to run against a Prowler App environment.
+End-to-end (E2E) tests validate complete user flows in Prowler Local Server (UI + API). These tests are implemented with [Playwright](https://playwright.dev/) under the `ui/tests` folder and are designed to run against a Prowler Local Server environment.
## General Recommendations
-When adding or maintaining E2E tests for Prowler App, follow these guidelines:
+When adding or maintaining E2E tests for Prowler Local Server, follow these guidelines:
1. **Test real user journeys**
Focus on full workflows (for example, sign-up → login → add provider → launch scan) instead of low-level UI details already covered by unit or integration tests.
@@ -19,8 +19,8 @@ When adding or maintaining E2E tests for Prowler App, follow these guidelines:
3. **Use a Page Model (Page Object Model)**
- Encapsulate selectors and common actions in page classes instead of repeating them in each test.
- Leverage and extend the existing Playwright page models in `ui/tests`—such as `ProvidersPage`, `ScansPage`, and others—which are all based on the shared `BasePage`.
- - Page models for Prowler App pages should be placed in their respective entity folders (for example, `ui/tests/providers/providers-page.ts`).
- - Page models for external pages (not part of Prowler App) should be grouped in the `external` folder (for example, `ui/tests/external/github-page.ts`).
+ - Page models for Prowler Local Server pages should be placed in their respective entity folders (for example, `ui/tests/providers/providers-page.ts`).
+ - Page models for external pages (not part of Prowler Local Server) should be grouped in the `external` folder (for example, `ui/tests/external/github-page.ts`).
- This approach improves readability, reduces duplication, and makes refactors safer.
4. **Reuse authentication states (StorageState)**
@@ -193,7 +193,7 @@ When adding or maintaining E2E tests for Prowler App, follow these guidelines:
## Running Prowler Tests
-E2E tests for Prowler App run from the `ui` project using Playwright. The Playwright configuration lives in `ui/playwright.config.ts` and defines:
+E2E tests for Prowler Local Server run from the `ui` project using Playwright. The Playwright configuration lives in `ui/playwright.config.ts` and defines:
- `testDir: "./tests"` – location of E2E test files (relative to the `ui` project root, so `ui/tests`).
- `webServer` – how to start the Next.js development server and connect to Prowler API.
@@ -225,7 +225,7 @@ Before running E2E tests:
- Start Prowler API so it is reachable on that URL (for example, via `docker-compose-dev.yml` or the development orchestration used locally).
- If a different API URL is required, set `UI_API_BASE_URL` accordingly before running the tests.
-- **Ensure Prowler App UI is available**
+- **Ensure Prowler Local Server UI is available**
- Playwright automatically starts the Next.js server through the `webServer` block in `playwright.config.ts` (`pnpm run dev` by default).
- If the UI is already running on `http://localhost:3000`, Playwright will reuse the existing server when `reuseExistingServer` is `true`.
@@ -246,7 +246,7 @@ Before running E2E tests:
### Executing Tests
-To execute E2E tests for Prowler App:
+To execute E2E tests for Prowler Local Server:
1. **Run the full E2E suite (headless)**
diff --git a/docs/developer-guide/environment-variables.mdx b/docs/developer-guide/environment-variables.mdx
index 1f4d17ee2e..913444d84b 100644
--- a/docs/developer-guide/environment-variables.mdx
+++ b/docs/developer-guide/environment-variables.mdx
@@ -2,7 +2,7 @@
title: 'Environment Variable Naming Convention'
---
-Prowler is a monorepo composed of several runtime components — Prowler App (the web user interface), Prowler API (the backend), Prowler SDK, and Prowler MCP Server (Model Context Protocol) — that frequently share a single `.env` file. To keep that shared configuration unambiguous, each component namespaces its environment variables with a component-specific prefix.
+Prowler is a monorepo composed of several runtime components — Prowler Local Server (the web user interface), Prowler API (the backend), Prowler SDK, and Prowler MCP Server (Model Context Protocol) — that frequently share a single `.env` file. To keep that shared configuration unambiguous, each component namespaces its environment variables with a component-specific prefix.
## Component Prefixes
@@ -10,7 +10,7 @@ Each component owns a dedicated prefix for the environment variables it reads:
| Component | Prefix | Status |
|-----------|--------|--------|
-| Prowler App (web UI) | `UI_` | Adopted |
+| Prowler Local Server (web UI) | `UI_` | Adopted |
| Prowler API (backend) | `API_` | Planned |
| Prowler SDK | `SDK_` | Planned |
| Prowler MCP Server | `MCP_` | Planned |
@@ -21,11 +21,11 @@ Component prefixes solve three concrete problems in a shared configuration file:
- **Collisions in a shared `.env`:** Several components historically read identically named variables. The API base URL, for example, is consumed by more than one component, so a single unprefixed name is ambiguous. A component prefix removes that ambiguity.
- **Explicit ownership:** A prefix states, at a glance, which component consumes a variable.
-- **Reduced accidental exposure:** For Prowler App, scoping browser-facing configuration under one intentional prefix prevents server-only values from leaking into the client bundle.
+- **Reduced accidental exposure:** For Prowler Local Server, scoping browser-facing configuration under one intentional prefix prevents server-only values from leaking into the client bundle.
-## Prowler App
+## Prowler Local Server
-Prowler App has adopted the `UI_` prefix. Its public configuration is resolved from the container environment at runtime rather than inlined at build time, so a single pre-built image serves any deployment. For the operational details on changing these values without rebuilding the image, see [Troubleshooting](/troubleshooting).
+Prowler Local Server has adopted the `UI_` prefix. Its public configuration is resolved from the container environment at runtime rather than inlined at build time, so a single pre-built image serves any deployment. For the operational details on changing these values without rebuilding the image, see [Troubleshooting](/troubleshooting).
The former build-time variables map to the new runtime variables as follows:
@@ -37,7 +37,25 @@ The former build-time variables map to the new runtime variables as follows:
| `NEXT_PUBLIC_SENTRY_DSN`, `SENTRY_DSN` | `UI_SENTRY_DSN` |
| `NEXT_PUBLIC_SENTRY_ENVIRONMENT`, `SENTRY_ENVIRONMENT` | `UI_SENTRY_ENVIRONMENT` |
-The build-time-only Sentry variables used for source-map upload — `SENTRY_ORG`, `SENTRY_PROJECT`, `SENTRY_AUTH_TOKEN`, and `SENTRY_RELEASE` — keep their names, as they are not part of the App's runtime configuration.
+The build-time-only Sentry variables used for source-map upload — `SENTRY_ORG`, `SENTRY_PROJECT`, `SENTRY_AUTH_TOKEN`, and `SENTRY_RELEASE` — keep their names, as they are not part of Prowler Local Server's runtime configuration.
+
+## Enabling Third-Party Integrations
+
+Prowler Local Server gates each optional third-party integration behind an explicit enable flag. When an integration is configured through its new `UI_*` variables, it loads only when its flag is set to the exact string `"true"`; any other value, including unset, leaves it off. This default-off behavior keeps a deployment free of third-party egress unless it opts in. Deployments still using the deprecated legacy variable names keep loading without the flag, for backward compatibility (see [Deprecated Names](#deprecated-names)).
+
+| Integration | Enable flag | Required configuration when enabled |
+|-------------|-------------|-------------------------------------|
+| Sentry (error monitoring) | `UI_SENTRY_ENABLED` | `UI_SENTRY_DSN` |
+| Google Tag Manager | `UI_GOOGLE_TAG_MANAGER_ENABLED` | `UI_GOOGLE_TAG_MANAGER_ID` |
+| PostHog (product analytics) | `UI_POSTHOG_ENABLED` | `UI_POSTHOG_KEY` and `UI_POSTHOG_HOST` |
+
+When an integration is enabled but its required configuration is missing, Prowler Local Server fails fast at server startup with a clear error, so a misconfigured container never starts silently. A new `UI_*` value set while its enable flag is not `"true"` is ignored, and the server logs a one-time startup warning noting that the integration will not load. Legacy names follow the backward-compatible rule described in [Deprecated Names](#deprecated-names).
+
+PostHog support is currently limited to configuration validation: Prowler Local Server reads and validates the PostHog variables but does not yet load a PostHog client.
+
+
+Configuring an integration through the new `UI_*` variables now requires its enable flag. A deployment that adopted `UI_SENTRY_DSN` or `UI_GOOGLE_TAG_MANAGER_ID` must also set `UI_SENTRY_ENABLED=true` or `UI_GOOGLE_TAG_MANAGER_ENABLED=true` to keep the integration active. Deployments still using the legacy names (`NEXT_PUBLIC_*`, or `POSTHOG_KEY` and `POSTHOG_HOST`) keep working without the flag.
+
## Upcoming Breaking Change
@@ -49,5 +67,5 @@ Prowler API, Prowler SDK, and Prowler MCP Server have not yet adopted the conven
## Deprecated Names
-- **Prowler App:** The bare server-side `SENTRY_DSN` and `SENTRY_ENVIRONMENT` are no longer read; the server and edge runtimes now read `UI_SENTRY_DSN` and `UI_SENTRY_ENVIRONMENT`. The former `NEXT_PUBLIC_*` build-time variables are deprecated but still read at runtime as a fallback when the matching `UI_*` variable is unset. This fallback will be removed in a future release, so set the `UI_*` runtime variables on the running container.
+- **Prowler Local Server:** The bare server-side `SENTRY_DSN` and `SENTRY_ENVIRONMENT` are no longer read; the server and edge runtimes now read `UI_SENTRY_DSN` and `UI_SENTRY_ENVIRONMENT`. The former `NEXT_PUBLIC_*` names — and, for PostHog, the unprefixed `POSTHOG_KEY` and `POSTHOG_HOST` — are deprecated but stay backward compatible: they are read at runtime regardless of the enable flag, so an existing deployment keeps its integration active without opting in. The new `UI_*` names, by contrast, load only when the matching enable flag is set to `"true"`. These legacy names will be removed in a future release, so migrate to the `UI_*` runtime variables — and set the enable flag — on the running container.
- **Prowler API, Prowler SDK, and Prowler MCP Server:** The current, unprefixed variable names are deprecated. They continue to work today and will be removed once the prefixed convention is adopted for each component, as described in [Upcoming Breaking Change](#upcoming-breaking-change).
diff --git a/docs/developer-guide/introduction.mdx b/docs/developer-guide/introduction.mdx
index 1d434912ef..08c38ee17c 100644
--- a/docs/developer-guide/introduction.mdx
+++ b/docs/developer-guide/introduction.mdx
@@ -240,7 +240,7 @@ prowler/
├── README.md # Project overview and getting started
├── Makefile # Common development commands
├── Dockerfile # SDK Docker container
-├── docker-compose.yml # Prowler App Docker compose
+├── docker-compose.yml # Prowler Local Server Docker compose
└── ... # Other supporting files
```
diff --git a/docs/developer-guide/lighthouse-architecture.mdx b/docs/developer-guide/lighthouse-architecture.mdx
index e8acc6278c..e12eff9549 100644
--- a/docs/developer-guide/lighthouse-architecture.mdx
+++ b/docs/developer-guide/lighthouse-architecture.mdx
@@ -132,7 +132,7 @@ The MCP client manages connections to the Prowler MCP Server using a singleton p
- **Connection Management**: Retry logic with configurable attempts and delays
- **Tool Discovery**: Fetches available tools from MCP server on initialization
-- **Authentication Injection**: Automatically adds JWT tokens to `prowler_app_*` tool calls
+- **Authentication Injection**: Automatically adds JWT tokens to `prowler_*` tool calls
- **Reconnection**: Supports forced reconnection after server restarts
Key constants:
@@ -141,10 +141,14 @@ Key constants:
- `RECONNECT_INTERVAL_MS`: 5 minutes before retry after failure
```typescript
-// Authentication injection for Prowler App tools
+// Authentication injection for core prowler_ tools (Hub/Docs excluded)
private handleBeforeToolCall = ({ name, args }) => {
- // Only inject auth for prowler_app_* tools (user-specific data)
- if (!name.startsWith("prowler_app_")) {
+ // Only inject auth for prowler_* tools (user-specific data).
+ // The legacy prowler_app_ prefix is also accepted for a resilient rollout.
+ if (
+ !name.startsWith("prowler_") &&
+ !name.startsWith("prowler_app_")
+ ) {
return { args };
}
@@ -307,15 +311,15 @@ MCP tools are organized into three namespaces based on authentication requiremen
| Namespace | Auth Required | Description |
|-----------|---------------|-------------|
-| `prowler_app_*` | Yes (JWT) | Prowler Cloud/App tools for findings, providers, scans, resources |
+| `prowler_*` | Yes (JWT) | Prowler Cloud, Prowler Private Cloud, and Prowler Local Server tools for findings, providers, scans, resources |
| `prowler_hub_*` | No | Security checks catalog, compliance frameworks |
| `prowler_docs_*` | No | Documentation search and retrieval |
### Authentication Flow
-1. User authenticates with Prowler App, receiving a JWT token
+1. User authenticates with Prowler Local Server, receiving a JWT token
2. Token is stored in session and propagated via `authContextStorage`
-3. MCP client injects `Authorization: Bearer ` header for `prowler_app_*` calls
+3. MCP client injects `Authorization: Bearer ` header for `prowler_*` calls
4. MCP Server validates token and applies RLS filtering
### Tool Execution Pattern
@@ -323,7 +327,7 @@ MCP tools are organized into three namespaces based on authentication requiremen
The agent uses meta-tools rather than direct tool registration:
```
-Agent needs data → describe_tool("prowler_app_search_findings")
+Agent needs data → describe_tool("prowler_search_findings")
→ Returns parameter schema → execute_tool with parameters
→ MCP client adds auth header → MCP Server executes
→ Results returned to agent → Agent continues reasoning
diff --git a/docs/developer-guide/llm-details.mdx b/docs/developer-guide/llm-details.mdx
index 3647552c0f..3dc0f2653d 100644
--- a/docs/developer-guide/llm-details.mdx
+++ b/docs/developer-guide/llm-details.mdx
@@ -101,4 +101,4 @@ The LLM provider seamlessly integrates with Prowler's existing infrastructure:
- **Output Formats**: Supports all Prowler output formats (JSON, CSV, HTML, etc.)
- **Compliance Frameworks**: Integrates with Prowler's compliance reporting
- **Fixer Integration**: Supports automated remediation recommendations
-- **Dashboard Integration**: Compatible with Prowler App for centralized management
+- **Dashboard Integration**: Compatible with Prowler Cloud and Prowler Local Server for centralized management
diff --git a/docs/developer-guide/mcp-server.mdx b/docs/developer-guide/mcp-server.mdx
index 4174f0f730..6d409ccc02 100644
--- a/docs/developer-guide/mcp-server.mdx
+++ b/docs/developer-guide/mcp-server.mdx
@@ -18,11 +18,15 @@ The Prowler MCP Server brings the entire Prowler ecosystem to AI assistants thro
The server follows a modular architecture with three independent sub-servers:
-| Sub-Server | Auth Required | Description |
-|------------|---------------|-------------|
-| Prowler App | Yes | Full access to Prowler Cloud and Self-Managed features |
-| Prowler Hub | No | Security checks catalog with **over 1000 checks**, fixers, and **70+ compliance frameworks** |
-| Prowler Documentation | No | Full-text search and retrieval of official documentation |
+| Sub-Server | Tool Prefix | Auth Required | Description |
+|------------|-------------|---------------|-------------|
+| Prowler | `prowler_` | Yes | Full access to Prowler Cloud, Prowler Private Cloud, and Prowler Local Server features |
+| Prowler Hub | `prowler_hub_` | No | Security checks catalog with **over 2,000 checks**, fixers, and **70+ compliance frameworks** |
+| Prowler Documentation | `prowler_docs_` | No | Full-text search and retrieval of official documentation |
+
+
+The core Prowler sub-server is served under the `prowler_` tool prefix, while its source lives in the `prowler_app/` module for historical reasons. Tool names use the prefix; import paths use the module.
+
For a complete list of tools and their descriptions, see the [Tools Reference](/getting-started/basic-usage/prowler-mcp-tools).
@@ -53,9 +57,9 @@ mcp_server/prowler_mcp_server/
The MCP Server uses two patterns for tool registration:
1. **Direct Decorators** (Prowler Hub/Docs): Tools are registered using `@mcp.tool()` decorators
-2. **Auto-Discovery** (Prowler App): All public methods of `BaseTool` subclasses are auto-registered
+2. **Auto-Discovery** (`prowler_app`): All public methods of `BaseTool` subclasses are auto-registered
-## Adding Tools to Prowler App
+## Adding Tools to the `prowler_app` Sub-Server
### Step 1: Create the Tool Class
@@ -413,7 +417,7 @@ uv run prowler-mcp
uv run prowler-mcp --transport http --host 0.0.0.0 --port 8000
# Run with environment variables
-PROWLER_APP_API_KEY="pk_xxx" uv run prowler-mcp
+PROWLER_API_KEY="pk_xxx" uv run prowler-mcp
```
For complete installation and deployment options, see:
diff --git a/docs/developer-guide/provider.mdx b/docs/developer-guide/provider.mdx
index d3e7d3631f..af621c005a 100644
--- a/docs/developer-guide/provider.mdx
+++ b/docs/developer-guide/provider.mdx
@@ -3211,21 +3211,18 @@ class YourProviderAPITestCase(APITestCase):
#### 2.6.1. Add your mocked provider to the tests
-If needed, add your mocked provider to the tests config file so you can use it on the tests.
+If needed, add a named provider fixture or extend the provider factory defaults so tests can request only the provider they need.
**File:** `api/src/backend/conftest.py`
```python
@pytest.fixture
-def providers_fixture(tenants_fixture):
- tenant, *_ = tenants_fixture
- providerX = Provider.objects.create(
+def your_provider(provider_factory):
+ return provider_factory(
provider="your_provider",
uid="your_uid",
alias="your_alias",
- tenant_id=tenant.id,
)
- return provider1, provider2, provider3, ... providerX
```
### 2.7. Compliance and Output Support
@@ -3421,7 +3418,7 @@ Use existing providers as templates, this will help you to understand better the
- **Documentation & Maintenance**
- **README Updates**: Update provider-specific documentation
- - **Changelog**: Document changes and new features
+ - **Changelog**: Document changes and new features with a fragment under `prowler/changelog.d/` (see the [Pull Request Template](https://github.com/prowler-cloud/prowler/blob/master/.github/pull_request_template.md))
- **Examples**: Provide usage examples and common scenarios
- **Troubleshooting**: Include common issues and solutions
- **Documentation**: Update the provider documentation to include your new tool provider in the examples and implementation guidance.
diff --git a/docs/developer-guide/prowler-studio.mdx b/docs/developer-guide/prowler-studio.mdx
index a4a2a609b5..b89eea7175 100644
--- a/docs/developer-guide/prowler-studio.mdx
+++ b/docs/developer-guide/prowler-studio.mdx
@@ -5,7 +5,7 @@ title: 'Prowler Studio'
**Prowler Studio is an AI workflow that ensures Claude Code follows Prowler's skills, guardrails, and best practices when creating new security checks.** What lands in the resulting pull request is consistent, tested, and ready for human review — not half-correct boilerplate that needs to be rewritten.
-**Contributor Tool**: Prowler Studio is a workflow for advanced contributors adding new Prowler security checks. It is not part of Prowler Cloud, Prowler App, or Prowler CLI.
+**Contributor Tool**: Prowler Studio is a workflow for advanced contributors adding new Prowler security checks. It is not part of Prowler Cloud, Prowler Local Server, or Prowler CLI.
diff --git a/docs/developer-guide/secret-scanning-checks.mdx b/docs/developer-guide/secret-scanning-checks.mdx
new file mode 100644
index 0000000000..5044366b7e
--- /dev/null
+++ b/docs/developer-guide/secret-scanning-checks.mdx
@@ -0,0 +1,119 @@
+---
+title: 'Secret-Scanning Checks'
+---
+
+import { VersionBadge } from "/snippets/version-badge.mdx"
+
+
+
+Prowler scans audited resources for plaintext secrets using [Kingfisher](https://github.com/mongodb/kingfisher), an open-source secret-scanning engine that Prowler invokes as a subprocess. This guide explains the structure every secret-scanning check must follow to keep scanning correct and efficient on large accounts.
+
+
+Since Prowler 5.32.0 the secret-scanning checks scan with Kingfisher. Earlier versions used the `detect-secrets` library.
+
+
+## Overview
+
+Secret detection runs through a single helper in `prowler/lib/utils/utils.py`:
+
+- **`detect_secrets_scan_batch(payloads, excluded_secrets=..., validate=...)`** scans many payloads in chunked subprocess invocations and returns a `{key: [findings]}` dictionary. To scan a single payload, pass a one-entry mapping (for example, `{0: data}`).
+
+Every Kingfisher invocation carries a fixed process-startup cost (around 100 ms). Scanning once per resource would spawn thousands of subprocesses on large accounts (for example, thousands of CloudWatch log groups). `detect_secrets_scan_batch` amortizes that cost: it writes each payload to a temporary file as it consumes them, runs one subprocess per chunk (500 payloads by default), and maps the findings back to each payload by key.
+
+## The Batched Structure
+
+Every secret-scanning check follows three phases.
+
+### Phase 1: Collect
+
+Define a generator that yields `(key, payload)` for each scannable unit. The generator builds payload strings only — it does not call Kingfisher. Lazy yielding keeps memory and temporary-disk usage bounded to a single chunk, which matters when an account holds thousands of resources.
+
+### Phase 2: Batch
+
+Call `detect_secrets_scan_batch` once with the generator. The helper consumes it in chunks, runs Kingfisher per chunk, and returns the keys that produced findings mapped to their finding lists.
+
+### Phase 3: Report
+
+Iterate the resources, look up the findings by key, and build one report per resource. Emit a finding for **every** iterated resource — never drop one silently. When a resource's payload cannot be prepared for scanning (for example, user data that fails to base64-decode or decompress), report it as `MANUAL` with a status explaining the scan could not inspect it, rather than omitting it or claiming `PASS`.
+
+```python
+from prowler.lib.check.models import Check, Check_Report_AWS
+from prowler.lib.utils.utils import (
+ annotate_verified_secrets,
+ detect_secrets_scan_batch,
+)
+from prowler.providers.aws.services.example.example_client import example_client
+
+
+class example_resource_no_secrets(Check):
+ def execute(self):
+ findings = []
+ excluded = example_client.audit_config.get("secrets_ignore_patterns", [])
+ validate = example_client.audit_config.get("secrets_validate", False)
+ resources = list(example_client.resources)
+
+ # Phase 1: collect — builds strings only, no scan.
+ def payloads():
+ for index, resource in enumerate(resources):
+ if resource.scannable_data:
+ yield index, serialize(resource)
+
+ # Phase 2: batch — one call, chunked subprocesses.
+ batch_results = detect_secrets_scan_batch(
+ payloads(), excluded_secrets=excluded, validate=validate
+ )
+
+ # Phase 3: report — look up findings by key.
+ for index, resource in enumerate(resources):
+ report = Check_Report_AWS(metadata=self.metadata(), resource=resource)
+ report.status = "PASS"
+ report.status_extended = f"No secrets found in {resource.name}."
+ detect_secrets_output = batch_results.get(index)
+ if detect_secrets_output:
+ report.status = "FAIL"
+ report.status_extended = (
+ f"Potential secret found in {resource.name} -> ..."
+ )
+ annotate_verified_secrets(report, detect_secrets_output)
+ findings.append(report)
+
+ return findings
+```
+
+## Choosing the Key
+
+The key maps each finding back to its source. Two shapes cover every check:
+
+- **One payload per resource:** use the resource index. This fits checks that serialize a single payload per resource, such as launch configurations, CloudFormation outputs, SSM documents, Step Functions definitions, and OpenStack metadata.
+- **Several payloads per resource:** use a `(resource_index, fragment)` tuple, where the fragment identifies the variable, log stream, container, file, or version. Phase 3 groups the per-fragment findings to build the resource report. This fits CloudWatch log streams, ECS containers, CodeBuild variables, Glue arguments, and Lambda code files.
+
+Derive the indices from the same `list(...)` of resources in both Phase 1 and Phase 3 so the order stays stable and the keys align.
+
+## Preserving Per-Payload Results
+
+`detect_secrets_scan_batch` runs Kingfisher with `--no-dedup`, so a secret that appears in more than one payload is reported for each one. This reproduces the result of scanning each payload individually. Build payload strings exactly as a single scan would: serialize the same data and keep line ordering, because messages often map a finding's `line_number` back to a variable name or metadata key.
+
+## Validation and Severity
+
+`detect_secrets_scan_batch` accepts `validate`, read from `secrets_validate` in the provider configuration or the `--scan-secrets-validate` flag. When enabled, Kingfisher confirms whether each secret is live, and confirmed secrets carry `is_verified: True`.
+
+After marking a report as `FAIL`, pass the findings to `annotate_verified_secrets(report, findings)`. When any secret is verified, the helper escalates the finding to critical severity and appends a note that the secret was confirmed live. Validation stays off by default because it sends the discovered secret to the provider API.
+
+## Excluded Secrets
+
+`detect_secrets_scan_batch` applies `secrets_ignore_patterns` — regular expressions from the provider configuration — against each finding's source line and drops the matches, mirroring single-scan behavior.
+
+## Testing
+
+To assert on the verified-secret path, mock `detect_secrets_scan_batch` in the check module and return the keyed dictionary. For a single resource scanned at index `0`:
+
+```python
+mock.patch(
+ "prowler.providers.aws.services.example.example_resource_no_secrets.example_resource_no_secrets.detect_secrets_scan_batch",
+ return_value={
+ 0: [{"type": "...", "line_number": 1, "is_verified": True}]
+ },
+)
+```
+
+Most tests need no mock at all: they seed resources that contain example secrets and assert on the `FAIL` status and message, which exercises the real batched path. Refer to the [Testing](/developer-guide/unit-testing) documentation for the general structure.
diff --git a/docs/developer-guide/security-compliance-framework.mdx b/docs/developer-guide/security-compliance-framework.mdx
index cf756c4da0..2eeabebe2a 100644
--- a/docs/developer-guide/security-compliance-framework.mdx
+++ b/docs/developer-guide/security-compliance-framework.mdx
@@ -2,6 +2,8 @@
title: 'Creating a New Security Compliance Framework in Prowler'
---
+import { VersionBadge } from "/snippets/version-badge.mdx"
+
This guide explains how to add a new security compliance framework to Prowler, end to end. It covers directory layout, the two supported JSON schemas (universal and legacy), the Pydantic models that validate each framework, check mapping conventions, output formatting, local validation, testing, and the pull request process.
## Introduction
@@ -23,7 +25,7 @@ Requirement coverage feeds the compliance percentage calculations and the metada
| **Universal (recommended for new frameworks)** | Multi-provider frameworks, or single-provider frameworks that benefit from declarative table/PDF rendering | `prowler/compliance/.json` (top-level) | Available for **every** provider whose key appears in any `requirement.checks` dict |
| **Legacy provider-specific** | Single-provider frameworks with framework-specific attribute classes already declared in the codebase (CIS, ENS, ISO 27001, etc.) | `prowler/compliance//__.json` | Available only under that provider |
-Auto-discovery happens in `get_bulk_compliance_frameworks_universal(provider)` (`prowler/lib/check/compliance_models.py:915`), which scans **both** the top-level `prowler/compliance/` directory and every per-provider sub-directory. Legacy frameworks are transparently converted to the universal `ComplianceFramework` model via `adapt_legacy_to_universal()` before being returned, so the rest of Prowler — CLI table rendering, CSV/OCSF outputs, PDF generation — works the same regardless of the source schema.
+Auto-discovery happens in `get_bulk_compliance_frameworks_universal(provider)` (`prowler/lib/check/compliance_models.py`), which scans **both** the top-level `prowler/compliance/` directory and every per-provider sub-directory. Legacy frameworks are transparently converted to the universal `ComplianceFramework` model via `adapt_legacy_to_universal()` before being returned, so the rest of Prowler — CLI table rendering, CSV/OCSF outputs, PDF generation — works the same regardless of the source schema.
> The legacy entry-point `Compliance.get_bulk(provider)` (used by older code paths) only scans per-provider sub-directories. Universal top-level files are picked up exclusively via the universal loader; this matters if you are wiring a new code path against the legacy API.
@@ -70,13 +72,13 @@ The file is auto-discovered — there is **no** need to register it in any `__in
}
```
-A `provider` field at the top level is **optional**. The framework's effective provider list is derived by `ComplianceFramework.get_providers()` (`compliance_models.py:739`) from the union of all keys appearing in `requirement.checks` across all requirements; the explicit `provider` field is used **only as a fallback** when no requirement carries any `checks` key. This is what enables a single file (e.g. `dora_2022_2554.json`) to cover AWS today and add Azure / GCP / etc. tomorrow without restructuring.
+A `provider` field at the top level is **optional**. The framework's effective provider list is derived by `ComplianceFramework.get_providers()` (`compliance_models.py`) from the union of all keys appearing in `requirement.checks` across all requirements; the explicit `provider` field is used **only as a fallback** when no requirement carries any `checks` key. This is what enables a single file (e.g. `dora_2022_2554.json`) to cover AWS today and add Azure / GCP / etc. tomorrow without restructuring.
Provider keys inside `requirement.checks` must match the directory names under `prowler/providers/`. The valid keys at present are: `aws`, `azure`, `gcp`, `m365`, `kubernetes`, `iac`, `github`, `googleworkspace`, `alibabacloud`, `cloudflare`, `mongodbatlas`, `nhn`, `openstack`, `oraclecloud`, `llm`. Comparison in `supports_provider()` is case-insensitive, but lowercase is the convention used everywhere in the repository.
### `attributes_metadata`
-Declares the shape of the per-requirement `attributes` dict. When this field is present, the root validator `validate_attributes_against_metadata` (`compliance_models.py:669`) enforces the schema at load time and rejects:
+Declares the shape of the per-requirement `attributes` dict. When this field is present, the root validator `validate_attributes_against_metadata` (`compliance_models.py`) enforces the schema at load time and rejects:
- Missing keys marked `required: true`.
- Keys present in `attributes` but not declared in `attributes_metadata` (typo / drift guard).
@@ -192,6 +194,7 @@ Per requirement:
- `name`: short title shown alongside the id.
- `attributes`: flat dict; keys must conform to `attributes_metadata`.
- `checks`: dict keyed by provider name (the same lowercase keys listed in the previous section). Each value is a list of Prowler check names that evidence this requirement for that provider. The list **may be empty** and the dict itself defaults to `{}` if omitted; either way the requirement is still loaded and listed by `--list-compliance-requirements`, it just has zero checks to execute. Note: there is **no automatic check-existence validation** at load time — referencing a non-existent check name will silently produce a requirement with no findings. Validate this yourself (see "Validating Your Framework" below).
+- `config_requirements`: optional list of configuration guardrails. Each entry asserts that a configurable check referenced by this requirement ran with a configuration strict enough to actually satisfy the requirement; otherwise the requirement is forced to FAIL. See [Configuration Guardrails for Requirements](#configuration-guardrails-for-requirements) for the full schema and semantics. In the universal schema the field name is lowercase (`config_requirements`); legacy files use `ConfigRequirements`.
For MITRE-style frameworks, additional optional fields are available on the requirement: `tactics`, `sub_techniques`, `platforms`, `technique_url` (these are populated automatically when adapting a legacy MITRE JSON to the universal model).
@@ -258,12 +261,12 @@ prowler/lib/outputs/compliance//
### JSON schema reference
-Every legacy compliance file is a JSON document with the following top-level keys. `Framework`, `Name` and `Provider` are validated non-empty by the root validator `framework_and_provider_must_not_be_empty` (`compliance_models.py:329`).
+Every legacy compliance file is a JSON document with the following top-level keys. `Framework`, `Name` and `Provider` are validated non-empty by the root validator `framework_and_provider_must_not_be_empty` (`compliance_models.py`).
| Field | Type | Required | Description |
|---|---|---|---|
| `Framework` | string | Yes | Canonical framework identifier, for example `CIS`, `NIST-800-53-Revision-5`, `ENS`, `CCC`. |
-| `Name` | string | Yes | Human-readable framework name displayed by Prowler App. |
+| `Name` | string | Yes | Human-readable framework name displayed by Prowler Cloud and Prowler Local Server. |
| `Version` | string | Yes (recommended) | Framework version, e.g. `2.0`. See [Version Handling](#version-handling). |
| `Provider` | string | Yes | Upper-cased provider identifier: `AWS`, `AZURE`, `GCP`, `KUBERNETES`, `M365`, `GITHUB`, `GOOGLEWORKSPACE`, and so on. |
| `Description` | string | Yes | Short description of the framework's scope and purpose. |
@@ -280,10 +283,11 @@ Each entry in `Requirements` describes one control or requirement.
| `Description` | string | Yes | Verbatim description from the source framework. |
| `Attributes` | array | Yes | List of [attribute objects](#attribute-objects). The shape depends on the framework. |
| `Checks` | array of strings | Yes | Prowler check identifiers that automate the requirement. Leave the list empty when the control cannot be automated. |
+| `ConfigRequirements` | array of objects | No | Optional [configuration guardrails](#configuration-guardrails-for-requirements). Each entry asserts that a configurable check ran with a configuration strict enough to satisfy the requirement; when it did not, the requirement is forced to FAIL. |
#### Attribute Objects
-`Attributes` is parsed against the union declared in `Compliance_Requirement.Attributes` (`compliance_models.py:293`). Pydantic v1 tries each member of the union in declaration order and falls back to `Generic_Compliance_Requirement_Attribute` (the last entry) when nothing else matches — so a brand-new shape that doesn't match any existing class will silently be accepted as Generic, losing its specific fields.
+`Attributes` is parsed against the union declared in `Compliance_Requirement.Attributes` (`compliance_models.py`). Pydantic v1 tries each member of the union in declaration order and falls back to `Generic_Compliance_Requirement_Attribute` (the last entry) when nothing else matches — so a brand-new shape that doesn't match any existing class will silently be accepted as Generic, losing its specific fields.
As of today, the registered attribute classes are: `CIS_Requirement_Attribute`, `ENS_Requirement_Attribute`, `ASDEssentialEight_Requirement_Attribute`, `ISO27001_2013_Requirement_Attribute`, `AWS_Well_Architected_Requirement_Attribute`, `KISA_ISMSP_Requirement_Attribute`, `Prowler_ThreatScore_Requirement_Attribute`, `CCC_Requirement_Attribute`, `C5Germany_Requirement_Attribute`, `CSA_CCM_Requirement_Attribute`, and `Generic_Compliance_Requirement_Attribute` (fallback). MITRE-style frameworks use the separate `Mitre_Requirement` model with `Tactics` / `SubTechniques` / `Platforms` / `TechniqueURL` at the requirement top level. The most common shapes are summarized below.
@@ -472,13 +476,188 @@ For NIST-style catalogs that use `Generic_Compliance_Requirement_Attribute`, no
### Legacy-to-universal adapter
-At load time, every legacy file is transparently adapted to a `ComplianceFramework` via `adapt_legacy_to_universal()` (`compliance_models.py:819`), which: (a) flattens the first element of `Attributes` into a flat `attributes` dict, (b) wraps `Checks` as `{provider_lower: [...]}`, (c) infers `attributes_metadata` from the matched Pydantic class via `_infer_attribute_metadata()`. The rest of Prowler (CSV/OCSF/PDF output, CLI table) then treats both formats identically.
+At load time, every legacy file is transparently adapted to a `ComplianceFramework` via `adapt_legacy_to_universal()` (`compliance_models.py`), which: (a) flattens the first element of `Attributes` into a flat `attributes` dict, (b) wraps `Checks` as `{provider_lower: [...]}`, (c) infers `attributes_metadata` from the matched Pydantic class via `_infer_attribute_metadata()`. The rest of Prowler (CSV/OCSF/PDF output, CLI table) then treats both formats identically.
Loader-error behaviour differs between the two entry points:
-- `load_compliance_framework()` (legacy) is **fail-fast**: it calls `sys.exit(1)` on any `ValidationError` (`compliance_models.py:464`).
+- `load_compliance_framework()` (legacy) is **fail-fast**: it calls `sys.exit(1)` on any `ValidationError` (`compliance_models.py`).
- `load_compliance_framework_universal()` is more lenient — it logs the error and returns `None`, so `get_bulk_compliance_frameworks_universal()` simply skips the broken file and keeps loading the rest.
+## Configuration Guardrails for Requirements
+
+
+
+Some requirements are only truly satisfied when the configurable checks behind them ran with a configuration strict enough to meet the control. A [configurable check](/developer-guide/configurable-checks) reads thresholds from the scan's `audit_config`, so loosening a value can make the check PASS while the requirement it backs is, in fact, not satisfied.
+
+A worked example: CIS AWS 6.0 requirement 2.11 ("credentials unused for 45 days or more are disabled") maps to `iam_user_accesskey_unused`, which is driven by the `max_unused_access_keys_days` config key. If a user raises that value to `120`, the check passes for a key unused for 90 days — yet the requirement explicitly demands a 45-day threshold, so the PASS is misleading.
+
+Configuration guardrails close that gap. A requirement declares the configuration it expects, and when the scan ran with a configuration too loose to honor it, the requirement is forced to **FAIL** in every compliance output, with the reason surfaced in the finding's extended status.
+
+
+Guardrails are an **optional** safety net for configurable checks. A requirement that maps only to non-configurable checks does not need them. When the field is absent, behavior is unchanged.
+
+
+### Where guardrails are declared
+
+The field is attached to each requirement and exists in both schemas:
+
+- **Legacy** (`prowler/compliance//...`): `ConfigRequirements`, a list of objects, validated against the `Compliance_Requirement_ConfigConstraint` Pydantic model (`prowler/lib/check/compliance_models.py`).
+- **Universal** (`prowler/compliance/...`): `config_requirements`, the same list of objects as plain dicts on `UniversalComplianceRequirement`.
+
+When a legacy file is adapted to the universal model, `adapt_legacy_to_universal()` copies `ConfigRequirements` into `config_requirements` (`compliance_models.py`), so downstream code only ever reads one shape.
+
+### Constraint schema
+
+Each entry in the list is a single constraint with the following fields:
+
+| Field | Type | Required | Description |
+|---|---|---|---|
+| `Check` | string | Yes | The configurable check this constraint guards. Should be one of the requirement's `Checks`. Used only to build a human-readable reason. |
+| `ConfigKey` | string | Yes | The `audit_config` key the check reads (for example `max_unused_access_keys_days`). |
+| `Operator` | enum | Yes | How to compare the applied value against `Value`. One of `lte`, `gte`, `eq`, `in`, `subset`, `superset`. |
+| `Value` | bool, int, float, string, or list | Yes | The strictest configuration the requirement tolerates. The accepted Python type depends on the operator (see below). |
+| `Provider` | string | No | The provider this constraint applies to (e.g. `aws`). **Required for universal (multi-provider) frameworks**, where the same requirement maps checks across providers — the constraint is only evaluated when the scanned provider matches. Single-provider (legacy) frameworks omit it. |
+
+### Operators
+
+| Operator | Applied value satisfies the guardrail when… | Typical use |
+|---|---|---|
+| `lte` | `applied <= Value` | Maximum-age / maximum-count thresholds (e.g. `max_unused_access_keys_days <= 45`). |
+| `gte` | `applied >= Value` | Minimum-retention / minimum-count thresholds. |
+| `eq` | `applied == Value` | Boolean toggles or an exact required value (e.g. `mute_non_default_regions == false`). |
+| `in` | `applied` is one of `Value` (a list) | The applied scalar must belong to an allowed set. |
+| `subset` | `set(applied) <= set(Value)` | **Allowlist** configs — every applied value must already be permitted. Widening the allowlist with a weaker value (e.g. adding TLS `1.0` to `recommended_minimal_tls_versions`) breaks the guardrail. |
+| `superset` | `set(applied) >= set(Value)` | **Denylist** configs — every forbidden value must remain forbidden. Removing an entry from a denylist (e.g. dropping a weak algorithm from `insecure_key_algorithms`) breaks the guardrail. |
+
+
+`subset` / `superset` require both the applied value and `Value` to be lists; any other type is treated as not satisfied. For `eq` against a boolean, declare `Value` as a JSON boolean (`false`, not `0`) — the model keeps booleans distinct from integers.
+
+
+### How guardrails are evaluated
+
+All evaluation lives in one shared module, `prowler/lib/check/compliance_config_eval.py`, consumed by every compliance output (CSV, OCSF, and the CLI tables) and reused by the Prowler API backend so the rule is defined exactly once.
+
+1. The applied configuration is the scan-global `audit_config` (the same mapping for every resource and region), resolved via `get_scan_audit_config()`.
+2. For each requirement that declares constraints, `evaluate_config_constraints()` walks the list and returns `(is_compliant, reason)`. The requirement is compliant when **every** explicitly-set key satisfies its constraint.
+3. A constraint tagged with a `Provider` that does **not** match the provider being scanned (resolved via `get_scan_provider_type()`) is **skipped**. This scopes a universal framework's constraints to the right provider, so a guardrail authored for an AWS check never affects a GCP or Azure scan of the same requirement. Untagged constraints (legacy single-provider frameworks) always apply.
+4. A constraint whose `ConfigKey` is **not present** in `audit_config` is **skipped** — the check's built-in default is assumed to already match what the requirement expects. This is why nothing changes for the default configuration.
+5. When a constraint is violated, the finding's status is overridden to `FAIL` and a plain-language explanation is prepended to `status_extended` (via `apply_config_status()`). The message opens with `Configuration not valid for this requirement.` and names the check, the value the scan applied, what the requirement needs and how to fix it. For the table generators, `get_effective_status()` applies the same FAIL roll-up so per-section counts stay consistent.
+
+
+Guardrails only ever make a result **stricter** (they can turn PASS into FAIL); they never relax a real FAIL into PASS. A requirement with no constraints, or whose keys all use defaults, is reported exactly as before.
+
+
+### Example: legacy framework
+
+From `prowler/compliance/aws/cis_6.0_aws.json`, requirement 2.11 declares two guardrails — one per configurable check it maps to:
+
+```json title="prowler/compliance/aws/cis_6.0_aws.json"
+{
+ "Id": "2.11",
+ "Description": "Ensure credentials unused for 45 days or more are disabled.",
+ "Checks": [
+ "iam_user_accesskey_unused",
+ "iam_user_console_access_unused"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "iam_user_accesskey_unused",
+ "ConfigKey": "max_unused_access_keys_days",
+ "Operator": "lte",
+ "Value": 45
+ },
+ {
+ "Check": "iam_user_console_access_unused",
+ "ConfigKey": "max_console_access_days",
+ "Operator": "lte",
+ "Value": 45
+ }
+ ],
+ "Attributes": [ /* ... */ ]
+}
+```
+
+A boolean guardrail from the same file: requirement 2.5 (IAM Access Analyzer) only holds when regions are not muted, so a scan with `mute_non_default_regions: true` cannot be trusted for it:
+
+```json
+"ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+]
+```
+
+### Example: universal framework
+
+The universal schema uses the lowercase `config_requirements` key with the identical object shape:
+
+```json
+{
+ "id": "MF-2.1",
+ "name": "Restrict TLS to modern versions",
+ "description": "Endpoints must negotiate only TLS 1.2 or higher.",
+ "checks": {
+ "aws": ["elbv2_listener_ssl_listeners"]
+ },
+ "config_requirements": [
+ {
+ "Check": "elbv2_listener_ssl_listeners",
+ "Provider": "aws",
+ "ConfigKey": "recommended_minimal_tls_versions",
+ "Operator": "subset",
+ "Value": ["TLS 1.2", "TLS 1.3"]
+ }
+ ]
+}
+```
+
+Each constraint declares the `Provider` it targets so the guardrail is only evaluated on scans of that provider — essential for universal frameworks like CSA CCM and DORA, where one requirement maps checks across `aws`, `azure`, `gcp` and more. Because the operator is `subset`, adding `"TLS 1.0"` to `recommended_minimal_tls_versions` widens the allowlist beyond `["TLS 1.2", "TLS 1.3"]` and the requirement is forced to FAIL.
+
+### What the user sees
+
+With a loosened config, the affected requirement's findings report:
+
+```text
+Status: FAIL
+StatusExtended: Configuration not valid for this requirement. The check
+ iam_user_accesskey_unused has max_unused_access_keys_days set
+ to 120, but the requirement needs a value of 45 or lower.
+ Update it to 45 or lower.
+```
+
+The same `Configuration not valid for this requirement.` message appears identically across the CSV, OCSF, and console-table outputs.
+
+### Authoring guidelines
+
+- Declare a guardrail only for keys whose value actually changes whether the requirement is met. Most configurable checks do not need one.
+- Set `Value` to the **strictest** configuration the control tolerates — the same number the control text cites (CIS 45 days, NIST ≤90, and so on).
+- Keep `ConfigKey` spelled exactly as the check reads it from `audit_config`; an unknown key is never present in the config and the constraint is silently skipped.
+- In a **universal (multi-provider) framework**, always set `Provider` to the provider that owns `Check` — otherwise the guardrail would leak onto scans of the other providers the requirement maps. Legacy single-provider files omit it.
+- Pick the operator from the value's role: a max threshold is `lte`, a min threshold is `gte`, a toggle is `eq`, an allowlist is `subset`, a denylist is `superset`.
+- An unrecognized operator does **not** block the requirement — a malformed constraint is treated as satisfied rather than failing the whole framework. Validate your JSON with the tests below.
+
+### Testing guardrails
+
+The shared evaluator and the per-output integration are covered by:
+
+- `tests/lib/check/compliance_config_eval_test.py` — operator semantics, skipped-key behavior, and the FAIL override.
+- `tests/lib/check/compliance_config_constraint_model_test.py` — model validation (types, operator enum, bool-vs-int).
+- `tests/lib/check/compliance_config_requirements_data_test.py` — sanity-checks the guardrails shipped in the JSON catalog.
+- Per-output tests under `tests/lib/outputs/compliance/` (CIS AWS/Azure, ENS AWS, OCSF, universal table) confirm the override reaches each format.
+
+Run them with:
+
+```bash
+uv run pytest -n auto \
+ tests/lib/check/compliance_config_eval_test.py \
+ tests/lib/check/compliance_config_constraint_model_test.py \
+ tests/lib/check/compliance_config_requirements_data_test.py \
+ tests/lib/outputs/compliance/
+```
+
## Version handling
Prowler matches frameworks by concatenating `Framework` and `Version`. A missing or empty `Version` collapses several frameworks to the same key and breaks CLI filtering with `--compliance`.
@@ -557,9 +736,9 @@ Open the generated CSV and confirm:
- Every requirement has at least one row per scanned resource (when there are findings).
- Attribute values such as `Requirements_Attributes_Section` reflect the JSON content.
-### 5. Verify the framework in Prowler App
+### 5. Verify the Framework in Prowler Local Server
-Launch Prowler App locally (`docker compose up` from the repository root) and run a scan with the new compliance framework. Confirm the compliance page renders the requirements, sections, and status widgets correctly.
+Launch Prowler Local Server (`docker compose up` from the repository root) and run a scan with the new compliance framework. Confirm the compliance page renders the requirements, sections, and status widgets correctly.
## Testing
@@ -599,7 +778,7 @@ Before opening the pull request:
uv run pre-commit run --all-files
uv run pytest -n auto
```
-2. Add a changelog entry under the `### 🚀 Added` section of `prowler/CHANGELOG.md`, describing the new framework and the providers it covers.
+2. Add a changelog fragment `prowler/changelog.d/.added.md`, describing the new framework and the providers it covers (no PR link in the text; it is attached automatically at release time).
3. Follow the [Pull Request Template](https://github.com/prowler-cloud/prowler/blob/master/.github/pull_request_template.md) and set the PR title using Conventional Commits, e.g. `feat(compliance): add My Framework 1.0 for AWS`.
4. Request review from the compliance codeowners listed in `.github/CODEOWNERS`.
@@ -609,7 +788,7 @@ The following issues are the most common when contributing a compliance framewor
- **`ValidationError: field required` during scan (legacy).** The JSON is missing a required attribute field. Re-check the matching Pydantic model in `prowler/lib/check/compliance_models.py`.
- **All attributes collapse to `Generic_Compliance_Requirement_Attribute` values (legacy).** The Pydantic `Union` is ordered incorrectly, or the JSON matches only the generic shape. Keep the generic model in the last Union position and ensure every required field is present in the JSON.
-- **`attributes_metadata validation failed` (universal).** The root validator in `compliance_models.py:669` rejected the file. The error message lists each offending requirement; common causes are unknown attribute keys (typo or missing entry in `attributes_metadata`), enum violations, or missing required keys.
+- **`attributes_metadata validation failed` (universal).** The root validator in `compliance_models.py` rejected the file. The error message lists each offending requirement; common causes are unknown attribute keys (typo or missing entry in `attributes_metadata`), enum violations, or missing required keys.
- **`--compliance` filter does not find the framework.** For legacy: the filename does not match `__.json`, the version is empty, or the file lives outside `prowler/compliance//`. For universal: the file is not at the top level of `prowler/compliance/` or it loaded as `None` (check logs for the validation error).
- **CLI summary table is empty but the CSV is populated (legacy).** The dispatcher branch in `prowler/lib/outputs/compliance/compliance.py` is missing or its substring match does not catch the framework key.
- **CSV file is missing after the scan (legacy).** The transformer class is not registered in `prowler/lib/outputs/compliance/compliance_output.py`, or `transform()` raises silently. Run the scan with `--log-level DEBUG`.
diff --git a/docs/developer-guide/stackit-details.mdx b/docs/developer-guide/stackit-details.mdx
index 9d4ea5d458..58a5cf19a5 100644
--- a/docs/developer-guide/stackit-details.mdx
+++ b/docs/developer-guide/stackit-details.mdx
@@ -59,7 +59,7 @@ StackIT uses service account keys for API authentication. Service account keys a
1. **Navigate to Service Accounts**
- Go to the [StackIT Portal](https://portal.stackit.cloud/)
- Select your project
- - Click on **Service Accounts** in the left sidebar
+ - Click **Service Accounts** in the left sidebar
2. **Create or Select Service Account**
- If you don't have a service account, click **Create Service Account**
diff --git a/docs/docs.json b/docs/docs.json
index 5b88b5d2da..b9bc195182 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -38,61 +38,73 @@
{
"group": "Welcome",
"pages": [
- "introduction"
+ "introduction",
+ "getting-started/products/index"
]
},
{
- "group": "Prowler Cloud",
+ "group": "Prowler Products",
"pages": [
- "getting-started/products/prowler-cloud",
- "getting-started/products/prowler-cloud-pricing",
- "getting-started/products/prowler-cloud-aws-marketplace",
- "getting-started/goto/prowler-cloud",
- "getting-started/goto/prowler-api-reference"
+ {
+ "group": "Prowler Cloud",
+ "pages": [
+ "getting-started/products/prowler-cloud",
+ "getting-started/products/prowler-cloud-pricing",
+ "getting-started/products/prowler-cloud-aws-marketplace",
+ "getting-started/goto/prowler-cloud",
+ "getting-started/goto/prowler-api-reference"
+ ]
+ },
+ {
+ "group": "Prowler Lighthouse AI",
+ "pages": [
+ "getting-started/products/prowler-cloud-lighthouse"
+ ]
+ },
+ {
+ "group": "Prowler Hub",
+ "pages": [
+ "getting-started/products/prowler-hub",
+ "getting-started/goto/prowler-hub"
+ ]
+ },
+ {
+ "group": "Prowler MCP",
+ "pages": [
+ "getting-started/products/prowler-mcp",
+ "getting-started/basic-usage/prowler-mcp",
+ "getting-started/basic-usage/prowler-mcp-tools",
+ "getting-started/installation/prowler-mcp"
+ ]
+ },
+ {
+ "group": "Prowler for AI Agents",
+ "pages": [
+ "getting-started/products/prowler-claude-code-plugin"
+ ]
+ }
]
},
{
- "group": "Prowler CLI",
+ "group": "Open Source",
"pages": [
- "getting-started/products/prowler-cli",
- "getting-started/installation/prowler-cli",
- "getting-started/basic-usage/prowler-cli"
- ]
- },
- {
- "group": "Prowler App",
- "pages": [
- "getting-started/products/prowler-app",
- "getting-started/installation/prowler-app",
- "getting-started/basic-usage/prowler-app"
- ]
- },
- {
- "group": "Prowler Lighthouse AI",
- "pages": [
- "getting-started/products/prowler-lighthouse-ai"
- ]
- },
- {
- "group": "Prowler for Claude Code",
- "pages": [
- "getting-started/products/prowler-claude-code-plugin"
- ]
- },
- {
- "group": "Prowler MCP Server",
- "pages": [
- "getting-started/products/prowler-mcp",
- "getting-started/installation/prowler-mcp",
- "getting-started/basic-usage/prowler-mcp",
- "getting-started/basic-usage/prowler-mcp-tools"
- ]
- },
- {
- "group": "Prowler Hub",
- "pages": [
- "getting-started/products/prowler-hub",
- "getting-started/goto/prowler-hub"
+ {
+ "group": "Prowler CLI",
+ "pages": [
+ "getting-started/products/prowler-cli",
+ "getting-started/installation/prowler-cli",
+ "getting-started/basic-usage/prowler-cli"
+ ]
+ },
+ {
+ "group": "Prowler Local Server",
+ "pages": [
+ "getting-started/products/prowler-app",
+ "getting-started/installation/prowler-app",
+ "getting-started/basic-usage/prowler-app"
+ ]
+ },
+ "getting-started/products/prowler-sdk"
]
},
{
@@ -111,32 +123,38 @@
"tab": "Guides",
"groups": [
{
- "group": "Prowler Cloud/App",
+ "group": "Prowler Cloud",
"pages": [
"user-guide/tutorials/prowler-app",
{
- "group": "Authentication",
+ "group": "Authentication & Access",
"pages": [
+ "user-guide/tutorials/prowler-app-api-keys",
+ "user-guide/tutorials/prowler-app-multi-tenant",
+ "user-guide/tutorials/prowler-app-sso",
"user-guide/tutorials/prowler-app-social-login",
- "user-guide/tutorials/prowler-app-sso"
+ "user-guide/tutorials/prowler-app-rbac"
]
},
- "user-guide/tutorials/prowler-app-rbac",
- "user-guide/tutorials/prowler-app-multi-tenant",
- "user-guide/tutorials/prowler-app-api-keys",
- "user-guide/tutorials/prowler-import-findings",
- "user-guide/tutorials/prowler-alerts",
{
- "group": "Mutelist",
- "expanded": true,
+ "group": "Compliance",
"pages": [
- "user-guide/tutorials/prowler-app-simple-mutelist",
- "user-guide/tutorials/prowler-app-mute-findings"
+ "user-guide/compliance/tutorials/compliance",
+ "user-guide/compliance/tutorials/cross-provider-compliance",
+ "user-guide/compliance/tutorials/threatscore"
+ ]
+ },
+ {
+ "group": "Findings",
+ "pages": [
+ "user-guide/tutorials/prowler-alerts",
+ "user-guide/tutorials/prowler-app-attack-paths",
+ "user-guide/tutorials/prowler-app-finding-groups",
+ "user-guide/tutorials/prowler-app-findings-triage"
]
},
{
"group": "Integrations",
- "expanded": true,
"pages": [
"user-guide/tutorials/prowler-app-s3-integration",
"user-guide/tutorials/prowler-app-security-hub-integration",
@@ -144,33 +162,64 @@
]
},
{
- "group": "AWS Organizations",
- "expanded": true,
+ "group": "Mutelist",
"pages": [
- "user-guide/tutorials/prowler-cloud-aws-organizations"
+ "user-guide/tutorials/prowler-app-mute-findings",
+ "user-guide/tutorials/prowler-app-simple-mutelist"
]
},
{
- "group": "Lighthouse AI",
+ "group": "Providers",
"pages": [
- "user-guide/tutorials/prowler-app-lighthouse",
- "user-guide/tutorials/prowler-app-lighthouse-multi-llm"
+ "user-guide/tutorials/prowler-cloud-aws-organizations",
+ "user-guide/tutorials/prowler-cloud-azure-management-groups",
+ "user-guide/tutorials/prowler-cloud-gcp-organizations"
+ ]
+ },
+ {
+ "group": "Scans",
+ "pages": [
+ "user-guide/tutorials/prowler-app-scan-configuration",
+ "user-guide/tutorials/prowler-import-findings",
+ "user-guide/tutorials/prowler-scan-scheduling"
]
},
- "user-guide/tutorials/prowler-app-attack-paths",
- "user-guide/tutorials/prowler-app-finding-groups",
- "user-guide/tutorials/prowler-cloud-public-ips",
{
"group": "Tutorials",
"pages": [
- "user-guide/tutorials/prowler-app-sso-entra",
- "user-guide/tutorials/prowler-app-sso-google-workspace",
+ "user-guide/tutorials/aws-organizations-bulk-provisioning",
"user-guide/tutorials/bulk-provider-provisioning",
- "user-guide/tutorials/aws-organizations-bulk-provisioning"
+ "user-guide/tutorials/prowler-app-sso-entra",
+ "user-guide/tutorials/prowler-app-sso-google-workspace"
]
}
]
},
+ {
+ "group": "Prowler Lighthouse AI",
+ "pages": [
+ {
+ "group": "Prowler Cloud",
+ "pages": [
+ "user-guide/tutorials/prowler-cloud-lighthouse-multi-llm"
+ ]
+ },
+ {
+ "group": "Prowler Local Server",
+ "pages": [
+ "getting-started/products/prowler-lighthouse-ai",
+ "user-guide/tutorials/prowler-app-lighthouse",
+ "user-guide/tutorials/prowler-app-lighthouse-multi-llm"
+ ]
+ }
+ ]
+ },
+ {
+ "group": "Prowler for AI Agents",
+ "pages": [
+ "getting-started/products/prowler-claude-code-plugin"
+ ]
+ },
{
"group": "CI/CD",
"pages": [
@@ -212,6 +261,13 @@
{
"group": "Providers",
"pages": [
+ {
+ "group": "Alibaba Cloud",
+ "pages": [
+ "user-guide/providers/alibabacloud/getting-started-alibabacloud",
+ "user-guide/providers/alibabacloud/authentication"
+ ]
+ },
{
"group": "AWS",
"pages": [
@@ -235,9 +291,31 @@
"user-guide/providers/azure/authentication",
"user-guide/providers/azure/use-non-default-cloud",
"user-guide/providers/azure/subscriptions",
+ "user-guide/providers/azure/resource-groups",
"user-guide/providers/azure/create-prowler-service-principal"
]
},
+ {
+ "group": "Cloudflare",
+ "pages": [
+ "user-guide/providers/cloudflare/getting-started-cloudflare",
+ "user-guide/providers/cloudflare/authentication"
+ ]
+ },
+ {
+ "group": "E2E Networks",
+ "pages": [
+ "user-guide/providers/e2enetworks/getting-started-e2enetworks",
+ "user-guide/providers/e2enetworks/authentication"
+ ]
+ },
+ {
+ "group": "GitHub",
+ "pages": [
+ "user-guide/providers/github/getting-started-github",
+ "user-guide/providers/github/authentication"
+ ]
+ },
{
"group": "Google Cloud",
"pages": [
@@ -249,10 +327,24 @@
]
},
{
- "group": "Alibaba Cloud",
+ "group": "Google Workspace",
"pages": [
- "user-guide/providers/alibabacloud/getting-started-alibabacloud",
- "user-guide/providers/alibabacloud/authentication"
+ "user-guide/providers/googleworkspace/getting-started-googleworkspace",
+ "user-guide/providers/googleworkspace/authentication"
+ ]
+ },
+ {
+ "group": "IaC",
+ "pages": [
+ "user-guide/providers/iac/getting-started-iac",
+ "user-guide/providers/iac/authentication"
+ ]
+ },
+ {
+ "group": "Image",
+ "pages": [
+ "user-guide/providers/image/getting-started-image",
+ "user-guide/providers/image/authentication"
]
},
{
@@ -262,6 +354,19 @@
"user-guide/providers/kubernetes/misc"
]
},
+ {
+ "group": "Linode",
+ "pages": [
+ "user-guide/providers/linode/getting-started-linode",
+ "user-guide/providers/linode/authentication"
+ ]
+ },
+ {
+ "group": "LLM",
+ "pages": [
+ "user-guide/providers/llm/getting-started-llm"
+ ]
+ },
{
"group": "Microsoft 365",
"pages": [
@@ -270,27 +375,6 @@
"user-guide/providers/microsoft365/use-of-powershell"
]
},
- {
- "group": "Google Workspace",
- "pages": [
- "user-guide/providers/googleworkspace/getting-started-googleworkspace",
- "user-guide/providers/googleworkspace/authentication"
- ]
- },
- {
- "group": "GitHub",
- "pages": [
- "user-guide/providers/github/getting-started-github",
- "user-guide/providers/github/authentication"
- ]
- },
- {
- "group": "IaC",
- "pages": [
- "user-guide/providers/iac/getting-started-iac",
- "user-guide/providers/iac/authentication"
- ]
- },
{
"group": "MongoDB Atlas",
"pages": [
@@ -299,30 +383,11 @@
]
},
{
- "group": "Cloudflare",
+ "group": "Okta",
"pages": [
- "user-guide/providers/cloudflare/getting-started-cloudflare",
- "user-guide/providers/cloudflare/authentication"
- ]
- },
- {
- "group": "Image",
- "pages": [
- "user-guide/providers/image/getting-started-image",
- "user-guide/providers/image/authentication"
- ]
- },
- {
- "group": "LLM",
- "pages": [
- "user-guide/providers/llm/getting-started-llm"
- ]
- },
- {
- "group": "Oracle Cloud Infrastructure",
- "pages": [
- "user-guide/providers/oci/getting-started-oci",
- "user-guide/providers/oci/authentication"
+ "user-guide/providers/okta/getting-started-okta",
+ "user-guide/providers/okta/authentication",
+ "user-guide/providers/okta/retry-configuration"
]
},
{
@@ -332,6 +397,13 @@
"user-guide/providers/openstack/authentication"
]
},
+ {
+ "group": "Oracle Cloud Infrastructure",
+ "pages": [
+ "user-guide/providers/oci/getting-started-oci",
+ "user-guide/providers/oci/authentication"
+ ]
+ },
{
"group": "Scaleway",
"pages": [
@@ -352,30 +424,9 @@
"user-guide/providers/vercel/getting-started-vercel",
"user-guide/providers/vercel/authentication"
]
- },
- {
- "group": "Okta",
- "pages": [
- "user-guide/providers/okta/getting-started-okta",
- "user-guide/providers/okta/authentication"
- ]
- },
- {
- "group": "Linode",
- "pages": [
- "user-guide/providers/linode/getting-started-linode",
- "user-guide/providers/linode/authentication"
- ]
}
]
},
- {
- "group": "Compliance",
- "pages": [
- "user-guide/compliance/tutorials/compliance",
- "user-guide/compliance/tutorials/threatscore"
- ]
- },
{
"group": "Cookbooks",
"pages": [
@@ -396,6 +447,7 @@
"developer-guide/provider",
"developer-guide/services",
"developer-guide/checks",
+ "developer-guide/secret-scanning-checks",
"developer-guide/outputs",
"developer-guide/integrations",
"developer-guide/security-compliance-framework",
@@ -482,10 +534,6 @@
"tab": "Changelog",
"icon": "github",
"href": "https://github.com/prowler-cloud/prowler/releases"
- },
- {
- "tab": "Public Roadmap",
- "href": "https://roadmap.prowler.com/"
}
],
"global": {
@@ -521,6 +569,13 @@
}
]
},
+ "banner": {
+ "content": "Prowler App is now Prowler Local Server, and Prowler Enterprise is now Prowler Private Cloud. See [Prowler product families](/getting-started/products).",
+ "dismissible": false
+ },
+ "markdown": {
+ "instructions": "Prowler product naming: Prowler App is now Prowler Local Server, and Prowler Enterprise is now Prowler Private Cloud. Always use the current names when answering. The full product reference is at /getting-started/products: Open Source projects are Prowler CLI, Prowler Local Server, Prowler Local Dashboard, and Prowler SDK; Prowler Products are Prowler Cloud, Prowler Private Cloud, Prowler Hub, Prowler Lighthouse AI, and Prowler MCP."
+ },
"analytics": {
"ga4": {
"measurementId": "G-KBKV70W5Y2"
@@ -601,6 +656,10 @@
{
"source": "/user-guide/tutorials/prowler-app-alerts",
"destination": "/user-guide/tutorials/prowler-alerts"
+ },
+ {
+ "source": "/user-guide/tutorials/prowler-cloud-public-ips",
+ "destination": "/security/networking"
}
]
}
diff --git a/docs/getting-started/basic-usage/prowler-app.mdx b/docs/getting-started/basic-usage/prowler-app.mdx
index bc39353dcc..0f4cf80a91 100644
--- a/docs/getting-started/basic-usage/prowler-app.mdx
+++ b/docs/getting-started/basic-usage/prowler-app.mdx
@@ -2,7 +2,7 @@
title: 'Basic Usage'
---
-## Access Prowler App
+## Access Prowler Local Server
After [installation](/getting-started/installation/prowler-app), navigate to [http://localhost:3000](http://localhost:3000) and sign up with email and password.
@@ -28,7 +28,7 @@ This mechanism ensures that the first user in a newly created tenant has adminis
## Log In
-Access Prowler App by logging in with **email and password**.
+Access Prowler Local Server by logging in with **email and password**.
@@ -62,7 +62,7 @@ Review findings during scan execution in the following sections:
- **Compliance** – Displays compliance insights based on security frameworks.
-> For detailed usage instructions, refer to the [Prowler App Guide](/user-guide/tutorials/prowler-app).
+> For detailed usage instructions, refer to the [Prowler Cloud guide](/user-guide/tutorials/prowler-app), which also applies to Prowler Local Server.
Prowler will automatically scan all configured providers every **24 hours**, ensuring your cloud environment stays continuously monitored.
diff --git a/docs/getting-started/basic-usage/prowler-mcp-tools.mdx b/docs/getting-started/basic-usage/prowler-mcp-tools.mdx
index ec11680dd5..acb50c9e81 100644
--- a/docs/getting-started/basic-usage/prowler-mcp-tools.mdx
+++ b/docs/getting-started/basic-usage/prowler-mcp-tools.mdx
@@ -10,7 +10,7 @@ Complete reference guide for all tools available in the Prowler MCP Server. Tool
|----------|------------|------------------------|
| Prowler Hub | 10 tools | No |
| Prowler Documentation | 2 tools | No |
-| Prowler Cloud/App | 32 tools | Yes |
+| Prowler Cloud, Private Cloud & Local Server | 32 tools | Yes |
## Tool Naming Convention
@@ -18,11 +18,11 @@ All tools follow a consistent naming pattern with prefixes:
- `prowler_hub_*` - Prowler Hub catalog and compliance tools
- `prowler_docs_*` - Prowler documentation search and retrieval
-- `prowler_app_*` - Prowler Cloud and App (Self-Managed) management tools
+- `prowler_*` - Prowler Cloud, Prowler Private Cloud & Prowler Local Server management tools
-## Prowler Cloud/App Tools
+## Prowler Tools
-Manage Prowler Cloud or Prowler App (Self-Managed) features. **Requires authentication.**
+Manage your Prowler deployment — Prowler Cloud, Prowler Private Cloud, or Prowler Local Server. **Requires authentication.**
These tools require a valid API key. See the [Configuration Guide](/getting-started/basic-usage/prowler-mcp) for authentication setup.
@@ -32,44 +32,44 @@ These tools require a valid API key. See the [Configuration Guide](/getting-star
Tools for searching, viewing, and analyzing security findings across all cloud providers.
-- **`prowler_app_search_security_findings`** - Search and filter security findings with advanced filtering options (severity, status, provider, region, service, check ID, date range, muted status)
-- **`prowler_app_get_finding_details`** - Get comprehensive details about a specific finding including remediation guidance, check metadata, and resource relationships
-- **`prowler_app_get_findings_overview`** - Get aggregate statistics and trends about security findings as a markdown report
+- **`prowler_search_security_findings`** - Search and filter security findings with advanced filtering options (severity, status, provider, region, service, check ID, date range, muted status)
+- **`prowler_get_finding_details`** - Get comprehensive details about a specific finding including remediation guidance, check metadata, and resource relationships
+- **`prowler_get_findings_overview`** - Get aggregate statistics and trends about security findings as a markdown report
### Finding Groups Management
Tools for listing finding groups aggregated by check ID, viewing complete group counters, and drilling down into affected resources.
-- **`prowler_app_list_finding_groups`** - List latest or historical finding groups with filters for provider, region, service, resource, category, check, severity, status, muted state, delta, date range, and sorting
-- **`prowler_app_get_finding_group_details`** - Get complete details for a specific finding group including counters, description, timestamps, and impacted providers
-- **`prowler_app_list_finding_group_resources`** - List actionable unmuted resources affected by a finding group by default, including nested resource and provider data plus the `finding_id` for remediation details. Set `include_muted` to include suppressed resources
+- **`prowler_list_finding_groups`** - List latest or historical finding groups with filters for provider, region, service, resource, category, check, severity, status, muted state, delta, date range, and sorting
+- **`prowler_get_finding_group_details`** - Get complete details for a specific finding group including counters, description, timestamps, and impacted providers
+- **`prowler_list_finding_group_resources`** - List actionable unmuted resources affected by a finding group by default, including nested resource and provider data plus the `finding_id` for remediation details. Set `include_muted` to include suppressed resources
### Provider Management
Tools for managing cloud provider connections in Prowler.
-- **`prowler_app_search_providers`** - Search and view configured providers with their connection status
-- **`prowler_app_connect_provider`** - Register and connect a provider with credentials for security scanning
-- **`prowler_app_delete_provider`** - Permanently remove a provider from Prowler
+- **`prowler_search_providers`** - Search and view configured providers with their connection status
+- **`prowler_connect_provider`** - Register and connect a provider with credentials for security scanning
+- **`prowler_delete_provider`** - Permanently remove a provider from Prowler
### Scan Management
Tools for managing and monitoring security scans.
-- **`prowler_app_list_scans`** - List and filter security scans across all providers
-- **`prowler_app_get_scan`** - Get comprehensive details about a specific scan (progress, duration, resource counts)
-- **`prowler_app_trigger_scan`** - Trigger a manual security scan for a provider
-- **`prowler_app_schedule_daily_scan`** - Schedule automated daily scans for continuous monitoring
-- **`prowler_app_update_scan`** - Update scan name for better organization
+- **`prowler_list_scans`** - List and filter security scans across all providers
+- **`prowler_get_scan`** - Get comprehensive details about a specific scan (progress, duration, resource counts)
+- **`prowler_trigger_scan`** - Trigger a manual security scan for a provider
+- **`prowler_schedule_daily_scan`** - Schedule automated daily scans for continuous monitoring
+- **`prowler_update_scan`** - Update scan name for better organization
### Resources Management
Tools for searching, viewing, and analyzing cloud resources discovered by Prowler.
-- **`prowler_app_list_resources`** - List and filter cloud resources with advanced filtering options (provider, region, service, resource type, tags)
-- **`prowler_app_get_resource`** - Get comprehensive details about a specific resource including configuration, metadata, and finding relationships
-- **`prowler_app_get_resource_events`** - Get the timeline of cloud API actions performed on a resource (AWS CloudTrail). Shows who did what and when, with full request/response payloads
-- **`prowler_app_get_resources_overview`** - Get aggregate statistics about cloud resources as a markdown report
+- **`prowler_list_resources`** - List and filter cloud resources with advanced filtering options (provider, region, service, resource type, tags)
+- **`prowler_get_resource`** - Get comprehensive details about a specific resource including configuration, metadata, and finding relationships
+- **`prowler_get_resource_events`** - Get the timeline of cloud API actions performed on a resource (AWS CloudTrail). Shows who did what and when, with full request/response payloads
+- **`prowler_get_resources_overview`** - Get aggregate statistics about cloud resources as a markdown report
### Muting Management
@@ -77,33 +77,33 @@ Tools for managing finding muting, including pattern-based bulk muting (mutelist
#### Mutelist (Pattern-Based Muting)
-- **`prowler_app_get_mutelist`** - Retrieve the current mutelist configuration for the tenant
-- **`prowler_app_set_mutelist`** - Create or update the mutelist configuration for pattern-based bulk muting
-- **`prowler_app_delete_mutelist`** - Remove the mutelist configuration from the tenant
+- **`prowler_get_mutelist`** - Retrieve the current mutelist configuration for the tenant
+- **`prowler_set_mutelist`** - Create or update the mutelist configuration for pattern-based bulk muting
+- **`prowler_delete_mutelist`** - Remove the mutelist configuration from the tenant
#### Mute Rules (Finding-Specific Muting)
-- **`prowler_app_list_mute_rules`** - Search and filter mute rules with pagination support
-- **`prowler_app_get_mute_rule`** - Retrieve comprehensive details about a specific mute rule
-- **`prowler_app_create_mute_rule`** - Create a new mute rule to mute specific findings with documentation and audit trail
-- **`prowler_app_update_mute_rule`** - Update a mute rule's name, reason, or enabled status
-- **`prowler_app_delete_mute_rule`** - Delete a mute rule from the system
+- **`prowler_list_mute_rules`** - Search and filter mute rules with pagination support
+- **`prowler_get_mute_rule`** - Retrieve comprehensive details about a specific mute rule
+- **`prowler_create_mute_rule`** - Create a new mute rule to mute specific findings with documentation and audit trail
+- **`prowler_update_mute_rule`** - Update a mute rule's name, reason, or enabled status
+- **`prowler_delete_mute_rule`** - Delete a mute rule from the system
### Attack Paths Analysis
Tools for analyzing privilege escalation chains and security misconfigurations using graph-based analysis. Attack Paths maps relationships between cloud resources, permissions, and security findings to detect how privileges can be escalated and how misconfigurations can be exploited.
-- **`prowler_app_list_attack_paths_scans`** - List Attack Paths scans with filtering by provider, provider type, and scan state (available, scheduled, executing, completed, failed, cancelled)
-- **`prowler_app_list_attack_paths_queries`** - Discover available Attack Paths queries for a completed scan, including query names, descriptions, and required parameters
-- **`prowler_app_run_attack_paths_query`** - Execute an Attack Paths query against a completed scan and retrieve graph results with nodes (cloud resources, findings, virtual nodes) and relationships (access paths, role assumptions, security group memberships)
-- **`prowler_app_get_attack_paths_cartography_schema`** - Retrieve the Cartography graph schema (node labels, relationships, properties) for writing accurate custom openCypher queries
+- **`prowler_list_attack_paths_scans`** - List Attack Paths scans with filtering by provider, provider type, and scan state (available, scheduled, executing, completed, failed, cancelled)
+- **`prowler_list_attack_paths_queries`** - Discover available Attack Paths queries for a completed scan, including query names, descriptions, and required parameters
+- **`prowler_run_attack_paths_query`** - Execute an Attack Paths query against a completed scan and retrieve graph results with nodes (cloud resources, findings, virtual nodes) and relationships (access paths, role assumptions, security group memberships)
+- **`prowler_get_attack_paths_cartography_schema`** - Retrieve the Cartography graph schema (node labels, relationships, properties) for writing accurate custom openCypher queries
### Compliance Management
Tools for viewing compliance status and framework details across all cloud providers.
-- **`prowler_app_get_compliance_overview`** - Get high-level compliance status across all frameworks for a specific scan or provider, including pass/fail statistics per framework
-- **`prowler_app_get_compliance_framework_state_details`** - Get detailed requirement-level breakdown for a specific compliance framework, including failed requirements and associated finding IDs
+- **`prowler_get_compliance_overview`** - Get high-level compliance status across all frameworks for a specific scan or provider, including pass/fail statistics per framework
+- **`prowler_get_compliance_framework_state_details`** - Get detailed requirement-level breakdown for a specific compliance framework, including failed requirements and associated finding IDs
## Prowler Hub Tools
@@ -145,7 +145,7 @@ Search and access official Prowler documentation. **No authentication required.*
- Use natural language to interact with the tools through your AI assistant
- Tools can be combined for complex workflows
- Filter options are available on most list tools
-- Authentication is only required for Prowler Cloud/App tools
+- Authentication is only required for Prowler tools (Prowler Cloud, Prowler Private Cloud, or Prowler Local Server)
## Additional Resources
diff --git a/docs/getting-started/basic-usage/prowler-mcp.mdx b/docs/getting-started/basic-usage/prowler-mcp.mdx
index 2c32dbdbfc..120e5c038b 100644
--- a/docs/getting-started/basic-usage/prowler-mcp.mdx
+++ b/docs/getting-started/basic-usage/prowler-mcp.mdx
@@ -7,10 +7,10 @@ Configure your MCP client to connect to Prowler MCP Server.
## Step 1: Get Your API Key
-**Authentication is optional**: Prowler Hub and Prowler Documentation features work without authentication. An API key is only required for Prowler Cloud and Prowler App (Self-Managed) features.
+**Authentication is optional**: Prowler Hub and Prowler Documentation features work without authentication. An API key is only required for Prowler tools (Prowler Cloud, Prowler Private Cloud, or Prowler Local Server).
-To use Prowler Cloud or Prowler App (Self-Managed) features. To get the API key, please refer to the [API Keys](/user-guide/tutorials/prowler-app-api-keys) guide.
+An API key authenticates the Prowler tools (Prowler Cloud, Prowler Private Cloud, or Prowler Local Server). To get the API key, please refer to the [API Keys](/user-guide/tutorials/prowler-app-api-keys) guide.
Keep the API key secure. Never share it publicly or commit it to version control.
@@ -18,12 +18,14 @@ Keep the API key secure. Never share it publicly or commit it to version control
## Step 2: Configure Your MCP Host/Client
-Choose the configuration based on your deployment:
+Most users should use the **Cloud MCP Server** — it needs no installation and is maintained by Prowler. The [Local MCP Server](#local-mcp-server-configuration) configuration is provided afterwards for users who run the server themselves.
-- **HTTP Mode**: Prowler Cloud MCP Server or self-hosted Prowler MCP Server.
-- **STDIO Mode**: Local installation only (runs as subprocess of your MCP client).
+- **Cloud MCP Server (HTTP)**: the managed server at `https://mcp.prowler.com/mcp` (or your own self-hosted HTTP server).
+- **Local MCP Server (STDIO)**: local installation only (runs as a subprocess of your MCP client).
-### HTTP Mode
+## Cloud MCP Server Configuration (Recommended)
+
+Connect to the **Cloud MCP Server** at `https://mcp.prowler.com/mcp` over HTTP. This is the recommended path — no installation, always up to date. The same configuration works for a self-hosted HTTP server: just swap the URL.
@@ -61,10 +63,10 @@ Choose the configuration based on your deployment:
"args": [
"https://mcp.prowler.com/mcp", // or your self-hosted Prowler MCP Server URL
"--header",
- "Authorization: Bearer ${PROWLER_APP_API_KEY}"
+ "Authorization: Bearer ${PROWLER_API_KEY}"
],
"env": {
- "PROWLER_APP_API_KEY": ""
+ "PROWLER_API_KEY": ""
}
}
}
@@ -96,10 +98,10 @@ Choose the configuration based on your deployment:
"args": [
"https://mcp.prowler.com/mcp",
"--header",
- "Authorization: Bearer ${PROWLER_APP_API_KEY}"
+ "Authorization: Bearer ${PROWLER_API_KEY}"
],
"env": {
- "PROWLER_APP_API_KEY": ""
+ "PROWLER_API_KEY": ""
}
}
}
@@ -110,8 +112,8 @@ Choose the configuration based on your deployment:
Run the following command:
```bash
- export PROWLER_APP_API_KEY=""
- claude mcp add --transport http prowler https://mcp.prowler.com/mcp --header "Authorization: Bearer $PROWLER_APP_API_KEY" --scope user
+ export PROWLER_API_KEY=""
+ claude mcp add --transport http prowler https://mcp.prowler.com/mcp --header "Authorization: Bearer $PROWLER_API_KEY" --scope user
```
@@ -137,9 +139,9 @@ Choose the configuration based on your deployment:
-### STDIO Mode
+## Local MCP Server Configuration
-STDIO mode is only available when running the MCP server locally.
+STDIO mode is only available when running the **Local MCP Server** on your own machine. See the [Installation guide](/getting-started/installation/prowler-mcp) to set it up first.
@@ -152,7 +154,7 @@ STDIO mode is only available when running the MCP server locally.
"command": "uvx",
"args": ["/absolute/path/to/prowler/mcp_server/"],
"env": {
- "PROWLER_APP_API_KEY": "",
+ "PROWLER_API_KEY": "",
"API_BASE_URL": "https://api.prowler.com/api/v1"
}
}
@@ -179,7 +181,7 @@ STDIO mode is only available when running the MCP server locally.
"--rm",
"-i",
"--env",
- "PROWLER_APP_API_KEY=",
+ "PROWLER_API_KEY=",
"--env",
"API_BASE_URL=https://api.prowler.com/api/v1",
"prowlercloud/prowler-mcp"
@@ -205,7 +207,7 @@ Restart your MCP client and start asking questions:
## Authentication Methods
-Prowler MCP Server supports two authentication methods to connect to Prowler Cloud or Prowler App (Self-Managed):
+Prowler MCP Server supports two authentication methods to connect to Prowler (Prowler Cloud, Prowler Private Cloud, or Prowler Local Server):
### API Key (Recommended)
diff --git a/docs/getting-started/installation/prowler-app.mdx b/docs/getting-started/installation/prowler-app.mdx
index 598b2ac44a..1994b8ad0f 100644
--- a/docs/getting-started/installation/prowler-app.mdx
+++ b/docs/getting-started/installation/prowler-app.mdx
@@ -4,9 +4,9 @@ title: "Installation"
### Installation
-Prowler App offers flexible installation methods tailored to various environments.
+Prowler Local Server offers flexible installation methods tailored to various environments.
-Refer to the [Prowler App Tutorial](/user-guide/tutorials/prowler-app) for detailed usage instructions.
+Refer to the [Prowler Cloud guide](/user-guide/tutorials/prowler-app) for detailed usage instructions.
Prowler configuration is based on `.env` files. Every version of Prowler can have differences on that file, so, please, use the file that corresponds with that version or repository branch or tag.
@@ -109,17 +109,17 @@ Refer to the [Prowler App Tutorial](/user-guide/tutorials/prowler-app) for detai
pnpm start
```
- > Enjoy Prowler App at http://localhost:3000 by signing up with your email and password.
+ > Enjoy Prowler Local Server at http://localhost:3000 by signing up with your email and password.
- Google and GitHub authentication is only available in [Prowler Cloud](https://prowler.com).
+ Google and GitHub authentication works out of the box in [Prowler Cloud](https://prowler.com). In Prowler Local Server it requires OAuth credentials: see [Social Login Configuration](/user-guide/tutorials/prowler-app-social-login).
-### Updating Prowler App
+### Updating Prowler Local Server
-Upgrade Prowler App installation using one of two options:
+Upgrade Prowler Local Server installation using one of two options:
#### Option 1: Updating the Environment File
@@ -128,12 +128,12 @@ To update the environment file:
Edit the `.env` file and change version values:
```env
-PROWLER_UI_VERSION="5.31.0"
-PROWLER_API_VERSION="5.31.0"
+PROWLER_UI_VERSION="5.35.0"
+PROWLER_API_VERSION="5.35.0"
```
- You can find the latest versions of Prowler App in the [Releases Github section](https://github.com/prowler-cloud/prowler/releases) or in the [Container Versions](#container-versions) section of this documentation.
+ You can find the latest versions of Prowler Local Server in the [Releases Github section](https://github.com/prowler-cloud/prowler/releases) or in the [Container Versions](#container-versions) section of this documentation.
@@ -172,7 +172,7 @@ docker compose up -d
### Container Versions
-The available versions of Prowler App are the following:
+The available versions of Prowler Local Server are the following:
- `latest`: in sync with `master` branch (please note that it is not a stable version)
- `v4-latest`: in sync with `v4` branch (please note that it is not a stable version)
@@ -184,6 +184,6 @@ The available versions of Prowler App are the following:
The container images are available here:
-- Prowler App:
+- Prowler Local Server:
- [DockerHub - Prowler UI](https://hub.docker.com/r/prowlercloud/prowler-ui/tags)
- [DockerHub - Prowler API](https://hub.docker.com/r/prowlercloud/prowler-api/tags)
diff --git a/docs/getting-started/installation/prowler-mcp.mdx b/docs/getting-started/installation/prowler-mcp.mdx
index 06f204da6a..5be469b5b2 100644
--- a/docs/getting-started/installation/prowler-mcp.mdx
+++ b/docs/getting-started/installation/prowler-mcp.mdx
@@ -5,12 +5,12 @@ title: "Installation"
There are **two ways** to use Prowler MCP Server:
-
+
**No installation required** - Just configuration
Use `https://mcp.prowler.com/mcp`
-
+
**Local installation** - Full control
Install via Docker, PyPI, or source code
@@ -18,8 +18,8 @@ There are **two ways** to use Prowler MCP Server:
-For "Option 1: Managed by Prowler", go directly to the [Configuration Guide](/getting-started/basic-usage/prowler-mcp#hosted-server-configuration-recommended) to set up your Claude Desktop, Cursor, or other MCP client.
-**This guide is focused on local installation, "Option 2: Run Locally"**.
+For the Cloud MCP Server, go directly to the [Configuration Guide](/getting-started/basic-usage/prowler-mcp#cloud-mcp-server-configuration-recommended) to set up your Claude Desktop, Cursor, or other MCP client.
+**This guide is focused on local installation, the Local MCP Server**.
## Installation Methods
@@ -51,7 +51,7 @@ Choose one of the following installation methods:
```bash
docker run --rm -i \
- -e PROWLER_APP_API_KEY="pk_your_api_key" \
+ -e PROWLER_API_KEY="pk_your_api_key" \
-e API_BASE_URL="https://api.prowler.com/api/v1" \
prowlercloud/prowler-mcp
```
@@ -143,7 +143,7 @@ Choose one of the following installation methods:
## Updating Prowler MCP Server
-When running Prowler MCP Server locally ("Option 2: Run Locally"), upgrade to the latest version using the same method chosen for installation. The hosted server (`https://mcp.prowler.com/mcp`) is always kept up to date by Prowler and requires no action.
+When running the Local MCP Server, upgrade to the latest version using the same method chosen for installation. The Cloud MCP Server (`https://mcp.prowler.com/mcp`) is always kept up to date by Prowler and requires no action.
@@ -219,19 +219,19 @@ Configure the server using environment variables:
| Variable | Description | Required | Default |
|----------|-------------|----------|---------|
-| `PROWLER_APP_API_KEY` | Prowler API key | Only for STDIO mode | - |
+| `PROWLER_API_KEY` | Prowler API key | Only for STDIO mode | - |
| `API_BASE_URL` | Custom Prowler API endpoint | No | `https://api.prowler.com/api/v1` |
| `PROWLER_MCP_TRANSPORT_MODE` | Default transport mode (overwritten by `--transport` argument) | No | `stdio` |
```bash macOS/Linux
-export PROWLER_APP_API_KEY="pk_your_api_key_here"
+export PROWLER_API_KEY="pk_your_api_key_here"
export API_BASE_URL="https://api.prowler.com/api/v1"
export PROWLER_MCP_TRANSPORT_MODE="http"
```
```bash Windows PowerShell
-$env:PROWLER_APP_API_KEY="pk_your_api_key_here"
+$env:PROWLER_API_KEY="pk_your_api_key_here"
$env:API_BASE_URL="https://api.prowler.com/api/v1"
$env:PROWLER_MCP_TRANSPORT_MODE="http"
```
@@ -246,7 +246,7 @@ Never commit your API key to version control. Use environment variables or secur
For convenience, create a `.env` file in the `mcp_server` directory:
```bash .env
-PROWLER_APP_API_KEY=pk_your_api_key_here
+PROWLER_API_KEY=pk_your_api_key_here
API_BASE_URL=https://api.prowler.com/api/v1
PROWLER_MCP_TRANSPORT_MODE=stdio
```
diff --git a/docs/getting-started/products/index.mdx b/docs/getting-started/products/index.mdx
new file mode 100644
index 0000000000..c14ea37471
--- /dev/null
+++ b/docs/getting-started/products/index.mdx
@@ -0,0 +1,52 @@
+---
+title: 'Prowler Product Families'
+description: 'Official names for Prowler Open Source projects and Prowler Products, including former product names.'
+boost: 2
+---
+
+Prowler ships two product families: Prowler Products, operated or licensed by the Prowler team, and Open Source projects, free to run and extend. This page is the reference for every official name. If a page or blog post uses a former name, the [Former Names](#former-names) table maps it to the current one.
+
+
+Read the [public announcement of the Prowler product families](https://prowler-workspace.slack.com/archives/C03JUQVM33L/p1784120677833319) in our Slack community.
+
+
+## Prowler Products
+
+| Name | Description |
+|------|-------------|
+| [Prowler Cloud](/getting-started/products/prowler-cloud) | Managed cloud security platform operated by the Prowler team. See [pricing](https://prowler.com/pricing). |
+| Prowler Private Cloud | Prowler Cloud deployed in your own environment. Formerly Prowler Enterprise. See [pricing](https://prowler.com/pricing). |
+| [Prowler Hub](https://hub.prowler.com) | Free public library of versioned checks, cloud service artifacts, and compliance frameworks. |
+| [Prowler Lighthouse AI](/getting-started/products/prowler-cloud-lighthouse) | AI security analyst capabilities within Prowler Cloud and Prowler Private Cloud. |
+| [Prowler MCP](/getting-started/products/prowler-mcp) | MCP server that connects AI assistants and agents to Prowler, including IDE plugins such as [Prowler for Claude Code](/getting-started/products/prowler-claude-code-plugin). |
+
+{/* Unreleased products. Uncomment these rows in the Prowler Products table when announced:
+| Prowler Registry | Distribution service for Prowler content such as checks and compliance frameworks. Free and paid tiers. |
+| Prowler Local Registry | Prowler Registry running in your own environment. Paid. |
+*/}
+
+
+Throughout this documentation, the green cloud icon in the sidebar marks sections and pages for capabilities that require a Prowler Cloud or Prowler Private Cloud [subscription](https://prowler.com/pricing).
+
+
+Products without a documentation page here are available through the Prowler team. [Contact us](https://prowler.com/contact) for details.
+
+## Open Source Projects
+
+| Name | Description |
+|------|-------------|
+| [Prowler CLI](/getting-started/products/prowler-cli) | Command line tool to run security scans across all supported providers. |
+| [Prowler Local Server](/getting-started/products/prowler-app) | Self-hosted web application and API to run scans, visualize findings, and manage cloud providers. Formerly Prowler App. |
+| [Prowler Local Dashboard](/user-guide/cli/tutorials/dashboard) | Local web dashboard to visualize scan results from Prowler CLI CSV outputs. Shipped with Prowler CLI. |
+| [Prowler SDK](/getting-started/products/prowler-sdk) | Python library that powers Prowler CLI and Prowler Local Server. Part of the [prowler repository](https://github.com/prowler-cloud/prowler). |
+
+## Former Names
+
+| Former name | Current name |
+|-------------|--------------|
+| Prowler App | [Prowler Local Server](/getting-started/products/prowler-app) |
+| Prowler Enterprise | Prowler Private Cloud |
+
+## Prowler for MSPs and MSSPs
+
+Prowler partners with managed service providers (MSPs) and managed security service providers (MSSPs) that operate Prowler for their customers. Visit [partners.prowler.com](https://partners.prowler.com) to become a partner.
diff --git a/docs/getting-started/products/prowler-app.mdx b/docs/getting-started/products/prowler-app.mdx
index 2df6015d06..76af591ba0 100644
--- a/docs/getting-started/products/prowler-app.mdx
+++ b/docs/getting-started/products/prowler-app.mdx
@@ -2,16 +2,16 @@
title: 'Overview'
---
-Prowler App is a web application that simplifies running Prowler. It provides:
+Prowler Local Server is a self-hosted web application that simplifies running Prowler. It provides:
- **User-friendly interface** for configuring and executing scans
- Dashboard to **view results** and manage **security findings**
-
+
## Components
-Prowler App consists of four main components:
+Prowler Local Server consists of four main components:
- **Prowler UI**: User-friendly web interface for running Prowler and viewing results, powered by Next.js
- **Prowler API**: Backend API that executes Prowler scans and stores results, built with Django REST Framework
@@ -26,4 +26,42 @@ Supporting infrastructure includes:
- **Valkey**: In-memory database serving as message broker for Celery workers
- **Neo4j**: Graph database used by the Attack Paths feature to combine cloud inventory with Prowler findings (currently populated by AWS scans)
-
+```mermaid
+flowchart TB
+ user([User / Security Team])
+ cli([Prowler CLI])
+
+ subgraph APP["Prowler Local Server"]
+ ui["Prowler UI (Next.js)"]
+ api["Prowler API (Django REST Framework)"]
+ worker["API Worker (Celery)"]
+ beat["API Scheduler (Celery Beat)"]
+ mcp["Prowler MCP Server (Lighthouse AI tools)"]
+ end
+
+ sdk["Prowler SDK (Python)"]
+
+ subgraph DATA["Data Layer"]
+ pg[("PostgreSQL")]
+ valkey[("Valkey / Redis")]
+ neo4j[("Neo4j")]
+ end
+
+ providers["Providers"]
+
+ user --> ui
+ user --> cli
+ ui -->|REST| api
+ ui -->|MCP HTTP| mcp
+ mcp -->|REST| api
+ api --> pg
+ api --> valkey
+ beat -->|enqueue jobs| valkey
+ valkey -->|dispatch| worker
+ worker --> pg
+ worker -->|Attack Paths| neo4j
+ worker -->|invokes| sdk
+ cli --> sdk
+
+ sdk --> providers
+```
diff --git a/docs/getting-started/products/prowler-claude-code-plugin.mdx b/docs/getting-started/products/prowler-claude-code-plugin.mdx
index e3c11ec810..99c92a1488 100644
--- a/docs/getting-started/products/prowler-claude-code-plugin.mdx
+++ b/docs/getting-started/products/prowler-claude-code-plugin.mdx
@@ -1,5 +1,6 @@
---
title: 'Prowler for Claude Code'
+sidebarTitle: 'Claude Code'
---
End-to-end cloud security and compliance from inside [Claude Code](https://www.claude.com/product/claude-code), powered by the [Prowler MCP server](/getting-started/products/prowler-mcp). The plugin lets Claude walk a Prowler Cloud-connected account through a compliance assessment and remediate findings until the chosen security or industry framework is compliant.
diff --git a/docs/getting-started/products/prowler-cli.mdx b/docs/getting-started/products/prowler-cli.mdx
index ac4f37c291..fa75e0456e 100644
--- a/docs/getting-started/products/prowler-cli.mdx
+++ b/docs/getting-started/products/prowler-cli.mdx
@@ -9,12 +9,12 @@ prowler
```

-## Prowler Dashboard
+## Prowler Local Dashboard
```console
prowler dashboard
```
-
+
Prowler includes hundreds of security controls aligned with widely recognized industry frameworks and standards, including:
diff --git a/docs/getting-started/products/prowler-cloud-lighthouse.mdx b/docs/getting-started/products/prowler-cloud-lighthouse.mdx
new file mode 100644
index 0000000000..d32118d468
--- /dev/null
+++ b/docs/getting-started/products/prowler-cloud-lighthouse.mdx
@@ -0,0 +1,154 @@
+---
+title: 'Overview'
+---
+
+import { SubscriptionBanner } from "/snippets/subscription-banner.mdx"
+
+Prowler Cloud runs an enhanced version of Lighthouse AI in Open Source repository, the Agentic Cloud Defender that helps teams understand, prioritize, and remediate security findings across cloud environments.
+
+
+
+
+
+## What's New
+
+The Agentic Cloud Defender does more than answer questions, it helps teams **find and remediate what actually matters**, cutting through the noise to focus on the risk that counts. Prowler Cloud sharpens Lighthouse AI with the following improvements over the open-source version:
+
+
+
+ Conversations are saved and can be revisited or resumed at any time.
+
+
+ An upgraded default model delivers stronger reasoning and tool calling.
+
+
+ Switch between the standard interface and a chat-first agentic view.
+
+
+ Open Lighthouse AI as a side panel from any page to get help in context.
+
+
+ Credentials are validated automatically when a provider is configured.
+
+
+
+## Chat View
+
+Lighthouse AI is no longer a separate section in the left navigation. Prowler Cloud now offers two application views: a normal view for browsing dashboards, findings, and configuration, and an agentic chat view, powered by Lighthouse AI, for conversational, multi-step security analysis. Conversations are saved automatically, so earlier sessions can be reopened and resumed at any time.
+
+Promoting the chat to a top-level view gives Lighthouse AI the room it needs for a fully agentic workflow and makes the Agentic Cloud Defender a primary way to work in Prowler Cloud.
+
+
+
+### Side Panel
+
+You do not have to switch to the full chat view to reach Lighthouse AI. A side panel is available on every page of Prowler Cloud. While collapsed it stays out of the way; open it from any dashboard, findings list, or configuration screen to ask questions without leaving what you are working on. Open it using the Lighthouse AI button, circled in red in the image below.
+
+
+
+Once open, the panel slides in alongside your current page and shares the same agent, tools, and persistent chat sessions as the full Chat View, so a conversation started in the panel can be reopened and continued later from either place.
+
+
+
+- **Available everywhere:** Summon the assistant from any page while you keep working in the normal view.
+- **Context-aware help:** Ask about the findings, resources, or compliance data you are currently looking at.
+- **Continuous sessions:** Conversations opened in the side panel are saved alongside the rest of your chat history.
+
+### Tool Usage
+
+Lighthouse AI on Prowler Cloud renders the agent's work as it happens, so responses are easier to follow and to trust. Tool calls and reasoning steps appear in the order they occur within the conversation.
+
+- **Ordered steps:** Tool calls and reasoning are shown in sequence, reflecting how the agent reached its answer.
+- **Tool visibility:** The data tools invoked to retrieve findings and other Prowler information are displayed as the agent uses them.
+- **Thought process:** The agent's reasoning is presented alongside its actions, and can be expanded to review the full chain of steps.
+
+
+
+## Configuration
+
+Configure Lighthouse AI on Prowler Cloud from **Configuration** → **Lighthouse AI**:
+
+1. Click the desired provider (OpenAI, Amazon Bedrock, or OpenAI Compatible).
+2. Enter the required credentials.
+3. Click **Save**. The connection is validated automatically before the provider becomes available.
+
+
+
+### Business Context
+
+At the top of the configuration page, the optional **Business Context** field lets teams add environment priorities, compliance requirements, and ownership details, so responses align with organizational needs.
+
+Lighthouse AI on Prowler Cloud supports OpenAI, Amazon Bedrock, and OpenAI-compatible providers, with GPT-5.5 as the default. For per-provider setup and how to switch the default provider or model, see [Using Multiple LLM Providers](/user-guide/tutorials/prowler-cloud-lighthouse-multi-llm).
+
+## Capabilities
+
+Lighthouse AI works through the [Prowler MCP Server](/getting-started/products/prowler-mcp), which gives the agent a growing catalog of tools to explore and act on your security data. These actions run inside Prowler and never modify your cloud resources. Everything the agent can do maps to one of the following capability areas.
+
+### Findings and Finding Groups
+
+- Search and filter security findings across every connected provider by severity, status, region, service, check, date range, and muted state.
+- Retrieve full finding details, including remediation guidance, check metadata, and affected resources.
+- Summarize findings with aggregate statistics and trends.
+- Browse finding groups aggregated by check and drill down into the specific resources each group affects.
+
+### Resources
+
+- List and filter cloud resources by provider, region, service, resource type, and tags.
+- Inspect a resource's configuration, metadata, and related findings.
+- Review the timeline of cloud API actions performed on a resource (AWS CloudTrail), including who did what and when.
+- Get an aggregate overview of the resources Prowler has discovered.
+
+### Compliance
+
+- Review high-level compliance status across all frameworks, with pass/fail statistics per framework.
+- Get a requirement-level breakdown for a specific framework, including failed requirements and their associated findings.
+
+### Attack Paths
+
+- List Attack Paths scans and discover the queries available for each completed scan.
+- Run graph-based queries to reveal privilege-escalation chains and exploitable misconfigurations.
+- Retrieve the Cartography graph schema to build accurate custom queries.
+
+### Scans and Providers
+
+- List, inspect, and rename security scans across providers.
+- Trigger manual scans and schedule automated daily scans for continuous monitoring.
+- Search connected providers and check their connection status, connect new providers, or remove existing ones.
+
+### Muting
+
+- Manage the mutelist for pattern-based bulk muting.
+- Create, update, list, and delete finding-specific mute rules, each with a documented reason and audit trail.
+
+### Security Check Catalog and Documentation
+
+- Browse and search the Prowler Hub catalog of security checks and compliance frameworks, including check code and automated fixers.
+- Search and retrieve official Prowler documentation to answer how-to and product questions.
+
+For the complete list of underlying tools, see the [Prowler MCP Tools Reference](/getting-started/basic-usage/prowler-mcp-tools).
+
+## FAQ
+
+**Which LLM providers are supported?**
+
+OpenAI (GPT models, including the default GPT-5.5), Amazon Bedrock (Claude, Llama, Titan, and others), and any OpenAI-compatible service such as OpenRouter.
+
+**Can Lighthouse AI change my cloud environment?**
+
+No. Lighthouse AI cannot modify the resources in your connected cloud providers (AWS, Azure, GCP, and others). It has read-only access to that environment and no tools to change it, even when the connected cloud credentials would allow it.
+
+**Can Lighthouse AI change my Prowler Cloud environment?**
+
+Yes. Lighthouse AI can take action within Prowler Cloud itself, such as connecting or removing providers, triggering and scheduling scans, and managing mute rules and the mutelist. See [Capabilities](#capabilities) for the full list of what it can do. These actions only affect your Prowler Cloud workspace, never the resources in your cloud providers.
+
+## Looking for the Open Source Version?
+
+Lighthouse AI is also available in the open-source Prowler Local Server. For its capabilities, FAQs, and limitations, see the open-source documentation.
+
+
+ Capabilities, FAQs, and limitations for Lighthouse AI in the open-source Prowler Local Server
+
+
+## Getting Help
+
+For issues or suggestions with Lighthouse AI on Prowler Cloud, request support at [support.prowler.com](https://support.prowler.com) or [reach out through our Slack channel](https://goto.prowler.com/slack).
diff --git a/docs/getting-started/products/prowler-lighthouse-ai.mdx b/docs/getting-started/products/prowler-lighthouse-ai.mdx
index 4e2eed8538..6cb6edf502 100644
--- a/docs/getting-started/products/prowler-lighthouse-ai.mdx
+++ b/docs/getting-started/products/prowler-lighthouse-ai.mdx
@@ -8,11 +8,16 @@ import { VersionBadge } from "/snippets/version-badge.mdx"
Prowler Lighthouse AI is a Cloud Security Analyst chatbot that helps you understand, prioritize, and remediate security findings in your cloud environments. It's designed to provide security expertise for teams without dedicated resources, acting as your 24/7 virtual cloud security analyst.
-
+
-
- Learn how to configure Lighthouse AI with your preferred LLM provider
-
+
+
+ Discover the enhanced Cloud experience: persistent chat sessions, GPT-5.5 by default, a dedicated agentic view, and transparent reasoning
+
+
+ Learn how to configure Lighthouse AI with your preferred LLM provider
+
+
## Capabilities
@@ -26,7 +31,7 @@ Ask questions in plain English about your security findings. Examples:
- "Show me all S3 buckets with public access."
- "What security issues were found in my production accounts?"
-
+
### Detailed Remediation Guidance
@@ -36,7 +41,7 @@ Get tailored step-by-step instructions for fixing security issues:
- Commands or console steps to implement fixes
- Alternative approaches with different solutions
-
+
### Enhanced Context and Analysis
@@ -46,9 +51,9 @@ Lighthouse AI can provide additional context to help you understand the findings
- Provide risk assessments based on your environment and context
- Connect related findings to show broader security patterns
-
+
-
+
## Important Notes
diff --git a/docs/getting-started/products/prowler-mcp.mdx b/docs/getting-started/products/prowler-mcp.mdx
index 762b088326..93159b2e7d 100644
--- a/docs/getting-started/products/prowler-mcp.mdx
+++ b/docs/getting-started/products/prowler-mcp.mdx
@@ -8,6 +8,31 @@ title: "Overview"
**Preview Feature**: This MCP server is currently under active development. Features and functionality may change. We welcome your feedback—please report any issues on [GitHub](https://github.com/prowler-cloud/prowler/issues) or join our [Slack community](https://goto.prowler.com/slack) to discuss and share your thoughts.
+## Quickest Way to Connect: Cloud MCP Server
+
+The fastest way to get started is the **Cloud MCP Server** at `https://mcp.prowler.com/mcp` — no installation, always up to date, and maintained by Prowler. Just point your MCP client at the URL and authenticate with a [Prowler API key](/user-guide/tutorials/prowler-app-api-keys) as a Bearer token:
+
+```json
+{
+ "mcpServers": {
+ "prowler": {
+ "url": "https://mcp.prowler.com/mcp",
+ "headers": {
+ "Authorization": "Bearer "
+ }
+ }
+ }
+}
+```
+
+
+ Step-by-step setup for Claude Desktop, Claude Code, Cursor, and other clients.
+
+
+
+Prefer to run it yourself? The **Local MCP Server** runs on your own machine or infrastructure. The Cloud MCP Server additionally provides tools for Prowler Cloud-specific features such as [Alerts](/user-guide/tutorials/prowler-alerts), [Scan Scheduling](/user-guide/tutorials/prowler-scan-scheduling), and [Findings Triage](/user-guide/tutorials/prowler-app-findings-triage). See [Cloud vs Local MCP Server](#cloud-vs-local-mcp-server).
+
+
## What is the Model Context Protocol?
The [Model Context Protocol (MCP)](https://modelcontextprotocol.io) is an open standard developed by Anthropic that enables AI assistants to securely connect to external data sources and tools. It functions as a universal adapter enabling AI assistants to interact with various services through a standardized interface.
@@ -16,9 +41,9 @@ The [Model Context Protocol (MCP)](https://modelcontextprotocol.io) is an open s
The Prowler MCP Server provides three main integration points:
-### 1. Prowler Cloud and Prowler App (Self-Managed)
+### 1. Prowler Cloud, Private Cloud & Local Server
-Full access to Prowler Cloud platform and self-managed Prowler App for:
+Full access to your Prowler deployment — Prowler Cloud, Prowler Private Cloud, or Prowler Local Server — for:
- **Findings Analysis**: Query, filter, and analyze security findings across all your cloud environments
- **Provider Management**: Create, configure, and manage your configured Prowler providers (AWS, Azure, GCP, etc.)
- **Scan Orchestration**: Trigger on-demand scans and schedule recurring security assessments
@@ -29,7 +54,7 @@ Full access to Prowler Cloud platform and self-managed Prowler App for:
### 2. Prowler Hub
Access to Prowler's comprehensive security knowledge base:
-- **Security Checks Catalog**: Browse and search **over 1000 security checks** across multiple cloud providers.
+- **Security Checks Catalog**: Browse and search **over 2,000 security checks** across multiple cloud providers.
- **Check Implementation**: View the Python code that powers each security check.
- **Automated Fixers**: Access remediation scripts for common security issues.
- **Compliance Frameworks**: Explore mappings to **over 70 compliance standards and frameworks**.
@@ -44,12 +69,53 @@ Search and retrieve official Prowler documentation:
## MCP Server Architecture
-The following diagram illustrates the Prowler MCP Server architecture and its integration points:
+The following diagram illustrates the Prowler MCP Server architecture and its integration points. MCP clients connect to either the **Cloud MCP Server** (recommended) or a **Local MCP Server**; both expose the same tools and reach the same Prowler backends:
-
+```mermaid
+flowchart LR
+ subgraph HOSTS["MCP Clients"]
+ chat["Chat Interfaces (Claude Desktop, LobeChat)"]
+ ide["IDEs and Code Editors (Claude Code, Cursor)"]
+ apps["Other AI Applications (5ire, custom agents)"]
+ end
+
+ subgraph SERVERS["Prowler MCP Server"]
+ direction TB
+ cloud["☁️ Cloud MCP Server (Recommended) mcp.prowler.com/mcp · HTTP Managed by Prowler · always up to date Adds Cloud-only tools (Alerts, Scan Scheduling, Findings Triage)"]
+ local["💻 Local MCP Server Self-run · STDIO or HTTP Python 3.12+ or Docker You manage updates"]
+ end
+
+ subgraph TOOLS["Prowler MCP Tools"]
+ prowler_tools["prowler_* tools (API key or JWT auth) Findings · Providers · Scans Resources · Muting · Compliance Attack Paths"]
+ hub_tools["prowler_hub_* tools (no auth) Checks Catalog · Check Code Fixers · Compliance Frameworks"]
+ docs_tools["prowler_docs_* tools (no auth) Search · Document Retrieval"]
+ end
+
+ api["Prowler API (REST) Cloud · Private Cloud · Local Server"]
+ hub["hub.prowler.com (REST)"]
+ docs["docs.prowler.com (Mintlify)"]
+
+ chat -->|HTTP| cloud
+ ide -->|HTTP| cloud
+ apps -->|HTTP| cloud
+ chat -->|STDIO or HTTP| local
+ ide -->|STDIO or HTTP| local
+ apps -->|STDIO or HTTP| local
+
+ cloud --> prowler_tools
+ cloud --> hub_tools
+ cloud --> docs_tools
+ local --> prowler_tools
+ local --> hub_tools
+ local --> docs_tools
+
+ prowler_tools -->|REST| api
+ hub_tools -->|REST| hub
+ docs_tools -->|REST| docs
+```
The architecture shows how AI assistants connect through the MCP protocol to access Prowler's three main components:
-- Prowler Cloud/App for security operations
+- Prowler Cloud, Prowler Private Cloud, or Prowler Local Server for security operations
- Prowler Hub for security knowledge
- Prowler Documentation for guidance and reference.
@@ -88,8 +154,8 @@ REQUIREMENTS:
DATA TO FETCH:
Use these MCP tools in this order:
-1. Prowler app list providers - To get all available configured provider in the account
-2. Prowler app get latest findings - To get findings information, if there are so many you can use the filter_fields to get less information, or pagination to get in different batches
+1. Prowler list providers - To get all available configured provider in the account
+2. Prowler get latest findings - To get findings information, if there are so many you can use the filter_fields to get less information, or pagination to get in different batches
3. For most critical findings you can get more context and remediation with Prowler Hub to get remediations for example
DESIGN REQUIREMENTS:
@@ -126,65 +192,48 @@ Generate the complete HTML file and display it
>
-## Deployment Options
+## Cloud vs Local MCP Server
-Prowler MCP Server can be used in three ways:
+There are two ways to run the Prowler MCP Server. For almost everyone, the **Cloud MCP Server** is the right choice — it needs no installation and is maintained by Prowler. The **Local MCP Server** exists for users who need to run it on their own machine or infrastructure.
-### 1. Prowler Cloud MCP Server
+| | ☁️ **Cloud MCP Server** (Recommended) | 💻 **Local MCP Server** |
+|---|---|---|
+| **Endpoint** | `https://mcp.prowler.com/mcp` | Runs on your machine or infrastructure |
+| **Setup** | Just configure your MCP client | Install via Docker, or source |
+| **Transport** | HTTP | STDIO (subprocess) or self-hosted HTTP |
+| **Maintenance** | Managed by Prowler, always up to date | You manage updates |
+| **Requirements** | None (just an MCP client) | Python 3.12+ or Docker |
+| **Cloud-only tools** | ✅ Alerts, Scan Scheduling, Findings Triage | ❌ Not available |
+| **Authentication** | API key or JWT token | API key/JWT (HTTP) or env vars (STDIO) |
-**Use Prowler's managed MCP server at `https://mcp.prowler.com/mcp`**
+### ☁️ Cloud MCP Server (Recommended)
-- No installation required.
-- Managed and maintained by Prowler team.
-- Authentication to Prowler Cloud or Prowler App (self-managed) via API key or JWT token.
+Prowler's managed MCP server at `https://mcp.prowler.com/mcp`. No installation, always up to date, and it includes tools for Prowler Cloud-specific features such as Alerts, Scan Scheduling, and Findings Triage. This is the path we recommend for nearly all users — go straight to the [Configuration guide](/getting-started/basic-usage/prowler-mcp#cloud-mcp-server-configuration-recommended).
-### 2. Local STDIO Mode
+### 💻 Local MCP Server
-**Run the server locally on your machine**
+Run the server yourself when you need full control over the deployment. It connects to Prowler Cloud, Prowler Private Cloud, or Prowler Local Server and can run in two modes:
-- Runs as a subprocess of your MCP client.
-- Possibility to connect to a self-hosted Prowler App (e.g. self-hosted Prowler App).
-- Authentication to Prowler Cloud or Prowler App (self-managed) via environment variables.
-- Requires Python 3.12+ or Docker.
+- **STDIO mode** — the server runs as a subprocess of your MCP client. Authentication via environment variables.
+- **Self-hosted HTTP mode** — deploy your own remote HTTP server. Authentication via API key or JWT token.
-### 3. Self-Hosted HTTP Mode
-
-**Deploy your own remote MCP server**
-
-- Full control over deployment.
-- Possibility to connect to a self-hosted Prowler App (e.g. self-hosted Prowler App).
-- Authentication to Prowler App (self-managed) via API key or JWT token.
-- Requires Python 3.12+ or Docker.
-
-## Requirements
-
-Requirements vary based on deployment option:
-
-**For Prowler Cloud MCP Server:**
-- Prowler Cloud account and API key (only for Prowler Cloud/App features)
-
-**For self-hosted STDIO/HTTP Mode:**
-- Python 3.12+ or Docker
-- Network access to:
- - `https://hub.prowler.com` (for Prowler Hub)
- - `https://docs.prowler.com` (for Prowler Documentation)
- - Prowler Cloud API or self-hosted Prowler App API (for Prowler Cloud/App features)
+Both require Python 3.12+ or Docker, plus network access to `https://hub.prowler.com` (Prowler Hub), `https://docs.prowler.com` (Prowler Documentation), and the Prowler API or Prowler Local Server API (Prowler features). See the [Installation guide](/getting-started/installation/prowler-mcp) to get started.
-**No Authentication Required**: Prowler Hub and Prowler Documentation features work without authentication in both deployment options. A Prowler API key is only required to access Prowler Cloud or Prowler App (Self-Managed) features.
+**No Authentication Required**: Prowler Hub and Prowler Documentation features work without authentication on both the Cloud and Local MCP Server. A Prowler API key is only required to access Prowler features (Prowler Cloud, Prowler Private Cloud, or Prowler Local Server).
## Next Steps
-
- Install the Prowler MCP Server using uv or Docker
-
- Configure your MCP client to connect to the server
+ Connect your MCP client to the Cloud MCP Server
+
+
+ Explore all available tools and capabilities
-
- Explore all available tools and capabilities
+
+ Run the Local MCP Server yourself using Docker, source, or uvx
diff --git a/docs/getting-started/products/prowler-sdk.mdx b/docs/getting-started/products/prowler-sdk.mdx
new file mode 100644
index 0000000000..b19f576e12
--- /dev/null
+++ b/docs/getting-started/products/prowler-sdk.mdx
@@ -0,0 +1,11 @@
+---
+title: 'Prowler SDK'
+---
+
+Prowler SDK is the Python library that powers Prowler CLI and Prowler Local Server. It implements the providers, services, and security checks that every Prowler product runs.
+
+To use or extend Prowler SDK, start with the Developer Guide:
+
+
+ Providers, services, checks, and testing: everything needed to work with Prowler SDK.
+
diff --git a/docs/images/compliance/prowler-app-cross-provider-detail.png b/docs/images/compliance/prowler-app-cross-provider-detail.png
new file mode 100644
index 0000000000..8ee82562e2
Binary files /dev/null and b/docs/images/compliance/prowler-app-cross-provider-detail.png differ
diff --git a/docs/images/compliance/prowler-app-cross-provider-overview.png b/docs/images/compliance/prowler-app-cross-provider-overview.png
new file mode 100644
index 0000000000..d818da1b80
Binary files /dev/null and b/docs/images/compliance/prowler-app-cross-provider-overview.png differ
diff --git a/docs/images/compliance/prowler-app-cross-provider-report.png b/docs/images/compliance/prowler-app-cross-provider-report.png
new file mode 100644
index 0000000000..e3b45ef74e
Binary files /dev/null and b/docs/images/compliance/prowler-app-cross-provider-report.png differ
diff --git a/docs/images/compliance/prowler-app-cross-provider-requirements-accordion.png b/docs/images/compliance/prowler-app-cross-provider-requirements-accordion.png
new file mode 100644
index 0000000000..cd87e3ee35
Binary files /dev/null and b/docs/images/compliance/prowler-app-cross-provider-requirements-accordion.png differ
diff --git a/docs/images/compliance/prowler-app-cross-provider-tab.png b/docs/images/compliance/prowler-app-cross-provider-tab.png
new file mode 100644
index 0000000000..b3aa8ed2b5
Binary files /dev/null and b/docs/images/compliance/prowler-app-cross-provider-tab.png differ
diff --git a/docs/images/icons/cloud-bold.svg b/docs/images/icons/cloud-bold.svg
new file mode 100644
index 0000000000..623bb36c11
--- /dev/null
+++ b/docs/images/icons/cloud-bold.svg
@@ -0,0 +1 @@
+
diff --git a/docs/images/lighthouse-architecture.mmd b/docs/images/lighthouse-architecture.mmd
index 47407544e9..6798801fb8 100644
--- a/docs/images/lighthouse-architecture.mmd
+++ b/docs/images/lighthouse-architecture.mmd
@@ -15,7 +15,7 @@ flowchart TB
llm["LLM Provider (OpenAI / Bedrock / OpenAI-compatible)"]
subgraph MCP["Prowler MCP Server"]
- app_tools["prowler_app_* tools (auth required)"]
+ app_tools["prowler_* tools (auth required)"]
hub_tools["prowler_hub_* tools (no auth)"]
docs_tools["prowler_docs_* tools (no auth)"]
end
@@ -29,7 +29,7 @@ flowchart TB
agent <-->|LLM API| llm
agent --> metatools
metatools --> mcpclient
- mcpclient -->|MCP HTTP · Bearer token for prowler_app_* only| app_tools
+ mcpclient -->|MCP HTTP · Bearer token for prowler_* only| app_tools
mcpclient -->|MCP HTTP| hub_tools
mcpclient -->|MCP HTTP| docs_tools
app_tools -->|REST| api
diff --git a/docs/images/organizations/authentication-details.png b/docs/images/organizations/authentication-details.png
index 2b4ae782cf..aec5060afd 100644
Binary files a/docs/images/organizations/authentication-details.png and b/docs/images/organizations/authentication-details.png differ
diff --git a/docs/images/organizations/onboarding-flow.svg b/docs/images/organizations/onboarding-flow.svg
index f6e11fc0a3..b5ba7858a0 100644
--- a/docs/images/organizations/onboarding-flow.svg
+++ b/docs/images/organizations/onboarding-flow.svg
@@ -3,41 +3,37 @@
+
+
+ Onboarding Flow
-
+ 1
- Create Management
- Account Role
-
- Quick Create or Manual
- Allows Prowler to
- discover your org
- structure
+ Start the Wizard
+
+ In Prowler Cloud
+ Enter your Org ID
+ and OU/root target
-
-
-
-
- 2
- Deploy StackSet
-
- In AWS Console
- Creates ProwlerScan
- role in every
- member account
+ Deploy the Roles
+
+ Single CF Stack
+ Management role +
+ StackSet to members
+ in one CF stack
@@ -46,11 +42,11 @@
3
- Run the Wizard
-
- In Prowler Cloud
- Discovers accounts,
- tests connections
+ Discover & Connect
+
+ In Prowler Cloud
+ Discovers accounts,
+ tests connections
@@ -59,13 +55,13 @@
4
- Launch Scans
-
- Automatic
- Scans run on all
- connected accounts
- on your schedule
+ Launch Scans
+
+ Automatic
+ Scans run on all
+ connected accounts
+ on your schedule
- Steps 1 and 2 are done once in AWS | Steps 3 and 4 are done in Prowler Cloud
+ Step 2 runs once in AWS | Steps 1, 3 and 4 are in Prowler Cloud
diff --git a/docs/images/organizations/two-roles-architecture.svg b/docs/images/organizations/two-roles-architecture.svg
index c67588b049..f8c40d5b21 100644
--- a/docs/images/organizations/two-roles-architecture.svg
+++ b/docs/images/organizations/two-roles-architecture.svg
@@ -47,7 +47,7 @@
- Deploy: Quick Create link or Manual
+ Deploy: single stack or standalone
@@ -86,7 +86,7 @@
- Deploy: via CloudFormation StackSet
+ Deploy: StackSet (single stack)Prowler discovers
diff --git a/docs/images/products/prowler-app-architecture.mmd b/docs/images/products/prowler-app-architecture.mmd
index 0c13d580c3..da99d0ab96 100644
--- a/docs/images/products/prowler-app-architecture.mmd
+++ b/docs/images/products/prowler-app-architecture.mmd
@@ -1,8 +1,10 @@
+%% Source of truth for the architecture diagram.
+%% Inlined as native mermaid blocks in the root README.md and in docs/getting-started/products/prowler-app.mdx: keep all copies in sync.
flowchart TB
user([User / Security Team])
cli([Prowler CLI])
- subgraph APP["Prowler App"]
+ subgraph APP["Prowler Local Server"]
ui["Prowler UI (Next.js)"]
api["Prowler API (Django REST Framework)"]
worker["API Worker (Celery)"]
diff --git a/docs/images/prowler-app/attack-paths/execute-query.png b/docs/images/prowler-app/attack-paths/execute-query.png
index 3872f0de2f..683c7c5bd3 100644
Binary files a/docs/images/prowler-app/attack-paths/execute-query.png and b/docs/images/prowler-app/attack-paths/execute-query.png differ
diff --git a/docs/images/prowler-app/attack-paths/fullscreen-mode.png b/docs/images/prowler-app/attack-paths/fullscreen-mode.png
index c5156925ba..190d973638 100644
Binary files a/docs/images/prowler-app/attack-paths/fullscreen-mode.png and b/docs/images/prowler-app/attack-paths/fullscreen-mode.png differ
diff --git a/docs/images/prowler-app/attack-paths/graph-filtered.png b/docs/images/prowler-app/attack-paths/graph-filtered.png
index 3ff4822a26..3eddf04473 100644
Binary files a/docs/images/prowler-app/attack-paths/graph-filtered.png and b/docs/images/prowler-app/attack-paths/graph-filtered.png differ
diff --git a/docs/images/prowler-app/attack-paths/graph-visualization.png b/docs/images/prowler-app/attack-paths/graph-visualization.png
index 2ea160a6b2..d7f2a747eb 100644
Binary files a/docs/images/prowler-app/attack-paths/graph-visualization.png and b/docs/images/prowler-app/attack-paths/graph-visualization.png differ
diff --git a/docs/images/prowler-app/attack-paths/navigation.png b/docs/images/prowler-app/attack-paths/navigation.png
index d133c7f6b4..0526e05e5c 100644
Binary files a/docs/images/prowler-app/attack-paths/navigation.png and b/docs/images/prowler-app/attack-paths/navigation.png differ
diff --git a/docs/images/prowler-app/attack-paths/node-details.png b/docs/images/prowler-app/attack-paths/node-details.png
index 9343eedd7d..8b02128604 100644
Binary files a/docs/images/prowler-app/attack-paths/node-details.png and b/docs/images/prowler-app/attack-paths/node-details.png differ
diff --git a/docs/images/prowler-app/attack-paths/query-parameters.png b/docs/images/prowler-app/attack-paths/query-parameters.png
index 9f44f81838..683c7c5bd3 100644
Binary files a/docs/images/prowler-app/attack-paths/query-parameters.png and b/docs/images/prowler-app/attack-paths/query-parameters.png differ
diff --git a/docs/images/prowler-app/attack-paths/query-selector.png b/docs/images/prowler-app/attack-paths/query-selector.png
index d8b7414156..828183fdbf 100644
Binary files a/docs/images/prowler-app/attack-paths/query-selector.png and b/docs/images/prowler-app/attack-paths/query-selector.png differ
diff --git a/docs/images/prowler-app/attack-paths/scan-list-table.png b/docs/images/prowler-app/attack-paths/scan-list-table.png
index 092b539dd0..45d0af41dc 100644
Binary files a/docs/images/prowler-app/attack-paths/scan-list-table.png and b/docs/images/prowler-app/attack-paths/scan-list-table.png differ
diff --git a/docs/images/prowler-app/findings-triage/findings-triage-note-modal.png b/docs/images/prowler-app/findings-triage/findings-triage-note-modal.png
new file mode 100644
index 0000000000..9d7926997d
Binary files /dev/null and b/docs/images/prowler-app/findings-triage/findings-triage-note-modal.png differ
diff --git a/docs/images/prowler-app/findings-triage/findings-triage-status-dropdown.png b/docs/images/prowler-app/findings-triage/findings-triage-status-dropdown.png
new file mode 100644
index 0000000000..7fb7790610
Binary files /dev/null and b/docs/images/prowler-app/findings-triage/findings-triage-status-dropdown.png differ
diff --git a/docs/images/prowler-app/findings-triage/findings-triage-table.png b/docs/images/prowler-app/findings-triage/findings-triage-table.png
new file mode 100644
index 0000000000..c8fa79e379
Binary files /dev/null and b/docs/images/prowler-app/findings-triage/findings-triage-table.png differ
diff --git a/docs/images/prowler-app/lighthouse-config.png b/docs/images/prowler-app/lighthouse/oss/config.png
similarity index 100%
rename from docs/images/prowler-app/lighthouse-config.png
rename to docs/images/prowler-app/lighthouse/oss/config.png
diff --git a/docs/images/prowler-app/lighthouse-configuration.png b/docs/images/prowler-app/lighthouse/oss/configuration.png
similarity index 100%
rename from docs/images/prowler-app/lighthouse-configuration.png
rename to docs/images/prowler-app/lighthouse/oss/configuration.png
diff --git a/docs/images/prowler-app/lighthouse-feature1.png b/docs/images/prowler-app/lighthouse/oss/feature1.png
similarity index 100%
rename from docs/images/prowler-app/lighthouse-feature1.png
rename to docs/images/prowler-app/lighthouse/oss/feature1.png
diff --git a/docs/images/prowler-app/lighthouse-feature2.png b/docs/images/prowler-app/lighthouse/oss/feature2.png
similarity index 100%
rename from docs/images/prowler-app/lighthouse-feature2.png
rename to docs/images/prowler-app/lighthouse/oss/feature2.png
diff --git a/docs/images/prowler-app/lighthouse-feature3.png b/docs/images/prowler-app/lighthouse/oss/feature3.png
similarity index 100%
rename from docs/images/prowler-app/lighthouse-feature3.png
rename to docs/images/prowler-app/lighthouse/oss/feature3.png
diff --git a/docs/images/prowler-app/lighthouse-intro.png b/docs/images/prowler-app/lighthouse/oss/intro.png
similarity index 100%
rename from docs/images/prowler-app/lighthouse-intro.png
rename to docs/images/prowler-app/lighthouse/oss/intro.png
diff --git a/docs/images/prowler-app/lighthouse-set-default-provider.png b/docs/images/prowler-app/lighthouse/oss/set-default-provider.png
similarity index 100%
rename from docs/images/prowler-app/lighthouse-set-default-provider.png
rename to docs/images/prowler-app/lighthouse/oss/set-default-provider.png
diff --git a/docs/images/prowler-app/lighthouse-switch-models.png b/docs/images/prowler-app/lighthouse/oss/switch-models.png
similarity index 100%
rename from docs/images/prowler-app/lighthouse-switch-models.png
rename to docs/images/prowler-app/lighthouse/oss/switch-models.png
diff --git a/docs/images/prowler-app/lighthouse/prowler-cloud/chat-animation.gif b/docs/images/prowler-app/lighthouse/prowler-cloud/chat-animation.gif
new file mode 100644
index 0000000000..c2e69c4816
Binary files /dev/null and b/docs/images/prowler-app/lighthouse/prowler-cloud/chat-animation.gif differ
diff --git a/docs/images/prowler-app/lighthouse/prowler-cloud/config-page.png b/docs/images/prowler-app/lighthouse/prowler-cloud/config-page.png
new file mode 100644
index 0000000000..ad1b812e03
Binary files /dev/null and b/docs/images/prowler-app/lighthouse/prowler-cloud/config-page.png differ
diff --git a/docs/images/prowler-app/lighthouse/prowler-cloud/main-chat-page.png b/docs/images/prowler-app/lighthouse/prowler-cloud/main-chat-page.png
new file mode 100644
index 0000000000..7a83637285
Binary files /dev/null and b/docs/images/prowler-app/lighthouse/prowler-cloud/main-chat-page.png differ
diff --git a/docs/images/prowler-app/lighthouse/prowler-cloud/side-panel-closed.png b/docs/images/prowler-app/lighthouse/prowler-cloud/side-panel-closed.png
new file mode 100644
index 0000000000..c36da34a95
Binary files /dev/null and b/docs/images/prowler-app/lighthouse/prowler-cloud/side-panel-closed.png differ
diff --git a/docs/images/prowler-app/lighthouse/prowler-cloud/side-panel-open.png b/docs/images/prowler-app/lighthouse/prowler-cloud/side-panel-open.png
new file mode 100644
index 0000000000..fd10f5a00b
Binary files /dev/null and b/docs/images/prowler-app/lighthouse/prowler-cloud/side-panel-open.png differ
diff --git a/docs/images/prowler-app/lighthouse/prowler-cloud/tool-usage.png b/docs/images/prowler-app/lighthouse/prowler-cloud/tool-usage.png
new file mode 100644
index 0000000000..ae637b3ff3
Binary files /dev/null and b/docs/images/prowler-app/lighthouse/prowler-cloud/tool-usage.png differ
diff --git a/docs/images/prowler-app/rbac/provider_group.png b/docs/images/prowler-app/rbac/provider_group.png
index 878306e02f..8698cc9c41 100644
Binary files a/docs/images/prowler-app/rbac/provider_group.png and b/docs/images/prowler-app/rbac/provider_group.png differ
diff --git a/docs/images/prowler-app/rbac/provider_group_edit.png b/docs/images/prowler-app/rbac/provider_group_edit.png
index 5de9649578..3d37b329b7 100644
Binary files a/docs/images/prowler-app/rbac/provider_group_edit.png and b/docs/images/prowler-app/rbac/provider_group_edit.png differ
diff --git a/docs/images/prowler-app/rbac/provider_group_edit_1.png b/docs/images/prowler-app/rbac/provider_group_edit_1.png
index ed4a090eed..4369983a20 100644
Binary files a/docs/images/prowler-app/rbac/provider_group_edit_1.png and b/docs/images/prowler-app/rbac/provider_group_edit_1.png differ
diff --git a/docs/images/prowler-app/rbac/provider_group_remove.png b/docs/images/prowler-app/rbac/provider_group_remove.png
index 580a8533cf..f504617159 100644
Binary files a/docs/images/prowler-app/rbac/provider_group_remove.png and b/docs/images/prowler-app/rbac/provider_group_remove.png differ
diff --git a/docs/images/prowler-app/rbac/role_create_1.png b/docs/images/prowler-app/rbac/role_create_1.png
index a96b0ac9ef..b88fe990db 100644
Binary files a/docs/images/prowler-app/rbac/role_create_1.png and b/docs/images/prowler-app/rbac/role_create_1.png differ
diff --git a/docs/images/prowler-app/scan-scheduling/edit-scan-schedule.png b/docs/images/prowler-app/scan-scheduling/edit-scan-schedule.png
new file mode 100644
index 0000000000..e76809b810
Binary files /dev/null and b/docs/images/prowler-app/scan-scheduling/edit-scan-schedule.png differ
diff --git a/docs/images/prowler-app/scan-scheduling/launch-scan-schedule.png b/docs/images/prowler-app/scan-scheduling/launch-scan-schedule.png
new file mode 100644
index 0000000000..980b16bf7f
Binary files /dev/null and b/docs/images/prowler-app/scan-scheduling/launch-scan-schedule.png differ
diff --git a/docs/images/prowler-app/scan-scheduling/providers-scan-schedule.png b/docs/images/prowler-app/scan-scheduling/providers-scan-schedule.png
new file mode 100644
index 0000000000..a7dab3310c
Binary files /dev/null and b/docs/images/prowler-app/scan-scheduling/providers-scan-schedule.png differ
diff --git a/docs/images/prowler-app/scan-scheduling/scheduled-scans-tab.png b/docs/images/prowler-app/scan-scheduling/scheduled-scans-tab.png
new file mode 100644
index 0000000000..26b4b160ec
Binary files /dev/null and b/docs/images/prowler-app/scan-scheduling/scheduled-scans-tab.png differ
diff --git a/docs/images/prowler_mcp_schema.mmd b/docs/images/prowler_mcp_schema.mmd
index 96973546f6..2b8508cd18 100644
--- a/docs/images/prowler_mcp_schema.mmd
+++ b/docs/images/prowler_mcp_schema.mmd
@@ -1,29 +1,40 @@
flowchart LR
- subgraph HOSTS["MCP Hosts"]
+ subgraph HOSTS["MCP Clients"]
chat["Chat Interfaces (Claude Desktop, LobeChat)"]
ide["IDEs and Code Editors (Claude Code, Cursor)"]
apps["Other AI Applications (5ire, custom agents)"]
end
- subgraph MCP["Prowler MCP Server"]
- app_tools["prowler_app_* tools (JWT or API key auth) Findings · Providers · Scans Resources · Muting · Compliance Attack Paths"]
+ subgraph SERVERS["Prowler MCP Server"]
+ direction TB
+ cloud["☁️ Cloud MCP Server (Recommended) mcp.prowler.com/mcp · HTTP Managed by Prowler · always up to date Adds Cloud-only tools (Alerts, Scan Scheduling, Findings Triage)"]
+ local["💻 Local MCP Server Self-run · STDIO or HTTP Python 3.12+ or Docker You manage updates"]
+ end
+
+ subgraph TOOLS["Prowler MCP Tools"]
+ prowler_tools["prowler_* tools (API key or JWT auth) Findings · Providers · Scans Resources · Muting · Compliance Attack Paths"]
hub_tools["prowler_hub_* tools (no auth) Checks Catalog · Check Code Fixers · Compliance Frameworks"]
docs_tools["prowler_docs_* tools (no auth) Search · Document Retrieval"]
end
- api["Prowler API (REST)"]
+ api["Prowler API (REST) Cloud · Private Cloud · Local Server"]
hub["hub.prowler.com (REST)"]
docs["docs.prowler.com (Mintlify)"]
- chat -->|STDIO or HTTP| app_tools
- chat -->|STDIO or HTTP| hub_tools
- chat -->|STDIO or HTTP| docs_tools
- ide -->|STDIO or HTTP| app_tools
- ide -->|STDIO or HTTP| hub_tools
- ide -->|STDIO or HTTP| docs_tools
- apps -->|STDIO or HTTP| app_tools
- apps -->|STDIO or HTTP| hub_tools
- apps -->|STDIO or HTTP| docs_tools
- app_tools -->|REST| api
+ chat -->|HTTP| cloud
+ ide -->|HTTP| cloud
+ apps -->|HTTP| cloud
+ chat -->|STDIO or HTTP| local
+ ide -->|STDIO or HTTP| local
+ apps -->|STDIO or HTTP| local
+
+ cloud --> prowler_tools
+ cloud --> hub_tools
+ cloud --> docs_tools
+ local --> prowler_tools
+ local --> hub_tools
+ local --> docs_tools
+
+ prowler_tools -->|REST| api
hub_tools -->|REST| hub
docs_tools -->|REST| docs
diff --git a/docs/images/prowler_mcp_schema.png b/docs/images/prowler_mcp_schema.png
deleted file mode 100644
index 8a8884fa5e..0000000000
Binary files a/docs/images/prowler_mcp_schema.png and /dev/null differ
diff --git a/docs/introduction.mdx b/docs/introduction.mdx
index 51a27eb555..9307fa351a 100644
--- a/docs/introduction.mdx
+++ b/docs/introduction.mdx
@@ -1,21 +1,36 @@
# What is Prowler?
-**Prowler** is the world’s most widely used open-source cloud security platform that **automates security and compliance** across any cloud environment. With hundreds of ready-to-use security checks, remediation guidance, and compliance frameworks, Prowler delivers AI-driven, customizable, and easy-to-use monitoring and integrations, making cloud security simple, scalable, and cost-effective for organizations of any size.
+**Prowler** is the world’s most widely used open-source cloud security platform that **automates security and compliance** across any cloud environment. With thousands of ready-to-use security checks, remediation guidance, and compliance frameworks, Prowler delivers AI-driven, customizable, and easy-to-use monitoring and integrations, making cloud security simple, scalable, and cost-effective for organizations of any size.

+Prowler ships two product families: Prowler Products, operated or licensed by the Prowler team, and Open Source projects, free to run and extend. See [Prowler product families](/getting-started/products) for every official name, including former names.
+
+### Prowler Products
+
-
- Command Line Interface
-
-
- Web Application
-
-
- A managed service built on top of Prowler App.
+
+ Managed cloud security platform operated by the Prowler team.
- A public library of versioned checks, cloud service artifacts, and compliance frameworks.
+ Free public library of versioned checks, cloud service artifacts, and compliance frameworks.
+
+
+ MCP server that connects AI assistants and agents to Prowler.
+
+
+ Prowler Private Cloud, Prowler Lighthouse AI, and more.
+
+
+
+### Open Source
+
+
+
+ Command line tool to run security scans across all supported providers.
+
+
+ Self-hosted web application and API.
@@ -31,6 +46,7 @@ Prowler supports a wide range of providers organized by category:
| [AWS](/user-guide/providers/aws/getting-started-aws) | Official | Accounts | UI, API, CLI |
| [Azure](/user-guide/providers/azure/getting-started-azure) | Official | Subscriptions | UI, API, CLI |
| [Cloudflare](/user-guide/providers/cloudflare/getting-started-cloudflare) | Official | Accounts | UI, API, CLI |
+| [E2E Networks](/user-guide/providers/e2enetworks/getting-started-e2enetworks) | [Contact us](https://prowler.com/contact) | Projects | CLI |
| [Google Cloud](/user-guide/providers/gcp/getting-started-gcp) | Official | Projects | UI, API, CLI |
| [Linode](/user-guide/providers/linode/getting-started-linode) | [Contact us](https://prowler.com/contact) | Accounts | CLI |
| **NHN** | [Contact us](https://prowler.com/contact) | Tenants | CLI |
@@ -69,7 +85,7 @@ Prowler supports a wide range of providers organized by category:
| ------------------------------------------------------------------- | -------- | -------------------- | --------- |
| [Image](/user-guide/providers/image/getting-started-image) | Official | Container Images / Registries | CLI, API |
-### Custom Providers (Prowler Cloud Enterprise Only)
+### Custom Providers (Prowler Private Cloud Only)
| Provider | Support | Audit Scope/Entities | Interface |
| -------------------- | -------- | -------------------- | --------- |
diff --git a/docs/scripts/generate_provider_cards.py b/docs/scripts/generate_provider_cards.py
new file mode 100644
index 0000000000..1b35755507
--- /dev/null
+++ b/docs/scripts/generate_provider_cards.py
@@ -0,0 +1,155 @@
+#!/usr/bin/env python3
+"""Generate docs/snippets/provider-cards.mdx from provider getting-started pages.
+
+Scans docs/user-guide/providers//getting-started-*.mdx, keeps only the
+providers that Prowler Cloud and Prowler Local Server actually support (source of truth: the
+`ProviderChoices` enum in api/src/backend/api/models.py — CLI-only providers
+such as Linode/LLM/Scaleway/StackIT are excluded), reads the frontmatter
+`title`, derives a display name, and emits a snippet exporting a
+`ProviderCards` component. Wired into pre-commit so the snippet stays in sync
+whenever a provider page or the API enum changes.
+"""
+
+from __future__ import annotations
+
+import ast
+import re
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+PROVIDERS_DIR = REPO_ROOT / "docs" / "user-guide" / "providers"
+SNIPPET_PATH = REPO_ROOT / "docs" / "snippets" / "provider-cards.mdx"
+API_MODELS_PATH = REPO_ROOT / "api" / "src" / "backend" / "api" / "models.py"
+
+# Docs folder names that don't match the API enum key. Keep tiny — only rename
+# entries when the docs folder disagrees with the API-side identifier.
+DOCS_DIR_TO_API_KEY = {
+ "microsoft365": "m365",
+ "oci": "oraclecloud",
+}
+
+# Folder-name → Mintlify icon override. Providers not listed fall back to
+# DEFAULT_ICON. Add an entry only when the default looks wrong for a provider.
+ICON_OVERRIDES = {
+ "alibabacloud": "cloud",
+ "aws": "aws",
+ "azure": "microsoft",
+ "cloudflare": "cloudflare",
+ "gcp": "google",
+ "github": "github",
+ "googleworkspace": "users",
+ "iac": "code",
+ "image": "docker",
+ "kubernetes": "dharmachakra",
+ "microsoft365": "briefcase",
+ "mongodbatlas": "leaf",
+ "oci": "database",
+ "okta": "key",
+ "openstack": "cubes",
+ "vercel": "triangle",
+}
+DEFAULT_ICON = "cloud"
+
+TITLE_RE = re.compile(r"^\s*title\s*:\s*['\"](?P.+?)['\"]\s*$", re.MULTILINE)
+NAME_CLEANUP_RE = re.compile(
+ r"^Getting Started [Ww]ith (?:the )?(?P.+?)(?: on Prowler)?(?: Provider)?$"
+)
+
+
+def app_supported_provider_keys() -> set[str]:
+ """Return the set of provider keys declared in the API's ProviderChoices enum.
+
+ Uses ast rather than regex so formatting changes, decorators, comments, or
+ multi-line values in the enum body don't silently drop or invent providers.
+ """
+ tree = ast.parse(API_MODELS_PATH.read_text(encoding="utf-8"))
+ for node in ast.walk(tree):
+ if not (isinstance(node, ast.ClassDef) and node.name == "ProviderChoices"):
+ continue
+ keys: set[str] = set()
+ for item in node.body:
+ if not isinstance(item, ast.Assign):
+ continue
+ value = item.value
+ # Django TextChoices members look like: NAME = "key", _("Label")
+ # which parses as an ast.Tuple whose first element is the key.
+ if isinstance(value, ast.Tuple) and value.elts:
+ first = value.elts[0]
+ if isinstance(first, ast.Constant) and isinstance(first.value, str):
+ keys.add(first.value)
+ return keys
+ raise RuntimeError(
+ f"Could not locate ProviderChoices class in {API_MODELS_PATH.relative_to(REPO_ROOT)}"
+ )
+
+
+def extract_title(mdx_path: Path) -> str:
+ text = mdx_path.read_text(encoding="utf-8")
+ match = TITLE_RE.search(text)
+ if not match:
+ raise ValueError(f"No frontmatter title in {mdx_path}")
+ return match.group("title")
+
+
+def display_name(title: str) -> str:
+ match = NAME_CLEANUP_RE.match(title)
+ return match.group("name") if match else title
+
+
+def collect_providers() -> list[dict]:
+ supported = app_supported_provider_keys()
+ providers = []
+ for provider_dir in sorted(PROVIDERS_DIR.iterdir()):
+ if not provider_dir.is_dir():
+ continue
+ api_key = DOCS_DIR_TO_API_KEY.get(provider_dir.name, provider_dir.name)
+ if api_key not in supported:
+ continue
+ pages = sorted(provider_dir.glob("getting-started-*.mdx"))
+ if not pages:
+ continue
+ page = pages[0]
+ name = display_name(extract_title(page))
+ href = f"/user-guide/providers/{provider_dir.name}/{page.stem}"
+ icon = ICON_OVERRIDES.get(provider_dir.name, DEFAULT_ICON)
+ providers.append({"name": name, "href": href, "icon": icon})
+ providers.sort(key=lambda p: p["name"].lower())
+ return providers
+
+
+def render_snippet(providers: list[dict]) -> str:
+ cards = "\n".join(
+ f' '
+ for p in providers
+ )
+ return (
+ "{/* AUTO-GENERATED by docs/scripts/generate_provider_cards.py — do not edit by hand. */}\n"
+ "{/* Regenerated on pre-commit whenever any provider getting-started page changes. */}\n"
+ "\n"
+ "export const ProviderCards = () => (\n"
+ " \n"
+ f"{cards}\n"
+ " \n"
+ ");\n"
+ )
+
+
+def main() -> int:
+ providers = collect_providers()
+ if not providers:
+ print("No provider getting-started pages found", file=sys.stderr)
+ return 1
+ new_content = render_snippet(providers)
+ current = SNIPPET_PATH.read_text(encoding="utf-8") if SNIPPET_PATH.exists() else ""
+ if new_content == current:
+ return 0
+ SNIPPET_PATH.write_text(new_content, encoding="utf-8")
+ print(
+ f"Regenerated {SNIPPET_PATH.relative_to(REPO_ROOT)} ({len(providers)} providers)"
+ )
+ return 1 # signal pre-commit that the file changed
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/docs/security/index.mdx b/docs/security/index.mdx
index 30364d5b82..45b39d608b 100644
--- a/docs/security/index.mdx
+++ b/docs/security/index.mdx
@@ -27,7 +27,7 @@ All Prowler code goes through the same security pipeline, whether running on Pro
| **Updates** | Automatic | Manual |
-Self-Managed includes Prowler App and Prowler CLI. They can run anywhere — any cloud provider, any region, on-premises, or air-gapped environments. Full control over data residency and infrastructure decisions. See the [Prowler App Installation Guide](/getting-started/installation/prowler-app) to get started.
+Self-Managed includes Prowler Local Server and Prowler CLI. They can run anywhere — any cloud provider, any region, on-premises, or air-gapped environments. Full control over data residency and infrastructure decisions. See the [Prowler Local Server Installation Guide](/getting-started/installation/prowler-app) to get started.
---
diff --git a/docs/security/networking.mdx b/docs/security/networking.mdx
index 767e6ac4bf..eb00c9a840 100644
--- a/docs/security/networking.mdx
+++ b/docs/security/networking.mdx
@@ -16,6 +16,18 @@ Resolve the egress IP via DNS:
dig egress.prowler.com +short
```
+
+The egress IP address is stable, but it is recommended to periodically verify it remains current by querying `egress.prowler.com`.
+
+
+## Use Cases
+
+Allowlisting Prowler Cloud's egress IP address enables:
+
+- **Credential Usage Control**: Restrict where cloud provider credentials can be used from across AWS, Azure, GCP, and other providers
+- **Kubernetes Security**: Limit inbound HTTPS traffic to clusters by allowing only Prowler Cloud's IP address
+- **Compliance Requirements**: Meet security policies requiring allowlisting of external services
+
## Contact
For questions about networking, visit the [Support page](/support).
diff --git a/docs/security/software-security.mdx b/docs/security/software-security.mdx
index 3fee8d1251..64c2645d3f 100644
--- a/docs/security/software-security.mdx
+++ b/docs/security/software-security.mdx
@@ -158,7 +158,7 @@ The MCP Server has a small direct-dependency surface and does not yet declare a
The UI uses [pnpm](https://pnpm.io) with supply-chain controls configured in [`ui/pnpm-workspace.yaml`](https://github.com/prowler-cloud/prowler/blob/master/ui/pnpm-workspace.yaml).
- **Minimum release age** (`minimumReleaseAge: 1440`): packages must publish at least 24 hours before install. This reduces exposure during the window when a compromised release has not yet been detected and yanked.
-- **Lifecycle script allow-list** (`strictDepBuilds: true` + `allowBuilds`): only explicitly approved packages may run `install` or `postinstall` scripts (currently `sharp`, `esbuild`, `@sentry/cli`, `@heroui/shared-utils`, `unrs-resolver`, `msw`). Any unlisted package with lifecycle scripts fails the install.
+- **Lifecycle script allow-list** (`strictDepBuilds: true` + `allowBuilds`): only explicitly approved packages may run `install` or `postinstall` scripts (currently `sharp`, `esbuild`, `@sentry/cli`, `unrs-resolver`, `msw`). Any unlisted package with lifecycle scripts fails the install.
- **Trust policy** (`trustPolicy: no-downgrade`): the install fails when a package's trust evidence drops, for example after a new publisher takes over.
- **Block exotic subdeps** (`blockExoticSubdeps: true`): transitive dependencies cannot ship as git URLs or tarballs. Every package in the tree resolves from the configured registry.
- **Transitive overrides** in [`ui/package.json`](https://github.com/prowler-cloud/prowler/blob/master/ui/package.json) force specific versions for transitive packages (`lodash`, `serialize-javascript`, `qs`, `rollup`, `minimatch`, `ajv`, and others).
diff --git a/docs/snippets/applies-to.mdx b/docs/snippets/applies-to.mdx
new file mode 100644
index 0000000000..0ce22af78d
--- /dev/null
+++ b/docs/snippets/applies-to.mdx
@@ -0,0 +1,14 @@
+export const AppliesTo = ({ products = ["Prowler Cloud", "Prowler Private Cloud", "Prowler Local Server"] }) => {
+ return (
+
+ This guide applies to{" "}
+ {products.map((name, index) => (
+
+ {index > 0 && (index === products.length - 1 ? (products.length > 2 ? ", and " : " and ") : ", ")}
+ {name}
+
+ ))}
+ . See Prowler product families.
+
+ );
+};
diff --git a/docs/snippets/provider-cards.mdx b/docs/snippets/provider-cards.mdx
new file mode 100644
index 0000000000..f469616cde
--- /dev/null
+++ b/docs/snippets/provider-cards.mdx
@@ -0,0 +1,23 @@
+{/* AUTO-GENERATED by docs/scripts/generate_provider_cards.py — do not edit by hand. */}
+{/* Regenerated on pre-commit whenever any provider getting-started page changes. */}
+
+export const ProviderCards = () => (
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+);
diff --git a/docs/snippets/subscription-banner.mdx b/docs/snippets/subscription-banner.mdx
new file mode 100644
index 0000000000..90d9b651b5
--- /dev/null
+++ b/docs/snippets/subscription-banner.mdx
@@ -0,0 +1,8 @@
+export const SubscriptionBanner = ({ children, label = "feature" }) => {
+ return (
+
+ This {label} is available exclusively in Prowler Cloud and Prowler Private Cloud with a subscription.
+ {children}
+
+ );
+};
diff --git a/docs/style.css b/docs/style.css
index 5c626fb06b..9a1ed19a0f 100644
--- a/docs/style.css
+++ b/docs/style.css
@@ -66,3 +66,59 @@
color: #000000;
border: none;
}
+
+/* Cloud marker: subscription-gated sections and pages (Prowler Cloud / Prowler Private Cloud).
+ Rendered as a trailing ::after glyph so sidebar labels stay left-aligned.
+ Nested groups render as li[data-title] with a button toggle; top-level groups
+ render as h3 headings. Every ungated group that shares a name with a gated one
+ (Providers, Prowler Cloud, Prowler Lighthouse AI) is top-level,
+ so plain li[data-title] selectors match only the gated nested groups, folded
+ or unfolded. The Security tab group is top-level (h3) and always expanded,
+ so it is selected through its sibling list content with :has().
+ Pages are selected by their li id, which equals the page URL. The strict
+ > div > div > span:first-child path targets the title span only, never the
+ nested spans of a tag pill such as Coming Soon.
+ Icon source: /images/icons/cloud-bold.svg. See AGENTS.md "Cloud Marker" convention. */
+li[data-title="Prowler Cloud"] > button span:first-child::after,
+li[data-title="Prowler Lighthouse AI"] > button span:first-child::after,
+li[data-title="Providers"] > button span:first-child::after,
+li[data-title="Scans"] > button span:first-child::after,
+li[data-title="Prowler MCP"] > button span:first-child::after,
+div:has(+ ul a[href="/security/encryption"]) h3 span::after,
+li[id="/user-guide/compliance/tutorials/cross-provider-compliance"] a > div > div > span:first-child::after,
+li[id="/user-guide/tutorials/prowler-alerts"] a > div > div > span:first-child::after,
+li[id="/user-guide/tutorials/prowler-app-findings-triage"] a > div > div > span:first-child::after,
+li[id="/user-guide/tutorials/prowler-app-scan-configuration"] a > div > div > span:first-child::after,
+li[id="/user-guide/tutorials/prowler-cloud-aws-organizations"] a > div > div > span:first-child::after,
+li[id="/user-guide/tutorials/prowler-cloud-azure-management-groups"] a > div > div > span:first-child::after,
+li[id="/user-guide/tutorials/prowler-cloud-gcp-organizations"] a > div > div > span:first-child::after,
+li[id="/user-guide/tutorials/prowler-cloud-lighthouse-multi-llm"] a > div > div > span:first-child::after,
+li[id="/user-guide/tutorials/prowler-import-findings"] a > div > div > span:first-child::after,
+li[id="/user-guide/tutorials/prowler-scan-scheduling"] a > div > div > span:first-child::after {
+ content: "";
+ display: inline-block;
+ width: 0.875rem;
+ height: 0.875rem;
+ margin-left: 0.375rem;
+ vertical-align: -0.125rem;
+ background: url("/images/icons/cloud-bold.svg") no-repeat center / contain;
+}
+/* Wider sidebar: +2rem over the theme default (18rem) so gated labels with the
+ cloud marker fit on one line. The content column offsets are coupled to the
+ sidebar width and must shift by the same amount, hence the two companion
+ overrides selected by their Tailwind arbitrary-value class substrings. */
+@media (min-width: 1024px) {
+ #sidebar {
+ width: 20rem !important;
+ }
+
+ div[class*="pl-[23.7rem]"] {
+ padding-left: 25.7rem !important;
+ }
+}
+
+@media (min-width: 1280px) {
+ div[class*="(100%-28rem)"] {
+ width: calc(100% - 30rem) !important;
+ }
+}
diff --git a/docs/support.mdx b/docs/support.mdx
index 6999d5efbf..07c9843e12 100644
--- a/docs/support.mdx
+++ b/docs/support.mdx
@@ -3,23 +3,25 @@ title: 'Support'
description: 'Get help with Prowler'
---
-## Lighthouse AI
+import { SubscriptionBanner } from "/snippets/subscription-banner.mdx"
-Lighthouse AI is a Cloud Security Analyst chatbot powered by [Prowler MCP](/getting-started/products/prowler-mcp), your 24/7 virtual cloud security analyst. It can:
+## Prowler Lighthouse AI
+
+Prowler Lighthouse AI is your 24/7 cloud security analyst chatbot, the agentic cloud defender. Powered by [Prowler MCP](/getting-started/products/prowler-mcp), it can:
- **Query your security data**: Findings, compliance status, resources, and remediation guidance
-- **Search Prowler Hub**: Over 1,000 security checks and 70+ compliance frameworks
+- **Search Prowler Hub**: Over 2,000 security checks and 70+ compliance frameworks
- **Access documentation**: Search and retrieve Prowler docs contextually
-Available in Prowler Cloud and Prowler App.
+Available in Prowler Cloud, Prowler Private Cloud, and Prowler Local Server.
-[Learn more about Lighthouse AI](/getting-started/products/prowler-lighthouse-ai)
+[Learn more about Prowler Lighthouse AI](/getting-started/products/prowler-cloud-lighthouse)
## Support Desk
-> Available to **Prowler Cloud** customers.
+
-For Prowler Cloud customers, submit support requests through our support desk. We'll route your request to the right team and respond via email.
+Submit support requests through our support desk. We'll route your request to the right team and respond via email.
Contact our support team
diff --git a/docs/troubleshooting.mdx b/docs/troubleshooting.mdx
index 3125d74ef5..9e0c849796 100644
--- a/docs/troubleshooting.mdx
+++ b/docs/troubleshooting.mdx
@@ -4,7 +4,9 @@ title: 'Troubleshooting'
import { VersionBadge } from "/snippets/version-badge.mdx"
-## Running `prowler` I get `[File: utils.py:15] [Module: utils] CRITICAL: path/redacted: OSError[13]`
+## Prowler CLI
+
+### Running `prowler` I get `[File: utils.py:15] [Module: utils] CRITICAL: path/redacted: OSError[13]`
That is an error related to file descriptors or opened files allowed by your operating system.
@@ -16,13 +18,15 @@ This error is also related with a lack of system requirements. To improve perfor
See section [Logging](/user-guide/cli/tutorials/logging) for further information or [contact us](/contact).
-## Common Issues with Docker Compose Installation
+## Prowler Local Server
+
+Common issues with the Docker Compose installation of Prowler Local Server.
### Problem adding AWS Provider using "Connect assuming IAM Role" in Docker
See [GitHub Issue #7745](https://github.com/prowler-cloud/prowler/issues/7745) for more details.
-When running Prowler App via Docker, you may encounter errors such as `Provider not set`, `AWS assume role error - Unable to locate credentials`, or `Provider has no secret` when trying to add an AWS Provider using the "Connect assuming IAM Role" option. This typically happens because the container does not have access to the necessary AWS credentials or profiles.
+When running Prowler Local Server via Docker, you may encounter errors such as `Provider not set`, `AWS assume role error - Unable to locate credentials`, or `Provider has no secret` when trying to add an AWS Provider using the "Connect assuming IAM Role" option. This typically happens because the container does not have access to the necessary AWS credentials or profiles.
**Workaround:**
@@ -53,7 +57,7 @@ AWS_PROFILE=prowler-profile
### Scans Complete but Reports Are Missing or Compliance Data Is Empty (`Too many open files` Error)
-When running Prowler App via Docker Compose, scans may complete successfully but reports are not available for download, compliance data shows as empty, or 404 errors appear when trying to access scan reports. Checking the `worker` container logs may reveal errors like `[Errno 24] Too many open files`.
+When running Prowler Local Server via Docker Compose, scans may complete successfully but reports are not available for download, compliance data shows as empty, or 404 errors appear when trying to access scan reports. Checking the `worker` container logs may reveal errors like `[Errno 24] Too many open files`.
This issue occurs because the default file descriptor limits in Docker containers are too low for Prowler's operations. The default `docker-compose.yml` already includes `ulimits` configuration with `nofile` set to `65536` for the `worker` and `worker-beat` services to prevent this issue.
@@ -87,7 +91,7 @@ docker compose up -d
-When Prowler App runs self-hosted on a machine or Kubernetes node with many CPUs,
+When Prowler Local Server runs on a machine or Kubernetes node with many CPUs,
the Celery worker may create one prefork process per detected CPU if concurrency
is not configured explicitly. Each process loads the SDK runtime and cloud
provider clients, so idle memory can be high and worker containers can be
@@ -196,7 +200,7 @@ A fix addressing this permission issue is being evaluated in [PR #9953](https://
### Scan Stuck in Executing State After Worker Crash
-When running Prowler App via Docker Compose, a scan may remain indefinitely in the `executing` state if the worker process crashes (for example, due to an Out of Memory condition) before it can update the scan status. Since it is not currently possible to cancel a scan in `executing` state through the UI, the workaround is to manually update the scan record in the database.
+When running Prowler Local Server via Docker Compose, a scan may remain indefinitely in the `executing` state if the worker process crashes (for example, due to an Out of Memory condition) before it can update the scan status. Since it is not currently possible to cancel a scan in `executing` state through the UI, the workaround is to manually update the scan record in the database.
**Root Cause:**
diff --git a/docs/user-guide/cli/tutorials/configuration_file.mdx b/docs/user-guide/cli/tutorials/configuration_file.mdx
index 657549f8b0..e637ea9c9a 100644
--- a/docs/user-guide/cli/tutorials/configuration_file.mdx
+++ b/docs/user-guide/cli/tutorials/configuration_file.mdx
@@ -2,6 +2,8 @@
title: "Configuration File"
---
+import { VersionBadge } from "/snippets/version-badge.mdx"
+
Several Prowler's checks have user configurable variables that can be modified in a common **configuration file**. This file can be found in the following [path](https://github.com/prowler-cloud/prowler/blob/master/prowler/config/config.yaml):
```
@@ -20,71 +22,181 @@ Numeric thresholds enforce hard limits. A value outside the accepted range is dr
The following list includes all the AWS checks with configurable variables that can be changed in the configuration yaml file:
-| Check Name | Value | Type |
-|---------------------------------------------------------------|--------------------------------------------------|-----------------|
-| `acm_certificates_expiration_check` | `days_to_expire_threshold` | Integer |
-| `acmpca_certificate_authority_pqc_key_algorithm` | `acmpca_pqc_key_algorithms` | List of Strings |
-| `appstream_fleet_maximum_session_duration` | `max_session_duration_seconds` | Integer |
-| `appstream_fleet_session_disconnect_timeout` | `max_disconnect_timeout_in_seconds` | Integer |
-| `appstream_fleet_session_idle_disconnect_timeout` | `max_idle_disconnect_timeout_in_seconds` | Integer |
-| `autoscaling_find_secrets_ec2_launch_configuration` | `secrets_ignore_patterns` | List of Strings |
-| `awslambda_function_no_secrets_in_code` | `secrets_ignore_patterns` | List of Strings |
-| `awslambda_function_no_secrets_in_variables` | `secrets_ignore_patterns` | List of Strings |
-| `awslambda_function_using_supported_runtimes` | `obsolete_lambda_runtimes` | Integer |
-| `awslambda_function_vpc_is_in_multi_azs` | `lambda_min_azs` | Integer |
-| `cloudformation_stack_outputs_find_secrets` | `secrets_ignore_patterns` | List of Strings |
-| `cloudtrail_threat_detection_enumeration` | `threat_detection_enumeration_actions` | List of Strings |
-| `cloudtrail_threat_detection_enumeration` | `threat_detection_enumeration_entropy` | Integer |
-| `cloudtrail_threat_detection_enumeration` | `threat_detection_enumeration_minutes` | Integer |
-| `cloudtrail_threat_detection_privilege_escalation` | `threat_detection_privilege_escalation_actions` | List of Strings |
-| `cloudtrail_threat_detection_privilege_escalation` | `threat_detection_privilege_escalation_entropy` | Integer |
-| `cloudtrail_threat_detection_privilege_escalation` | `threat_detection_privilege_escalation_minutes` | Integer |
-| `cloudwatch_log_group_no_secrets_in_logs` | `secrets_ignore_patterns` | List of Strings |
-| `cloudwatch_log_group_retention_policy_specific_days_enabled` | `log_group_retention_days` | Integer |
-| `codebuild_github_allowed_organizations` | `github_allowed_organizations` | List of Strings |
-| `codebuild_project_no_secrets_in_variables` | `excluded_sensitive_environment_variables` | List of Strings |
-| `codebuild_project_no_secrets_in_variables` | `secrets_ignore_patterns` | List of Strings |
-| `config_recorder_all_regions_enabled` | `mute_non_default_regions` | Boolean |
-| `drs_job_exist` | `mute_non_default_regions` | Boolean |
-| `ec2_elastic_ip_shodan` | `shodan_api_key` | String |
-| `ec2_instance_older_than_specific_days` | `max_ec2_instance_age_in_days` | Integer |
-| `ec2_instance_secrets_user_data` | `secrets_ignore_patterns` | List of Strings |
-| `ec2_launch_template_no_secrets` | `secrets_ignore_patterns` | List of Strings |
-| `ec2_securitygroup_allow_ingress_from_internet_to_any_port` | `ec2_allowed_instance_owners` | List of Strings |
-| `ec2_securitygroup_allow_ingress_from_internet_to_any_port` | `ec2_allowed_interface_types` | List of Strings |
-| `ec2_securitygroup_allow_ingress_from_internet_to_high_risk_tcp_ports`| `ec2_high_risk_ports` | List of Integer |
-| `ec2_securitygroup_with_many_ingress_egress_rules` | `max_security_group_rules` | Integer |
-| `ecs_task_definitions_no_environment_secrets` | `secrets_ignore_patterns` | List of Strings |
-| `ecr_repositories_scan_vulnerabilities_in_latest_image` | `ecr_repository_vulnerability_minimum_severity` | String |
-| `eks_cluster_uses_a_supported_version` | `eks_cluster_oldest_version_supported` | String |
-| `eks_control_plane_logging_all_types_enabled` | `eks_required_log_types` | List of Strings |
-| `elasticache_redis_cluster_backup_enabled` | `minimum_snapshot_retention_period` | Integer |
-| `elb_is_in_multiple_az` | `elb_min_azs` | Integer |
-| `elbv2_is_in_multiple_az` | `elbv2_min_azs` | Integer |
-| `rolesanywhere_trust_anchor_pqc_pki` | `rolesanywhere_pqc_pca_key_algorithms` | List of Strings |
-| `cloudfront_distributions_pqc_tls_enabled` | `cloudfront_pqc_min_protocol_versions` | List of Strings |
-| `apigateway_domain_name_pqc_tls_enabled` | `apigateway_pqc_tls_allowed_policies` | List of Strings |
-| `guardduty_is_enabled` | `mute_non_default_regions` | Boolean |
-| `iam_user_access_not_stale_to_sagemaker` | `max_unused_sagemaker_access_days` | Integer |
-| `iam_user_accesskey_unused` | `max_unused_access_keys_days` | Integer |
-| `iam_user_console_access_unused` | `max_console_access_days` | Integer |
-| `organizations_delegated_administrators` | `organizations_trusted_delegated_administrators` | List of Strings |
-| `organizations_scp_check_deny_regions` | `organizations_enabled_regions` | List of Strings |
-| `rds_instance_backup_enabled` | `check_rds_instance_replicas` | Boolean |
-| `securityhub_enabled` | `mute_non_default_regions` | Boolean |
-| `secretsmanager_secret_unused` | `max_days_secret_unused` | Integer |
-| `secretsmanager_secret_rotated_periodically` | `max_days_secret_unrotated` | Integer |
-| `ssm_document_secrets` | `secrets_ignore_patterns` | List of Strings |
-| `trustedadvisor_premium_support_plan_subscribed` | `verify_premium_support_plans` | Boolean |
-| `transfer_server_pqc_ssh_kex_enabled` | `transfer_pqc_ssh_allowed_policies` | List of Strings |
-| `dynamodb_table_cross_account_access` | `trusted_account_ids` | List of Strings |
-| `eventbridge_bus_cross_account_access` | `trusted_account_ids` | List of Strings |
-| `eventbridge_schema_registry_cross_account_access` | `trusted_account_ids` | List of Strings |
-| `s3_bucket_cross_account_access` | `trusted_account_ids` | List of Strings |
-| `ssm_documents_set_as_public` | `trusted_account_ids` | List of Strings |
-| `vpc_endpoint_connections_trust_boundaries` | `trusted_account_ids` | List of Strings |
-| `vpc_endpoint_services_allowed_principals_trust_boundaries` | `trusted_account_ids` | List of Strings |
-| `opensearch_service_domains_not_publicly_accessible` | `trusted_ips` | List of Strings |
+| Check Name | Value | Type | Default |
+|------------------------------------------------------------------------|---------------------------------------------------|-----------------|--------------------------------------------------------------------------------------------------------------------------------------|
+| `accessanalyzer_enabled` | `mute_non_default_regions` | Boolean | `False` |
+| `acm_certificates_expiration_check` | `days_to_expire_threshold` | Integer | `7` |
+| `acm_certificates_with_secure_key_algorithms` | `insecure_key_algorithms` | List of Strings | `["RSA-1024", "P-192"]` |
+| `acmpca_certificate_authority_pqc_key_algorithm` | `acmpca_pqc_key_algorithms` | List of Strings | `["ML_DSA_44", "ML_DSA_65", "ML_DSA_87"]` |
+| `apigateway_domain_name_pqc_tls_enabled` | `apigateway_pqc_tls_allowed_policies` | List of Strings | `["SecurityPolicy_TLS13_1_2_FIPS_PFS_PQ_2025_09", "SecurityPolicy_TLS13_1_2_PFS_PQ_2025_09", "SecurityPolicy_TLS13_1_2_PQ_2025_09"]` |
+| `apigateway_restapi_no_secrets_in_stage_variables` | `secrets_ignore_patterns` | List of Strings | `[]` |
+| `appstream_fleet_maximum_session_duration` | `max_session_duration_seconds` | Integer | `36000` |
+| `appstream_fleet_session_disconnect_timeout` | `max_disconnect_timeout_in_seconds` | Integer | `300` |
+| `appstream_fleet_session_idle_disconnect_timeout` | `max_idle_disconnect_timeout_in_seconds` | Integer | `600` |
+| `autoscaling_find_secrets_ec2_launch_configuration` | `secrets_ignore_patterns` | List of Strings | `[]` |
+| `awslambda_function_no_secrets_in_code` | `secrets_ignore_files` | List of Strings | `[]` |
+| `awslambda_function_no_secrets_in_code` | `secrets_ignore_patterns` | List of Strings | `[]` |
+| `awslambda_function_no_secrets_in_variables` | `secrets_ignore_patterns` | List of Strings | `[]` |
+| `awslambda_function_using_supported_runtimes` | `obsolete_lambda_runtimes` | List of Strings | See `config.yaml` |
+| `awslambda_function_vpc_multi_az` | `lambda_min_azs` | Integer | `2` |
+| `cloudformation_stack_cdktoolkit_bootstrap_version` | `recommended_cdk_bootstrap_version` | Integer | `21` |
+| `cloudformation_stack_outputs_find_secrets` | `secrets_ignore_patterns` | List of Strings | `[]` |
+| `cloudfront_distributions_pqc_tls_enabled` | `cloudfront_pqc_min_protocol_versions` | List of Strings | `["TLSv1.3_2025"]` |
+| `cloudtrail_threat_detection_enumeration` | `threat_detection_enumeration_actions` | List of Strings | See `config.yaml` |
+| `cloudtrail_threat_detection_enumeration` | `threat_detection_enumeration_minutes` | Integer | `1440` |
+| `cloudtrail_threat_detection_enumeration` | `threat_detection_enumeration_threshold` | Float | `0.3` |
+| `cloudtrail_threat_detection_llm_jacking` | `threat_detection_llm_jacking_actions` | List of Strings | See `config.yaml` |
+| `cloudtrail_threat_detection_llm_jacking` | `threat_detection_llm_jacking_minutes` | Integer | `1440` |
+| `cloudtrail_threat_detection_llm_jacking` | `threat_detection_llm_jacking_threshold` | Float | `0.4` |
+| `cloudtrail_threat_detection_privilege_escalation` | `threat_detection_privilege_escalation_actions` | List of Strings | See `config.yaml` |
+| `cloudtrail_threat_detection_privilege_escalation` | `threat_detection_privilege_escalation_minutes` | Integer | `1440` |
+| `cloudtrail_threat_detection_privilege_escalation` | `threat_detection_privilege_escalation_threshold` | Float | `0.2` |
+| `cloudwatch_log_group_no_secrets_in_logs` | `secrets_ignore_patterns` | List of Strings | `[]` |
+| `cloudwatch_log_group_retention_policy_specific_days_enabled` | `log_group_retention_days` | Integer | `365` |
+| `codebuild_project_no_secrets_in_variables` | `excluded_sensitive_environment_variables` | List of Strings | `[]` |
+| `codebuild_project_no_secrets_in_variables` | `secrets_ignore_patterns` | List of Strings | `[]` |
+| `codebuild_project_uses_allowed_github_organizations` | `codebuild_github_allowed_organizations` | List of Strings | `[]` |
+| `config_delegated_admin_and_org_aggregator_all_regions` | `mute_non_default_regions` | Boolean | `False` |
+| `config_recorder_all_regions_enabled` | `mute_non_default_regions` | Boolean | `False` |
+| `documentdb_cluster_backup_enabled` | `minimum_backup_retention_period` | Integer | `7` |
+| `drs_job_exist` | `mute_non_default_regions` | Boolean | `False` |
+| `dynamodb_table_cross_account_access` | `trusted_account_ids` | List of Strings | `[]` |
+| `ec2_elastic_ip_shodan` | `shodan_api_key` | String | `null` |
+| `ec2_instance_older_than_specific_days` | `max_ec2_instance_age_in_days` | Integer | `180` |
+| `ec2_instance_secrets_user_data` | `secrets_ignore_patterns` | List of Strings | `[]` |
+| `ec2_launch_template_no_secrets` | `secrets_ignore_patterns` | List of Strings | `[]` |
+| `ec2_securitygroup_allow_ingress_from_internet_to_any_port` | `ec2_allowed_instance_owners` | List of Strings | `["amazon-elb"]` |
+| `ec2_securitygroup_allow_ingress_from_internet_to_any_port` | `ec2_allowed_interface_types` | List of Strings | `["api_gateway_managed", "vpc_endpoint"]` |
+| `ec2_securitygroup_allow_ingress_from_internet_to_high_risk_tcp_ports` | `ec2_high_risk_ports` | List of Integer | `[25, 110, 135, 143, 445, 3000, 4333, 5000, 5500, 8080, 8088]` |
+| `ec2_securitygroup_with_many_ingress_egress_rules` | `max_security_group_rules` | Integer | `50` |
+| `ecr_repositories_scan_vulnerabilities_in_latest_image` | `ecr_repository_vulnerability_minimum_severity` | String | `"MEDIUM"` |
+| `ecs_service_fargate_latest_platform_version` | `fargate_linux_latest_version` | String | `"1.4.0"` |
+| `ecs_service_fargate_latest_platform_version` | `fargate_windows_latest_version` | String | `"1.0.0"` |
+| `ecs_task_definitions_no_environment_secrets` | `secrets_ignore_patterns` | List of Strings | `[]` |
+| `eks_cluster_uses_a_supported_version` | `eks_cluster_oldest_version_supported` | String | `"1.28"` |
+| `eks_control_plane_logging_all_types_enabled` | `eks_required_log_types` | List of Strings | `["api", "audit", "authenticator", "controllerManager", "scheduler"]` |
+| `elasticache_redis_cluster_backup_enabled` | `minimum_snapshot_retention_period` | Integer | `7` |
+| `elb_is_in_multiple_az` | `elb_min_azs` | Integer | `2` |
+| `elbv2_is_in_multiple_az` | `elbv2_min_azs` | Integer | `2` |
+| `elbv2_listener_pqc_tls_enabled` | `elbv2_listener_pqc_tls_allowed_policies` | List of Strings | See `config.yaml` |
+| `eventbridge_bus_cross_account_access` | `trusted_account_ids` | List of Strings | `[]` |
+| `eventbridge_schema_registry_cross_account_access` | `trusted_account_ids` | List of Strings | `[]` |
+| `glue_etl_jobs_no_secrets_in_arguments` | `secrets_ignore_patterns` | List of Strings | `[]` |
+| `guardduty_delegated_admin_enabled_all_regions` | `mute_non_default_regions` | Boolean | `False` |
+| `guardduty_is_enabled` | `mute_non_default_regions` | Boolean | `False` |
+| `iam_role_access_not_stale_to_bedrock` | `max_unused_bedrock_access_days` | Integer | `60` |
+| `iam_user_access_not_stale_to_bedrock` | `max_unused_bedrock_access_days` | Integer | `60` |
+| `iam_user_access_not_stale_to_sagemaker` | `max_unused_sagemaker_access_days` | Integer | `90` |
+| `iam_user_accesskey_unused` | `max_unused_access_keys_days` | Integer | `45` |
+| `iam_user_console_access_unused` | `max_console_access_days` | Integer | `45` |
+| `kinesis_stream_data_retention_period` | `min_kinesis_stream_retention_hours` | Integer | `168` |
+| `neptune_cluster_backup_enabled` | `minimum_backup_retention_period` | Integer | `7` |
+| `opensearch_service_domains_not_publicly_accessible` | `trusted_ips` | List of Strings | `[]` |
+| `organizations_delegated_administrators` | `organizations_trusted_delegated_administrators` | List of Strings | `[]` |
+| `organizations_scp_check_deny_regions` | `organizations_enabled_regions` | List of Strings | `[]` |
+| `rds_instance_backup_enabled` | `check_rds_instance_replicas` | Boolean | `False` |
+| `rolesanywhere_trust_anchor_pqc_pki` | `rolesanywhere_pqc_pca_key_algorithms` | List of Strings | `["ML_DSA_44", "ML_DSA_65", "ML_DSA_87"]` |
+| `s3_bucket_cross_account_access` | `trusted_account_ids` | List of Strings | `[]` |
+| `s3_bucket_object_public` | `s3_bucket_object_public_enabled` | Boolean | `False` |
+| `s3_bucket_object_public` | `s3_bucket_object_public_max_objects` | Integer | `100` |
+| `s3_bucket_object_public` | `s3_bucket_object_public_sample_size` | Integer | `3` |
+| `secretsmanager_has_restrictive_resource_policy` | `organizations_trusted_ids` | List of Strings | `[]` |
+| `secretsmanager_secret_rotated_periodically` | `max_days_secret_unrotated` | Integer | `90` |
+| `secretsmanager_secret_unused` | `max_days_secret_unused` | Integer | `90` |
+| `securityhub_delegated_admin_enabled_all_regions` | `mute_non_default_regions` | Boolean | `False` |
+| `securityhub_enabled` | `mute_non_default_regions` | Boolean | `False` |
+| `ssm_document_secrets` | `secrets_ignore_patterns` | List of Strings | `[]` |
+| `ssm_documents_set_as_public` | `trusted_account_ids` | List of Strings | `[]` |
+| `stepfunctions_statemachine_no_secrets_in_definition` | `secrets_ignore_patterns` | List of Strings | `[]` |
+| `transfer_server_pqc_ssh_kex_enabled` | `transfer_pqc_ssh_allowed_policies` | List of Strings | `["TransferSecurityPolicy-2025-03", "TransferSecurityPolicy-FIPS-2025-03", "TransferSecurityPolicy-AS2Restricted-2025-07"]` |
+| `trustedadvisor_premium_support_plan_subscribed` | `verify_premium_support_plans` | Boolean | `True` |
+| `vpc_endpoint_connections_trust_boundaries` | `trusted_account_ids` | List of Strings | `[]` |
+| `vpc_endpoint_services_allowed_principals_trust_boundaries` | `trusted_account_ids` | List of Strings | `[]` |
+
+### Resource Scan Limit
+
+
+
+Some AWS services accumulate large numbers of resources (EBS snapshots, backup recovery points, CloudWatch log groups, Lambda functions, ECS task definitions, and CodeArtifact packages). Scanning every resource increases scan time, cost, API throttling, and finding volume. By default, Prowler scans every resource. Configure a positive resource scan limit to cap how many resources Prowler analyzes for these high-volume AWS resource paths.
+
+The global default applies to the supported resources below and is overridable per resource. The default global value is `0`, which disables the limit and scans every resource. A global `null` value is also unlimited. For per-resource values, `null` means inherit the global default; set `0` or a negative value to disable that resource limit explicitly. Positive values enable limits.
+
+
+When positive resource scan limits are configured, compliance results are based only on the selected resources, not on the full set of matching resources in the account. Treat compliance summaries and percentages as partial evidence, because unselected resources are not analyzed and can change the real compliance posture.
+
+
+#### Global Behavior
+
+Resource scan limits select resources for analysis. They do not cap, prioritize, or reorder findings.
+
+* **`0`, negative, or global `null` values:** Disable the limit and keep the legacy behavior for that resource path. Prowler analyzes every discovered matching resource.
+* **Positive values:** Select at most that many resources for the affected resource path. A selected resource can produce zero, one, or many findings.
+* **No PASS/FAIL prioritization:** Prowler does not inspect the compliance result before selecting resources. Limits do not prefer failed resources, passed resources, or resources with more findings.
+* **Latest-first where possible:** When AWS exposes timestamps or useful ordering, Prowler selects the newest resources first. When AWS only exposes API order, Prowler preserves that API order and documents the behavior as best effort.
+* **Findings are downstream:** Checks only evaluate the resources exposed by the service client after selection. Findings from unselected resources are not produced because those resources are not analyzed.
+
+Exact list API call reduction depends on each AWS API's ordering and pagination capabilities. When Prowler must enumerate candidates locally to select the latest resources, list calls may still read candidates, but expensive per-resource enrichment calls are bounded to the selected resources for the supported paths below.
+
+#### Full Collections Versus Limited Analysis Sets
+
+Some checks need lightweight evidence from a complete resource collection to avoid incorrect cross-service conclusions, while other checks perform primary analysis on a limited resource set.
+
+Prowler keeps full lightweight collections where they are needed for cross-service evidence. For example:
+
+* **Lambda security groups and regions:** Prowler records security groups used by all discovered Lambda functions and the regions where functions exist before it limits Lambda functions for primary Lambda checks. This helps Amazon EC2 and Amazon Inspector checks avoid false positives such as treating Lambda security groups as unused or assuming a region has no Lambda functions.
+* **CloudWatch `all_log_groups`:** Prowler records all discovered CloudWatch log groups in `all_log_groups` before limiting the primary `log_groups` analysis set. Other services can still resolve log group evidence, while CloudWatch log group checks only analyze the selected log groups.
+
+This split is intentional. It reduces expensive per-resource analysis calls without discarding lightweight context that other services need for accurate results.
+
+#### Supported AWS Resource Limits
+
+| Value | Scope | Type |
+|-------|-------|------|
+| `max_scanned_resources_per_service` | Global default for all supported high-volume AWS resources (default `0`, disabled/unlimited) | Integer |
+| `max_ebs_snapshots` | EBS snapshots (`ec2_ebs_*` checks) | Integer |
+| `max_backup_recovery_points` | Backup recovery points (`backup_recovery_point_*`) | Integer |
+| `max_cloudwatch_log_groups` | CloudWatch log groups (`cloudwatch_log_group_*`) | Integer |
+| `max_lambda_functions` | Lambda functions (`awslambda_function_*`) | Integer |
+| `max_ecs_task_definitions` | ECS task definitions (`ecs_task_definitions_*`) | Integer |
+| `max_codeartifact_packages` | CodeArtifact packages (`codeartifact_packages_*`) | Integer |
+
+#### Resource Limit Behavior By Resource Path
+
+| Resource Path | What Prowler Discovers | What A Positive Limit Selects For Analysis | Ordering And Latest Behavior | AWS Calls Reduced | Drawbacks And Consequences |
+|---------------|------------------------|--------------------------------------------|------------------------------|-------------------|----------------------------|
+| EBS snapshots (`max_ebs_snapshots`) | Prowler lists self-owned snapshots and keeps lightweight evidence that volumes and regions have snapshots. | The selected EBS snapshots exposed to `ec2_ebs_*` checks. | Prowler sorts discovered snapshots by `StartTime` newest first, then applies the limit. Snapshots without a timestamp sort last. | Bounds expensive per-snapshot public attribute checks to selected snapshots. Snapshot listing still runs so Prowler can choose the newest snapshots and keep volume/region evidence. | Older unselected snapshots are not analyzed by snapshot checks. A public, unencrypted, or otherwise noncompliant older snapshot can be missed when the limit is lower than the number of snapshots. |
+| Backup recovery points (`max_backup_recovery_points`) | Prowler lists backup vaults, plans, selections, and recovery point candidates in discovered vaults. | The selected recovery points exposed to `backup_recovery_point_*` checks and tag hydration. | Prowler sorts discovered recovery points by `CreationDate` newest first across vaults, then applies the limit. Recovery points without a timestamp sort last. | Bounds recovery point tag calls to selected recovery points. Vault and recovery point list calls still run so Prowler can choose the newest points. | Older unselected recovery points are not analyzed. A nonencrypted or otherwise noncompliant older recovery point can be missed. |
+| CloudWatch log groups (`max_cloudwatch_log_groups`) | Prowler lists log groups into both `all_log_groups` and the primary `log_groups` collection. `all_log_groups` remains available as lightweight cross-service evidence. | The selected log groups exposed to `cloudwatch_log_group_*` checks, tag hydration, and log event retrieval for checks that need log contents. | Prowler sorts discovered log groups by `creationTime` newest first, then applies the limit. Log groups without a creation time sort last. | Bounds tag calls and log event retrieval to selected log groups. Log group listing still runs to build `all_log_groups` and choose newest log groups. | Older unselected log groups are not analyzed by CloudWatch log group checks. Retention, encryption, or secrets-in-logs issues in older log groups can be missed, although cross-service evidence can still use `all_log_groups`. |
+| Lambda functions (`max_lambda_functions`) | Prowler lists Lambda functions and records lightweight security group and region evidence for all discovered functions. | The selected Lambda functions exposed to `awslambda_function_*` checks and per-function enrichment such as tags, policies, function URLs, and event source mappings. | Prowler sorts discovered functions by `LastModified` newest first, then applies the limit. Functions without `LastModified` sort last. | Bounds per-function enrichment calls to selected functions. Function listing still runs to choose newest functions and keep security group/region evidence. | Older unselected functions are not analyzed by Lambda checks. Runtime, policy, URL, environment secret, or dead-letter queue issues in older functions can be missed. Cross-service checks can still use full Lambda security group and region evidence to avoid false positives. |
+| ECS task definitions (`max_ecs_task_definitions`) | Prowler lists ECS task definition ARN candidates in each region. Candidate ARNs can remain visible and discoverable through AWS list operations, even when not all are described. | The selected task definitions that Prowler describes and exposes to `ecs_task_definitions_*` checks. | Selection is not random. Prowler calls `ListTaskDefinitions` with `sort=DESC`, which asks AWS to return task definition ARNs in descending family and revision order. Prowler then interleaves regional candidate lists to avoid starving later regions before applying the limit. This selects the latest task definition revisions according to the ARN order AWS provides, while preserving regional fairness. | Bounds `DescribeTaskDefinition` calls to selected task definitions. Prowler may still list candidates so it can select the bounded set and keep discovery deterministic. | Unselected task definitions are not described or analyzed. Issues in older task definition revisions, or in lower-priority families outside the selected AWS `sort=DESC` order, can be missed. Because ECS ordering is family/revision based rather than a registration timestamp sort across every family, this is latest-first according to AWS task definition ARN ordering, not a global newest-by-time guarantee. |
+| CodeArtifact packages (`max_codeartifact_packages`) | Prowler lists CodeArtifact repositories and lazily lists packages inside them. | The selected packages exposed to `codeartifact_packages_*` checks, including latest-version metadata for those packages. | AWS `ListPackages` does not provide a newest-package timestamp ordering in this path. Prowler preserves repository order and package API order, then applies the limit. Latest package version metadata is retrieved for selected packages with `sortBy=PUBLISHED_TIME` and `maxResults=1`. | Bounds `ListPackageVersions` calls to selected packages and can stop package listing once the limit is reached. Repository listing still runs. | Package selection is best effort by API order, not newest package order. Packages outside the selected repository/API order are not analyzed, so origin restriction or latest-version issues can be missed. |
+
+Use limits when scan duration, API throttling, or cost are more important than exhaustive coverage for these high-volume resources. Keep limits disabled when you need complete evidence for every resource in the affected checks.
+
+### Validating Discovered Secrets
+
+
+
+By default, the secret-scanning checks run fully offline: secrets are detected but never sent anywhere. Setting `secrets_validate` to `True` additionally confirms whether each discovered secret is live by authenticating with it against the corresponding provider API. The discovered secret itself serves as the credential, so Prowler requires no additional permissions to validate it.
+
+`secrets_validate` applies to every AWS secret-scanning check listed above (those that accept `secrets_ignore_patterns`). The `--scan-secrets-validate` CLI flag is provider-wide: it also enables validation for the secret-scanning checks of other providers, such as the OpenStack metadata checks.
+
+To enable validation through the configuration file, set the value under the `aws` section:
+
+```yaml
+aws:
+ secrets_validate: True
+```
+
+To enable validation for a single scan (any provider), use Prowler CLI:
+
+```
+prowler aws --scan-secrets-validate
+```
+
+
+Secret validation makes outbound network calls that authenticate with each discovered secret. The credential is exercised against the provider, so the call appears in the audited account's logs and can trigger its monitoring (for example, AWS CloudTrail records the validation request). Validation stays disabled by default so that scans remain fully offline.
+
## Azure
@@ -92,20 +204,20 @@ The following list includes all the AWS checks with configurable variables that
### Configurable Checks
The following list includes all the Azure checks with configurable variables that can be changed in the configuration yaml file:
-| Check Name | Value | Type |
-|---------------------------------------------------------------|--------------------------------------------------|-----------------|
-| `network_public_ip_shodan` | `shodan_api_key` | String |
-| `app_ensure_php_version_is_latest` | `php_latest_version` | String |
-| `app_ensure_python_version_is_latest` | `python_latest_version` | String |
-| `app_ensure_java_version_is_latest` | `java_latest_version` | String |
-| `sqlserver_recommended_minimal_tls_version` | `recommended_minimal_tls_versions` | List of Strings |
-| `vm_sufficient_daily_backup_retention_period` | `vm_backup_min_daily_retention_days` | Integer |
-| `vm_desired_sku_size` | `desired_vm_sku_sizes` | List of Strings |
-| `storage_smb_channel_encryption_with_secure_algorithm` | `recommended_smb_channel_encryption_algorithms` | List of Strings |
-| `defender_attack_path_notifications_properly_configured` | `defender_attack_path_minimal_risk_level` | String |
-| `apim_threat_detection_llm_jacking` | `apim_threat_detection_llm_jacking_threshold` | Float |
-| `apim_threat_detection_llm_jacking` | `apim_threat_detection_llm_jacking_minutes` | Integer |
-| `apim_threat_detection_llm_jacking` | `apim_threat_detection_llm_jacking_actions` | List of Strings |
+| Check Name | Value | Type | Default |
+|----------------------------------------------------------|-------------------------------------------------|-----------------|------------------------------------------------------------|
+| `apim_threat_detection_llm_jacking` | `apim_threat_detection_llm_jacking_actions` | List of Strings | See `config.yaml` |
+| `apim_threat_detection_llm_jacking` | `apim_threat_detection_llm_jacking_minutes` | Integer | `1440` |
+| `apim_threat_detection_llm_jacking` | `apim_threat_detection_llm_jacking_threshold` | Float | `0.1` |
+| `app_ensure_java_version_is_latest` | `java_latest_version` | String | `"17"` |
+| `app_ensure_php_version_is_latest` | `php_latest_version` | String | `"8.2"` |
+| `app_ensure_python_version_is_latest` | `python_latest_version` | String | `"3.12"` |
+| `defender_attack_path_notifications_properly_configured` | `defender_attack_path_minimal_risk_level` | String | `"High"` |
+| `network_public_ip_shodan` | `shodan_api_key` | String | `null` |
+| `sqlserver_recommended_minimal_tls_version` | `recommended_minimal_tls_versions` | List of Strings | `["1.2", "1.3"]` |
+| `storage_smb_channel_encryption_with_secure_algorithm` | `recommended_smb_channel_encryption_algorithms` | List of Strings | `["AES-256-GCM"]` |
+| `vm_desired_sku_size` | `desired_vm_sku_sizes` | List of Strings | `["Standard_A8_v2", "Standard_DS3_v2", "Standard_D4s_v3"]` |
+| `vm_sufficient_daily_backup_retention_period` | `vm_backup_min_daily_retention_days` | Integer | `7` |
## GCP
@@ -113,23 +225,28 @@ The following list includes all the Azure checks with configurable variables tha
### Configurable Checks
The following list includes all the GCP checks with configurable variables that can be changed in the configuration yaml file:
-| Check Name | Value | Type |
-|---------------------------------------------------------------|--------------------------------------------------|-----------------|
-| `compute_configuration_changes` | `compute_audit_log_lookback_days` | Integer |
-| `compute_instance_group_multiple_zones` | `mig_min_zones` | Integer |
+| Check Name | Value | Type | Default |
+|---------------------------------------------------|-----------------------------------|---------|---------|
+| `cloudstorage_bucket_sufficient_retention_period` | `storage_min_retention_days` | Integer | `90` |
+| `compute_instance_group_multiple_zones` | `mig_min_zones` | Integer | `2` |
+| `compute_public_address_shodan` | `shodan_api_key` | String | `null` |
+| `compute_snapshot_not_outdated` | `max_snapshot_age_days` | Integer | `90` |
+| `iam_sa_user_managed_key_unused` | `max_unused_account_days` | Integer | `180` |
+| `iam_service_account_unused` | `max_unused_account_days` | Integer | `180` |
+| `secretmanager_secret_rotation_enabled` | `secretmanager_max_rotation_days` | Integer | `90` |
## Kubernetes
### Configurable Checks
The following list includes all the Kubernetes checks with configurable variables that can be changed in the configuration yaml file:
-| Check Name | Value | Type |
-|---------------------------------------------------------------|--------------------------------------------------|-----------------|
-| `audit_log_maxbackup` | `audit_log_maxbackup` | String |
-| `audit_log_maxsize` | `audit_log_maxsize` | String |
-| `audit_log_maxage` | `audit_log_maxage` | String |
-| `apiserver_strong_ciphers` | `apiserver_strong_ciphers` | String |
-| `kubelet_strong_ciphers_only` | `kubelet_strong_ciphers` | String |
+| Check Name | Value | Type | Default |
+|-------------------------------------|----------------------------|-----------------|----------------------------------------------------------------------------------------|
+| `apiserver_audit_log_maxage_set` | `audit_log_maxage` | Integer | `30` |
+| `apiserver_audit_log_maxbackup_set` | `audit_log_maxbackup` | Integer | `10` |
+| `apiserver_audit_log_maxsize_set` | `audit_log_maxsize` | Integer | `100` |
+| `apiserver_strong_ciphers_only` | `apiserver_strong_ciphers` | List of Strings | `["TLS_AES_128_GCM_SHA256", "TLS_AES_256_GCM_SHA384", "TLS_CHACHA20_POLY1305_SHA256"]` |
+| `kubelet_strong_ciphers_only` | `kubelet_strong_ciphers` | List of Strings | See `config.yaml` |
## M365
@@ -137,11 +254,13 @@ The following list includes all the Kubernetes checks with configurable variable
### Configurable Checks
The following list includes all the Microsoft 365 checks with configurable variables that can be changed in the configuration yaml file:
-| Check Name | Value | Type |
-|---------------------------------------------------------------|--------------------------------------------------|-----------------|
-| `entra_admin_users_sign_in_frequency_enabled` | `sign_in_frequency` | Integer |
-| `teams_external_file_sharing_restricted` | `allowed_cloud_storage_services` | List of Strings |
-| `exchange_organization_mailtips_enabled` | `recommended_mailtips_large_audience_threshold` | Integer |
+| Check Name | Value | Type | Default |
+|--------------------------------------------------------------------|-------------------------------------------------|-----------------|--------------------|
+| `defender_malware_policy_comprehensive_attachments_filter_applied` | `recommended_blocked_file_types` | List of Strings | See check defaults |
+| `entra_admin_users_sign_in_frequency_enabled` | `sign_in_frequency` | Integer | `4` |
+| `exchange_organization_mailtips_enabled` | `recommended_mailtips_large_audience_threshold` | Integer | `25` |
+| `exchange_user_mailbox_auditing_enabled` | `audit_log_age` | Integer | `90` |
+| `teams_external_file_sharing_restricted` | `allowed_cloud_storage_services` | List of Strings | `[]` |
## GitHub
@@ -149,35 +268,76 @@ The following list includes all the Microsoft 365 checks with configurable varia
### Configurable Checks
The following list includes all the GitHub checks with configurable variables that can be changed in the configuration yaml file:
-| Check Name | Value | Type |
-|--------------------------------------------|---------------------------------------------|---------|
-| `repository_inactive_not_archived` | `inactive_not_archived_days_threshold` | Integer |
+| Check Name | Value | Type | Default |
+|------------------------------------|----------------------------------------|---------|---------|
+| `repository_inactive_not_archived` | `inactive_not_archived_days_threshold` | Integer | `180` |
## Vercel
### Configurable Checks
The following list includes all the Vercel checks with configurable variables that can be changed in the configuration YAML file:
-| Check Name | Value | Type |
-|-----------------------------------------------------|------------------------------------|-----------------|
-| `authentication_no_stale_tokens` | `stale_token_threshold_days` | Integer |
-| `authentication_token_not_expired` | `days_to_expire_threshold` | Integer |
-| `deployment_production_uses_stable_target` | `stable_branches` | List of Strings |
-| `domain_ssl_certificate_valid` | `days_to_expire_threshold` | Integer |
-| `project_environment_no_secrets_in_plain_type` | `secret_suffixes` | List of Strings |
-| `team_member_role_least_privilege` | `max_owner_percentage` | Integer |
-| `team_member_role_least_privilege` | `max_owners` | Integer |
-| `team_no_stale_invitations` | `stale_invitation_threshold_days` | Integer |
+| Check Name | Value | Type | Default |
+|------------------------------------------------|-----------------------------------|-----------------|--------------------------------------------------------------------------|
+| `authentication_no_stale_tokens` | `stale_token_threshold_days` | Integer | `90` |
+| `authentication_token_not_expired` | `days_to_expire_threshold` | Integer | `7` |
+| `deployment_production_uses_stable_target` | `stable_branches` | List of Strings | `["main", "master"]` |
+| `domain_ssl_certificate_valid` | `days_to_expire_threshold` | Integer | `7` |
+| `project_environment_no_secrets_in_plain_type` | `secret_suffixes` | List of Strings | `["_KEY", "_SECRET", "_TOKEN", "_PASSWORD", "_API_KEY", "_PRIVATE_KEY"]` |
+| `team_member_role_least_privilege` | `max_owner_percentage` | Integer | `20` |
+| `team_member_role_least_privilege` | `max_owners` | Integer | `3` |
+| `team_no_stale_invitations` | `stale_invitation_threshold_days` | Integer | `30` |
## Okta
### Configurable Checks
The following list includes all the Okta checks with configurable variables that can be changed in the configuration YAML file:
-| Check Name | Value | Type |
-|---------------------------------------------------------------|------------------------------------|---------|
-| `application_admin_console_session_idle_timeout_15min` | `okta_admin_console_idle_timeout_max_minutes` | Integer |
-| `signon_global_session_idle_timeout_15min` | `okta_max_session_idle_minutes` | Integer |
+| Check Name | Value | Type | Default |
+|--------------------------------------------------------|-----------------------------------------------|-----------------|---------|
+| `application_admin_console_session_idle_timeout_15min` | `okta_admin_console_idle_timeout_max_minutes` | Integer | `15` |
+| `idp_smart_card_dod_approved_ca` | `okta_dod_approved_ca_issuer_patterns` | List of Strings | `[]` |
+| `signon_global_session_idle_timeout_15min` | `okta_max_session_idle_minutes` | Integer | `15` |
+| `signon_global_session_lifetime_18h` | `okta_max_session_lifetime_minutes` | Integer | `1080` |
+| `user_inactivity_automation_35d_enabled` | `okta_user_inactivity_max_days` | Integer | `35` |
+
+## Alibaba Cloud
+
+### Configurable Checks
+The following list includes all the Alibaba Cloud checks with configurable variables that can be changed in the configuration YAML file:
+
+| Check Name | Value | Type | Default |
+|--------------------------------------|--------------------------------|---------|---------|
+| `cs_kubernetes_cluster_check_recent` | `max_cluster_check_days` | Integer | `7` |
+| `cs_kubernetes_cluster_check_weekly` | `max_cluster_check_days` | Integer | `7` |
+| `ram_user_console_access_unused` | `max_console_access_days` | Integer | `90` |
+| `rds_instance_sql_audit_retention` | `min_rds_audit_retention_days` | Integer | `180` |
+| `sls_logstore_retention_period` | `min_log_retention_days` | Integer | `365` |
+
+
+## MongoDB Atlas
+
+### Configurable Checks
+The following list includes all the MongoDB Atlas checks with configurable variables that can be changed in the configuration YAML file:
+
+| Check Name | Value | Type | Default |
+|----------------------------------------------------|---------------------------------------------|---------|---------|
+| `organizations_service_account_secrets_expiration` | `max_service_account_secret_validity_hours` | Integer | `8` |
+
+
+## OpenStack
+
+### Configurable Checks
+The following list includes all the OpenStack checks with configurable variables that can be changed in the configuration YAML file:
+
+| Check Name | Value | Type | Default |
+|---------------------------------------------------|---------------------------|-----------------|---------|
+| `blockstorage_snapshot_metadata_sensitive_data` | `secrets_ignore_patterns` | List of Strings | `[]` |
+| `blockstorage_volume_metadata_sensitive_data` | `secrets_ignore_patterns` | List of Strings | `[]` |
+| `compute_instance_metadata_sensitive_data` | `secrets_ignore_patterns` | List of Strings | `[]` |
+| `image_not_shared_with_multiple_projects` | `image_sharing_threshold` | Integer | `5` |
+| `objectstorage_container_metadata_sensitive_data` | `secrets_ignore_patterns` | List of Strings | `[]` |
+
## Config YAML File Structure
@@ -191,6 +351,19 @@ aws:
# AWS Global Configuration
# aws.mute_non_default_regions --> Set to True to muted failed findings in non-default regions for AccessAnalyzer, GuardDuty, SecurityHub, DRS and Config
mute_non_default_regions: False
+
+ # AWS Resource Scan Limit Configuration
+ # Disabled by default: scan every resource unless a positive limit is configured.
+ # Findings are not capped. Set to 0 (or a negative value) to disable the limit.
+ # aws.max_scanned_resources_per_service --> global default for all services below
+ max_scanned_resources_per_service: 0
+ # Per-service overrides. Leave as null to fall back to the global default.
+ max_ebs_snapshots: null
+ max_backup_recovery_points: null
+ max_cloudwatch_log_groups: null
+ max_lambda_functions: null
+ max_ecs_task_definitions: null
+ max_codeartifact_packages: null
# If you want to mute failed findings only in specific regions, create a file with the following syntax and run it with `prowler aws -w mutelist.yaml`:
# Mutelist:
# Accounts:
diff --git a/docs/user-guide/cli/tutorials/dashboard.mdx b/docs/user-guide/cli/tutorials/dashboard.mdx
index 0fe3c69fed..abb3872657 100644
--- a/docs/user-guide/cli/tutorials/dashboard.mdx
+++ b/docs/user-guide/cli/tutorials/dashboard.mdx
@@ -1,8 +1,8 @@
---
-title: "Dashboard"
+title: "Prowler Local Dashboard"
---
-Prowler allows you to run your own local dashboards using the csv outputs provided by Prowler
+Prowler Local Dashboard is a local web dashboard built from the CSV outputs produced by Prowler CLI. Launch it with:
```sh
prowler dashboard
@@ -12,7 +12,7 @@ prowler dashboard
You can expose the `dashboard` server in another address using the `HOST` environment variable.
-To run Prowler local dashboard with Docker, use:
+To run Prowler Local Dashboard with Docker, use:
```sh
docker run -v /your/local/dir/prowler-output:/home/prowler/output --env HOST=0.0.0.0 --publish 127.0.0.1:11666:11666 toniblyx/prowler:latest dashboard
diff --git a/docs/user-guide/cli/tutorials/integrations.mdx b/docs/user-guide/cli/tutorials/integrations.mdx
index f3e698d799..bfd53b0c3c 100644
--- a/docs/user-guide/cli/tutorials/integrations.mdx
+++ b/docs/user-guide/cli/tutorials/integrations.mdx
@@ -33,7 +33,7 @@ To configure the Slack Integration, follow the next steps:
2. Optionally, create a Slack Channel (you can use an existing one)
3. Integrate the created Slack App to your Slack channel:
- - Click on the channel, go to the Integrations tab, and Add an App.
+ - Click the channel, go to the Integrations tab, and Add an App.

4. Set the following environment variables that Prowler will read:
diff --git a/docs/user-guide/cli/tutorials/pentesting.mdx b/docs/user-guide/cli/tutorials/pentesting.mdx
index 0ad5313611..a9a8c728df 100644
--- a/docs/user-guide/cli/tutorials/pentesting.mdx
+++ b/docs/user-guide/cli/tutorials/pentesting.mdx
@@ -6,20 +6,34 @@ Prowler has some checks that analyse pentesting risks (Secrets, Internet Exposed
## Detect Secrets
-Prowler uses `detect-secrets` library to search for any secrets that are stores in plaintext within your environment.
+Prowler scans for secrets stored in plaintext within the audited environment using [Kingfisher](https://github.com/mongodb/kingfisher), an open-source secret-scanning engine. By default these scans run fully offline, so no data leaves the audited environment. Discovered secrets can optionally be validated against the provider APIs to confirm whether they are live — see [Validating Discovered Secrets](/user-guide/cli/tutorials/configuration_file#validating-discovered-secrets).
-The actual checks that have this functionality are the following:
+The checks with this functionality are the following.
+AWS:
+
+- apigateway\_restapi\_no\_secrets\_in\_stage\_variables
- autoscaling\_find\_secrets\_ec2\_launch\_configuration
- awslambda\_function\_no\_secrets\_in\_code
- awslambda\_function\_no\_secrets\_in\_variables
- cloudformation\_stack\_outputs\_find\_secrets
+- cloudwatch\_log\_group\_no\_secrets\_in\_logs
+- codebuild\_project\_no\_secrets\_in\_variables
- ec2\_instance\_secrets\_user\_data
- ec2\_launch\_template\_no\_secrets
- ecs\_task\_definitions\_no\_environment\_secrets
+- glue\_etl\_jobs\_no\_secrets\_in\_arguments
- ssm\_document\_secrets
+- stepfunctions\_statemachine\_no\_secrets\_in\_definition
-To execute detect-secrets related checks, you can run the following command:
+OpenStack:
+
+- compute\_instance\_metadata\_sensitive\_data
+- blockstorage\_volume\_metadata\_sensitive\_data
+- blockstorage\_snapshot\_metadata\_sensitive\_data
+- objectstorage\_container\_metadata\_sensitive\_data
+
+To execute the secret-scanning checks, run the following command:
```console
prowler --categories secrets
diff --git a/docs/user-guide/compliance/tutorials/compliance.mdx b/docs/user-guide/compliance/tutorials/compliance.mdx
index 63b2502b25..6c13f60529 100644
--- a/docs/user-guide/compliance/tutorials/compliance.mdx
+++ b/docs/user-guide/compliance/tutorials/compliance.mdx
@@ -1,14 +1,15 @@
---
title: 'Compliance'
-description: 'Run security checks against compliance frameworks, review posture across providers, and download CSV or PDF reports from Prowler Cloud, Prowler App, and Prowler CLI.'
+sidebarTitle: 'Overview'
+description: 'Run security checks against compliance frameworks, review posture across providers, and download CSV or PDF reports from Prowler Cloud and Prowler Local Server, or CSV reports from Prowler CLI.'
---
-Prowler maps every security check to one or more industry-standard compliance frameworks, so a single scan produces both technical findings and framework-aligned evidence. The same evaluation runs identically whether scans are launched from Prowler Cloud, Prowler App, or Prowler CLI.
+Prowler maps every security check to one or more industry-standard compliance frameworks, so a single scan produces both technical findings and framework-aligned evidence. The same evaluation runs identically whether scans are launched from Prowler Cloud, Prowler Local Server, or Prowler CLI.
Out of the box, Prowler covers frameworks such as CIS Benchmarks, NIST 800-53, NIST CSF, NIS2, ENS RD2022, ISO 27001, PCI-DSS, SOC 2, GDPR, HIPAA, AWS Well-Architected, BSI C5, CSA CCM, MITRE ATT&CK, KISA ISMS-P, FedRAMP, and Prowler ThreatScore. The full catalog is available at [Prowler Hub](https://hub.prowler.com/compliance).
-For the unified compliance score methodology used across frameworks, see [Prowler ThreatScore Documentation](/user-guide/compliance/tutorials/threatscore).
+For the unified compliance score methodology used across frameworks, see [Prowler ThreatScore](/user-guide/compliance/tutorials/threatscore).
@@ -20,15 +21,15 @@ For the unified compliance score methodology used across frameworks, see [Prowle
-## Prowler Cloud
+## Prowler Cloud and Prowler Local Server
-The Compliance section in Prowler Cloud and Prowler App centralizes compliance posture across every connected provider. It aggregates scan results, surfaces Prowler ThreatScore, and exposes detailed requirement-level evidence for each supported framework.
+The Compliance section in Prowler Cloud and Prowler Local Server centralizes compliance posture across every connected provider. It aggregates scan results, surfaces Prowler ThreatScore, and exposes detailed requirement-level evidence for each supported framework.
### Accessing the Compliance Section
To open the compliance overview, follow these steps:
-1. Sign in to Prowler Cloud at [cloud.prowler.com](https://cloud.prowler.com/sign-in) or to a self-hosted Prowler App instance.
+1. Sign in to Prowler Cloud at [cloud.prowler.com](https://cloud.prowler.com/sign-in) or to a Prowler Local Server instance.
2. Select **Compliance** from the left navigation.
The page lists every framework evaluated by the most recent completed scan of the selected provider.
@@ -74,7 +75,7 @@ When the selected scan includes Prowler ThreatScore data, a dedicated card appea
Selecting the card opens the ThreatScore framework detail page, covered in [Working With the Framework Detail Page](#working-with-the-framework-detail-page).
-For a complete explanation of the methodology, formula, and weighting, see [Prowler ThreatScore Documentation](/user-guide/compliance/tutorials/threatscore).
+For a complete explanation of the methodology, formula, and weighting, see [Prowler ThreatScore](/user-guide/compliance/tutorials/threatscore).
### Exploring the Framework Grid
@@ -169,7 +170,7 @@ Region filters disable the per-card download dropdown to avoid generating partia
#### Downloading the Full Scan Output
-To export every framework, finding, and resource at once, use the **Scan Jobs** section instead. The ZIP archive contains the CSV, JSON-OCSF, and HTML reports plus a `compliance/` subfolder with one CSV per framework. See [Prowler App — Getting Started](/user-guide/tutorials/prowler-app) for details.
+To export every framework, finding, and resource at once, use the **Scan Jobs** section instead. The ZIP archive contains the CSV, JSON-OCSF, and HTML reports plus a `compliance/` subfolder with one CSV per framework. See [Prowler Cloud — Getting Started](/user-guide/tutorials/prowler-app) for details.
### API Access
@@ -262,6 +263,7 @@ To request a new framework or contribute one, see [Creating a New Security Compl
## Related Documentation
-* [Prowler ThreatScore Documentation](/user-guide/compliance/tutorials/threatscore)
+* [Cross-Provider Compliance](/user-guide/compliance/tutorials/cross-provider-compliance)
+* [Prowler ThreatScore](/user-guide/compliance/tutorials/threatscore)
* [Creating a New Security Compliance Framework in Prowler](/developer-guide/security-compliance-framework)
-* [Prowler App — Getting Started](/user-guide/tutorials/prowler-app)
+* [Prowler Cloud — Getting Started](/user-guide/tutorials/prowler-app)
diff --git a/docs/user-guide/compliance/tutorials/cross-provider-compliance.mdx b/docs/user-guide/compliance/tutorials/cross-provider-compliance.mdx
new file mode 100644
index 0000000000..545f5fb834
--- /dev/null
+++ b/docs/user-guide/compliance/tutorials/cross-provider-compliance.mdx
@@ -0,0 +1,209 @@
+---
+title: 'Cross-Provider Compliance'
+sidebarTitle: 'Cross-Provider Compliance'
+description: 'Aggregate a single universal compliance framework across every connected provider in Prowler Cloud, review a consolidated roll-up and per-provider breakdown, and download a combined PDF report.'
+---
+
+import { VersionBadge } from "/snippets/version-badge.mdx"
+import { SubscriptionBanner } from "/snippets/subscription-banner.mdx"
+
+
+
+Cross-Provider Compliance consolidates a single **universal compliance framework** across all of your connected providers into one unified view. Instead of reviewing the same framework on AWS, Azure, Google Cloud, and every other provider as separate reports, Prowler takes the most recent completed scan of every compatible provider, aggregates them by requirement, and produces a single roll-up posture with a per-provider breakdown and a combined executive PDF.
+
+
+
+## What Is a Universal Compliance Framework
+
+Most Prowler compliance frameworks target a single provider (for example, CIS AWS or CIS Azure). A **universal** framework declares its requirements once in a single JSON and maps each requirement to checks for many providers at the same time, so the same CSA CCM control maps to both AWS and Azure checks. Universal frameworks live at the top of the compliance catalog (`prowler/compliance/.json`), as opposed to the legacy per-provider frameworks under `prowler/compliance//`. For real definitions, see [`csa_ccm_4.0.json`](https://github.com/prowler-cloud/prowler/blob/master/prowler/compliance/csa_ccm_4.0.json), [`cis_controls_8.1.json`](https://github.com/prowler-cloud/prowler/blob/master/prowler/compliance/cis_controls_8.1.json), and [`dora_2022_2554.json`](https://github.com/prowler-cloud/prowler/blob/master/prowler/compliance/dora_2022_2554.json) in the Prowler repository.
+
+Prowler currently ships three universal frameworks: [CSA CCM](https://hub.prowler.com/compliance/csa_ccm_4.0), [CIS Controls](https://hub.prowler.com/compliance/cis_controls_8.1), and [DORA](https://hub.prowler.com/compliance/dora_2022_2554). Each framework page on Prowler Hub lists the full requirement-to-check mapping per provider.
+
+## How Cross-Provider Compliance Works
+
+Cross-Provider Compliance uses this structure to answer a single question: **"How compliant is my whole estate against this framework, regardless of provider?"** For a chosen universal framework, Prowler Cloud:
+
+1. Selects **one scan per compatible provider**: by default, the latest completed scan of each provider the framework supports and that you are allowed to see.
+2. Aggregates the requirement results across those scans, folding multiple accounts of the same provider type together.
+3. Computes a **roll-up status** for each requirement and an overall pass / fail / manual summary for the framework.
+4. Exposes a **per-provider breakdown** so you can see exactly which provider is failing a given control.
+
+
+Cross-Provider Compliance never mixes different frameworks. It aggregates one universal framework at a time across providers. To review a single provider in isolation, use the standard per-scan [Compliance](/user-guide/compliance/tutorials/compliance) view.
+
+
+### Supported Universal Frameworks
+
+The Cross-Provider Compliance view currently supports the following universal frameworks. The compatible providers are the ones each framework declares checks for; a provider only contributes to the roll-up when it has a completed scan.
+
+| Framework | Version | Compatible providers |
+|-----------|---------|----------------------|
+| [**CSA CCM**](https://hub.prowler.com/compliance/csa_ccm_4.0) (Cloud Controls Matrix) | 4.0 | AWS, Azure, Google Cloud, Alibaba Cloud, Oracle Cloud |
+| [**CIS Controls**](https://hub.prowler.com/compliance/cis_controls_8.1) | 8.1 | AWS, Azure, Google Cloud, Microsoft 365, Kubernetes, GitHub, Google Workspace, Okta, Oracle Cloud, Alibaba Cloud, Cloudflare, MongoDB Atlas, OpenStack, Vercel |
+| [**DORA**](https://hub.prowler.com/compliance/dora_2022_2554) (Digital Operational Resilience Act) | 2022/2554 | AWS, Azure, Google Cloud, Alibaba Cloud, Cloudflare |
+
+The catalog grows as new universal frameworks ship in Prowler. Browse the full compliance catalog at [Prowler Hub](https://hub.prowler.com/compliance).
+
+## Accessing the Cross-Provider View
+
+
+
+ Sign in to Prowler Cloud at [cloud.prowler.com](https://cloud.prowler.com/sign-in) and select **Compliance** from the left navigation.
+
+
+ At the top of the Compliance page, select the **Cross-provider** tab. The **Per Scan** tab (the default) keeps the single-provider compliance experience unchanged.
+
+
+
+
+
+
+Cross-Provider Compliance requires at least one completed scan for a compatible provider. If no compatible provider has finished a scan yet, the page shows a notice prompting you to launch or wait for a scan to complete.
+
+
+## Exploring the Overview
+
+The overview presents one card per supported universal framework, each summarizing the consolidated posture across every contributing provider.
+
+
+
+Each **framework card** includes:
+
+* **Framework logo, name, and version:** Identifies the universal standard (CSA CCM, CIS Controls, DORA).
+* **Score:** The percentage of passing requirements over the total evaluated, aggregated across every contributing provider. Color coding follows three thresholds: red for severely low compliance, amber for partial compliance, and green for healthy posture.
+* **Passing Requirements:** A `passed / total` counter with the aggregated roll-up.
+* **Provider chips:** One icon per compatible provider. Providers with a completed scan appear active with their passing percentage; providers without a scan appear dimmed with a "no completed scan yet" tooltip so coverage gaps are obvious at a glance.
+* **Failed and manual counts:** The number of failing and manual requirements in the roll-up.
+
+Select any card to open the framework detail page.
+
+### Filtering the Roll-Up
+
+The filters bar controls which providers and accounts feed every card and detail view. Cross-Provider Compliance supports three filters:
+
+* **Provider type:** Narrow the roll-up to specific provider types (for example, only AWS and Azure).
+* **Provider / account:** Narrow to specific connected accounts.
+* **Provider group:** Narrow to accounts within one or more provider groups.
+
+Select **Clear filters** to reset all filters. Filters applied on the overview are carried through into the detail page and the PDF report so the view stays consistent end to end.
+
+
+Filters narrow **which providers contribute** to the aggregation. They do not change how a requirement rolls up (see [Understanding the Roll-Up Status](#understanding-the-roll-up-status)).
+
+
+## Working With the Framework Detail Page
+
+The detail page provides the full breakdown for a single universal framework: aggregate metrics, provider coverage, top failing sections, and a requirement-by-requirement view with per-provider status.
+
+
+
+### Header
+
+The header shows the framework name and version, a link to the framework page on [Prowler Hub](https://hub.prowler.com/compliance), and a summary such as *"X of Y compatible providers scanned · N scans aggregated"* so you always know the coverage behind the numbers. The **Report** button in the top-right generates and downloads the combined PDF (see [Downloading the Combined PDF Report](#downloading-the-combined-pdf-report)).
+
+### Summary Cards
+
+Below the header, three summary cards condense the framework state:
+
+* **Requirements Status:** Donut chart with `Pass`, `Fail`, and `Manual` counts plus the total number of requirements, reflecting the consolidated roll-up.
+* **Provider Coverage:** Shows which compatible providers contributed a scan and their individual posture, so coverage gaps and per-provider weak spots are visible at a glance.
+* **Top Failed Sections:** Ranks the framework sections with the highest number of failing requirements, with deep links into the requirements accordion.
+
+### Requirements Accordion
+
+The accordion organizes every requirement of the framework. For each requirement you see:
+
+* **Requirement ID and title:** The official identifier from the framework.
+* **Roll-up status badge:** A single `Pass`, `Fail`, or `Manual` badge representing the consolidated status across all contributing providers.
+* **Per-provider status:** The status each contributing provider returned for that requirement, so a single failing provider is immediately attributable.
+* **Provider-labeled checks:** When you expand a requirement, the underlying checks are labeled with the provider they belong to (each universal requirement maps to different check IDs per provider).
+
+Expand a requirement to review the failing checks per provider, the affected resources, and remediation guidance. Findings are queried across every contributing scan and merged into a single table.
+
+
+
+## Understanding the Roll-Up Status
+
+Cross-Provider Compliance rolls up results in two stages, with a strict **FAIL > PASS > MANUAL** precedence.
+
+**Per provider, per requirement:**
+
+* If any check fails → the provider contributes **FAIL** for that requirement.
+* Else if every check passes → **PASS**.
+* Otherwise (no pass/fail evidence) → **MANUAL**.
+
+Multiple accounts of the same provider type (for example, three AWS accounts) are folded together first, so a failure in any one account marks that provider type as failing.
+
+**Across providers, per requirement (the roll-up badge):**
+
+* If at least one contributing provider is **FAIL** → the requirement is **FAIL**.
+* Else if at least one contributing provider is **PASS** → **PASS**.
+* Otherwise → **MANUAL**.
+
+
+Only providers that **actually contributed a result** for a requirement are counted. A provider that has a scan in the aggregation but produced no result for a specific requirement (for example, because the framework maps no checks to that provider for that control) does **not** degrade the requirement to Manual. This keeps the roll-up focused on real evidence.
+
+
+### How Scans Are Selected
+
+By default, Cross-Provider Compliance auto-selects the **latest completed scan** of each compatible provider you are allowed to see. This means:
+
+* The view always reflects your most recent posture per provider, without any manual scan selection.
+* Adding a new compatible provider and running a scan automatically brings it into the roll-up.
+* Provider visibility follows your role: you only ever see providers your permissions allow, and the roll-up is scoped accordingly.
+
+## Downloading the Combined PDF Report
+
+The **Report** button on the detail page generates a single PDF that combines every contributing provider's latest scan for the framework into one executive document: a cover page listing all providers and accounts, an executive summary with the consolidated roll-up, charts, a requirements index, and detailed findings grouped by requirement, provider, and account.
+
+### The Report Follows Your Filters
+
+A report covers the exact set of scans your current filters resolve to. The provider type, provider / account, and provider group filters applied on the detail page determine which providers contribute, and the auto-select rule pins each contributing provider's latest completed scan. The PDF is built from that resolved scan set together with the framework.
+
+As a result, each filter combination produces its own report. For example:
+
+* No filters → a report covering every compatible provider that has a completed scan.
+* `Provider type = AWS, Azure` → a report covering only your AWS and Azure scans.
+* `Provider group = Production` → a report covering only the accounts in that group.
+
+Changing the filters and generating again produces a different, independent report. Each combination is tracked on its own, so switching filters back and forth never overwrites a previously generated report.
+
+
+Region filtering is **not** supported for the combined PDF report. The report recomputes status live across every region of the contributing scans, so a region-scoped request is rejected rather than producing a report that contradicts a region-filtered view.
+
+
+### Generating and Reusing a Report
+
+Because the report aggregates many scans, it is generated **asynchronously**:
+
+
+
+ Select **Report → Generate new report…**, optionally give it a name, and confirm. Prowler starts a background job and shows a "Report generation started" confirmation.
+
+
+ The button shows a "Generating report…" state while the job runs. Generation continues in the background: you can navigate away, and a toast notification appears when the report is ready, even after a page reload.
+
+
+ When the report is ready, select **Download** from the notification, or use **Report → Download latest** at any time to fetch the most recent report for the current filters.
+
+
+
+
+
+A report already generated for a given set of filters does not need to be generated again. When you open the detail page with a filter combination that was reported before, Prowler detects the existing report and surfaces **Report → Download latest** so you can download it immediately, without launching a new job. You only need to generate a fresh report when:
+
+* You apply a filter combination that has never been reported before, or
+* A contributing provider has run a new scan since the report was generated. The report is tied to the specific scans it was built from, so a newer scan makes the previous report stale; Prowler recognizes it no longer matches the current selection and offers to generate an up-to-date one.
+
+"Download latest" reuses an existing report only when it matches the framework, the exact resolved scan set for the current filters, and the same report options. This guarantees the PDF you download reflects the posture you are looking at, rather than a report generated for a different filter or an older scan.
+
+
+The PDF detail section renders only **failed** requirements by default so the report stays focused as an executive/auditor document. As with every Prowler PDF, the detail section is capped at the first 100 failed findings per check; use the per-scan CSV or JSON-OCSF exports for the complete, untruncated list. See [Downloading Compliance Reports](/user-guide/compliance/tutorials/compliance#downloading-compliance-reports) for the full PDF behavior and the `DJANGO_PDF_MAX_FINDINGS_PER_CHECK` setting.
+
+
+## Related Documentation
+
+* [Compliance](/user-guide/compliance/tutorials/compliance)
+* [Prowler ThreatScore](/user-guide/compliance/tutorials/threatscore)
+* [Creating a New Security Compliance Framework in Prowler](/developer-guide/security-compliance-framework)
+* [Prowler Cloud — Getting Started](/user-guide/tutorials/prowler-app)
diff --git a/docs/user-guide/compliance/tutorials/threatscore.mdx b/docs/user-guide/compliance/tutorials/threatscore.mdx
index bb5a006342..8d790cf90d 100644
--- a/docs/user-guide/compliance/tutorials/threatscore.mdx
+++ b/docs/user-guide/compliance/tutorials/threatscore.mdx
@@ -1,19 +1,17 @@
---
-title: "Prowler ThreatScore Documentation"
+title: "Prowler ThreatScore"
---
-
-
-
## Introduction
-The **Prowler ThreatScore** is a comprehensive compliance scoring system that provides a unified metric for assessing your organization's security posture across compliance frameworks. It aggregates findings from individual security checks into a single, normalized score ranging from 0 to 100.
+Prowler ThreatScore is a comprehensive compliance scoring system that provides a unified metric for assessing security posture across compliance frameworks. It aggregates findings from individual security checks into a single, normalized score ranging from 0 to 100.
### Purpose
-- **Unified View**: Get a single metric representing overall compliance health
-- **Risk Prioritization**: Understand which areas pose the highest security risks
-- **Progress Tracking**: Monitor improvements in compliance posture over time
-- **Executive Reporting**: Provide clear, quantifiable security metrics to stakeholders
+
+- **Unified view:** A single metric represents overall compliance health.
+- **Risk prioritization:** Highlights which areas pose the highest security risks.
+- **Progress tracking:** Monitors improvements in compliance posture over time.
+- **Executive reporting:** Delivers clear, quantifiable security metrics to stakeholders.
## How ThreatScore Works
@@ -29,7 +27,7 @@ Pass Rate = (Number of PASS findings) / (Total findings)
The total number of checks performed (both PASS and FAIL) for a requirement. This represents the amount of evidence available - more findings provide greater confidence in the assessment.
### 3. Weight (`weight_i`)
-A numerical value (1-1000) representing the business importance or criticality of the requirement within your organization's context.
+A numerical value (1-1000) representing the business importance or criticality of the requirement within the organizational context.
### 4. Risk Level (`risk_i`)
A severity rating (1-5) indicating the potential impact of non-compliance with this requirement.
@@ -380,7 +378,7 @@ This comprehensive example demonstrates how:
### Example 4: Impact of Parameter Changes
-Using the scenario, let's see how parameter changes affect the score:
+Using the scenario, the following changes show how parameter adjustments affect the score:
#### Scenario A: Increase Encryption Risk Level
diff --git a/docs/user-guide/cookbooks/powerbi-cis-benchmarks.mdx b/docs/user-guide/cookbooks/powerbi-cis-benchmarks.mdx
index 9b9e41ed93..15985aab28 100644
--- a/docs/user-guide/cookbooks/powerbi-cis-benchmarks.mdx
+++ b/docs/user-guide/cookbooks/powerbi-cis-benchmarks.mdx
@@ -14,7 +14,7 @@ The template and its source files live in the Prowler repository under [`contrib
The setup requires the following components:
* **Microsoft Power BI Desktop:** free download from Microsoft.
-* **Prowler compliance CSV exports:** produced by Prowler CLI or downloaded from Prowler Cloud or Prowler App.
+* **Prowler compliance CSV exports:** produced by Prowler CLI or downloaded from Prowler Cloud or Prowler Local Server.
* **Local directory:** holds the CSV exports that the template ingests at load time.
## Supported CIS Benchmarks
@@ -40,7 +40,7 @@ Download and install Microsoft Power BI Desktop from the official Microsoft site
### Step 2: Generate Compliance CSV Exports
-Compliance CSV exports can be generated through Prowler CLI or downloaded from Prowler Cloud and Prowler App.
+Compliance CSV exports can be generated through Prowler CLI or downloaded from Prowler Cloud and Prowler Local Server.
#### Option A: Prowler CLI
@@ -55,7 +55,7 @@ prowler kubernetes --compliance cis_1.12_kubernetes
The compliance CSV exports are written to `output/compliance/` by default.
-#### Option B: Prowler Cloud or Prowler App
+#### Option B: Prowler Cloud or Prowler Local Server
Open the Compliance section, select the desired CIS Benchmark, and download the CSV export.
@@ -160,7 +160,7 @@ A full walkthrough is available on YouTube:
- Review the Compliance workflow across Prowler Cloud, Prowler App, and Prowler CLI.
+ Review the Compliance workflow across Prowler Cloud, Prowler Local Server, and Prowler CLI.
Explore the built-in local dashboard for Prowler CSV exports.
diff --git a/docs/user-guide/providers/alibabacloud/getting-started-alibabacloud.mdx b/docs/user-guide/providers/alibabacloud/getting-started-alibabacloud.mdx
index 36520a8f8c..ce9778a3b5 100644
--- a/docs/user-guide/providers/alibabacloud/getting-started-alibabacloud.mdx
+++ b/docs/user-guide/providers/alibabacloud/getting-started-alibabacloud.mdx
@@ -32,14 +32,14 @@ Before you begin, make sure you have:
### Step 1: Get Your Alibaba Cloud Account ID
1. Log in to the [Alibaba Cloud Console](https://home.console.alibabacloud.com/)
-2. Click on your profile avatar in the top-right corner
+2. Click your profile avatar in the top-right corner
3. Locate and copy your Account ID

### Step 2: Access Prowler Cloud
-1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler App](/user-guide/tutorials/prowler-app)
+1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler Local Server](/user-guide/tutorials/prowler-app)
2. Go to "Configuration" > "Providers"

diff --git a/docs/user-guide/providers/aws/authentication.mdx b/docs/user-guide/providers/aws/authentication.mdx
index 22deb6ab99..e3c20ca99d 100644
--- a/docs/user-guide/providers/aws/authentication.mdx
+++ b/docs/user-guide/providers/aws/authentication.mdx
@@ -7,9 +7,9 @@ Prowler requires AWS credentials to function properly. Authentication is availab
- Static Credentials
- Assumed Role
-When using **Assumed Role**, the Prowler UI exposes two credential sources for calling `sts:AssumeRole`. The labels differ between Prowler Cloud and self-hosted Prowler App, but both map to the same underlying credential types:
+When using **Assumed Role**, the Prowler UI exposes two credential sources for calling `sts:AssumeRole`. The labels differ between Prowler Cloud and Prowler Local Server, but both map to the same underlying credential types:
-- **AWS SDK Default** (shown as *"Prowler Cloud will assume your IAM role"* in Prowler Cloud and *"AWS SDK Default"* in self-hosted Prowler App): Prowler uses the credentials already available to the API and worker containers through the [AWS SDK default credential chain](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html). This is the default in Prowler Cloud and requires extra configuration in self-hosted Prowler App (see [Configuring AWS SDK Default for Self-Hosted Prowler App](#configuring-aws-sdk-default-for-self-hosted-prowler-app)).
+- **AWS SDK Default** (shown as *"Prowler Cloud will assume your IAM role"* in Prowler Cloud and *"AWS SDK Default"* in Prowler Local Server): Prowler uses the credentials already available to the API and worker containers through the [AWS SDK default credential chain](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html). This is the default in Prowler Cloud and requires extra configuration in Prowler Local Server (see [Configuring AWS SDK Default for Prowler Local Server](#configuring-aws-sdk-default-for-prowler-local-server)).
- **Access & Secret Key**: You paste an IAM user's `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and optionally `AWS_SESSION_TOKEN` into the form. Prowler uses those keys to call `sts:AssumeRole`.
## Required Permissions
@@ -81,9 +81,9 @@ This method grants permanent access and is the recommended setup for production
---
-## Configuring AWS SDK Default for Self-Hosted Prowler App
+## Configuring AWS SDK Default for Prowler Local Server
-When self-hosting Prowler App with Docker Compose, the API and worker containers do not have AWS credentials by default. Selecting **AWS SDK Default** without configuring those credentials produces:
+When running Prowler Local Server with Docker Compose, the API and worker containers do not have AWS credentials by default. Selecting **AWS SDK Default** without configuring those credentials produces:
```
AWSAssumeRoleError[1012]: AWS assume role error - An error occurred (InvalidClientTokenId) when calling the AssumeRole operation: The security token included in the request is invalid.
@@ -116,7 +116,7 @@ docker compose up -d --force-recreate api worker worker-beat
### Option 2: IAM Role (Host with Instance Metadata)
-If you run Prowler App on an EC2 instance, ECS task, or EKS pod with an attached IAM role that can assume the scan role, no extra configuration is needed — `boto3` resolves credentials through instance or task metadata automatically.
+If you run Prowler Local Server on an EC2 instance, ECS task, or EKS pod with an attached IAM role that can assume the scan role, no extra configuration is needed — `boto3` resolves credentials through instance or task metadata automatically.
### Trust Policy: Align `IAMPrincipal` With Your Identity
diff --git a/docs/user-guide/providers/aws/getting-started-aws.mdx b/docs/user-guide/providers/aws/getting-started-aws.mdx
index f0c5ab882a..11516e88b3 100644
--- a/docs/user-guide/providers/aws/getting-started-aws.mdx
+++ b/docs/user-guide/providers/aws/getting-started-aws.mdx
@@ -18,7 +18,7 @@ title: 'Getting Started With AWS on Prowler'
### Step 2: Access Prowler Cloud
-1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler App](/user-guide/tutorials/prowler-app)
+1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler Local Server](/user-guide/tutorials/prowler-app)
2. Go to "Configuration" > "Providers"

@@ -67,7 +67,7 @@ This method grants permanent access and is the recommended setup for production
For detailed instructions on how to create the role, see [Authentication > Assume Role](/user-guide/providers/aws/authentication#assume-role-recommended).
-7. Once the role is created, go to the **IAM Console**, click on the "ProwlerScan" role to open its details:
+7. Once the role is created, go to the **IAM Console**, click the "ProwlerScan" role to open its details:

@@ -75,13 +75,13 @@ For detailed instructions on how to create the role, see [Authentication > Assum

-9. Paste the ARN into the corresponding field in Prowler Cloud or Prowler App
+9. Paste the ARN into the corresponding field in Prowler Cloud or Prowler Local Server

10. Select the credential source Prowler should use to call `sts:AssumeRole`. The option label differs between deployments but both map to the same `aws-sdk-default` credential type:
- - **"Prowler Cloud will assume your IAM role"** (default in Prowler Cloud) / **"AWS SDK Default"** (in self-hosted Prowler App): Prowler uses the credentials available in the API and worker environment through the [AWS SDK default credential chain](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html). In self-hosted Prowler App, these containers have no AWS credentials by default — see [Configuring AWS SDK Default for Self-Hosted Prowler App](/user-guide/providers/aws/authentication#configuring-aws-sdk-default-for-self-hosted-prowler-app) before choosing this option, or the connection test will fail with `InvalidClientTokenId`.
+ - **"Prowler Cloud will assume your IAM role"** (default in Prowler Cloud) / **"AWS SDK Default"** (in Prowler Local Server): Prowler uses the credentials available in the API and worker environment through the [AWS SDK default credential chain](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html). In Prowler Local Server, these containers have no AWS credentials by default — see [Configuring AWS SDK Default for Prowler Local Server](/user-guide/providers/aws/authentication#configuring-aws-sdk-default-for-prowler-local-server) before choosing this option, or the connection test will fail with `InvalidClientTokenId`.
- **Access & Secret Key**: Paste an IAM user's `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` (and optional `AWS_SESSION_TOKEN`) into the form. The IAM principal must be allowed to assume the target role and must match the `IAMPrincipal` parameter of the scan role template (default: `role/prowler*`).
11. Click "Next", then "Launch Scan"
@@ -110,7 +110,7 @@ AWS accounts can also be configured using static credentials (not recommended fo
For detailed instructions on how to create the credentials, see [Authentication > Credentials](/user-guide/providers/aws/authentication#credentials).
-1. Complete the form in Prowler Cloud or Prowler App and click "Next"
+1. Complete the form in Prowler Cloud or Prowler Local Server and click "Next"

diff --git a/docs/user-guide/providers/aws/organizations.mdx b/docs/user-guide/providers/aws/organizations.mdx
index bbdedef50b..b48df1c442 100644
--- a/docs/user-guide/providers/aws/organizations.mdx
+++ b/docs/user-guide/providers/aws/organizations.mdx
@@ -2,10 +2,12 @@
title: 'AWS Organizations in Prowler'
---
+import { VersionBadge } from "/snippets/version-badge.mdx"
+
**Using Prowler Cloud?** You can onboard your entire AWS Organization through the UI with automatic account discovery, OU-aware tree selection, and bulk connection testing — no scripts or YAML files required.
-See [AWS Organizations in Prowler Cloud](/user-guide/tutorials/prowler-cloud-aws-organizations) for the full walkthrough.
+See [AWS Organizations](/user-guide/tutorials/prowler-cloud-aws-organizations) in Prowler Cloud for the full walkthrough.
Prowler can integrate with AWS Organizations to manage the visibility and onboarding of accounts centrally.
@@ -71,11 +73,43 @@ The additional fields in CSV header output are as follows:
## Deploying Prowler IAM Roles Across AWS Organizations
+
+
When onboarding multiple AWS accounts into Prowler Cloud, it is important to deploy the Prowler Scan IAM Role in each account. The most efficient way to do this across an AWS Organization is by leveraging AWS CloudFormation StackSets, which rolls out infrastructure—like IAM roles—to all accounts centrally from the Management or Delegated Admin account.
-When using Infrastructure as Code (IaC), Terraform is recommended to manage this deployment systematically.
+### Native CloudFormation StackSet Deployment (Recommended)
-### Recommended Approach
+The [Prowler Scan IAM Role CloudFormation template](https://github.com/prowler-cloud/prowler/blob/master/permissions/templates/cloudformation/prowler-scan-role.yml) can deploy the role across your entire AWS Organization on its own—no third-party modules required. When launched in the **Management Account** (or a **Delegated Administrator** account) with `DeployStackSet=true` and `EnableOrganizations=true`, it creates a service-managed CloudFormation StackSet that rolls the ProwlerScan role out to every account under the target Organizational Unit (or the organization root), and keeps new accounts covered automatically through auto-deployment.
+
+To deploy from the CloudFormation console: open **CloudFormation → Create stack → With new resources**, choose **Upload a template file** and select `prowler-scan-role.yml` (or paste its S3 URL), then set the parameters below on the **Specify stack details** step. Leave the **Configure stack options** step at its defaults.
+
+Deploy a single CloudFormation Stack in the Management Account with the following parameters:
+
+| Parameter | Description | Default |
+| --- | --- | --- |
+| `ExternalId` | External ID provided by Prowler Cloud to secure role assumption. | — |
+| `DeployLocalRole` | Create the ProwlerScan role in this (Management) account. | `true` |
+| `DeployStackSet` | Create a service-managed StackSet that deploys the role to member accounts. | `false` |
+| `AWSOrganizationalUnitId` | Target OU (`ou-xxxx-yyyyyyyy`) or organization root (`r-xxxx`) for the StackSet. Required when `DeployStackSet=true`. | `""` |
+| `DeployFromDelegatedAdmin` | Set to `true` when deploying from a Delegated Administrator account instead of the Management Account (uses `CallAs: DELEGATED_ADMIN`). | `false` |
+| `EnableOrganizations` | Add AWS Organizations permissions to the Management Account role: read-only account discovery plus the StackSet-management permissions the deployment needs. Set to `true` when deploying in the Management Account. | `false` |
+| `FailureTolerancePercentage` | Percentage of accounts in which the StackSet operation can fail before CloudFormation stops the operation. | `10` |
+| `RetainStacksOnAccountRemoval` | Keep the role in an account after it leaves the Organization or OU. | `false` |
+
+
+On the review step, select **"I acknowledge that AWS CloudFormation might create IAM resources with custom names"** — the template provisions the named `ProwlerScan` IAM role, so the stack requires the `CAPABILITY_NAMED_IAM` capability and fails without this acknowledgment. (The quick-create link handles this for you.)
+
+
+
+The service-managed StackSet does **not** deploy to the Management Account itself. Keeping `DeployLocalRole=true` ensures the role also exists there, so a single stack covers both the Management and member accounts.
+
+Trusted access for CloudFormation StackSets must be enabled in the Organization (see the note at the top of this page) before `DeployStackSet` will work.
+
+Deploying for the CLI or a self-hosted Prowler (not Prowler Cloud)? Also set `AccountId` to the account you assume the role from and `IAMPrincipal` to your identity — the defaults target Prowler Cloud. See [Aligning the trust policy with your identity](/user-guide/providers/aws/authentication#trust-policy-align-iamprincipal-with-your-identity).
+
+
+
+### Alternative: Deploy with Terraform
- **Use StackSets** from the **Management Account** (or a Delegated Admin/Security Account).
- **Use Terraform** to orchestrate the deployment.
diff --git a/docs/user-guide/providers/aws/regions-and-partitions.mdx b/docs/user-guide/providers/aws/regions-and-partitions.mdx
index 377612013e..8556ccc74e 100644
--- a/docs/user-guide/providers/aws/regions-and-partitions.mdx
+++ b/docs/user-guide/providers/aws/regions-and-partitions.mdx
@@ -64,7 +64,7 @@ When more than one source is set, precedence is:
3. `aws.disallowed_regions` in `config.yaml`
-For self-hosted App or API-triggered scans, set `PROWLER_AWS_DISALLOWED_REGIONS` in the runtime environment of the backend scan containers such as `api` and `worker`. The `ui` container does not enforce AWS region selection.
+For Prowler Local Server or API-triggered scans, set `PROWLER_AWS_DISALLOWED_REGIONS` in the runtime environment of the backend scan containers such as `api` and `worker`. The `ui` container does not enforce AWS region selection.
diff --git a/docs/user-guide/providers/aws/role-assumption.mdx b/docs/user-guide/providers/aws/role-assumption.mdx
index b714beafbd..54dd0e214a 100644
--- a/docs/user-guide/providers/aws/role-assumption.mdx
+++ b/docs/user-guide/providers/aws/role-assumption.mdx
@@ -77,6 +77,15 @@ The template requires the following parameters:
- **AccountId:** *(Optional)* AWS Account ID that will assume the role (default: Prowler Cloud account)
- **IAMPrincipal:** *(Optional)* The IAM principal allowed to assume the role (default: `role/prowler*`)
+
+From the CLI you assume the role with **your own** identity, not from Prowler Cloud. The `AccountId` and `IAMPrincipal` defaults target Prowler Cloud, so set **`AccountId`** to the account you run Prowler from and **`IAMPrincipal`** to your identity (for example `role/` or `user/`). Otherwise `sts:AssumeRole` fails with `AccessDenied`. See [Aligning the trust policy with your identity](/user-guide/providers/aws/authentication#trust-policy-align-iamprincipal-with-your-identity).
+
+
+
+To deploy the role across an entire AWS Organization from a single stack (Management Account role plus a service-managed StackSet for the member accounts), the template also accepts `DeployLocalRole`, `DeployStackSet`, `AWSOrganizationalUnitId`, `DeployFromDelegatedAdmin`, `EnableOrganizations`, `FailureTolerancePercentage`, and `RetainStacksOnAccountRemoval`. See [AWS Organizations in Prowler](/user-guide/providers/aws/organizations#native-cloudformation-stackset-deployment-recommended) for the full parameter reference.
+
+
+
When running Prowler CLI, include the External ID using the `-I/--external-id` flag:
```sh
diff --git a/docs/user-guide/providers/azure/authentication.mdx b/docs/user-guide/providers/azure/authentication.mdx
index 852e79d115..f41e9dd9b3 100644
--- a/docs/user-guide/providers/azure/authentication.mdx
+++ b/docs/user-guide/providers/azure/authentication.mdx
@@ -2,9 +2,9 @@
title: 'Azure Authentication in Prowler'
---
-Prowler for Azure supports multiple authentication types. Authentication methods vary between Prowler App and Prowler CLI:
+Prowler for Azure supports multiple authentication types. Authentication methods vary between Prowler Cloud and Prowler CLI:
-**Prowler App:**
+**Prowler Cloud:**
- [**Service Principal Application**](#service-principal-application-authentication-recommended)
@@ -210,13 +210,15 @@ For more detailed guidance on subscription management and permissions:
The following security checks require the `ProwlerRole` permissions for execution. Ensure the role is assigned to the identity assumed by Prowler before running these checks:
- `app_function_access_keys_configured`
+- `app_function_application_insights_enabled`
- `app_function_ftps_deployment_disabled`
+- `app_function_latest_runtime_version`
---
## Service Principal Application Authentication (Recommended)
-This method is required for Prowler App and recommended for Prowler CLI.
+This method is required for Prowler Cloud and recommended for Prowler CLI.
### Creating the Service Principal
For more information, see [Creating Prowler Service Principal](/user-guide/providers/azure/create-prowler-service-principal).
diff --git a/docs/user-guide/providers/azure/getting-started-azure.mdx b/docs/user-guide/providers/azure/getting-started-azure.mdx
index 66b3b14e3a..034e8eacfe 100644
--- a/docs/user-guide/providers/azure/getting-started-azure.mdx
+++ b/docs/user-guide/providers/azure/getting-started-azure.mdx
@@ -16,7 +16,7 @@ Government cloud subscriptions (Azure Government) are not currently supported, b
### Prerequisites
-Before setting up Azure in Prowler App, you need to create a Service Principal with proper permissions.
+Before setting up Azure in Prowler Cloud, you need to create a Service Principal with proper permissions.
For detailed instructions on how to create the Service Principal and configure permissions, see [Authentication > Service Principal](/user-guide/providers/azure/authentication#service-principal-application-authentication-recommended).
@@ -34,12 +34,12 @@ For detailed instructions on how to create the Service Principal and configure p
### Step 2: Access Prowler Cloud
-1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler App](/user-guide/tutorials/prowler-app)
+1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler Local Server](/user-guide/tutorials/prowler-app)
2. Navigate to `Configuration` > `Providers`

-3. Click on `Add Provider`
+3. Click `Add Provider`

@@ -53,14 +53,14 @@ For detailed instructions on how to create the Service Principal and configure p
### Step 3: Add Credentials to Prowler Cloud
-For Azure, Prowler App uses a service principal application to authenticate. For more information about the process of creating and adding permissions to a service principal refer to this [section](/user-guide/providers/azure/authentication). When you finish creating and adding the [Entra](/user-guide/providers/azure/create-prowler-service-principal#assigning-proper-permissions) and [Subscription](/user-guide/providers/azure/subscriptions) scope permissions to the service principal, enter the `Tenant ID`, `Client ID` and `Client Secret` of the service principal application.
+For Azure, Prowler Cloud uses a service principal application to authenticate. For more information about the process of creating and adding permissions to a service principal refer to this [section](/user-guide/providers/azure/authentication). When you finish creating and adding the [Entra](/user-guide/providers/azure/create-prowler-service-principal#assigning-proper-permissions) and [Subscription](/user-guide/providers/azure/subscriptions) scope permissions to the service principal, enter the `Tenant ID`, `Client ID` and `Client Secret` of the service principal application.
1. Go to your App Registration overview and copy the `Client ID` and `Tenant ID`

-2. Go to Prowler App and paste:
+2. Go to Prowler Cloud and paste:
- `Client ID`
- `Tenant ID`
diff --git a/docs/user-guide/providers/azure/resource-groups.mdx b/docs/user-guide/providers/azure/resource-groups.mdx
new file mode 100644
index 0000000000..0dbda18235
--- /dev/null
+++ b/docs/user-guide/providers/azure/resource-groups.mdx
@@ -0,0 +1,47 @@
+---
+title: 'Azure Resource Group Scope'
+---
+
+Prowler supports narrowing security scans to specific resource groups within Azure subscriptions. This is useful when you want to audit only a subset of resources rather than scanning an entire subscription.
+
+By default, Prowler scans all resource groups it has permission to access. Passing `--azure-resource-group` limits the scan to only the specified resource groups across all accessible subscriptions.
+
+## Configuring Resource Group Scoped Scans
+
+To restrict a scan to one or more resource groups, pass them as arguments using the `--azure-resource-group` flag:
+
+```console
+prowler azure --az-cli-auth --azure-resource-group ...
+```
+
+For example, to scan only `rg-production` and `rg-staging`:
+
+```console
+prowler azure --az-cli-auth --azure-resource-group rg-production rg-staging
+```
+
+This works with all supported authentication methods:
+
+```console
+# Service Principal
+prowler azure --sp-env-auth --azure-resource-group rg-production
+
+# Browser
+prowler azure --browser-auth --tenant-id --azure-resource-group rg-production
+
+# Managed Identity
+prowler azure --managed-identity-auth --azure-resource-group rg-production
+```
+
+## How It Works
+
+When `--azure-resource-group` is provided, Prowler validates each specified resource group against all accessible subscriptions. A resource group is included in the scan if it exists in **at least one** subscription.
+
+- If a resource group is found in one or more subscriptions, it will be scanned in those subscriptions only.
+- If a resource group is **not found in any** subscription, Prowler logs a warning and skips it.
+- If **none** of the provided resource groups are found across any subscription, Prowler logs a warning and no resource group scoped checks will run.
+- Resource group names are matched case-insensitively, so `MyGroup` and `mygroup` are treated as the same group, mirroring Azure's own behavior.
+
+
+If `--azure-resource-group` is used, checks that apply to specific resources are limited to the relevant resource groups. But if checks that apply to tenant or subscription scope (identity, policy, or subscription-level configuration checks) are involved, then these checks will run in their natural scope.
+
diff --git a/docs/user-guide/providers/azure/subscriptions.mdx b/docs/user-guide/providers/azure/subscriptions.mdx
index 8fa6c73740..efd37c13e5 100644
--- a/docs/user-guide/providers/azure/subscriptions.mdx
+++ b/docs/user-guide/providers/azure/subscriptions.mdx
@@ -17,7 +17,7 @@ prowler azure --az-cli-auth --subscription-ids
-The multi-subscription feature is available only in the CLI. In Prowler App, each scan is limited to a single subscription.
+The multi-subscription feature is available only in the CLI. In Prowler Cloud, each scan is limited to a single subscription.
## Assigning Permissions for Subscription Scans
diff --git a/docs/user-guide/providers/cloudflare/authentication.mdx b/docs/user-guide/providers/cloudflare/authentication.mdx
index fe69656a04..37e2ffafef 100644
--- a/docs/user-guide/providers/cloudflare/authentication.mdx
+++ b/docs/user-guide/providers/cloudflare/authentication.mdx
@@ -56,8 +56,8 @@ Template URLs only pre-fill the token creation form. Review the permissions, con
### Step 1: Create a User API Token
1. Log into the [Cloudflare Dashboard](https://dash.cloudflare.com).
-2. Click on the profile icon in the top right corner, then select "My Profile".
-3. Click on the **API Tokens** tab.
+2. Click the profile icon in the top right corner, then select "My Profile".
+3. Click the **API Tokens** tab.
4. Click **Create Token**, then select **Create Custom Token** at the bottom of the page.
5. Configure the token with the following settings:
- **Token name:** A descriptive name (e.g., "Prowler Security Scanner")
@@ -102,8 +102,8 @@ API Keys provide full access to the Cloudflare account. While supported, this me
### Step 1: Get the Global API Key
1. Log into the [Cloudflare Dashboard](https://dash.cloudflare.com).
-2. Click on the profile icon in the top right corner, then select "My Profile".
-3. Click on the **API Tokens** tab.
+2. Click the profile icon in the top right corner, then select "My Profile".
+3. Click the **API Tokens** tab.
4. Scroll down to the **API Keys** section.
5. Click **View** next to **Global API Key**.
6. Enter the account password to reveal the key, then copy it.
diff --git a/docs/user-guide/providers/cloudflare/getting-started-cloudflare.mdx b/docs/user-guide/providers/cloudflare/getting-started-cloudflare.mdx
index c4303b4d50..9af3dbe589 100644
--- a/docs/user-guide/providers/cloudflare/getting-started-cloudflare.mdx
+++ b/docs/user-guide/providers/cloudflare/getting-started-cloudflare.mdx
@@ -50,7 +50,7 @@ The Account ID is a 32-character hexadecimal string (e.g., `372e67954025e0ba6aaa
### Step 2: Open Prowler Cloud
-1. Go to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler App](/user-guide/tutorials/prowler-app).
+1. Go to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler Local Server](/user-guide/tutorials/prowler-app).
2. Navigate to "Configuration" > "Providers".

diff --git a/docs/user-guide/providers/e2enetworks/authentication.mdx b/docs/user-guide/providers/e2enetworks/authentication.mdx
new file mode 100644
index 0000000000..67d031861d
--- /dev/null
+++ b/docs/user-guide/providers/e2enetworks/authentication.mdx
@@ -0,0 +1,99 @@
+---
+title: "E2E Networks Authentication in Prowler"
+---
+
+import { VersionBadge } from "/snippets/version-badge.mdx"
+
+
+
+Prowler for E2E Networks authenticates against the E2E Networks MyAccount API using an **API key**, an **auth token**, and a numeric **project ID**. Set the API key and auth token as environment variables to avoid exposing secrets in shell history or process listings. Compatibility CLI flags are still accepted, but Prowler warns when secret values are passed directly on the command line.
+
+## Required Credentials
+
+Prowler requires read access to the E2E Networks project. The following values are needed:
+
+| Credential | Environment Variable | Description |
+|------------|----------------------|-------------|
+| API Key | `E2E_NETWORKS_API_KEY` | Identifies the MyAccount API key used for requests |
+| Auth Token | `E2E_NETWORKS_AUTH_TOKEN` | Bearer token authorizing the API key |
+| Project ID | `E2E_NETWORKS_PROJECT_ID` | Numeric ID of the project to scan |
+| Region | `E2E_NETWORKS_REGION` | Optional region to scan (defaults to all regions: Delhi, Chennai) |
+
+
+The project ID must be an integer. A missing or non-numeric project ID stops the scan before any resource is read.
+
+
+---
+
+## API Credentials
+
+### Step 1: Create the API Key and Auth Token
+
+1. Log into the [E2E Networks MyAccount portal](https://myaccount.e2enetworks.com).
+2. Open the **API Tokens** section under the account settings.
+3. Create a new API token and copy both the API key and the auth token.
+4. Copy the values immediately — the auth token is not shown again.
+
+### Step 2: Find the Project ID
+
+Select the target project in MyAccount and copy its numeric project ID from the project settings or the API context.
+
+### Step 3: Configure Authentication
+
+Export the credentials as environment variables:
+
+```bash
+export E2E_NETWORKS_API_KEY="your-api-key"
+export E2E_NETWORKS_AUTH_TOKEN="your-auth-token"
+export E2E_NETWORKS_PROJECT_ID="your-project-id"
+```
+
+Then run Prowler:
+
+```bash
+prowler e2enetworks
+```
+
+---
+
+## Verifying Authentication
+
+To confirm that Prowler can reach the E2E Networks project, run a scan against a single location:
+
+```bash
+prowler e2enetworks --region Delhi
+```
+
+A successful run reports findings for the discovered resources. A failed run displays an error message indicating the credential or connectivity issue.
+
+---
+
+## CI/CD Integration
+
+For automated pipelines, set the credentials as secret environment variables:
+
+**GitHub Actions:**
+
+```yaml
+env:
+ E2E_NETWORKS_API_KEY: ${{ secrets.E2E_NETWORKS_API_KEY }}
+ E2E_NETWORKS_AUTH_TOKEN: ${{ secrets.E2E_NETWORKS_AUTH_TOKEN }}
+ E2E_NETWORKS_PROJECT_ID: ${{ secrets.E2E_NETWORKS_PROJECT_ID }}
+
+steps:
+ - name: Run Prowler
+ run: prowler e2enetworks
+```
+
+**GitLab CI:**
+
+```yaml
+variables:
+ E2E_NETWORKS_API_KEY: $E2E_NETWORKS_API_KEY
+ E2E_NETWORKS_AUTH_TOKEN: $E2E_NETWORKS_AUTH_TOKEN
+ E2E_NETWORKS_PROJECT_ID: $E2E_NETWORKS_PROJECT_ID
+
+prowler_scan:
+ script:
+ - prowler e2enetworks
+```
diff --git a/docs/user-guide/providers/e2enetworks/getting-started-e2enetworks.mdx b/docs/user-guide/providers/e2enetworks/getting-started-e2enetworks.mdx
new file mode 100644
index 0000000000..6b67f4e32c
--- /dev/null
+++ b/docs/user-guide/providers/e2enetworks/getting-started-e2enetworks.mdx
@@ -0,0 +1,66 @@
+---
+title: 'Getting Started With E2E Networks on Prowler'
+---
+
+import { VersionBadge } from "/snippets/version-badge.mdx"
+
+
+
+Prowler for E2E Networks scans E2E Networks infrastructure for security misconfigurations across compute nodes, networking, security groups, load balancers, storage, and managed databases.
+
+
+E2E Networks support in Prowler is community-maintained. For commercial support or to request additional service coverage, [contact us](https://prowler.com/contact).
+
+
+## Prerequisites
+
+Set up authentication for E2E Networks with the [E2E Networks Authentication](/user-guide/providers/e2enetworks/authentication) guide before starting:
+
+- Create an E2E Networks API key and auth token from the MyAccount API Tokens section
+- Note the numeric project ID of the project to scan
+
+## Prowler CLI
+
+### Run Prowler for E2E Networks
+
+Once authenticated, export the credentials as environment variables and run Prowler for E2E Networks. Environment variables keep secrets out of shell history and process listings:
+
+```bash
+export E2E_NETWORKS_API_KEY="your-api-key"
+export E2E_NETWORKS_AUTH_TOKEN="your-auth-token"
+export E2E_NETWORKS_PROJECT_ID="your-project-id"
+prowler e2enetworks
+```
+
+### Run Specific Checks
+
+```bash
+prowler e2enetworks --checks node_encryption_enabled storage_block_volume_not_orphaned
+```
+
+### Run a Specific Service
+
+```bash
+prowler e2enetworks --services node
+```
+
+### Scan Specific Regions
+
+Use `--region` (aliases `--filter-region` and `-f`) to limit the scan to one or more E2E Networks regions. When the flag is omitted, Prowler reads `E2E_NETWORKS_REGION` and otherwise scans all regions (Delhi, Chennai).
+
+```bash
+prowler e2enetworks --region Delhi Chennai
+```
+
+## Available Services
+
+Prowler for E2E Networks currently supports the following services:
+
+| Service | Description |
+|---------|-------------|
+| `database` | Managed database clusters and their backup, network, and encryption settings |
+| `loadbalancer` | Application load balancers and their TLS, health-check, and protection settings |
+| `network` | Virtual Private Clouds, peering, and reserved public IP addresses |
+| `node` | Compute nodes and their encryption, protection, and network configuration |
+| `securitygroup` | Security groups and their inbound and default traffic rules |
+| `storage` | Block volumes and file storage (EFS/EPFS) with their protection settings |
diff --git a/docs/user-guide/providers/gcp/authentication.mdx b/docs/user-guide/providers/gcp/authentication.mdx
index ec53445c84..ce01c1ba23 100644
--- a/docs/user-guide/providers/gcp/authentication.mdx
+++ b/docs/user-guide/providers/gcp/authentication.mdx
@@ -55,7 +55,7 @@ This method uses the Google Cloud CLI to authenticate and is suitable for develo
### Setup Application Default Credentials
-1. In the [GCP Console](https://console.cloud.google.com/), click on "Activate Cloud Shell"
+1. In the [GCP Console](https://console.cloud.google.com/), click "Activate Cloud Shell"

@@ -89,7 +89,7 @@ This method uses the Google Cloud CLI to authenticate and is suitable for develo

-8. Extract the following values for Prowler Cloud/App:
+8. Extract the following values for Prowler Cloud or Prowler Local Server:
- `client_id`
- `client_secret`
diff --git a/docs/user-guide/providers/gcp/getting-started-gcp.mdx b/docs/user-guide/providers/gcp/getting-started-gcp.mdx
index e16114e19a..f40542a151 100644
--- a/docs/user-guide/providers/gcp/getting-started-gcp.mdx
+++ b/docs/user-guide/providers/gcp/getting-started-gcp.mdx
@@ -13,7 +13,7 @@ title: 'Getting Started With GCP on Prowler'
### Step 2: Access Prowler Cloud
-1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler App](/user-guide/tutorials/prowler-app)
+1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler Local Server](/user-guide/tutorials/prowler-app)
2. Go to "Configuration" > "Providers"

@@ -66,7 +66,7 @@ For Google Cloud, first enter your `GCP Project ID` and then select the authenti
2. Once authenticated, get the `Client ID`, `Client Secret` and `Refresh Token` from `~/.config/gcloud/application_default_credentials`.
- 3. Paste the `Client ID`, `Client Secret` and `Refresh Token` into Prowler App.
+ 3. Paste the `Client ID`, `Client Secret` and `Refresh Token` into Prowler Cloud.
diff --git a/docs/user-guide/providers/github/authentication.mdx b/docs/user-guide/providers/github/authentication.mdx
index 0b5ab6b720..1546bf284a 100644
--- a/docs/user-guide/providers/github/authentication.mdx
+++ b/docs/user-guide/providers/github/authentication.mdx
@@ -12,7 +12,7 @@ Prowler offers three authentication methods. Fine-Grained Personal Access Tokens
| Method | Best For | Key Benefit |
|--------|----------|-------------|
-| [**Fine-Grained Personal Access Token**](#fine-grained-personal-access-token-recommended) | Individual users, quick setup | Simple, user-scoped access |
+| [**Fine-Grained Personal Access Token**](#fine-grained-personal-access-token-recommended-for-individual-use) | Individual users, quick setup | Simple, user-scoped access |
| [**GitHub App**](#github-app-credentials) | Organizations, automation, CI/CD | Organization-scoped, no personal account dependency |
| [**OAuth App Token**](#oauth-app-token) | Delegated user authorization | User-consented access flows |
@@ -271,7 +271,7 @@ Store the `.pem` private key securely. Anyone with this key can authenticate as
## Prowler Cloud Authentication
-For step-by-step setup instructions for Prowler Cloud, see the [Getting Started Guide](/user-guide/providers/github/getting-started-github#prowler-cloudapp).
+For step-by-step setup instructions for Prowler Cloud, see the [Getting Started Guide](/user-guide/providers/github/getting-started-github#prowler-cloud-and-prowler-local-server).
### Using Personal Access Token
@@ -301,7 +301,7 @@ For step-by-step setup instructions for Prowler Cloud, see the [Getting Started
3. Enter your GitHub App ID and upload the private key (`.pem` file).
-For complete step-by-step instructions, see the [Getting Started Guide](/user-guide/providers/github/getting-started-github#prowler-cloudapp).
+For complete step-by-step instructions, see the [Getting Started Guide](/user-guide/providers/github/getting-started-github#prowler-cloud-and-prowler-local-server).
---
diff --git a/docs/user-guide/providers/github/getting-started-github.mdx b/docs/user-guide/providers/github/getting-started-github.mdx
index 079f9a1d7b..09acdfe0c9 100644
--- a/docs/user-guide/providers/github/getting-started-github.mdx
+++ b/docs/user-guide/providers/github/getting-started-github.mdx
@@ -16,7 +16,7 @@ Prowler can scan either:
-
+
Web-based interface with centralized management
@@ -26,7 +26,7 @@ Prowler can scan either:
---
-## Prowler Cloud/App
+## Prowler Cloud and Prowler Local Server
@@ -34,7 +34,7 @@ Prowler can scan either:
### Prerequisites
-Before adding GitHub to Prowler Cloud/App, ensure you have:
+Before adding GitHub to Prowler Cloud or Prowler Local Server, ensure you have:
1. **GitHub Account Access**
- Personal GitHub account, OR
@@ -46,9 +46,9 @@ Before adding GitHub to Prowler Cloud/App, ensure you have:
- OAuth App Token
- GitHub App Credentials (Not Recommended - limited data access)
-### Step 1: Access Prowler Cloud/App
+### Step 1: Access Prowler Cloud or Prowler Local Server
-1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler App](/user-guide/tutorials/prowler-app)
+1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler Local Server](/user-guide/tutorials/prowler-app)
2. Go to **Configuration** → **Providers**

diff --git a/docs/user-guide/providers/googleworkspace/getting-started-googleworkspace.mdx b/docs/user-guide/providers/googleworkspace/getting-started-googleworkspace.mdx
index 8931c43ebd..01e6e89986 100644
--- a/docs/user-guide/providers/googleworkspace/getting-started-googleworkspace.mdx
+++ b/docs/user-guide/providers/googleworkspace/getting-started-googleworkspace.mdx
@@ -42,7 +42,7 @@ The Customer ID starts with the letter "C" followed by alphanumeric characters (
### Step 2: Open Prowler Cloud
-1. Go to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler App](/user-guide/tutorials/prowler-app).
+1. Go to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler Local Server](/user-guide/tutorials/prowler-app).
2. Navigate to "Configuration" > "Providers".

diff --git a/docs/user-guide/providers/iac/getting-started-iac.mdx b/docs/user-guide/providers/iac/getting-started-iac.mdx
index d1e978dc75..9a941c633d 100644
--- a/docs/user-guide/providers/iac/getting-started-iac.mdx
+++ b/docs/user-guide/providers/iac/getting-started-iac.mdx
@@ -24,7 +24,7 @@ Prowler IaC provider scans the following Infrastructure as Code configurations f
## How It Works
-- Prowler App leverages [Trivy](https://trivy.dev/docs/latest/guide/coverage/iac/#scanner) to scan local directories (or specified paths) for supported IaC files, or scans remote repositories.
+- Prowler Cloud leverages [Trivy](https://trivy.dev/docs/latest/guide/coverage/iac/#scanner) to scan local directories (or specified paths) for supported IaC files, or scans remote repositories.
- No cloud credentials or authentication are required for local scans.
- For remote repository scans, authentication can be provided via [git URL](https://git-scm.com/docs/git-clone#_git_urls), CLI flags or environment variables.
- Check the [IaC Authentication](/user-guide/providers/iac/authentication) page for more details.
@@ -37,11 +37,11 @@ Prowler IaC provider scans the following Infrastructure as Code configurations f
### Supported Scanners
-Scanner selection is not configurable in Prowler App. Default scanners, misconfig and secret, run automatically during each scan.
+Scanner selection is not configurable in Prowler Cloud. Default scanners, misconfig and secret, run automatically during each scan.
-### Step 1: Access Prowler Cloud/App
+### Step 1: Access Prowler Cloud or Prowler Local Server
-1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler App](/user-guide/tutorials/prowler-app)
+1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler Local Server](/user-guide/tutorials/prowler-app)
2. Go to "Configuration" > "Providers"

diff --git a/docs/user-guide/providers/image/getting-started-image.mdx b/docs/user-guide/providers/image/getting-started-image.mdx
index b9c305d0ef..6382f10e5c 100644
--- a/docs/user-guide/providers/image/getting-started-image.mdx
+++ b/docs/user-guide/providers/image/getting-started-image.mdx
@@ -33,7 +33,7 @@ Prowler Cloud does not support scanner selection. The vulnerability, secret, and
### Step 1: Access Prowler Cloud
-1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler App](/user-guide/tutorials/prowler-app)
+1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler Local Server](/user-guide/tutorials/prowler-app)
2. Navigate to "Configuration" > "Providers"

diff --git a/docs/user-guide/providers/kubernetes/getting-started-k8s.mdx b/docs/user-guide/providers/kubernetes/getting-started-k8s.mdx
index 9ca791110f..c62ec2b8a1 100644
--- a/docs/user-guide/providers/kubernetes/getting-started-k8s.mdx
+++ b/docs/user-guide/providers/kubernetes/getting-started-k8s.mdx
@@ -4,9 +4,9 @@ title: 'Getting Started with Kubernetes'
## Prowler Cloud
-### Step 1: Access Prowler Cloud/App
+### Step 1: Access Prowler Cloud or Prowler Local Server
-1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler App](/user-guide/tutorials/prowler-app)
+1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler Local Server](/user-guide/tutorials/prowler-app)
2. Go to "Configuration" > "Providers"

@@ -21,7 +21,11 @@ title: 'Getting Started with Kubernetes'
### Step 2: Configure Kubernetes Authentication
-For Kubernetes, Prowler App uses a `kubeconfig` file to authenticate. Paste the contents of your `kubeconfig` file into the `Kubeconfig content` field.
+For Kubernetes, Prowler Cloud uses a `kubeconfig` file to authenticate. Paste the contents of your `kubeconfig` file into the `Kubeconfig content` field.
+
+
+Kubeconfigs that use `users[].user.exec` authentication are not supported in Prowler Cloud or Prowler Local Server. For security reasons, Prowler Cloud does not run commands declared by uploaded kubeconfigs. Use kubeconfig credentials that do not rely on `exec` authentication, such as the ServiceAccount token flow documented below.
+
By default, the `kubeconfig` file is located at `~/.kube/config`.
diff --git a/docs/user-guide/providers/linode/authentication.mdx b/docs/user-guide/providers/linode/authentication.mdx
index feac121f40..3ebb7ef326 100644
--- a/docs/user-guide/providers/linode/authentication.mdx
+++ b/docs/user-guide/providers/linode/authentication.mdx
@@ -29,7 +29,7 @@ Ensure the token has all required scopes. Missing permissions will cause some ch
### Step 1: Create a Personal Access Token
1. Log into the [Linode Cloud Manager](https://cloud.linode.com).
-2. Click on your username in the top-right corner, then select **API Tokens** under the "My Profile" section.
+2. Click your username in the top-right corner, then select **API Tokens** under the "My Profile" section.
3. Click **Create a Personal Access Token**.
4. Configure the token:
- **Label:** A descriptive name (e.g., "Prowler Security Scanner")
diff --git a/docs/user-guide/providers/microsoft365/getting-started-m365.mdx b/docs/user-guide/providers/microsoft365/getting-started-m365.mdx
index a21b796b5c..fd791cbbca 100644
--- a/docs/user-guide/providers/microsoft365/getting-started-m365.mdx
+++ b/docs/user-guide/providers/microsoft365/getting-started-m365.mdx
@@ -41,7 +41,7 @@ Set up authentication for Microsoft 365 with the [Microsoft 365 Authentication](
### Step 2: Open Prowler Cloud
-1. Go to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler App](/user-guide/tutorials/prowler-app).
+1. Go to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler Local Server](/user-guide/tutorials/prowler-app).
2. Navigate to "Configuration" > "Providers".

diff --git a/docs/user-guide/providers/mongodbatlas/getting-started-mongodbatlas.mdx b/docs/user-guide/providers/mongodbatlas/getting-started-mongodbatlas.mdx
index c68bfac9c2..2fb415a11b 100644
--- a/docs/user-guide/providers/mongodbatlas/getting-started-mongodbatlas.mdx
+++ b/docs/user-guide/providers/mongodbatlas/getting-started-mongodbatlas.mdx
@@ -15,12 +15,12 @@ Before you begin, make sure you have:
3. An **API Key pair** (public and private keys) with appropriate permissions:
- **Organization Read Only**: Provides read-only access to everything in the organization, including all projects in the organization. This permission is sufficient for most security checks.
- **Organization Owner**: Required to audit the [Auditing configuration](https://www.mongodb.com/docs/api/doc/atlas-admin-api-v2/group/endpoint-auditing) for projects. Database auditing tracks database operations and security events, including authentication attempts, data definition language (DDL) changes, user and role modifications, and privilege grants. This configuration is essential for security monitoring, forensics, and compliance. Without **Organization Owner** permission, the `projects_auditing_enabled` check cannot retrieve the audit configuration status.
-4. Prowler App access (cloud or self-hosted) or the Prowler CLI (`pip install prowler`).
+4. Access to Prowler Cloud or Prowler Local Server, or Prowler CLI (`pip install prowler`).
For detailed instructions on creating API keys, see the [MongoDB Atlas authentication guide](./authentication.mdx).
-If **Require IP Access List for the Atlas Administration API** is enabled in your organization settings, you **must** add the IP address of the host running Prowler (or the public IP of Prowler Cloud) to the organization IP Access List or Atlas will reject every API call. You can manage this under **Settings → Organization Settings → Security**. See step 7 of the [authentication guide](./authentication.mdx) for detailed instructions, and refer to the [Prowler Cloud public IP list](../../tutorials/prowler-cloud-public-ips) when using Prowler Cloud.
+If **Require IP Access List for the Atlas Administration API** is enabled in the organization settings, add the IP address of the host running Prowler (or the public IP of Prowler Cloud) to the organization IP Access List or Atlas will reject every API call. Manage this under **Settings → Organization Settings → Security**. See step 7 of the [authentication guide](./authentication.mdx) for detailed instructions, and refer to the [Prowler Cloud egress IPs](/security/networking) when using Prowler Cloud.
@@ -53,7 +53,7 @@ If **Require IP Access List for the Atlas Administration API** is enabled in you
### Step 3: Test the connection and start scanning
-1. Click **Test connection** to ensure Prowler App can reach the Atlas API.
+1. Click **Test connection** to ensure Prowler Cloud can reach the Atlas API.
2. Save the credentials. The provider will appear in the list with its current connection status.
3. Launch a scan from the provider row or from the **Scans** page.

@@ -108,6 +108,6 @@ prowler mongodbatlas --atlas-project-id
- Combine flags (for example, `--checks` or `--services`) just like with other providers.
- Use `--output-modes` to export findings in JSON, CSV, ASFF, etc.
-- Rotate API keys regularly and update the stored credentials in Prowler App to maintain connectivity.
+- Rotate API keys regularly and update the stored credentials in Prowler Cloud to maintain connectivity.
For more examples (filters, outputs, scheduling), refer back to the [MongoDB Atlas documentation hub](./authentication.mdx) and the main Prowler CLI usage guide.
diff --git a/docs/user-guide/providers/oci/authentication.mdx b/docs/user-guide/providers/oci/authentication.mdx
index f977a80eb2..9627e88cd4 100644
--- a/docs/user-guide/providers/oci/authentication.mdx
+++ b/docs/user-guide/providers/oci/authentication.mdx
@@ -55,7 +55,7 @@ After running `oci session authenticate`, you need to manually add your user OCI
**Get your user OCID from the OCI Console:**
-Navigate to: **Identity & Security** → **Users** → Click on your username → Copy the OCID
+Navigate to: **Identity & Security** → **Users** → Click your username → Copy the OCID

diff --git a/docs/user-guide/providers/oci/getting-started-oci.mdx b/docs/user-guide/providers/oci/getting-started-oci.mdx
index fc9fb620bf..2f610cd09c 100644
--- a/docs/user-guide/providers/oci/getting-started-oci.mdx
+++ b/docs/user-guide/providers/oci/getting-started-oci.mdx
@@ -6,7 +6,7 @@ Prowler supports security scanning of Oracle Cloud Infrastructure (OCI) environm
## Prowler Cloud
-The following steps apply to Prowler Cloud and the self-hosted Prowler App.
+The following steps apply to Prowler Cloud and Prowler Local Server.
### Step 1: Collect OCI Identifiers
1. Sign in to the [OCI Console](https://cloud.oracle.com/) and open **Tenancy Details** to copy the Tenancy OCID.
@@ -15,14 +15,14 @@ The following steps apply to Prowler Cloud and the self-hosted Prowler App.
4. Note the **Region** identifier to scan (for example, `us-ashburn-1`).
### Step 2: Access Prowler Cloud
-1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler App](/user-guide/tutorials/prowler-app).
+1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler Local Server](/user-guide/tutorials/prowler-app).
2. Go to **Configuration** → **Providers** and click **Add Provider**.

3. Select **Oracle Cloud** and enter the **Tenancy OCID** and an optional alias, then choose **Next**.

### Step 3: Add OCI API Key Credentials
-Prowler App connects to OCI with API key credentials. Provide:
+Prowler Cloud connects to OCI with API key credentials. Provide:
- **User OCID** for the API key owner
- **Fingerprint** of the API key
@@ -78,7 +78,7 @@ The easiest and most secure method is using OCI session authentication, which au
**Get your user OCID from the OCI Console:**
- Navigate to: **Identity & Security** → **Users** → Click on your username → Copy the OCID
+ Navigate to: **Identity & Security** → **Users** → Click your username → Copy the OCID

diff --git a/docs/user-guide/providers/okta/authentication.mdx b/docs/user-guide/providers/okta/authentication.mdx
index 2e08cac8af..8f664160a2 100644
--- a/docs/user-guide/providers/okta/authentication.mdx
+++ b/docs/user-guide/providers/okta/authentication.mdx
@@ -20,7 +20,7 @@ Prowler authenticates to Okta as a **service application** using **OAuth 2.0 wit
| Method | Status | Use Case |
|---|---|---|
-| **OAuth 2.0 (private-key JWT)** | Supported | Production scans, CI/CD, Prowler App. |
+| **OAuth 2.0 (private-key JWT)** | Supported | Production scans, CI/CD, Prowler Cloud. |
The private-key JWT flow is the only supported authentication method in the initial release. The service application proves possession of a private key on every token request; Okta returns a short-lived access token, refreshed automatically by the SDK.
diff --git a/docs/user-guide/providers/okta/getting-started-okta.mdx b/docs/user-guide/providers/okta/getting-started-okta.mdx
index e04e0d4a13..dbe63807d7 100644
--- a/docs/user-guide/providers/okta/getting-started-okta.mdx
+++ b/docs/user-guide/providers/okta/getting-started-okta.mdx
@@ -30,7 +30,7 @@ Set up authentication for Okta with the [Okta Authentication](/user-guide/provid
### Step 1: Add the Provider
-1. Go to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler App](/user-guide/tutorials/prowler-app).
+1. Go to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler Local Server](/user-guide/tutorials/prowler-app).
2. Navigate to "Configuration" > "Providers".

diff --git a/docs/user-guide/providers/okta/retry-configuration.mdx b/docs/user-guide/providers/okta/retry-configuration.mdx
new file mode 100644
index 0000000000..1575cf6329
--- /dev/null
+++ b/docs/user-guide/providers/okta/retry-configuration.mdx
@@ -0,0 +1,123 @@
+---
+title: "Okta Rate Limit Configuration in Prowler"
+---
+
+import { VersionBadge } from "/snippets/version-badge.mdx"
+
+
+
+Prowler's Okta Provider manages API rate limits with two complementary controls:
+
+- **Request throttling (proactive):** Prowler paces outbound requests through a shared limiter so scans stay under Okta's rate limits and rarely trigger a rate-limit response in the first place.
+- **Retries (reactive):** When Okta still returns a rate-limit response (HTTP 429), the official Okta Python SDK reads the `X-Rate-Limit-Reset` header and waits until the window resets before retrying. This acts as a safety net for occasional bursts.
+
+Both controls are configurable through the configuration file or command line flags.
+
+## Request Throttling (Requests per Second)
+
+Throttling is the primary control for avoiding rate limits. Prowler limits the aggregate number of Okta API requests per second across every service in a scan.
+
+### Using the Command Line Flag
+
+```bash
+prowler okta --okta-requests-per-second 4
+```
+
+Set the value to `0` to disable throttling.
+
+### Using the Configuration File
+
+```yaml
+okta:
+ # Maximum aggregate Okta API requests per second. Default: 4. Set to 0 to disable.
+ okta_requests_per_second: 4
+```
+
+Okta enforces rate limits per endpoint, so this single global cap is a deliberately simple control. Lower the value if scans still hit limits on large organizations; raise it to scan faster when the organization has generous limits.
+
+## Retries
+
+Retries cover the cases throttling does not prevent, such as short bursts or per-endpoint limits lower than the global cap.
+
+### Using the Command Line Flag
+
+```bash
+prowler okta --okta-retries-max-attempts 8
+```
+
+### Using the Configuration File
+
+```yaml
+okta:
+ # Maximum retries on HTTP 429. Default: 5.
+ okta_max_retries: 8
+ # Per-request timeout in seconds. Default: 300.
+ okta_request_timeout: 300
+```
+
+The command line flags override the configuration file values.
+
+## How It Works
+
+- **Automatic detection:** The Okta SDK retries the retryable statuses 429, 503, and 504.
+- **Reset-aware backoff:** On a 429 response the SDK sleeps until the `X-Rate-Limit-Reset` window before each retry, rather than using a fixed delay.
+- **Bounded attempts:** `okta_max_retries` caps how many times a single request is retried. The Okta SDK default is 2, which is often too low for large organizations, so Prowler defaults to 5.
+
+## Request Timeout
+
+The `okta_request_timeout` setting plays a dual role in the Okta SDK:
+
+- It is the per-request socket timeout, bounding how long a single HTTP call can hang.
+- It is also the total wall-clock budget for the whole retry-and-backoff loop of one request.
+
+For this reason, the value defaults to 300 seconds rather than 0 (no timeout). A value of 0 leaves hung connections unbounded, while a value that is too low cuts the rate-limit waits short and reintroduces the errors. As a guideline, keep `okta_request_timeout` greater than or equal to `okta_max_retries` multiplied by 60 when raising the retry count, because Okta reset windows are typically up to one minute.
+
+## Error Example Handled
+
+```
+Okta HTTP 429: Too Many Requests. Hit rate limit. Retry request in 42 seconds.
+```
+
+## Validation
+
+### Debug Logging
+
+To confirm that throttling and retries are active, run a scan with debug logging:
+
+```bash
+prowler okta --okta-requests-per-second 4 --log-level DEBUG --log-file debuglogs.txt
+```
+
+### Check the Messages
+
+```bash
+grep -i "throttling\|rate limit\|retry" debuglogs.txt
+```
+
+### Expected Output
+
+When throttling is enabled, Prowler logs the configured rate at startup:
+
+```
+Okta request throttling enabled at 4 req/s
+```
+
+If a rate limit is still hit, the SDK logs the backoff:
+
+```
+Hit rate limit. Retry request in 42 seconds.
+```
+
+## Troubleshooting
+
+If scans continue to hit rate limits:
+
+1. Lower `--okta-requests-per-second` so requests are paced more conservatively.
+2. Raise `--okta-retries-max-attempts` (and keep `okta_request_timeout` proportionally large) so the safety net absorbs more bursts.
+3. Review the rate-limit allocation for the Okta organization and request an increase if needed.
+4. Verify throttling and retry behavior with debug logging.
+
+## Official References
+
+- [Okta Rate Limits](https://developer.okta.com/docs/reference/rate-limits/)
+- [Okta SDK for Python](https://github.com/okta/okta-sdk-python)
diff --git a/docs/user-guide/providers/vercel/getting-started-vercel.mdx b/docs/user-guide/providers/vercel/getting-started-vercel.mdx
index c39c5f1e6a..da02019b6f 100644
--- a/docs/user-guide/providers/vercel/getting-started-vercel.mdx
+++ b/docs/user-guide/providers/vercel/getting-started-vercel.mdx
@@ -28,7 +28,7 @@ Set up authentication for Vercel with the [Vercel Authentication](/user-guide/pr
### Step 1: Add the Provider
-1. Go to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler App](/user-guide/tutorials/prowler-app).
+1. Go to [Prowler Cloud](https://cloud.prowler.com/) or launch [Prowler Local Server](/user-guide/tutorials/prowler-app).
2. Navigate to "Configuration" > "Providers".

diff --git a/docs/user-guide/tutorials/aws-organizations-bulk-provisioning.mdx b/docs/user-guide/tutorials/aws-organizations-bulk-provisioning.mdx
index 88a084dd17..188ac3540d 100644
--- a/docs/user-guide/tutorials/aws-organizations-bulk-provisioning.mdx
+++ b/docs/user-guide/tutorials/aws-organizations-bulk-provisioning.mdx
@@ -9,9 +9,9 @@ The tool, `aws_org_generator.py`, complements the [Bulk Provider Provisioning
**Native AWS Organizations support is now available in Prowler Cloud.** You can onboard all accounts via the UI wizard — with automatic discovery, hierarchical tree selection, connection testing, and bulk scan launch — without any scripts or YAML files.
-See [AWS Organizations in Prowler Cloud](/user-guide/tutorials/prowler-cloud-aws-organizations).
+See [AWS Organizations](/user-guide/tutorials/prowler-cloud-aws-organizations) in Prowler Cloud.
-The CLI-based tool below remains useful for self-hosted Prowler App and advanced automation scenarios.
+The CLI-based tool below remains useful for Prowler Local Server and advanced automation scenarios.
{/* TODO: Add screenshot of the tool in action */}
@@ -32,9 +32,9 @@ The AWS Organizations Bulk Provisioning tool simplifies multi-account onboarding
* Python 3.7 or higher
* AWS credentials with Organizations read access
* ProwlerRole (or custom role) deployed across all target accounts
-* Prowler API key (from Prowler Cloud or self-hosted Prowler App)
- * For self-hosted Prowler App, remember to [point to your API base URL](./bulk-provider-provisioning#custom-api-endpoints)
- * Learn how to create API keys: [Prowler App API Keys](../tutorials/prowler-app-api-keys)
+* Prowler API key (from Prowler Cloud or Prowler Local Server)
+ * For Prowler Local Server, remember to [point to your API base URL](./bulk-provider-provisioning#custom-api-endpoints)
+ * Learn how to create API keys: [Prowler Cloud API Keys](../tutorials/prowler-app-api-keys)
### Deploying ProwlerRole Across AWS Organizations
@@ -97,13 +97,13 @@ export PROWLER_API_KEY="pk_example-api-key"
To create an API key:
-1. Log in to Prowler Cloud or Prowler App
+1. Log in to Prowler Cloud or Prowler Local Server
2. Click **Profile** → **Account**
3. Click **Create API Key**
4. Provide a descriptive name and optionally set an expiration date
5. Copy the generated API key (it will only be shown once)
-For detailed instructions, see: [Prowler App API Keys](../tutorials/prowler-app-api-keys)
+For detailed instructions, see: [Prowler Cloud API Keys](../tutorials/prowler-app-api-keys)
## Basic Usage
@@ -272,6 +272,8 @@ python aws_org_generator.py \
4. Deploy to all organizational units
5. Use a unique external ID (e.g., `prowler-org-2024-abc123`)
+ Alternatively, deploy the same template as a **single stack** with `DeployStackSet=true` and `AWSOrganizationalUnitId` set to your root/OU ID — it creates the StackSet for you. See [Native CloudFormation StackSet Deployment](../providers/aws/organizations#native-cloudformation-stackset-deployment-recommended).
+
{/* TODO: Add screenshot of CloudFormation StackSets deployment */}
@@ -324,7 +326,7 @@ python aws_org_generator.py \
- Provision all accounts to Prowler Cloud or Prowler App:
+ Provision all accounts to Prowler Cloud or Prowler Local Server:
```bash
# Set Prowler API key
@@ -487,7 +489,7 @@ grep "provider: aws" aws-org-accounts.yaml | wc -l
Learn how to bulk provision providers in Prowler.
-
+
Detailed instructions on how to use Prowler.
diff --git a/docs/user-guide/tutorials/bulk-provider-provisioning.mdx b/docs/user-guide/tutorials/bulk-provider-provisioning.mdx
index 3ad5d9c0d5..cc759b6f85 100644
--- a/docs/user-guide/tutorials/bulk-provider-provisioning.mdx
+++ b/docs/user-guide/tutorials/bulk-provider-provisioning.mdx
@@ -10,7 +10,7 @@ The tool is available in the Prowler repository at: [util/prowler-bulk-provision
## Overview
-The Bulk Provider Provisioning tool automates the creation of cloud providers in Prowler App or Prowler Cloud by:
+The Bulk Provider Provisioning tool automates the creation of cloud providers in Prowler Cloud or Prowler Local Server by:
* Reading provider configurations from YAML files
* Creating providers with appropriate authentication credentials
@@ -26,9 +26,9 @@ The Bulk Provider Provisioning tool automates the creation of cloud providers in
### Requirements
* Python 3.7 or higher
-* Prowler API key (from Prowler Cloud or self-hosted Prowler App)
- * For self-hosted Prowler App, remember to [point to your API base URL](#custom-api-endpoints)
- * Learn how to create API keys: [Prowler App API Keys](../tutorials/prowler-app-api-keys)
+* Prowler API key (from Prowler Cloud or Prowler Local Server)
+ * For Prowler Local Server, remember to [point to your API base URL](#custom-api-endpoints)
+ * Learn how to create API keys: [Prowler Cloud API Keys](../tutorials/prowler-app-api-keys)
* Authentication credentials for target cloud providers
### Installation
@@ -51,13 +51,13 @@ export PROWLER_API_KEY="pk_example-api-key"
To create an API key:
-1. Log in to Prowler Cloud or Prowler App
+1. Log in to Prowler Cloud or Prowler Local Server
2. Click **Profile** → **Account**
3. Click **Create API Key**
4. Provide a descriptive name and optionally set an expiration date
5. Copy the generated API key (it will only be shown once)
-For detailed instructions, see: [Prowler App API Keys](../tutorials/prowler-app-api-keys)
+For detailed instructions, see: [Prowler Cloud API Keys](../tutorials/prowler-app-api-keys)
## Configuration File Structure
@@ -261,7 +261,7 @@ python prowler_bulk_provisioning.py providers.yaml --concurrency 10
### Custom API Endpoints
-For self-hosted Prowler App installations:
+For Prowler Local Server installations:
```bash
python prowler_bulk_provisioning.py providers.yaml \
diff --git a/docs/user-guide/tutorials/prowler-alerts.mdx b/docs/user-guide/tutorials/prowler-alerts.mdx
index 3fa49f84ff..fc205b72be 100644
--- a/docs/user-guide/tutorials/prowler-alerts.mdx
+++ b/docs/user-guide/tutorials/prowler-alerts.mdx
@@ -1,17 +1,17 @@
---
title: 'Alerts'
+sidebarTitle: 'Alerts'
description: 'Create email alerts from Prowler Cloud findings to monitor relevant security changes after scans or in daily digests.'
---
import { VersionBadge } from "/snippets/version-badge.mdx"
+import { SubscriptionBanner } from "/snippets/subscription-banner.mdx"
Alerts notify recipients by email when security findings match saved filter conditions. Use Alerts to track high-priority findings, monitor specific providers or services, and keep teams informed about scan results that match defined criteria.
-
-This feature is available exclusively in **Prowler Cloud** and **Prowler Enterprise** with a [paid subscription](https://prowler.com/pricing).
-
+
## Prerequisites
diff --git a/docs/user-guide/tutorials/prowler-app-api-keys.mdx b/docs/user-guide/tutorials/prowler-app-api-keys.mdx
index 4e51e62bac..c7d5f86ec4 100644
--- a/docs/user-guide/tutorials/prowler-app-api-keys.mdx
+++ b/docs/user-guide/tutorials/prowler-app-api-keys.mdx
@@ -3,14 +3,17 @@ title: 'API Keys'
---
import { VersionBadge } from "/snippets/version-badge.mdx"
+import { AppliesTo } from "/snippets/applies-to.mdx"
-API key authentication in Prowler App provides an alternative to JWT tokens and empowers automation, CI/CD pipelines, and third-party integrations. This guide explains how to create, manage, and safeguard API keys when working with the Prowler API.
+
+
+API key authentication in Prowler Cloud provides an alternative to JWT tokens and empowers automation, CI/CD pipelines, and third-party integrations. This guide explains how to create, manage, and safeguard API keys when working with the Prowler API.
## API Key Advantages
-- **Programmatic access:** Enables automated workflows and scripts to interact with Prowler App.
+- **Programmatic access:** Enables automated workflows and scripts to interact with Prowler Cloud.
- **Long-lived authentication:** Allows optional expiration dates, with a default of 1 year.
- **Granular control:** Supports multiple keys with distinct names and purposes.
- **Secure automation:** Simplifies safe integration into CI/CD pipelines and infrastructure-as-code tooling.
@@ -19,7 +22,7 @@ API key authentication in Prowler App provides an alternative to JWT tokens and
API keys provide a secure authentication mechanism for accessing the Prowler API:
-1. API keys are created through Prowler App with a user-defined name and optional expiration date.
+1. API keys are created through Prowler Cloud with a user-defined name and optional expiration date.
2. The full API key appears only once upon creation and cannot be retrieved later.
3. Each API key consists of a prefix (visible in the interface) and an encrypted secret portion.
4. Requests include the API key in the header as `Authorization: Api-Key `.
@@ -63,13 +66,13 @@ Creating, viewing, or managing API keys requires the **MANAGE_ACCOUNT** RBAC per
Without this permission, the API Keys section remains hidden. Access requests should be routed through the tenant administrator.
-For more information about RBAC permissions, refer to the [Prowler App RBAC documentation](/user-guide/tutorials/prowler-app-rbac).
+For more information about RBAC permissions, refer to the [Prowler Cloud RBAC documentation](/user-guide/tutorials/prowler-app-rbac).
## Creating API Keys
-Follow these steps to create an API key in Prowler App:
+Follow these steps to create an API key in Prowler Cloud:
-1. Navigate to **Profile** → **Account** in Prowler App.
+1. Navigate to **Profile** → **Account** in Prowler Cloud.
2. Select the **Create API Key** button.

@@ -206,7 +209,7 @@ When using API keys in CI/CD pipelines:
* Ensure the key has not been revoked by checking the Revoked column in the API Keys list.
* Confirm that the key has not expired by reviewing the expiration date.
* Confirm that the correct API key format is in use, including both prefix and secret portions.
-* Verify that the key prefix matches what is displayed in Prowler App.
+* Verify that the key prefix matches what is displayed in Prowler Cloud.
### API Key Not Working After Creation
diff --git a/docs/user-guide/tutorials/prowler-app-attack-paths.mdx b/docs/user-guide/tutorials/prowler-app-attack-paths.mdx
index 23d8b8d5a2..22e56e5634 100644
--- a/docs/user-guide/tutorials/prowler-app-attack-paths.mdx
+++ b/docs/user-guide/tutorials/prowler-app-attack-paths.mdx
@@ -3,13 +3,16 @@ title: "Attack Paths"
description: "Identify privilege escalation chains and security misconfigurations across cloud environments using graph-based analysis."
---
-import { VersionBadge } from "/snippets/version-badge.mdx"
+import { VersionBadge } from "/snippets/version-badge.mdx";
+import { AppliesTo } from "/snippets/applies-to.mdx";
+
+
Attack Paths analyzes relationships between cloud resources, permissions, and security findings to detect how privileges can be escalated and how misconfigurations can be exploited by threat actors.
-By mapping these relationships as a graph, Attack Paths reveals risks that individual security checks cannot detect on their own — such as an IAM role that can escalate its own permissions, or a chain of policies that grants unintended access to sensitive resources.
+By mapping these relationships as a graph, Attack Paths reveals risks that individual security checks cannot detect on their own, such as an IAM role that can escalate its own permissions, or a chain of policies that grants unintended access to sensitive resources.
Attack Paths is currently available for **AWS** providers. Support for
@@ -20,14 +23,14 @@ By mapping these relationships as a graph, Attack Paths reveals risks that indiv
The following prerequisites are required for Attack Paths:
-- **An AWS provider is configured** with valid credentials in Prowler App. For setup instructions, see [Getting Started with AWS](/user-guide/providers/aws/getting-started-aws).
-- **At least one scan has completed** on the configured AWS provider. Attack Paths scans run automatically alongside regular security scans — no separate configuration is required.
+- **An AWS provider is configured** with valid credentials in Prowler Cloud. For setup instructions, see [Getting Started with AWS](/user-guide/providers/aws/getting-started-aws).
+- **At least one scan has completed** on the configured AWS provider and produced graph data. Attack Paths scans run automatically alongside regular security scans, no separate configuration is required.
## How Attack Paths Scans Work
Attack Paths scans are generated automatically when a security scan runs on an AWS provider. Each completed scan produces graph data that maps relationships between IAM principals, policies, trust configurations, and other resources.
-Once the scan finishes and the graph data is ready, the scan appears in the Attack Paths scan table with a **Completed** status. Scans that are still processing display as **Executing** or **Scheduled**.
+Once the scan finishes and graph data is ready, the scan appears in the Attack Paths scan table with a **Completed** status and a check in the **Graph** column. Scans that are still queued or running remain visible, but they cannot be selected until graph data is ready.
Since Prowler scans all configured providers every **24 hours** by default,
@@ -41,25 +44,28 @@ To open Attack Paths, click **Attack Paths** in the left navigation menu.
-The main interface is divided into two areas:
+The Attack Paths page guides you through the workflow on one page:
-- **Left panel:** A table listing all available Attack Paths scans
-- **Right panel:** The query selector, parameter form, and execute controls
+- Select a scan with graph data.
+- Choose a built-in query or a custom openCypher query.
+- Add parameters when the selected query requires them.
+- Execute the query and explore the resulting graph.
## Selecting a Scan
The scans table displays all Attack Paths scans with the following columns:
-- **Provider / Account:** The AWS provider alias and account identifier
-- **Last scan date:** When the scan completed
-- **Status:** Current state of the scan (Completed, Executing, Scheduled, or Failed)
-- **Progress:** Completion percentage for in-progress scans
-- **Duration:** Total scan time
+- **Select:** A radio button used to choose a scan. The radio button is disabled when graph data is not available.
+- **Provider:** The AWS provider alias and account identifier.
+- **Last Scan Date:** When the scan completed.
+- **Status:** Current state of the scan, such as **Completed**, **Executing**, **Scheduled**, or **Failed**.
+- **Graph:** Whether Attack Paths graph data is available for the scan.
+- **Duration:** Total scan time.
-To select a scan for analysis, click **Select** on any row with a **Completed** status.
+To select a scan for analysis, click the radio button on any row with a **Completed** status and available graph data.
- Only scans with a **Completed** status and ready graph data can be selected.
- Scans that are still executing or have failed appear with disabled action
- buttons.
+ Only scans with graph data can be selected. Disabled rows include a tooltip
+ that explains why the graph is not available yet.
## Choosing a Query
-After selecting a scan, the right panel activates a query dropdown. Each query targets a specific type of privilege escalation or misconfiguration pattern.
+After selecting a scan, the query selector becomes available. Each query targets a specific privilege escalation, exposure, inventory, or misconfiguration pattern.
To choose a query, click the dropdown and select from the available options. Each option displays:
-- **Query name:** A descriptive title (e.g., "IAM Privilege Escalation via AssumeRole")
-- **Short description:** A brief summary of what the query detects
+- **Query name:** A descriptive title, such as **Internet-Exposed EC2 with Sensitive S3 Access**.
+- **Short description:** A brief summary of what the query detects.
-Once selected, a description card appears below the dropdown with additional context about the query, including attribution links to external references when available.
+Once selected, a description panel appears below the dropdown with more context about the query.
## Configuring Query Parameters
-Some queries accept optional or required parameters to narrow the scope of the analysis. When a query has parameters, a dynamic form appears below the query description.
+Some queries accept optional or required parameters to narrow the scope of the analysis. When a query has parameters, a form appears below the query description.
-- **Required fields** are marked with an asterisk (\*) and must be filled before executing
-- **Optional fields** refine the query results but are not mandatory
+- **Required fields** are marked with an asterisk (\*) and must be filled before executing.
+- **Optional fields** refine the query results but are not mandatory.
+- Queries without parameters show no parameter form.
-If a query requires no parameters, the form displays a message confirming that the query is ready to execute.
+For example, **Internet-Exposed EC2 with Sensitive S3 Access** uses **Tag key** and **Tag value** fields to identify sensitive S3 buckets.
(policy:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {effect: 'Allow'})
+MATCH (stmt)-[:HAS_ACTION]->(a:AWSPolicyStatementActionItem)
+WHERE a.value = '*'
+RETURN DISTINCT principal.arn AS principal, policy.arn AS policy
LIMIT 25
```
@@ -173,218 +178,89 @@ RETURN r.name AS role_name, r.arn AS role_arn, p.arn AS trusted_service
LIMIT 25
```
-### Advanced Attack Path Scenarios
+### Working with List-Typed Properties
-The following scenarios show how to compose graph traversals into real attack-path stories. Each query can be pasted directly into the custom query box: the API auto-scopes them to the selected provider and injects tenant/provider isolation, so there is no need to include account identifiers or `$provider_uid` in the text. All queries are openCypher v9 (Neo4j and Neptune compatible).
+Some Cartography node properties carry a list of values, such as `action`, `resource`, `notaction`, and `notresource` on `AWSPolicyStatement` nodes, the algorithms on `KMSKey`, the container-definition lists on `ECSContainerDefinition`, and many others. The Attack Paths graph models each such property as a set of child item nodes connected to the parent by a typed edge. To read the values, traverse the edge; the parent does not carry the list as a single field.
-#### 1. Live attacker on the box that owns the keys
+The naming convention for any list-typed property on a parent label is:
-**Query story:** Finds an internet-exposed EC2 under an active GuardDuty SSH brute-force whose instance role can assume a higher-privileged role that can read a sensitive S3 bucket.
+- **Child label:** `Item`. Example: `AWSPolicyStatement.resource` resolves to `AWSPolicyStatementResourceItem`.
+- **Edge type:** `HAS_`. Example: `resource` resolves to `HAS_RESOURCE`.
+- **Child property:** `value` for scalar lists (one string per list element). List-of-dict properties (rare; for example `SecretsManagerSecretVersion.tags`) carry the original dict keys as named fields on the child node.
+
+To express "at least one item in the list satisfies a predicate", traverse the `HAS_*` edge in its own `MATCH` clause and apply the predicate in the attached `WHERE`. `RETURN DISTINCT` collapses duplicate parent rows produced when multiple child items satisfy the filter:
```cypher
-MATCH path_ec2 = (acct:AWSAccount)--(ec2:EC2Instance)
-WHERE ec2.exposed_internet = true
-MATCH p0 = (gd:GuardDutyFinding)-[:AFFECTS]->(ec2)
-MATCH p1 = (ec2)-[:INSTANCE_PROFILE]->(prof:AWSInstanceProfile)-[:ASSOCIATED_WITH]->(low:AWSRole)
-MATCH p2 = (low)-[:STS_ASSUMEROLE_ALLOW]-(high:AWSRole)
-MATCH p3 = (high)--(pol:AWSPolicy)--(stmt:AWSPolicyStatement)
-OPTIONAL MATCH path_net = (internet:Internet)-[:CAN_ACCESS]->(ec2)
-MATCH path_s3 = (acct)--(s3:S3Bucket)
-WHERE high <> low
- AND stmt.effect = 'Allow'
- AND size([a IN stmt.action WHERE
- toLower(a) STARTS WITH 's3:getobject'
- OR toLower(a) STARTS WITH 's3:listbucket'
- OR toLower(a) IN ['s3:*']
- ]) > 0
- AND size([r IN stmt.resource WHERE
- r CONTAINS s3.name
- ]) > 0
-RETURN path_net, path_ec2, p0, p1, p2, p3, path_s3
-```
-
-**How it's built:**
-
-- `path_ec2` anchors the graph on the account node and its internet-exposed EC2 instance, via a real account-to-resource edge. This is the visible spine that keeps everything connected.
-- `p0` ties a `GuardDutyFinding` to that instance through the `AFFECTS` edge (the live SSH brute-force alert).
-- `p1` walks the real graph edges from the instance to its instance profile to the role it runs as.
-- `p2` follows the `STS_ASSUMEROLE_ALLOW` edge to the higher-privileged role the low role can assume. It is undirected so it works regardless of how the assume edge was ingested. `high <> low` stops a role matching itself.
-- `p3` walks that role into its policy and policy statement.
-- `path_net` is the optional `Internet -[:CAN_ACCESS]-> instance` edge. It makes "from the internet" literal on screen. Optional so a missing `Internet` node never breaks the query live.
-- `path_s3` connects the sensitive bucket to the same account node, so it draws connected instead of floating. There is no physical edge from a role to a bucket; the grant is logical, enforced in the `WHERE`: the statement must allow an S3 read action (list comprehension over the `action` array) and its resource must cover the bucket (`CONTAINS s3.name`). The account is the shared hub; the bucket hanging off it next to the role chain is the teaching moment — the access exists only in IAM.
-
-#### 2. Who can read the crown jewels
-
-**Query story:** The sensitive bucket from the previous scenario seen from the data side: every role whose IAM policy can read it, regardless of how the role is reached.
-
-```cypher
-MATCH (s3:S3Bucket)
-WHERE toLower(s3.name) CONTAINS 'sensitive'
-MATCH (role:AWSRole)--(pol:AWSPolicy)--(stmt:AWSPolicyStatement)
-WHERE stmt.effect = 'Allow'
- AND size([a IN stmt.action WHERE
- toLower(a) STARTS WITH 's3:get'
- OR toLower(a) STARTS WITH 's3:list'
- OR toLower(a) IN ['s3:*']
- ]) > 0
- AND size([r IN stmt.resource WHERE
- r CONTAINS s3.name
- ]) > 0
-WITH DISTINCT s3, role
+MATCH (stmt:AWSPolicyStatement {effect: 'Allow'})
+MATCH (stmt)-[:HAS_ACTION]->(a:AWSPolicyStatementActionItem)
+WHERE toLower(a.value) STARTS WITH 's3:get'
+ OR toLower(a.value) STARTS WITH 's3:list'
+RETURN DISTINCT stmt
LIMIT 25
-MATCH path_s3 = (acct:AWSAccount)--(s3)
-MATCH path_role = (acct)--(role)
-RETURN path_s3, path_role
```
-**How it's built:** data-centric, not attacker-centric — the same bucket the previous kill chain exfiltrates, approached from the other direction.
-
-- The `S3Bucket` is bound first by name (one node), so everything else filters against it.
-- `(role:AWSRole)--(pol:AWSPolicy)--(stmt:AWSPolicyStatement)` reaches statements only *through a role*, never via a global statement scan. A blanket `AWSPolicyStatement` scan also hits resource-policy statements whose shape differs and makes the list comprehension fail outright.
-- The `WHERE` filters in place: an S3 read action plus a resource that names that bucket.
-- `WITH DISTINCT s3, role LIMIT 25` collapses undirected-traversal duplicates and hard-caps the result.
-- `path_s3` and `path_role` attach the account hubs only after the cap, against at most 25 rows, so the bucket and role(s) draw connected through the account instead of floating.
-- No internet or EC2 here; this answers "who has the keys" instead of "how would an attacker get in."
-
-#### 3. Lateral reach from an internet-exposed instance
-
-**Query story:** The wide-angle view of the live-attacker scenario: every internet-exposed EC2, the role it runs as, and every role that role can assume. The first scenario is one specific exfiltration path inside this reach, under live attack.
+To check whether every item in the list satisfies a predicate, count the counter-examples and require zero, together with a guard that ensures at least one item is attached. This is the one case where the pattern-comprehension form is the right tool:
```cypher
-MATCH path_ec2 = (acct:AWSAccount)--(ec2:EC2Instance)
-WHERE ec2.exposed_internet = true
-MATCH p1 = (ec2)-[:INSTANCE_PROFILE]->(prof:AWSInstanceProfile)-[:ASSOCIATED_WITH]->(low:AWSRole)
-MATCH p2 = (low)-[:STS_ASSUMEROLE_ALLOW]-(high:AWSRole)
-OPTIONAL MATCH path_net = (internet:Internet)-[:CAN_ACCESS]->(ec2)
-WHERE high <> low
-RETURN path_net, path_ec2, p1, p2
+MATCH (stmt:AWSPolicyStatement)
+WHERE size([
+ (stmt)-[:HAS_ACTION]->(a:AWSPolicyStatementActionItem)
+ WHERE NOT toLower(a.value) STARTS WITH 's3:'
+ | a
+ ]) = 0
+ AND size([(stmt)-[:HAS_ACTION]->(a:AWSPolicyStatementActionItem) | a]) > 0
+RETURN stmt
+LIMIT 25
```
-**How it's built:** widens the lens instead of filtering down. It stops at the assume-role hop and shows every role reachable from any internet-exposed instance, without filtering down to a specific S3 leg.
-
-- `path_ec2` is the account-to-instance spine.
-- `p1` walks to the instance role.
-- `p2` fans out to every role that role can assume.
-- `path_net` adds the optional `Internet -[:CAN_ACCESS]->` edge.
-- The first scenario is the specific exfiltration path under live attack; this is the broader privilege reach an attacker inherits the moment they land on the box.
-
-#### 4. Role-chain privilege escalation
-
-**Query story:** A pure-IAM escalation, no compromised instance: a role that can assume a second role whose policy lets it assume a third, admin-level role.
+For the "is any item of this list a substring of a dynamic value" case, such as "does any resource pattern in this policy match a target role ARN", add the `HAS_*` traversal as its own `MATCH` and check the substring relationship between the item value and the dynamic node in `WHERE`:
```cypher
-MATCH path_root = (acct:AWSAccount)--(r1:AWSRole)
-MATCH p1 = (r1)-[:STS_ASSUMEROLE_ALLOW]-(r2:AWSRole)
-MATCH p2 = (r2)--(pol:AWSPolicy)--(stmt:AWSPolicyStatement)
-MATCH path_admin = (acct)--(admin:AWSRole)
-WHERE r1 <> r2 AND r1 <> admin AND r2 <> admin
- AND stmt.effect = 'Allow'
- AND size([a IN stmt.action WHERE
- toLower(a) IN ['sts:*', 'sts:assumerole']
- ]) > 0
- AND size([res IN stmt.resource WHERE
- res CONTAINS admin.name
- ]) > 0
-RETURN path_root, p1, p2, path_admin
+MATCH (role:AWSRole)
+WHERE role.name = 'Admin'
+MATCH (principal:AWSPrincipal)-[:POLICY]->(:AWSPolicy)-[:STATEMENT]->(stmt:AWSPolicyStatement {effect: 'Allow'})
+MATCH (stmt)-[:HAS_RESOURCE]->(r:AWSPolicyStatementResourceItem)
+WHERE r.value = '*'
+ OR r.value CONTAINS role.name
+ OR role.arn CONTAINS r.value
+RETURN DISTINCT principal.arn AS principal, stmt, role
+LIMIT 25
```
-**How it's built:**
-
-- `path_root` anchors role 1 to the account node, the spine that keeps the picture connected.
-- `p1` is the one real assume edge in the chain (role 1 to role 2).
-- `p2` walks role 2 into its policy and statement.
-- `path_admin` connects the target admin role to the same account node so it draws connected. The third hop is not a graph edge: it exists only as `sts:AssumeRole` on that role's ARN inside the statement. The query proves it the same way the first scenario proves S3 access — the statement action must include an assume-role action and its resource list must reference the admin role's name.
-- The three `<>` guards stop a role matching itself at any position.
-
-#### 5. External identity trust map
-
-**Query story:** Finds external identity providers (SSO, GitHub, GitLab, Terraform Cloud) and the AWS roles they are trusted to assume.
+To return the list of values directly, collect them from the child items:
```cypher
-MATCH p = (role:AWSRole)-[:TRUSTS_AWS_PRINCIPAL]-(idp:AWSPrincipal)
-WHERE idp.arn CONTAINS 'saml-provider'
- OR idp.arn CONTAINS 'oidc-provider'
-MATCH path_role = (acct:AWSAccount)--(role)
-RETURN p, path_role
+MATCH (stmt:AWSPolicyStatement {effect: 'Allow'})
+OPTIONAL MATCH (stmt)-[:HAS_ACTION]->(a:AWSPolicyStatementActionItem)
+RETURN stmt, collect(a.value) AS actions
+LIMIT 25
```
-**How it's built:** federated principals are stored as `AWSPrincipal` nodes whose ARN contains `saml-provider` (SSO) or `oidc-provider` (GitHub, GitLab, Terraform Cloud).
+### Working with JSON-Encoded Properties
-- `p` matches the trust edge undirected. It is written `(AWSRole)-[:TRUSTS_AWS_PRINCIPAL]->(AWSPrincipal)`, role to principal, so a directed `principal -> role` match returns nothing; undirected matches regardless of ingest direction.
-- The `WHERE` keeps only SAML or OIDC providers, drawing a fan-out from each external identity provider to every role it can assume (including reserved SSO admin roles).
-- `path_role` ties every trusted role to the account node so the provider stars share one spine instead of drawing as separate islands.
+Some Cartography properties represent nested objects, most notably `condition` on `AWSPolicyStatement` and `S3PolicyStatement` nodes. In the Attack Paths graph, object-typed properties are stored as JSON-encoded strings to keep the schema portable across graph backends. The value looks like:
-#### 6. Federated SSO roles flagged as admin or privesc
+```
+'{"StringEquals":{"aws:SourceAccount":"123456789012"}}'
+```
-**Query story:** The dangerous subset of the trust map above — externally-federated SSO roles that Prowler also flags for AdministratorAccess or privilege escalation.
+There is no JSON parser available at query time, so use `CONTAINS` for substring checks against keys or known values:
```cypher
-MATCH (idp:AWSPrincipal)-[:TRUSTS_AWS_PRINCIPAL]-(role:AWSRole)
-WHERE idp.arn CONTAINS 'saml-provider'
- OR idp.arn CONTAINS 'oidc-provider'
-MATCH (role)-[:HAS_FINDING]-(pf:ProwlerFinding)
-WHERE pf.status = 'FAIL'
- AND pf.check_id IN [
- 'iam_inline_policy_allows_privilege_escalation',
- 'iam_role_administratoraccess_policy',
- 'iam_inline_policy_no_administrative_privileges',
- 'iam_user_administrator_access_policy'
- ]
-WITH DISTINCT idp, role, pf
-LIMIT 60
-MATCH path_root = (acct:AWSAccount)--(role)
-MATCH p_trust = (idp)-[:TRUSTS_AWS_PRINCIPAL]-(role)
-MATCH p_find = (role)-[:HAS_FINDING]-(pf)
-RETURN path_root, p_trust, p_find
+MATCH (stmt:AWSPolicyStatement)
+WHERE stmt.effect = 'Allow'
+ AND stmt.condition CONTAINS '"aws:SourceAccount"'
+RETURN stmt
+LIMIT 25
```
-**How it's built:** a plain "list every flagged identity" query is a wide fan that draws as a column, and `ProwlerFinding` nodes accumulate across scans with no scan filter available in custom queries.
-
-- The first MATCH plus `WHERE` keeps only roles trusted by a SAML or OIDC provider (trust edge undirected, so direction does not matter).
-- The second MATCH plus `check_id IN [...]` keeps only those carrying one of the four privilege-escalation or admin checks.
-- `WITH DISTINCT ... LIMIT 60` collapses duplicate finding nodes and hard-caps the result.
-- `p_trust`, `p_find`, and `path_root` draw it connected three ways: provider to role through the trust edge, role to its finding, and role to the account.
-- The previous scenario shows who can walk in; this shows which of those roles Prowler already flags as over-privileged.
-
-#### 7. World-readable S3 buckets
-
-**Query story:** Unlike the IAM-gated sensitive bucket in scenarios 1 and 2, these buckets are open to anyone on the internet with no credentials at all.
-
-```cypher
-MATCH path_s3 = (acct:AWSAccount)--(s3:S3Bucket)
-WHERE s3.anonymous_access = true
-OPTIONAL MATCH p = (s3)--(stmt:S3PolicyStatement)
-RETURN path_s3, p
-```
-
-**How it's built:** the counterpoint to scenarios 1 and 2 — there the sensitive bucket is reachable only through an IAM role chain; here the bucket needs no role at all.
-
-- `path_s3` connects each public bucket to its account node so they draw connected. Cartography sets `anonymous_access = true` when a bucket's policy or ACL allows public access.
-- `p` is an optional match that pulls in the `S3PolicyStatement` granting the access where one exists, so the public grant is visible next to the bucket. Buckets that are public via ACL only still show, connected to the account.
-
-#### 8. Internet exposure surface
-
-**Query story:** The raw external attack surface behind scenarios 1 and 3: every internet-exposed EC2 instance with its security groups and the exact inbound ports left open.
-
-```cypher
-MATCH path_ec2 = (acct:AWSAccount)--(ec2:EC2Instance)
-WHERE ec2.exposed_internet = true
-MATCH p1 = (ec2)--(sg:EC2SecurityGroup)--(rule:IpPermissionInbound)
-OPTIONAL MATCH path_net = (internet:Internet)-[:CAN_ACCESS]->(ec2)
-OPTIONAL MATCH p2 = (ec2)-[:INSTANCE_PROFILE]->(:AWSInstanceProfile)-[:ASSOCIATED_WITH]->(:AWSRole)
-RETURN path_net, path_ec2, p1, p2
-```
-
-**How it's built:** `exposed_internet = true` is Cartography's computed reachability flag.
-
-- `path_ec2` hubs all exposed instances on the account node so they draw as one picture.
-- `p1` joins each instance to its security groups and inbound rules so the open ports are on screen.
-- `path_net` adds the optional `Internet -[:CAN_ACCESS]->` edge so the external reachability is explicit.
-- `p2` optionally adds the instance role, which connects this surface view back to the kill chains in scenarios 1 and 3.
+When a query needs to inspect the structured members of a condition (for example, evaluate every operator and key), fetch the rows first and parse the JSON in application code. Cypher cannot navigate JSON object keys or values.
### Tips for Writing Queries
- Start small with `LIMIT` to inspect the shape of the data before broadening the pattern.
+- Traverse `HAS_*` edges to reach list-typed property values (for example `action`, `resource`). The parent node does not carry the list as a single field; see [Working with List-Typed Properties](#working-with-list-typed-properties) for the patterns.
+- On large scans, avoid broad disconnected patterns such as `MATCH (a:Label), (b:OtherLabel)`. Bind one side with a selective predicate first, and use `WITH DISTINCT` between expanding traversals when duplicates are possible.
- Use `RETURN` projections (`RETURN n.name, n.region`) instead of returning whole nodes to keep responses compact.
- Combine resource nodes with `ProwlerFinding` nodes via `HAS_FINDING` to correlate misconfigurations with the affected resources.
- When a query times out or returns no rows, simplify the pattern step by step until the first variant runs successfully, then add constraints back.
@@ -401,64 +277,88 @@ In addition to the upstream schema, Prowler enriches the graph with:
- **`ProwlerFinding`** nodes representing Prowler check results, linked to affected resources via `HAS_FINDING` relationships.
- **`Internet`** nodes used to model exposure paths from the public internet to internal resources.
+- **List-typed properties** such as `action` or `resource` on `AWSPolicyStatement`, the algorithm lists on `KMSKey`, and similar lists on other node types are modeled as child item nodes linked by typed `HAS_*` edges. See [Working with List-Typed Properties](#working-with-list-typed-properties) for the read pattern.
+- **Object-typed properties** such as `condition` on `AWSPolicyStatement` are stored as JSON-encoded strings. See [Working with JSON-Encoded Properties](#working-with-json-encoded-properties) for the read pattern.
AI assistants connected through Prowler MCP Server can fetch the exact
Cartography schema for the active scan via the
- `prowler_app_get_attack_paths_cartography_schema` tool. This guarantees that
+ `prowler_get_attack_paths_cartography_schema` tool. This guarantees that
generated queries match the schema version pinned by the running Prowler
release.
## Executing a Query
-To run the selected query against the scan data, click **Execute Query**. The button displays a loading state while the query processes.
+To run the selected query against the scan data, click **Execute Query**. The button is disabled until a query is selected and all required parameters are valid.
+
+The button displays a loading state while the query runs. After the query completes, the graph appears below the query builder.
If the query returns no results, an informational message appears. Common reasons include:
-- **No matching patterns found:** The scanned environment does not contain the privilege escalation chain the query targets
-- **Insufficient permissions:** The scan credentials may not have captured all the data the query needs
+- **No matching patterns found:** The scanned environment does not contain the pattern the query targets.
+- **Not enough permissions:** The scan credentials may not have captured all the data the query needs.
+- **Server unavailable:** The graph service may be temporarily unavailable.
## Exploring the Graph
-After a successful execution, the graph visualization renders below the query builder in a full-width panel. The graph maps relationships between cloud resources, IAM entities, and security findings.
+After a successful execution, the graph visualization renders below the query builder. The graph maps relationships between cloud resources, IAM entities, public exposure, and security findings.
### Node Types
-- **Resource nodes** (rounded pills): Represent cloud resources such as IAM roles, policies, EC2 instances, and S3 buckets. Each resource type has a distinct color.
-- **Finding nodes** (hexagons): Represent Prowler security findings linked to resources in the graph. Colors indicate severity level (critical, high, medium, low).
+- **Provider root nodes:** Represent the AWS account or provider root for the selected scan.
+- **Resource nodes:** Represent cloud resources such as IAM roles, policies, EC2 instances, security groups, and S3 buckets.
+- **Internet nodes:** Represent exposure from the public internet.
+- **Finding nodes:** Represent Prowler findings linked to resources. Finding colors indicate risk level, such as critical, high, medium, or low.
### Edge Types
-- **Solid lines:** Direct relationships between resources (e.g., a role attached to a policy)
-- **Dashed lines:** Connections between resources and their associated findings
+- **Normal edges:** Direct relationships between graph nodes, such as role-to-policy or resource-to-security-group relationships.
+- **Finding edges:** Dashed relationships between resources and their associated findings.
+- **Highlighted paths:** Green edges that show the active path when you hover a node or focus a finding.
-A **legend** at the bottom of the graph lists all node types and edge types present in the current view.
+The standard graph view includes a minimap and a legend below the canvas. The legend shows the provider roots, visible node types, finding risk levels, node states, and edge types present in the current view.
## Interacting with the Graph
-### Filtering by Node
+The graph banner describes the main interactions:
-Click any node in the graph to filter the view and display only paths that pass through that node. When a filter is active:
+- Click a finding to focus its connected path.
+- Click a resource with findings to show or hide its related findings.
+- Hover a node to highlight its connected path.
-- An information banner shows which node is selected
-- Click **Back to Full View** to restore the complete graph
+### Showing Related Findings
+
+Resource nodes with related findings are clickable. Click one of these resources to show its finding nodes. Click the resource again to hide them.
+
+The graph automatically fits the selected resource and its related findings when the findings are shown.
+
+### Focusing a Finding Path
+
+Click a finding node to focus the graph on the path connected to that finding. When the graph is focused:
+
+- The graph shows **Back to Full View**.
+- The status banner shows the selected finding.
+- The graph keeps only the connected path in view.
+- The finding detail drawer opens.
+
+After you close the drawer, the graph remains focused on the selected path.
@@ -467,29 +367,29 @@ Click any node in the graph to filter the view and display only paths that pass
The toolbar in the top-right corner of the graph provides:
- **Zoom in / Zoom out:** Adjust the zoom level
-- **Fit to screen:** Reset the view to fit all nodes
-- **Export:** Download the current graph as an SVG file
-- **Fullscreen:** Open the graph in a full-screen modal with a side-by-side node detail panel
+- **Fit graph to view:** Reset the view to fit the visible graph
+- **Export graph:** Download the current graph as a PNG file
+- **Fullscreen:** Open the graph in a full-size modal
Use **Ctrl + Scroll** (or **Cmd + Scroll** on macOS) to zoom directly within
the graph area.
-## Viewing Node Details
+## Viewing Finding Details
-Click any node to open the **Node Details** panel below the graph. This panel displays:
+Click a finding node to open the finding detail drawer. The drawer uses the same finding detail layout as the Findings page and includes:
-- **Node type:** The resource category (e.g., "IAM Role," "EC2 Instance")
-- **Properties:** All attributes of the selected node, including identifiers, timestamps, and configuration details
-- **Related findings** (for resource nodes): A list of Prowler findings linked to the resource, with severity, title, and status
-- **Affected resources** (for finding nodes): A list of resources associated with the finding
+- The finding title, status, and severity.
+- The affected resource summary.
+- Overview, remediation, evidence, related findings, scans, and events tabs when data is available.
+- A Lighthouse AI action when the account has access to Lighthouse AI.
-For finding nodes, a "View Finding" button links directly to the finding detail page for further investigation.
+Resource nodes do not open a node detail panel. When a resource has related findings, clicking it expands or collapses those finding nodes in the graph.
@@ -497,16 +397,28 @@ For finding nodes, a "View Finding" button links directly to the finding detail
To expand the graph for detailed exploration, click the fullscreen icon in the graph toolbar. The fullscreen modal provides:
-- The full graph visualization with all zoom and export controls
-- A side panel for node details that appears when a node is selected
-- All filtering and interaction capabilities available in the standard view
+- The graph in a full-size modal.
+- The same zoom, fit, and export controls.
+- The same node expansion, finding focus, hover highlight, and minimap interactions available in the standard view.
+## Available Queries
+
+The query selector includes custom openCypher and built-in AWS queries for common security investigation workflows. Available queries are loaded from the selected scan and may change as new query packs are added.
+
+Available queries include:
+
+- **Custom openCypher query:** Write and run a read-only graph query.
+- **Exposure queries:** Find internet-exposed EC2 instances, load balancers, open security groups, and resources by public IP.
+- **Inventory queries:** List resources such as RDS instances.
+- **Misconfiguration queries:** Find unencrypted RDS instances, public S3 buckets, and wildcard IAM statements.
+- **Privilege escalation queries:** Detect IAM and AWS service paths based on known attack techniques, including queries based on [pathfinding.cloud](https://pathfinding.cloud) research by Datadog.
+
## Using Attack Paths with the MCP Server and Lighthouse AI
Attack Paths capabilities are also available through the [Prowler MCP Server](/getting-started/products/prowler-mcp), enabling interaction with Attack Paths data via AI assistants like Claude Desktop, Cursor, and other MCP clients.
@@ -515,10 +427,10 @@ Attack Paths capabilities are also available through the [Prowler MCP Server](/g
The following MCP tools are available for Attack Paths:
-- **`prowler_app_list_attack_paths_scans`** - List and filter Attack Paths scans
-- **`prowler_app_list_attack_paths_queries`** - Discover available queries for a completed scan
-- **`prowler_app_run_attack_paths_query`** - Execute a query and retrieve graph results with nodes and relationships
-- **`prowler_app_get_attack_paths_cartography_schema`** - Retrieve the Cartography graph schema for custom openCypher queries
+- **`prowler_list_attack_paths_scans`** - List and filter Attack Paths scans.
+- **`prowler_list_attack_paths_queries`** - Discover available queries for a completed scan.
+- **`prowler_run_attack_paths_query`** - Execute a query and retrieve graph results with nodes and relationships.
+- **`prowler_get_attack_paths_cartography_schema`** - Retrieve the Cartography graph schema for custom openCypher queries.
### Example Questions
@@ -533,111 +445,8 @@ Ask through the MCP Server or Lighthouse AI:
- "Are there any CloudFormation stacks that could be hijacked for privilege escalation?"
- "Show me all roles that can be assumed for lateral movement"
-### Supported Queries
-
-Attack Paths currently supports the following built-in queries for AWS:
-
-#### Custom Attack Path Queries
-
-| Query | Description |
-|---|---|
-| **Internet-Exposed EC2 with Sensitive S3 Access** | Find SSH-exposed EC2 instances that can assume roles to read tagged sensitive S3 buckets |
-
-#### Basic Resource Queries
-
-| Query | Description |
-|---|---|
-| **RDS Instances Inventory** | List all provisioned RDS database instances in the account |
-| **Unencrypted RDS Instances** | Find RDS instances with storage encryption disabled |
-| **S3 Buckets with Anonymous Access** | Find S3 buckets that allow anonymous access |
-| **IAM Statements Allowing All Actions** | Find IAM policy statements that allow all actions via wildcard (\*) |
-| **IAM Statements Allowing Policy Deletion** | Find IAM policy statements that allow iam:DeletePolicy |
-| **IAM Statements Allowing Create Actions** | Find IAM policy statements that allow any create action |
-
-#### Network Exposure Queries
-
-| Query | Description |
-|---|---|
-| **Internet-Exposed EC2 Instances** | Find EC2 instances flagged as exposed to the internet |
-| **Open Security Groups on Internet-Facing Resources** | Find internet-facing resources with security groups allowing inbound from 0.0.0.0/0 |
-| **Internet-Exposed Classic Load Balancers** | Find Classic Load Balancers exposed to the internet with their listeners |
-| **Internet-Exposed ALB/NLB Load Balancers** | Find ELBv2 (ALB/NLB) load balancers exposed to the internet with their listeners |
-| **Resource Lookup by Public IP** | Find the AWS resource associated with a given public IP address |
-
-#### Privilege Escalation Queries
-
-These queries are based on research from [pathfinding.cloud](https://pathfinding.cloud) by Datadog.
-
-| Query | Description |
-|---|---|
-| **App Runner Service Creation with Privileged Role (APPRUNNER-001)** | Create an App Runner service with a privileged IAM role to gain its permissions |
-| **App Runner Service Update for Role Access (APPRUNNER-002)** | Update an existing App Runner service to leverage its already-attached privileged role |
-| **Bedrock Code Interpreter with Privileged Role (BEDROCK-001)** | Create a Bedrock AgentCore Code Interpreter with a privileged role attached |
-| **Bedrock Code Interpreter Session Hijacking (BEDROCK-002)** | Start a session on an existing Bedrock code interpreter to exfiltrate its privileged role credentials |
-| **CloudFormation Stack Creation with Privileged Role (CLOUDFORMATION-001)** | Create a CloudFormation stack with a privileged role to provision arbitrary AWS resources |
-| **CloudFormation Stack Update for Role Access (CLOUDFORMATION-002)** | Update an existing CloudFormation stack to leverage its already-attached privileged service role |
-| **CloudFormation StackSet Creation with Privileged Role (CLOUDFORMATION-003)** | Create a CloudFormation StackSet with a privileged execution role to provision arbitrary resources across accounts |
-| **CloudFormation StackSet Update with Privileged Role (CLOUDFORMATION-004)** | Update an existing CloudFormation StackSet to inject malicious resources using a privileged execution role |
-| **CloudFormation Change Set Privilege Escalation (CLOUDFORMATION-005)** | Create and execute a change set on an existing stack to leverage its privileged service role |
-| **CodeBuild Project Creation with Privileged Role (CODEBUILD-001)** | Create a CodeBuild project with a privileged role to execute arbitrary code via a malicious buildspec |
-| **CodeBuild Buildspec Override for Role Access (CODEBUILD-002)** | Start a build on an existing CodeBuild project with a buildspec override to execute code with its privileged role |
-| **CodeBuild Batch Buildspec Override for Role Access (CODEBUILD-003)** | Start a batch build on an existing CodeBuild project with a buildspec override to execute code with its privileged role |
-| **CodeBuild Batch Project Creation with Privileged Role (CODEBUILD-004)** | Create a CodeBuild project configured for batch builds with a privileged role to execute arbitrary code via a malicious buildspec |
-| **Data Pipeline Creation with Privileged Role (DATAPIPELINE-001)** | Create a Data Pipeline with a privileged role to execute arbitrary commands on provisioned infrastructure |
-| **EC2 Instance Launch with Privileged Role (EC2-001)** | Launch EC2 instances with privileged IAM roles to gain their permissions via IMDS |
-| **EC2 Role Hijacking via UserData Injection (EC2-002)** | Inject malicious scripts into EC2 instance userData to gain the attached role's permissions |
-| **Spot Instance Launch with Privileged Role (EC2-003)** | Launch EC2 Spot Instances with privileged IAM roles to gain their permissions via IMDS |
-| **Launch Template Poisoning for Role Access (EC2-004)** | Inject malicious userData into launch templates that reference privileged roles, no PassRole needed |
-| **EC2 Instance Connect SSH Access for Role Credentials (EC2INSTANCECONNECT-003)** | Push a temporary SSH key to an EC2 instance via Instance Connect to access its attached role credentials through IMDS |
-| **ECS Service Creation with Privileged Role (ECS-001 - New Cluster)** | Create an ECS cluster and service with a privileged Fargate task role to execute arbitrary code |
-| **ECS Task Execution with Privileged Role (ECS-002 - New Cluster)** | Create an ECS cluster and run a one-off Fargate task with a privileged role to execute arbitrary code |
-| **ECS Service Creation with Privileged Role (ECS-003 - Existing Cluster)** | Deploy a Fargate service with a privileged role on an existing ECS cluster |
-| **ECS Task Execution with Privileged Role (ECS-004 - Existing Cluster)** | Run a one-off Fargate task with a privileged role on an existing ECS cluster |
-| **ECS Task Start with Privileged Role on EC2 (ECS-005 - Existing Cluster)** | Register a task definition with a privileged role and start it on an EC2 container instance to execute arbitrary code |
-| **ECS Exec Container Hijacking for Role Credentials (ECS-006)** | Shell into a running ECS container via ECS Exec to steal the attached task role's credentials |
-| **Glue Dev Endpoint with Privileged Role (GLUE-001)** | Create a Glue development endpoint with a privileged role attached to gain its permissions |
-| **Glue Dev Endpoint SSH Hijacking via Update (GLUE-002)** | Update an existing Glue development endpoint to inject an SSH public key and access its attached role credentials |
-| **Glue Job Creation with Privileged Role (GLUE-003)** | Create a Glue job with a privileged role and start it to execute arbitrary code with that role's permissions |
-| **Glue Job Creation with Scheduled Trigger and Privileged Role (GLUE-004)** | Create a Glue job with a privileged role and a scheduled trigger to persistently execute arbitrary code |
-| **Glue Job Hijacking via Update with Privileged Role (GLUE-005)** | Update an existing Glue job to attach a privileged role and inject malicious code, then start it to gain that role's permissions |
-| **Glue Job Hijacking with Scheduled Trigger and Privileged Role (GLUE-006)** | Update an existing Glue job to attach a privileged role and inject malicious code, then create a scheduled trigger for persistent automated execution |
-| **Policy Version Override for Self-Escalation (IAM-001)** | Create a new version of an attached policy with administrative permissions, instantly escalating the principal's own privileges |
-| **Access Key Creation for Lateral Movement (IAM-002)** | Create access keys for other IAM users to gain their permissions and move laterally across the account |
-| **Access Key Rotation Attack for Lateral Movement (IAM-003)** | Delete and recreate access keys for other IAM users to bypass the two-key limit and gain their permissions |
-| **Console Login Profile Creation for Lateral Movement (IAM-004)** | Create console login profiles for other IAM users to access the AWS Console with their permissions |
-| **Inline Policy Injection for Self-Escalation (IAM-005)** | Attach an inline policy with administrative permissions to your own role, instantly escalating privileges |
-| **Console Password Override for Lateral Movement (IAM-006)** | Change the console password of other IAM users to log in as them and gain their permissions |
-| **Inline Policy Injection on User for Self-Escalation (IAM-007)** | Attach an inline policy with administrative permissions to your own IAM user, instantly escalating privileges |
-| **Managed Policy Attachment on User for Self-Escalation (IAM-008)** | Attach existing managed policies with administrative permissions to your own IAM user, instantly escalating privileges |
-| **Managed Policy Attachment on Role for Self-Escalation (IAM-009)** | Attach existing managed policies with administrative permissions to your own IAM role, instantly escalating privileges |
-| **Managed Policy Attachment on Group for Self-Escalation (IAM-010)** | Attach existing managed policies with administrative permissions to a group you belong to, escalating privileges for all group members |
-| **Inline Policy Injection on Group for Self-Escalation (IAM-011)** | Attach an inline policy with administrative permissions to a group you belong to, escalating privileges for all group members |
-| **Trust Policy Hijacking for Role Assumption (IAM-012)** | Modify a role's trust policy to allow yourself to assume it, gaining the role's permissions |
-| **Group Membership Hijacking for Privilege Escalation (IAM-013)** | Add yourself to a privileged IAM group to inherit its permissions, gaining access to all policies attached to the group |
-| **Managed Policy Attachment with Role Assumption for Lateral Movement (IAM-014)** | Attach administrative managed policies to another role you can assume, then assume it to gain elevated privileges |
-| **Managed Policy Attachment with Access Key Creation for Lateral Movement (IAM-015)** | Attach administrative managed policies to another IAM user and create access keys for them to gain programmatic access with elevated privileges |
-| **Policy Version Override with Role Assumption for Lateral Movement (IAM-016)** | Create a new version of a customer-managed policy attached to another role with administrative permissions, then assume that role to gain elevated access |
-| **Inline Policy Injection with Role Assumption for Lateral Movement (IAM-017)** | Attach an inline policy with administrative permissions to another role you can assume, then assume it to gain elevated privileges |
-| **Inline Policy Injection with Access Key Creation for Lateral Movement (IAM-018)** | Attach an inline policy with administrative permissions to another IAM user and create access keys for them to gain programmatic access with elevated privileges |
-| **Managed Policy Attachment with Trust Policy Hijacking for Privilege Escalation (IAM-019)** | Attach administrative managed policies to a role and modify its trust policy to allow yourself to assume it, gaining elevated privileges without prior assume-role access |
-| **Policy Version Override with Trust Policy Hijacking for Privilege Escalation (IAM-020)** | Create a new version of a customer-managed policy attached to a role with administrative permissions and modify its trust policy to assume it, without prior assume-role access |
-| **Inline Policy Injection with Trust Policy Hijacking for Privilege Escalation (IAM-021)** | Add an inline policy with administrative permissions to a role and modify its trust policy to allow yourself to assume it, gaining elevated privileges without prior assume-role access |
-| **Lambda Function Creation with Privileged Role (LAMBDA-001)** | Create a Lambda function with a privileged IAM role and invoke it to execute code with that role's permissions |
-| **Lambda Function Creation with Event Source Trigger (LAMBDA-002)** | Create a Lambda function with a privileged IAM role and an event source mapping to trigger it automatically, executing code with the role's permissions |
-| **Lambda Function Code Injection (LAMBDA-003)** | Modify the code of an existing Lambda function to execute arbitrary commands with the function's execution role permissions |
-| **Lambda Function Code Injection with Direct Invocation (LAMBDA-004)** | Modify the code of an existing Lambda function and invoke it directly to execute arbitrary commands with the function's execution role permissions |
-| **Lambda Function Code Injection with Resource Policy Grant (LAMBDA-005)** | Modify the code of an existing Lambda function and grant yourself invocation permission via its resource-based policy to execute code with the function's execution role |
-| **Lambda Function Creation with Resource Policy Invocation (LAMBDA-006)** | Create a Lambda function with a privileged IAM role and grant yourself invocation permission via its resource-based policy to execute code with the role's permissions |
-| **SageMaker Notebook Creation with Privileged Role (SAGEMAKER-001)** | Create a SageMaker notebook instance with a privileged IAM role to execute arbitrary code with the role's permissions via the Jupyter environment |
-| **SageMaker Training Job Creation with Privileged Role (SAGEMAKER-002)** | Create a SageMaker training job with a privileged IAM role to execute arbitrary container code with the role's permissions |
-| **SageMaker Processing Job Creation with Privileged Role (SAGEMAKER-003)** | Create a SageMaker processing job with a privileged IAM role to execute arbitrary container code with the role's permissions |
-| **SageMaker Presigned Notebook URL for Privilege Escalation (SAGEMAKER-004)** | Generate a presigned URL to access an existing SageMaker notebook instance and execute code with its execution role's permissions |
-| **SageMaker Notebook Lifecycle Config Injection (SAGEMAKER-005)** | Inject a malicious lifecycle configuration into an existing SageMaker notebook to execute code with the notebook's execution role during startup |
-| **SSM Session Access for EC2 Role Credentials (SSM-001)** | Start an SSM session on an EC2 instance to access its attached role credentials through IMDS |
-| **SSM Send Command for EC2 Role Credentials (SSM-002)** | Execute commands on an EC2 instance via SSM Run Command to access its attached role credentials through IMDS |
-| **Role Assumption for Privilege Escalation (STS-001)** | Assume IAM roles with elevated permissions by exploiting bidirectional trust between the starting principal and the target role |
-
These tools enable workflows such as:
+
- Asking an AI assistant to identify privilege escalation paths in a specific AWS account
- Automating attack path analysis across multiple scans
- Combining attack path data with findings and compliance information for comprehensive security reports
diff --git a/docs/user-guide/tutorials/prowler-app-finding-groups.mdx b/docs/user-guide/tutorials/prowler-app-finding-groups.mdx
index e1bf83a50f..c5234bb41f 100644
--- a/docs/user-guide/tutorials/prowler-app-finding-groups.mdx
+++ b/docs/user-guide/tutorials/prowler-app-finding-groups.mdx
@@ -1,12 +1,16 @@
---
title: 'Finding Groups'
+sidebarTitle: 'Groups'
description: 'Organize and triage security findings by check to reduce noise and prioritize remediation effectively.'
---
import { VersionBadge } from "/snippets/version-badge.mdx"
+import { AppliesTo } from "/snippets/applies-to.mdx"
+
+
Finding Groups transforms security findings triage by grouping them by check instead of displaying a flat list. This dramatically reduces noise and enables faster, more effective prioritization.
## Triage Challenges with Flat Finding Lists
@@ -112,7 +116,7 @@ This provides full context without leaving the drawer.
## Getting Started
-1. Navigate to the **Findings** section in Prowler Cloud/App.
+1. Navigate to the **Findings** section in Prowler Cloud.
2. Toggle to the **Grouped View** to see findings organized by check.
3. Select any group row to expand and see affected resources.
4. Select a resource to open the detail drawer with full context.
diff --git a/docs/user-guide/tutorials/prowler-app-findings-triage.mdx b/docs/user-guide/tutorials/prowler-app-findings-triage.mdx
new file mode 100644
index 0000000000..bbceaef992
--- /dev/null
+++ b/docs/user-guide/tutorials/prowler-app-findings-triage.mdx
@@ -0,0 +1,125 @@
+---
+title: "Findings Triage"
+sidebarTitle: 'Triage'
+description: "Track finding review status and team notes in Prowler Cloud."
+---
+
+import { VersionBadge } from "/snippets/version-badge.mdx"
+import { SubscriptionBanner } from "/snippets/subscription-banner.mdx"
+
+
+
+Findings Triage lets teams track review status and notes for individual findings in Prowler Cloud. Use it to record investigation state, remediation work, accepted risk, or false positive decisions without leaving the Findings workflow.
+
+
+
+## What Is Findings Triage?
+
+Findings Triage adds a **Triage** status and team note workflow to individual finding rows. It is available from:
+
+- Expanded rows in **Finding Groups**
+- Standalone finding tables
+- Finding and resource detail drawers, including related findings tables
+
+Finding Groups rows do not show triage controls because a group row represents several findings. Expand a group to work with each affected resource.
+
+
+
+## Required Permissions
+
+To update triage statuses and notes, the user role must have the **Manage Scans** permission. For more information, see [Role-Based Access Control (RBAC)](/user-guide/tutorials/prowler-app-rbac).
+
+Users without this permission can still see existing triage context when it is available, but cannot change statuses or save notes.
+
+## Triage Statuses
+
+The status selector includes manual statuses. Prowler also sets automatic statuses after scans.
+
+| Status | Type | Use It When |
+| --- | --- | --- |
+| **Open** | Manual | A failed finding has not been reviewed yet. A failed finding with no saved triage state also appears as **Open**. |
+| **Under Review** | Manual | A team is investigating the finding. |
+| **Remediating** | Manual | Work is in progress to fix the finding. |
+| **Risk Accepted** | Manual | The team accepts the risk and wants to mute the finding. |
+| **False Positive** | Manual | The finding does not apply and should be muted. |
+| **Resolved** | Automatic | A finding changed from `FAIL` to `PASS` in a later scan. A passed finding with no saved triage state also appears as **Resolved**. |
+| **Reopened** | Automatic | A finding changed from `PASS` to `FAIL` in a later scan. |
+
+
+
+Resolved and Reopened are not manual selector options.
+
+These automatic states keep triage tied to the finding UID across scans, even when each scan creates a new finding snapshot.
+
+## Change a Triage Status
+
+
+
+ Go to **Findings** in Prowler Cloud.
+
+
+ Expand a Finding Group, open a resource findings table, or use a standalone finding row.
+
+
+ In the **Triage** column, click the current status.
+
+
+ Select **Open**, **Under Review**, **Remediating**, **Risk Accepted**, or **False Positive**.
+
+
+
+Changing a finding to **Risk Accepted** or **False Positive** will mute the finding. Prowler asks for confirmation and creates a mute rule for the finding.
+
+## Add or Edit a Triage Note
+
+Triage notes are visible only to the team in the current organization. Each note supports up to 500 characters.
+
+
+
+ On an individual finding row, click the actions menu.
+
+
+ Click **Add Triage Note**. If a note already exists, click **Open note**.
+
+
+ Optionally change the status, then write the note.
+
+
+ Click **Save changes**.
+
+
+
+
+
+To remove an existing note, clear the note text and save the change.
+
+## Mutelist Behavior
+
+Findings Triage uses Mutelist when a status means the finding should be muted:
+
+- **Risk Accepted** creates a mute rule because the team accepts the finding as a known risk.
+- **False Positive** creates a mute rule because the finding should not count as an active issue.
+
+Use [Simple Mutelist](/user-guide/tutorials/prowler-app-simple-mutelist) to review, disable, or delete mute rules created through this workflow. For pattern-based muting, use [Advanced Mutelist](/user-guide/tutorials/prowler-app-mute-findings).
+
+
+Muting a finding does not fix the underlying configuration. Review the finding before using **Risk Accepted** or **False Positive**.
+
+
+## Troubleshooting
+
+### Triage controls do not appear
+
+Make sure the row is an individual finding row. Finding Groups rows do not show triage controls. Expand a group to see affected resources and their triage controls.
+
+### Changes cannot be saved
+
+Confirm that the user role has **Manage Scans** permission. Prowler Local Server does not support Findings Triage writes.
+
+### Resolved or Reopened is missing from the selector
+
+This is expected. Prowler sets **Resolved** and **Reopened** automatically from scan result changes.
+
+### Risk Accepted or False Positive muted a finding
+
+This is expected. Those statuses create a mute rule through Mutelist.
diff --git a/docs/user-guide/tutorials/prowler-app-jira-integration.mdx b/docs/user-guide/tutorials/prowler-app-jira-integration.mdx
index 01779a6a96..83554ee8c0 100644
--- a/docs/user-guide/tutorials/prowler-app-jira-integration.mdx
+++ b/docs/user-guide/tutorials/prowler-app-jira-integration.mdx
@@ -1,13 +1,17 @@
---
title: "Jira Integration"
+sidebarTitle: 'Jira'
---
import { VersionBadge } from "/snippets/version-badge.mdx"
+import { AppliesTo } from "/snippets/applies-to.mdx"
-Prowler App enables automatic export of security findings to Jira, providing seamless integration with Atlassian's work item tracking and project management platform. This comprehensive guide demonstrates how to configure and manage Jira integrations to streamline security incident management and enhance team collaboration across security workflows.
+
-Integrating Prowler App with Jira provides:
+Prowler Cloud enables automatic export of security findings to Jira, providing seamless integration with Atlassian's work item tracking and project management platform. This comprehensive guide demonstrates how to configure and manage Jira integrations to streamline security incident management and enhance team collaboration across security workflows.
+
+Integrating Prowler Cloud with Jira provides:
* **Streamlined management:** Convert security findings directly into actionable Jira work items
* **Enhanced team collaboration:** Leverage existing project management workflows for security remediation
@@ -22,9 +26,9 @@ When enabled and configured:
## Configuration
-To configure Jira integration in Prowler App:
+To configure Jira integration in Prowler Cloud:
-1. Navigate to **Integrations** in the Prowler App interface
+1. Navigate to **Integrations** in Prowler Cloud
2. Locate the **Jira** card and click **Manage**, then select **Add integration**

@@ -50,7 +54,7 @@ Once configured successfully, the integration is ready to send findings to Jira.
To manually send individual findings to Jira:
-1. Navigate to the **Findings** section in Prowler App
+1. Navigate to the **Findings** section in Prowler Cloud
2. Select one finding you want to export
3. Click the action button on the table row and select **Send to Jira**
4. Select the Jira integration and project
diff --git a/docs/user-guide/tutorials/prowler-app-lighthouse-multi-llm.mdx b/docs/user-guide/tutorials/prowler-app-lighthouse-multi-llm.mdx
index 0a0179ee79..eee7564bcb 100644
--- a/docs/user-guide/tutorials/prowler-app-lighthouse-multi-llm.mdx
+++ b/docs/user-guide/tutorials/prowler-app-lighthouse-multi-llm.mdx
@@ -1,5 +1,6 @@
---
title: 'Using Multiple LLM Providers with Lighthouse'
+sidebarTitle: 'Multiple LLM Providers'
---
import { VersionBadge } from "/snippets/version-badge.mdx"
@@ -32,13 +33,13 @@ All three providers can be configured for a tenant, but only one can be set as t
When visiting Lighthouse AI chat, the default provider's default model loads automatically. Users can switch to any available LLM model (including those from non-default providers) using the dropdown in chat.
-
+
## Configuring Providers
Navigate to **Configuration** → **Lighthouse AI** to see all three provider options with a **Connect** button under each.
-
+
### Connecting a Provider
@@ -128,6 +129,25 @@ To connect a provider:
3. Configure in Lighthouse AI:
- **API Key**: OpenRouter API key
- **Base URL**: `https://openrouter.ai/api/v1`
+
+ ### Base URL Validation
+
+ To prevent server-side request forgery (SSRF), Prowler API validates the base URL before connecting to it:
+
+ - The URL must use HTTPS.
+ - The host must resolve to a public IP address. Private, loopback, link-local, and cloud metadata addresses are rejected.
+
+
+ This validation can break configurations that point to internal endpoints, such as a self-hosted Ollama server. This is intentional: it fixes a security issue where the Prowler API could be directed to internal services. Internal endpoints must now be allowed explicitly through `LIGHTHOUSE_AI_OPENAI_COMPATIBLE_ALLOWED_HOSTS`.
+
+
+ To allow internal endpoints, set a comma-separated list of hostnames or IP addresses in the Prowler API environment (for Docker Compose deployments, the shared `.env` file):
+
+ ```bash
+ LIGHTHOUSE_AI_OPENAI_COMPATIBLE_ALLOWED_HOSTS=custom-openai.internal,10.0.0.20
+ ```
+
+ Hosts in this list skip the public-endpoint validation. HTTPS is still required, so the endpoint needs a certificate the Prowler API trusts.
@@ -139,7 +159,7 @@ To set a different provider as default:
2. Click **Configure** under the desired provider to set as default
3. Click **Set as Default**
-
+
## Updating Provider Credentials
diff --git a/docs/user-guide/tutorials/prowler-app-lighthouse.mdx b/docs/user-guide/tutorials/prowler-app-lighthouse.mdx
index b119893cb5..5b4a0f5847 100644
--- a/docs/user-guide/tutorials/prowler-app-lighthouse.mdx
+++ b/docs/user-guide/tutorials/prowler-app-lighthouse.mdx
@@ -8,6 +8,10 @@ import { VersionBadge } from "/snippets/version-badge.mdx"
Prowler Lighthouse AI integrates Large Language Models (LLMs) with Prowler security findings data.
+
+Using Prowler Cloud? Lighthouse AI on Prowler Cloud adds persistent chat sessions, GPT-5.5 as the default model, a dedicated agentic (chat) view, and transparent reasoning. See [Lighthouse AI on Prowler Cloud](/getting-started/products/prowler-cloud-lighthouse).
+
+
Behind the scenes, Lighthouse AI works as follows:
- Lighthouse AI runs as a [Langchain agent](https://docs.langchain.com/oss/javascript/langchain/agents) in NextJS
@@ -15,7 +19,7 @@ Behind the scenes, Lighthouse AI works as follows:
- The agent accesses Prowler data through [Prowler MCP](https://docs.prowler.com/getting-started/products/prowler-mcp), which exposes tools from multiple sources, including:
- Prowler Hub
- Prowler Docs
- - Prowler App
+ - Prowler Local Server
- Instead of calling every tool directly, the agent uses two meta-tools:
- `describe_tool` to retrieve a tool schema and parameter requirements.
- `execute_tool` to run the selected tool with the required input.
@@ -47,7 +51,7 @@ Getting started with Prowler Lighthouse AI is easy:
For detailed configuration instructions for each provider, see [Using Multiple LLM Providers with Lighthouse](/user-guide/tutorials/prowler-app-lighthouse-multi-llm).
-
+
### Adding Business Context
diff --git a/docs/user-guide/tutorials/prowler-app-multi-tenant.mdx b/docs/user-guide/tutorials/prowler-app-multi-tenant.mdx
index b353bc85c5..8de9365fe9 100644
--- a/docs/user-guide/tutorials/prowler-app-multi-tenant.mdx
+++ b/docs/user-guide/tutorials/prowler-app-multi-tenant.mdx
@@ -1,12 +1,16 @@
---
title: 'Managing Organizations (Multi-Tenant)'
+sidebarTitle: 'Organizations'
---
import { VersionBadge } from "/snippets/version-badge.mdx"
+import { AppliesTo } from "/snippets/applies-to.mdx"
-Prowler App supports multi-tenancy through **Organizations**, allowing users to belong to multiple isolated environments within a single account. Each organization maintains its own providers, scans, findings, and user memberships, ensuring complete data separation between teams or business units.
+
+
+Prowler Cloud supports multi-tenancy through **Organizations**, allowing users to belong to multiple isolated environments within a single account. Each organization maintains its own providers, scans, findings, and user memberships, ensuring complete data separation between teams or business units.
## Key Concepts
@@ -128,7 +132,7 @@ When invited to join an organization, the invited user receives a link to accept
1. Open the invitation link.
-2. If already authenticated, the invitation is accepted automatically and the user is redirected to Prowler App.
+2. If already authenticated, the invitation is accepted automatically and the user is redirected to Prowler Cloud.
3. If not authenticated, choose **I have an account -- Sign in**, authenticate with existing credentials, and the invitation is accepted upon sign-in.
diff --git a/docs/user-guide/tutorials/prowler-app-mute-findings.mdx b/docs/user-guide/tutorials/prowler-app-mute-findings.mdx
index 82623b54cf..c2ada47e9c 100644
--- a/docs/user-guide/tutorials/prowler-app-mute-findings.mdx
+++ b/docs/user-guide/tutorials/prowler-app-mute-findings.mdx
@@ -1,11 +1,14 @@
---
-title: 'Advanced Mutelist (YAML)'
+title: 'Advanced Mutelist'
---
import { VersionBadge } from "/snippets/version-badge.mdx"
+import { AppliesTo } from "/snippets/applies-to.mdx"
-Prowler App allows users to mute specific findings to focus on the most critical security issues. This guide demonstrates how to use the Advanced Mutelist feature with YAML configuration for complex, pattern-based muting rules.
+
+
+Prowler Cloud allows users to mute specific findings to focus on the most critical security issues. This guide demonstrates how to use the Advanced Mutelist feature with YAML configuration for complex, pattern-based muting rules.
For muting individual findings without YAML configuration, use [Simple Mutelist](/user-guide/tutorials/prowler-app-simple-mutelist) to mute findings directly from the Findings table.
@@ -31,8 +34,8 @@ Advanced Mutelist requires the **Manage Account** permission. See [RBAC Administ
Before muting findings, ensure:
-- Valid access to Prowler App with appropriate permissions
-- A provider added to the Prowler App
+- Valid access to Prowler Cloud with appropriate permissions
+- A provider added to Prowler Cloud
- Understanding of the security implications of muting specific findings
@@ -43,7 +46,7 @@ Muting findings does not resolve underlying security issues. Review each finding
To configure Advanced Mutelist:
-1. Log into Prowler App
+1. Log into Prowler Cloud
2. Navigate to the Providers page

3. Connect a provider to enable Mutelist configuration
@@ -423,7 +426,7 @@ Mutelist:
### Priority: Advanced vs. Simple Mutelist
-When both Advanced Mutelist (YAML) and [Simple Mutelist](/user-guide/tutorials/prowler-app-simple-mutelist) rules match the same finding, the **Advanced Mutelist takes higher priority**. The finding will be muted with the reason "Muted by mutelist". If a finding is not matched by the Advanced Mutelist but matches a Simple Mutelist rule, the Simple rule's custom justification is used instead.
+When both Advanced Mutelist and [Simple Mutelist](/user-guide/tutorials/prowler-app-simple-mutelist) rules match the same finding, the **Advanced Mutelist takes higher priority**. The finding will be muted with the reason "Muted by mutelist". If a finding is not matched by the Advanced Mutelist but matches a Simple Mutelist rule, the Simple rule's custom justification is used instead.
### Best Practices
@@ -436,7 +439,7 @@ When both Advanced Mutelist (YAML) and [Simple Mutelist](/user-guide/tutorials/p
### Validation
-Prowler App validates your mutelist configuration and will display errors for:
+Prowler Cloud validates the mutelist configuration and will display errors for:
- Invalid YAML syntax
- Missing required fields
diff --git a/docs/user-guide/tutorials/prowler-app-rbac.mdx b/docs/user-guide/tutorials/prowler-app-rbac.mdx
index cabea5bd35..4533e0423c 100644
--- a/docs/user-guide/tutorials/prowler-app-rbac.mdx
+++ b/docs/user-guide/tutorials/prowler-app-rbac.mdx
@@ -1,12 +1,16 @@
---
title: 'Managing Users and Role-Based Access Control (RBAC)'
+sidebarTitle: 'Users & RBAC'
---
import { VersionBadge } from "/snippets/version-badge.mdx"
+import { AppliesTo } from "/snippets/applies-to.mdx"
-**Prowler App** supports multiple users within a single tenant, enabling seamless collaboration by allowing team members to easily share insights and manage security findings.
+
+
+**Prowler Cloud** supports multiple users within a single tenant, enabling seamless collaboration by allowing team members to easily share insights and manage security findings.
[Roles](#roles) help you control user permissions, determining what actions each user can perform and the data they can access within Prowler. By default, each account includes an immutable **admin** role, ensuring that your account always retains administrative access.
@@ -40,6 +44,11 @@ Follow these steps to edit a user of your account:
+
+Users can edit their own account details. Editing another user's account details requires the **Invite and Manage Users** or **admin** permission.
+
+
+
#### Removing a User
Follow these steps to remove a user of your account:
@@ -119,7 +128,7 @@ To resend the invitation to the user, it is necessary to explicitly **delete the
## Managing Groups and Roles
-The Roles section in Prowler is designed to facilitate the assignment of custom user privileges. This section allows administrators to define roles with specific permissions for Prowler administrative tasks and Account visibility.
+Roles combine administrative permissions with provider visibility. Administrative permissions control the actions a role can perform. Provider Groups and Unlimited Visibility control the providers, resources, findings, scans, and compliance results the role can access.
**Only users that have the _Manage Account_ or _admin_ permission can access this section.**
@@ -127,47 +136,53 @@ The Roles section in Prowler is designed to facilitate the assignment of custom
### Provider Groups
-Provider Groups control visibility across specific providers. When creating a new role, you can assign specific groups to define their Provider visibility. This ensures that users with that role have access only to the Providers that are required.
+Provider Groups limit visibility to selected providers. Assigning one or more Provider Groups to a role grants access to the providers in those groups and their resources, findings, scans, and compliance results.
-By default, a new user role does not have visibility into any group.
+New roles have no provider visibility by default. Assign at least one Provider Group or enable **Unlimited Visibility** before assigning the role to users who need access to provider data.
-Alternatively, to grant the role unlimited visibility across all providers, check the Grant Unlimited Visibility checkbox.
+**Unlimited Visibility** grants organization-wide visibility across every provider, regardless of the Provider Groups assigned to the role. It does not grant administrative permissions.
#### Creating a Provider Group
Follow these steps to create a provider group in your account:
-1. Navigate to **Provider Groups** from the side menu..
+1. Click **Providers** in the side menu.
-2. In this view you can select the provider groups you want to assign to one or more roles.
+2. Select the **Provider Groups** tab.
-3. Click the **Create Group** button on the center of the screen.
+3. Enter a group name in the **Create a new provider group** form.
-
+4. Select the providers that the group controls. Optionally, select the roles that should use the group.
+
+5. Click **Create Group**.
+
+
#### Editing a Provider Group
Follow these steps to edit a provider group on your account:
-1. Navigate to **Provider Groups** from the side menu.
+1. Click **Providers** in the side menu and select the **Provider Groups** tab.
-2. Click the edit button of the provider group you want to modify.
+2. Open the actions menu for the Provider Group and click **Edit Provider Group**.
-
+
-3. Change the provider group parameters you need and save the changes.
+3. Update the group name, providers, or roles, and save the changes.
-
+
#### Removing a Provider Group
-Follow these steps to remove a provider group of your account:
+Follow these steps to remove a provider group from your account:
-1. Navigate to **Provider Groups** from the side menu.
+1. Click **Providers** in the side menu and select the **Provider Groups** tab.
-2. Click on the delete button of the provider group you want to remove.
+2. Open the actions menu for the Provider Group and click **Delete Provider Group**.
-
+3. Confirm the deletion.
+
+
### Roles
@@ -177,19 +192,20 @@ Follow these steps to create a role for your account:
1. Navigate to **Roles** from the side menu.
-2. Click on the **Add Role** button on the top right-hand corner of the screen.
+2. Click **Add Role**.
-
+3. Enter the role name and select the required administrative permissions.
-3. In the Add Role screen, enter the role name, the administration permissions and the groups of providers to which the Role will have access to.
-
-4. In the Groups and Account Visibility section, you will see a list of available groups with checkboxes next to them. To assign a group to the user role, simply click the checkbox next to the group name. If you need to assign multiple groups, repeat the process for each group you wish to add.
+4. Configure **Visibility**:
+ - To grant organization-wide visibility, select **Enable Unlimited Visibility for this role**.
+ - To limit visibility, leave Unlimited Visibility cleared and select one or more Provider Groups.
+5. Click **Add Role**.
-To assign read-only access, select only the `Unlimited Visibility` permission when creating the role. Then, go to the Users page and assign this role to the appropriate user.
+To grant read-only access across the organization, enable **Unlimited Visibility** without selecting administrative permissions. Then, assign the role from the **Users** page.
#### Editing a Role
@@ -198,25 +214,21 @@ Follow these steps to edit a role on your account:
1. Navigate to **Roles** from the side menu.
-2. Click on the edit button of the role you want to modify.
+2. Open the actions menu for the role and click **Edit Role**.
-
-
-3. Adjust the settings as needed and save the changes.
-
-
+3. Update the role name, administrative permissions, Unlimited Visibility setting, or Provider Groups.
+4. Save the changes.
#### Removing a Role
-Follow these steps to remove a role of your account:
+Follow these steps to remove a role from your account:
1. Navigate to **Roles** from the side menu.
-2. Click on the delete button of the role you want to remove.
-
-
+2. Open the actions menu for the role and click **Delete Role**.
+3. Confirm the deletion.
## RBAC Administrative Permissions
@@ -226,8 +238,8 @@ Assign administrative permissions by selecting from the following options:
|------------|-------|-------------|
| Invite and Manage Users | All | Invite new users and manage existing ones. |
| Manage Account | All | Adjust account settings, delete users and read/manage users permissions. |
-| Manage Scans | All | Run and review scans. |
-| Manage Providers | All | Add or modify connected providers. |
+| Manage Scans | All | Run and review scans, and manage [Scan Configuration](/user-guide/tutorials/prowler-app-scan-configuration) settings. |
+| Manage Providers | All | Add or modify connected providers, and attach or detach providers from a [Scan Configuration](/user-guide/tutorials/prowler-app-scan-configuration) (in addition to Manage Scans). |
| Manage Integrations | All | Add or modify the Prowler Integrations. |
| Manage Ingestions | Prowler Cloud | Allow or deny the ability to submit findings ingestion batches via the API. |
| Manage Billing | Prowler Cloud | Access and manage billing settings and subscription information. |
diff --git a/docs/user-guide/tutorials/prowler-app-s3-integration.mdx b/docs/user-guide/tutorials/prowler-app-s3-integration.mdx
index 284b10eaaf..9b7d7a9a2e 100644
--- a/docs/user-guide/tutorials/prowler-app-s3-integration.mdx
+++ b/docs/user-guide/tutorials/prowler-app-s3-integration.mdx
@@ -1,12 +1,16 @@
---
title: 'Amazon S3 Integration'
+sidebarTitle: 'Amazon S3'
---
import { VersionBadge } from "/snippets/version-badge.mdx"
+import { AppliesTo } from "/snippets/applies-to.mdx"
-**Prowler App** allows automatic export of scan results to Amazon S3 buckets, providing seamless integration with existing data workflows and storage infrastructure. This comprehensive guide demonstrates configuration and management of Amazon S3 integrations to streamline security finding management and reporting.
+
+
+**Prowler Cloud** allows automatic export of scan results to Amazon S3 buckets, providing seamless integration with existing data workflows and storage infrastructure. This comprehensive guide demonstrates configuration and management of Amazon S3 integrations to streamline security finding management and reporting.
When enabled and configured, scan results are automatically stored in the configured bucket. Results are provided in `csv`, `html` and `json-ocsf` formats, offering flexibility for custom integrations:
@@ -201,7 +205,7 @@ Replace `` with the AWS account ID that contains the IAM role
### Available Templates
-**Prowler App** provides Infrastructure as Code (IaC) templates to automate IAM role setup with S3 integration permissions.
+**Prowler Cloud** provides Infrastructure as Code (IaC) templates to automate IAM role setup with S3 integration permissions.
Templates are optional. Custom IAM roles or static credentials can be used instead.
@@ -259,8 +263,8 @@ If using Prowler's CloudFormation template, execute the following command to upd
- `EnableS3Integration`: Select "true"
- `S3IntegrationBucketName`: Your bucket name
- `S3IntegrationBucketAccountId`: Bucket owner's AWS account ID
-5. In the "Configure stack options" screen, again, leave everything as it is and click on "Next"
-6. Finally, under "Review Prowler", at the bottom click on "Submit"
+5. In the "Configure stack options" screen, again, leave everything as it is and click "Next"
+6. Finally, under "Review Prowler", at the bottom click "Submit"
#### Terraform
@@ -278,7 +282,7 @@ If using Prowler's CloudFormation template, execute the following command to upd
3. Edit `terraform.tfvars` with your specific values:
```hcl
- # Required: External ID from Prowler App
+ # Required: External ID from Prowler Cloud
external_id = "your-unique-external-id-here"
# S3 Integration Configuration
@@ -310,11 +314,11 @@ For detailed information, refer to the [Terraform README](https://github.com/pro
## Configuration
-Once the required permissions are set up, proceed to configure the S3 integration in **Prowler App**.
+Once the required permissions are set up, proceed to configure the S3 integration in **Prowler Cloud**.
1. Navigate to "Integrations"

-2. Locate the Amazon S3 Integration card and click on the "Configure" button
+2. Locate the Amazon S3 Integration card and click the "Configure" button

3. Click the "Add Integration" button

diff --git a/docs/user-guide/tutorials/prowler-app-scan-configuration.mdx b/docs/user-guide/tutorials/prowler-app-scan-configuration.mdx
new file mode 100644
index 0000000000..60e0db2f4c
--- /dev/null
+++ b/docs/user-guide/tutorials/prowler-app-scan-configuration.mdx
@@ -0,0 +1,231 @@
+---
+title: 'Scan Configuration'
+sidebarTitle: 'Configuration'
+---
+
+import { VersionBadge } from "/snippets/version-badge.mdx"
+import { SubscriptionBanner } from "/snippets/subscription-banner.mdx"
+
+
+
+Scan Configuration lets you override, per provider, specific values in the default configuration Prowler's checks use during a scan. Each configuration can modify how specific checks behave, such as thresholds, allowed values, and retention windows, or exclude checks and services from the scan scope. Attach it to the providers that should use it on their next scan.
+
+
+
+## What Is a Scan Configuration?
+
+A Scan Configuration lets you **override specific values, per provider**, on top of Prowler's defaults. It's merged with those defaults, not a full replacement:
+
+- A provider type you don't add a section for keeps using `config.yaml` untouched.
+- **A provider type you do add a section for has its keys merged over `config.yaml` for that provider.** Only the keys you set are overridden; every key you leave out keeps its default from `config.yaml`, because each check falls back to the default configuration when a value isn't provided. See [How It's Applied](#how-its-applied) for details.
+- It is stored per organization and applied to the **providers you attach** to it.
+- **Attaching a provider is optional at creation time.** You can save a Scan Configuration with no providers attached and associate them later, either from the configuration's editor or from the **Providers** page (see [Attaching Providers](#attaching-providers)). It has no effect on any scan until at least one provider is attached.
+- A provider can be attached to **at most one** Scan Configuration at a time.
+- Changes take effect on the provider's **next scan** and do not re-run past scans.
+
+
+
+The full set of configurable values and their defaults lives in [`prowler/config/config.yaml`](https://github.com/prowler-cloud/prowler/blob/master/prowler/config/config.yaml). For what each key means and which checks read it, see the [Configuration File tutorial](/user-guide/cli/tutorials/configuration_file).
+
+
+## Required Permissions
+
+Scan Configuration access is governed by Role-Based Access Control (RBAC). See [RBAC Administrative Permissions](/user-guide/tutorials/prowler-app-rbac#rbac-administrative-permissions) for details on each permission.
+
+- **Viewing** a Scan Configuration doesn't require any specific permission.
+- **Creating, editing, and deleting** a Scan Configuration requires the **Manage Scans** permission.
+- **Attaching or detaching providers** requires the **Manage Providers** permission as well, in addition to Manage Scans. This applies to explicit changes to the attached providers, and to deleting a Scan Configuration that still has providers attached (deleting it detaches them too).
+- Attaching or detaching a provider also requires that provider to be **visible to your role**. Visibility comes from the [Provider Groups](/user-guide/tutorials/prowler-app-rbac#provider-groups) assigned to your role, or from **Unlimited Visibility**. You can't attach a provider you can't see, and you can't detach one either, whether by removing it from the list or by deleting the Scan Configuration it's attached to.
+
+## Config Schema
+
+The YAML follows the structure of `config.yaml`: a mapping keyed by provider, with each provider section holding the keys you want to change. You only list the keys you want to override; they're merged over that provider's `config.yaml` defaults.
+
+```yaml
+aws:
+ max_unused_access_keys_days: 30
+ max_console_access_days: 30
+ max_security_group_rules: 25
+
+azure:
+ defender_attack_path_minimal_risk_level: "Critical"
+
+gcp:
+ storage_min_retention_days: 30
+```
+
+### Limiting the Scan Scope
+
+
+
+Use `excluded_checks` to skip individual checks and `excluded_services` to skip every check in a service for the matching provider type:
+
+```yaml
+aws:
+ excluded_checks:
+ - s3_bucket_public_access
+ excluded_services:
+ - ec2
+```
+
+
+When a Scan Configuration excludes checks or services, Prowler calculates overviews, aggregations, and other result-based information from the reduced scan scope. The displayed information reflects only the checks and services that ran, not a complete assessment of the provider. Consider the applied Scan Configuration when interpreting totals and security posture.
+
+
+## Creating a Scan Configuration
+
+
+
+ On the **Scan** page (under **Configuration**), click **New Scan Configuration**.
+
+
+ Give the configuration a descriptive **Name** (3–100 characters), e.g. `stricter-iam-aws`.
+
+
+ In the **Configuration (YAML)** field, add the keys you want to change, grouped by provider. Only the keys you set are overridden; every other key keeps its `config.yaml` default. The editor is pre-filled with a representative default placeholder you can use as a starting point.
+
+
+ Under **Attach to providers**, pick the providers that should use this configuration. This is optional, you can save without any provider and attach them later, either by editing this configuration or from the **Providers** page (see [Attaching Providers](#attaching-providers)).
+
+
+ Click **Save**. The server validates the configuration values and, if everything is valid, stores it and attaches the selected providers.
+
+
+
+
+You don't need to fill in every provider. A section you don't include leaves that provider's `config.yaml` untouched. Within a section you do include, only add the keys you want to change; the rest keep their `config.yaml` defaults. The placeholder shown in the editor is just an example; if you leave the field with only the placeholder (greyed-out) text, nothing is saved.
+
+
+## How Validation Works
+
+Prowler checks your configuration in two stages, the same way the Advanced Mutelist editor does:
+
+1. **As you type: is it well-formed?** The editor checks that what you've written is valid YAML. If something is off, you'll see an `Invalid YAML format` message and **Save** stays disabled until you fix it. Once it's clean, it shows **Valid YAML format**.
+2. **When you save: are the values allowed?** Saving checks that each value is one Prowler accepts, the right type, within range, and one of the allowed options where a key only takes a fixed set of choices. If a value isn't allowed, the editor points to the exact key and explains why, right beneath the field, so you can correct it and save again.
+
+For example, `azure.defender_attack_path_minimal_risk_level` only accepts `Low`, `Medium`, `High`, or `Critical`. Saving any other value returns an inline error like:
+
+```
+azure.defender_attack_path_minimal_risk_level: Input should be 'Low', 'Medium', 'High' or 'Critical'
+```
+
+
+**Valid YAML format** only means the text is well-formed; it doesn't mean your values are accepted. Those are checked when you save.
+
+Be careful with indentation. A line like `azure: defender_attack_path_minimal_risk_level: Critical` (no line break and indent after `azure:`) is still valid YAML, but Prowler reads it as one long key name instead of a setting inside the `azure` section, so the value is silently ignored. Always nest provider keys:
+
+```yaml
+azure:
+ defender_attack_path_minimal_risk_level: "Critical"
+```
+
+
+
+Prowler won't flag a section or key it doesn't recognize. It accepts them without error, so custom checks and plugins can add their own settings. The trade-off: a typo in a key or section name isn't rejected either, and that misspelled setting simply won't apply. Double-check your spelling against `config.yaml`.
+
+
+## Attaching Providers
+
+A Scan Configuration only has an effect once it's attached to one or more providers. There are two ways to manage attachments.
+
+### From the Scan Config Editor
+
+In the **Attach to providers** field, select the providers that should use this configuration. Providers already attached to **another** configuration are hidden from the selector, since each provider can belong to only one configuration at a time.
+
+### From the Provider's Row Menu
+
+You can also manage a provider's configuration from **Providers**:
+
+
+
+ On the **Providers** page, open the **⋮** menu on a provider row.
+
+
+
+
+ In the dialog, pick a configuration from the dropdown to apply it (picking a different one moves the provider), or pick **Default** to detach it and go back to the built-in `config.yaml` defaults. Then click **Save**.
+
+
+
+
+This dialog only **associates or disassociates** an existing configuration. To create or edit the configuration's YAML, use the **Scan Config** view (a link is provided in the dialog).
+
+
+
+Because a provider can belong to only one configuration, associating a provider that is already attached elsewhere **moves** it to the new configuration automatically; it is removed from the previous one.
+
+
+## Editing and Deleting
+
+On the **Scan Config** page, open the **⋮** menu on a configuration row:
+
+- **Edit:** Choose **Edit** to open the editor, change its name, YAML, or attached providers, and click **Update**. Editing the YAML always happens here, never from the provider row.
+- **Delete:** Choose **Delete** (in the danger zone) and confirm. Providers that were attached fall back to the built-in defaults from `config.yaml` on their next scan.
+
+## How It's Applied
+
+When a scan runs for a provider:
+
+1. If the provider is attached to a Scan Configuration **and that configuration has a section for the provider's type** (e.g. `aws` for an AWS provider), Prowler merges that section over `config.yaml` for that provider's scan: the keys you set win, and every key you didn't set keeps its `config.yaml` default.
+2. If the provider is attached to a Scan Configuration, but that configuration **has no section for the provider's type** (for example, a configuration that only defines an `aws` section, attached to a GCP provider), the scan uses the built-in defaults from `config.yaml` for that provider, exactly as if no Scan Configuration were attached at all.
+3. If the provider isn't attached to any Scan Configuration, the built-in defaults from `config.yaml` are used.
+
+
+The merge is per key. A key you don't set keeps its `config.yaml` default, because each check falls back to the default configuration when a value isn't provided. You only need to list the keys you want to change.
+
+
+
+A single Scan Configuration can hold sections for several provider types at once (see [Config Schema](#config-schema)) and be attached to providers of different types. Each provider only ever picks up the section matching its own type; the rest of the YAML is ignored for that provider.
+
+
+## Effect on Compliance Results
+
+Some compliance requirements only hold if the checks they map to ran with a strict-enough configuration. For example, a requirement expecting unused access keys to be disabled within 45 days loses its meaning if a Scan Configuration raises `max_unused_access_keys_days` to 120: the check would still PASS, but the requirement wouldn't really be met.
+
+When a scan's applied configuration doesn't meet a requirement's expectations, Prowler marks that requirement as **FAIL** on the Compliance page, even if every individual finding passed. The requirement shows an info icon (and, when expanded, an inline alert) with:
+
+> Marked as FAIL because the applied scan configuration does not meet this requirement, even though all findings passed.
+
+This only affects requirements built around a configurable check that declares this kind of expectation; requirements without one are never affected by an attached Scan Configuration.
+
+## Common Examples
+
+Each example below shows only the keys being changed for that provider.
+
+
+Only the keys shown are overridden. Every other key for that provider keeps its `config.yaml` default (see [How It's Applied](#how-its-applied)).
+
+
+**Stricter IAM (Identity and Access Management) hygiene for AWS:**
+
+```yaml
+aws:
+ max_unused_access_keys_days: 30
+ max_console_access_days: 30
+ max_unused_sagemaker_access_days: 45
+```
+
+**Raise Azure Defender attack-path sensitivity:**
+
+```yaml
+azure:
+ defender_attack_path_minimal_risk_level: "Critical"
+```
+
+**Tighten GCP storage retention and key rotation:**
+
+```yaml
+gcp:
+ storage_min_retention_days: 30
+ secretmanager_max_rotation_days: 30
+```
+
+## Troubleshooting
+
+### A Provider Doesn't Appear in the Selector
+
+The provider is already attached to another Scan Configuration. Detach it there first, or use the provider row menu to move it.
+
+### You Can't Attach or Detach Providers
+
+If you can edit the configuration but not change its providers, or an error mentions a provider ID that "wasn't found", you're missing the **Manage Providers** permission or the provider isn't visible to your role. A provider outside your visibility is reported the same way as one that doesn't exist, so it isn't revealed to roles that shouldn't see it. See [Required Permissions](#required-permissions).
diff --git a/docs/user-guide/tutorials/prowler-app-security-hub-integration.mdx b/docs/user-guide/tutorials/prowler-app-security-hub-integration.mdx
index 592ff2b26d..977ad8e6f1 100644
--- a/docs/user-guide/tutorials/prowler-app-security-hub-integration.mdx
+++ b/docs/user-guide/tutorials/prowler-app-security-hub-integration.mdx
@@ -1,13 +1,17 @@
---
title: "AWS Security Hub Integration"
+sidebarTitle: 'AWS Security Hub'
---
import { VersionBadge } from "/snippets/version-badge.mdx"
+import { AppliesTo } from "/snippets/applies-to.mdx"
-Prowler App enables automatic export of security findings to AWS Security Hub, providing seamless integration with AWS's native security and compliance service. This comprehensive guide demonstrates how to configure and manage AWS Security Hub integrations to centralize security findings and enhance compliance tracking across AWS environments.
+
-Integrating Prowler App with AWS Security Hub provides:
+Prowler Cloud enables automatic export of security findings to AWS Security Hub, providing seamless integration with AWS's native security and compliance service. This comprehensive guide demonstrates how to configure and manage AWS Security Hub integrations to centralize security findings and enhance compliance tracking across AWS environments.
+
+Integrating Prowler Cloud with AWS Security Hub provides:
* **Centralized security visibility:** Consolidate findings from multiple AWS accounts and regions
* **Native AWS integration:** Leverage existing AWS security workflows and compliance frameworks
@@ -30,7 +34,7 @@ Refer to [AWS Security Hub pricing](https://aws.amazon.com/security-hub/pricing/
## Prerequisites
-Before configuring AWS Security Hub Integration in Prowler App, complete these steps:
+Before configuring AWS Security Hub Integration in Prowler Cloud, complete these steps:
### AWS Security Hub Setup
@@ -42,9 +46,9 @@ Configure AWS credentials by following the [AWS authentication setup guide](/use
## Configuration
-To configure AWS Security Hub integration in Prowler App:
+To configure AWS Security Hub integration in Prowler Cloud:
-1. Navigate to **Integrations** in the Prowler App interface
+1. Navigate to **Integrations** in Prowler Cloud
2. Locate the **AWS Security Hub** card and click **Manage**, then select **Add integration**

diff --git a/docs/user-guide/tutorials/prowler-app-simple-mutelist.mdx b/docs/user-guide/tutorials/prowler-app-simple-mutelist.mdx
index c0bd7db9b4..4b0d59e24a 100644
--- a/docs/user-guide/tutorials/prowler-app-simple-mutelist.mdx
+++ b/docs/user-guide/tutorials/prowler-app-simple-mutelist.mdx
@@ -3,10 +3,13 @@ title: "Simple Mutelist"
---
import { VersionBadge } from "/snippets/version-badge.mdx";
+import { AppliesTo } from "/snippets/applies-to.mdx";
-Prowler App provides Simple Mutelist, an intuitive way to mute findings directly from the Findings page without writing YAML configuration. This feature streamlines the muting workflow by allowing individual or bulk muting with just a few clicks.
+
+
+Prowler Cloud provides Simple Mutelist, an intuitive way to mute findings directly from the Findings page without writing YAML configuration. This feature streamlines the muting workflow by allowing individual or bulk muting with just a few clicks.
## What Is Simple Mutelist?
diff --git a/docs/user-guide/tutorials/prowler-app-social-login.mdx b/docs/user-guide/tutorials/prowler-app-social-login.mdx
index 45fe8ec62f..62de6fbc9c 100644
--- a/docs/user-guide/tutorials/prowler-app-social-login.mdx
+++ b/docs/user-guide/tutorials/prowler-app-social-login.mdx
@@ -1,12 +1,16 @@
---
title: 'Social Login Configuration'
+sidebarTitle: 'Social Login'
---
import { VersionBadge } from "/snippets/version-badge.mdx"
+import { AppliesTo } from "/snippets/applies-to.mdx"
-**Prowler App** supports social login using Google and GitHub OAuth providers. This document guides you through configuring the required environment variables to enable social authentication.
+
+
+Prowler supports social login using Google and GitHub OAuth providers. In **Prowler Cloud** social login is available out of the box. In **Prowler Local Server**, enable it by configuring the environment variables described in this guide.
## Configuring Social Login Credentials
diff --git a/docs/user-guide/tutorials/prowler-app-sso-entra.mdx b/docs/user-guide/tutorials/prowler-app-sso-entra.mdx
index 37f3bbdda5..07cf4709be 100644
--- a/docs/user-guide/tutorials/prowler-app-sso-entra.mdx
+++ b/docs/user-guide/tutorials/prowler-app-sso-entra.mdx
@@ -2,7 +2,11 @@
title: 'Entra ID Configuration'
---
-This page provides instructions for creating and configuring a Microsoft Entra ID (formerly Azure AD) application to use SAML SSO with Prowler App.
+import { AppliesTo } from "/snippets/applies-to.mdx"
+
+
+
+This page provides instructions for creating and configuring a Microsoft Entra ID (formerly Azure AD) application to use SAML SSO with Prowler Cloud.
You can find a walkthrough video [here](https://www.youtube.com/watch?v=zegqm55oJVk).
@@ -28,7 +32,7 @@ You can find a walkthrough video [here](https://www.youtube.com/watch?v=zegqm55o

-6. Enter the "Identifier (Entity ID)" and "Reply URL (Assertion Consumer Service URL)". These values can be obtained from the SAML SSO integration setup in Prowler App. For detailed instructions, refer to the [SAML SSO Configuration](/user-guide/tutorials/prowler-app-sso) page.
+6. Enter the "Identifier (Entity ID)" and "Reply URL (Assertion Consumer Service URL)". These values can be obtained from the SAML SSO integration setup in Prowler Cloud. For detailed instructions, refer to the [SAML SSO Configuration](/user-guide/tutorials/prowler-app-sso) page.

@@ -44,4 +48,4 @@ You can find a walkthrough video [here](https://www.youtube.com/watch?v=zegqm55o

-10. Save the downloaded Metadata XML to a file. To complete the setup, upload this file during the Prowler App integration. (See the [SAML SSO Configuration](/user-guide/tutorials/prowler-app-sso) page for details).
+10. Save the downloaded Metadata XML to a file. To complete the setup, upload this file during the SAML SSO integration setup in Prowler Cloud. (See the [SAML SSO Configuration](/user-guide/tutorials/prowler-app-sso) page for details).
diff --git a/docs/user-guide/tutorials/prowler-app-sso-google-workspace.mdx b/docs/user-guide/tutorials/prowler-app-sso-google-workspace.mdx
index 2f10d443ae..ce0e5edc79 100644
--- a/docs/user-guide/tutorials/prowler-app-sso-google-workspace.mdx
+++ b/docs/user-guide/tutorials/prowler-app-sso-google-workspace.mdx
@@ -2,20 +2,24 @@
title: 'SAML SSO: Google Workspace'
---
-This page explains how to configure SAML-based Single Sign-On (SSO) in Prowler App using **Google Workspace** as the Identity Provider (IdP). The setup is divided into two parts: create a custom SAML app in Google Admin Console, then complete the configuration in Prowler App.
+import { AppliesTo } from "/snippets/applies-to.mdx"
+
+
+
+This page explains how to configure SAML-based Single Sign-On (SSO) in Prowler Cloud using **Google Workspace** as the Identity Provider (IdP). The setup is divided into two parts: create a custom SAML app in Google Admin Console, then complete the configuration in Prowler Cloud.
**Parallel Setup Required**
-Google Admin Console requires the ACS URL and Entity ID from Prowler App, while Prowler App displays these values only after opening the SAML configuration dialog. To work around this, open Prowler App in a separate browser tab, navigate to the profile page, open the "Configure SAML SSO" dialog, and copy the ACS URL and Entity ID before proceeding with the Google configuration.
+Google Admin Console requires the ACS URL and Entity ID from Prowler Cloud, while Prowler Cloud displays these values only after opening the SAML configuration dialog. To work around this, open Prowler Cloud in a separate browser tab, navigate to the profile page, open the "Configure SAML SSO" dialog, and copy the ACS URL and Entity ID before proceeding with the Google configuration.
## Prerequisites
- **Google Workspace**: Super Admin access (or delegated admin with app management permissions).
-- **Prowler App**: Administrator access to the organization (role with "Manage Account" permission).
-- Prowler App version **5.9.0** or later.
+- **Prowler Cloud**: Administrator access to the organization (role with "Manage Account" permission).
+- Prowler version **5.9.0** or later.
---
@@ -44,7 +48,7 @@ On the **Google Identity Provider details** screen:
1. Google displays two options:
- **Option 1**: Click "Download Metadata" to save the XML file directly. This is the recommended approach.
- **Option 2**: Manually copy the **SSO URL**, **Entity ID**, and **Certificate**.
-2. Download the metadata. This file is required to complete the Prowler App configuration in Part B.
+2. Download the metadata. This file is required to complete the configuration in Prowler Cloud (Part B).
3. Click "Continue".

@@ -52,18 +56,18 @@ On the **Google Identity Provider details** screen:
**Save the Metadata File**
-Download and save the IdP metadata XML file before proceeding. This file cannot be easily retrieved later and is required to complete the SAML configuration in Prowler App.
+Download and save the IdP metadata XML file before proceeding. This file cannot be easily retrieved later and is required to complete the SAML configuration in Prowler Cloud.
### Step 4: Configure the Service Provider Details
-Enter the following values obtained from the SAML SSO configuration dialog in Prowler App (see [Part B, Step 1](#step-1-open-the-saml-configuration-dialog) for details on where to find them):
+Enter the following values obtained from the SAML SSO configuration dialog in Prowler Cloud (see [Part B, Step 1](#step-1-open-the-saml-configuration-dialog) for details on where to find them):
| Google Workspace Field | Value |
|------------------------|-------|
-| **ACS URL** | The Assertion Consumer Service (ACS) URL displayed in Prowler App (e.g., `https://api.prowler.com/api/v1/accounts/saml/your-domain.com/acs/`). Self-hosted deployments use a different base URL. |
-| **Entity ID** | The Audience URI displayed in Prowler App (e.g., `urn:prowler.com:sp`). |
+| **ACS URL** | The Assertion Consumer Service (ACS) URL displayed in Prowler Cloud (e.g., `https://api.prowler.com/api/v1/accounts/saml/your-domain.com/acs/`). Prowler Local Server deployments use a different base URL. |
+| **Entity ID** | The Audience URI displayed in Prowler Cloud (e.g., `urn:prowler.com:sp`). |
| **Name ID format** | Select `EMAIL` from the dropdown. |
| **Name ID** | Select `Basic Information > Primary email` from the dropdown. |
@@ -82,7 +86,7 @@ Click "Add mapping" for each entry:
| `Basic Information > First name` | `firstName` | Yes | |
| `Basic Information > Last name` | `lastName` | Yes | |
| `Employee Details > Department` | `userType` | No | Determines the Prowler role. **Case-sensitive.** |
-| `Employee Details > Organization` | `organization` | No | Company name displayed in Prowler App profile. |
+| `Employee Details > Organization` | `organization` | No | Company name displayed in the user profile in Prowler Cloud. |
**Remember the Mapped Fields**
@@ -98,7 +102,7 @@ Click "Finish" to create the SAML app.
**Dynamic Updates**
-Prowler App updates user attributes each time a user logs in. Any changes made in Google Workspace are reflected on the next login.
+Prowler Cloud updates user attributes each time a user logs in. Any changes made in Google Workspace are reflected on the next login.
@@ -108,7 +112,7 @@ Prowler App updates user attributes each time a user logs in. Any changes made i
The `userType` attribute controls which Prowler role is assigned to the user:
- If `userType` matches an existing Prowler role name, the user receives that role automatically.
-- If `userType` does not match any existing role, Prowler App creates a new role with that name **with read-only access** (visibility over all providers, no management permissions). A Prowler administrator can adjust its permissions afterward through the [RBAC Management](/user-guide/tutorials/prowler-app-rbac) tab.
+- If `userType` does not match any existing role, Prowler Cloud creates a new role with that name **with read-only access** (visibility over all providers, no management permissions). A Prowler administrator can adjust its permissions afterward through the [RBAC Management](/user-guide/tutorials/prowler-app-rbac) tab.
- If `userType` is not set, the user's existing roles are left unchanged.
The `userType` value is **case-sensitive** - for example, `Backend` and `backend` are treated as different roles.
@@ -148,13 +152,13 @@ If attempting to use the "Test SAML login" option in Google Admin Console and re
---
-## Part B - Prowler App Configuration
+## Part B - Prowler Cloud Configuration
### Step 1: Open the SAML Configuration Dialog
1. Navigate to the profile settings page:
- **Prowler Cloud**: `https://cloud.prowler.com/profile`
- - **Self-hosted**: `http://{your-domain}/profile`
+ - **Prowler Local Server**: `http://{your-domain}/profile`
2. Find the "SAML SSO Integration" card and click "Enable" (or "Update" if already configured).
3. The "Configure SAML SSO" dialog opens, displaying:
- **ACS URL**: The Assertion Consumer Service URL (copy this value for Part A, Step 4). This URL updates dynamically when the email domain is entered.
@@ -162,21 +166,21 @@ If attempting to use the "Test SAML login" option in Google Admin Console and re
- **Name ID Format**: The expected format (`urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress`).
- **Supported Assertion Attributes**: The list of accepted attributes (`firstName`, `lastName`, `userType`, `organization`).
-
+
### Step 2: Enter the Email Domain and Upload Metadata
-1. Enter the **email domain** for the organization (e.g., `prowler.cloud`). Prowler App uses this domain to identify users who should authenticate via SAML. The ACS URL updates automatically to reflect the configured domain.
+1. Enter the **email domain** for the organization (e.g., `prowler.cloud`). Prowler Cloud uses this domain to identify users who should authenticate via SAML. The ACS URL updates automatically to reflect the configured domain.
2. Upload the **metadata XML file** downloaded in Part A, Step 3.
3. Click "Save".
-
+
### Step 3: Verify the Enabled Status
The "SAML SSO Integration" card should now display a **"Status: Enabled"** indicator with a checkmark, confirming that the configuration is complete.
-
+
---
@@ -214,13 +218,13 @@ To test the `userType` → role mapping, set the **Department** attribute in the
1. Navigate to the Prowler login page.
2. Click "Continue with SAML SSO".
3. Enter an email from the configured domain (e.g., `adrian@prowler.cloud`).
-4. Click "Log in". The browser redirects to Google for authentication and returns to Prowler App upon success.
+4. Click "Log in". The browser redirects to Google for authentication and returns to Prowler Cloud upon success.
-
+
### Verify User Profile and Role Mapping
-After a successful SSO login, the user profile in Prowler App reflects the attributes sent by Google Workspace:
+After a successful SSO login, the user profile in Prowler Cloud reflects the attributes sent by Google Workspace:
- **Name**: Populated from the `firstName` and `lastName` attributes.
- **Role**: Created automatically from the `userType` attribute (e.g., `Backend`). If the role did not exist previously, it is created with read-only access by default.
@@ -230,14 +234,14 @@ After a successful SSO login, the user profile in Prowler App reflects the attri
For more details on role assignment behavior and attribute mapping, refer to the [SAML SSO Configuration](/user-guide/tutorials/prowler-app-sso#configure-attribute-mapping-in-the-idp) page.
-
+
### IdP-Initiated SSO (from Google)
1. Sign in to Google Workspace with an account that has access to the Prowler SAML app.
2. Open the Google Workspace app launcher (the grid icon in the top-right corner of any Google page).
-3. Click the Prowler app tile.
-4. The browser redirects directly to Prowler App, authenticated.
+3. Click the Prowler tile.
+4. The browser redirects directly to Prowler Cloud, authenticated.
For more information on the SSO login flows, refer to the [SAML SSO Configuration](/user-guide/tutorials/prowler-app-sso#idp-initiated-sso) page.
@@ -270,7 +274,7 @@ Prowler does not allow two tenants to share the same email domain. If the domain
**Just-in-Time Provisioning**
-Users who authenticate via SAML for the first time are automatically created in Prowler App. No prior invitation is needed. User attributes (`firstName`, `lastName`, `userType`) are updated on every login from the Google directory.
+Users who authenticate via SAML for the first time are automatically created in Prowler Cloud. No prior invitation is needed. User attributes (`firstName`, `lastName`, `userType`) are updated on every login from the Google directory.
@@ -278,10 +282,10 @@ Users who authenticate via SAML for the first time are automatically created in
## Quick Summary
-1. In **Google Admin Console**, create a custom SAML app using the ACS URL and Entity ID from Prowler App.
+1. In **Google Admin Console**, create a custom SAML app using the ACS URL and Entity ID from Prowler Cloud.
2. Configure **attribute mapping**: `firstName`, `lastName`, and optionally `userType` and `organization`.
3. **Download the metadata XML** from Google.
4. **Enable the app** in Google Workspace for the relevant users or groups.
-5. In **Prowler App**, enter the email domain, upload the metadata XML, and save.
+5. In **Prowler Cloud**, enter the email domain, upload the metadata XML, and save.
6. Verify the SAML SSO Integration shows **"Status: Enabled"**.
7. Test login via "Continue with SAML SSO" on the Prowler login page.
diff --git a/docs/user-guide/tutorials/prowler-app-sso.mdx b/docs/user-guide/tutorials/prowler-app-sso.mdx
index 1e61ec1060..bb993942cd 100644
--- a/docs/user-guide/tutorials/prowler-app-sso.mdx
+++ b/docs/user-guide/tutorials/prowler-app-sso.mdx
@@ -1,18 +1,22 @@
---
title: 'SAML Single Sign-On (SSO)'
+sidebarTitle: 'SAML SSO'
---
import { VersionBadge } from "/snippets/version-badge.mdx"
+import { AppliesTo } from "/snippets/applies-to.mdx"
-This guide provides comprehensive instructions to configure SAML-based Single Sign-On (SSO) in Prowler App. This configuration allows users to authenticate using the organization's Identity Provider (IdP).
+
+
+This guide provides comprehensive instructions to configure SAML-based Single Sign-On (SSO) in Prowler Cloud. This configuration allows users to authenticate using the organization's Identity Provider (IdP).
This document is divided into two main sections:
-- **[User Guide](#user-guide-configuration)**: For organization administrators to configure SAML SSO through Prowler App.
+- **[User Guide](#user-guide-configuration)**: For organization administrators to configure SAML SSO through Prowler Cloud.
-- **[Developer and Administrator Guide](#developer-and-administrator-guide)**: For developers and system administrators running self-hosted Prowler App instances, providing technical details on environment configuration, API usage, and testing.
+- **[Developer and Administrator Guide](#developer-and-administrator-guide)**: For developers and system administrators running Prowler Local Server instances, providing technical details on environment configuration, API usage, and testing.
---
@@ -43,7 +47,7 @@ If the SAML configuration is removed, users who previously authenticated via SAM
#### Step 1: Access Profile Settings
-To access the account settings, click the "Account" button in the top-right corner of Prowler App, or navigate directly to `https://cloud.prowler.com/profile` (or `http://localhost:3000/profile` for local setups).
+To access the account settings, click the "Account" button in the top-right corner of Prowler Cloud, or navigate directly to `https://cloud.prowler.com/profile` (or `http://localhost:3000/profile` for local setups).

@@ -63,12 +67,12 @@ Choose a Method:
- Prowler App displays the SAML configuration information needed to configure the IdP. Use this information to create a new SAML application in the IdP.
+ Prowler Cloud displays the SAML configuration information needed to configure the IdP. Use this information to create a new SAML application in the IdP.
1. **Assertion Consumer Service (ACS) URL**: The endpoint in Prowler that will receive the SAML assertion from the IdP.
2. **Audience URI (Entity ID)**: A unique identifier for the Prowler application (Service Provider).
- To configure the IdP, copy the **ACS URL** and **Audience URI** from Prowler App and use them to set up a new SAML application.
+ To configure the IdP, copy the **ACS URL** and **Audience URI** from Prowler Cloud and use them to set up a new SAML application.

@@ -81,13 +85,13 @@ Choose a Method:
**Configure Attribute Mapping in the IdP**
- For Prowler App to correctly identify and provision users, configure the IdP to send the following attributes in the SAML assertion:
+ For Prowler Cloud to correctly identify and provision users, configure the IdP to send the following attributes in the SAML assertion:
| Attribute Name | Description | Required |
|----------------|---------------------------------------------------------------------------------------------------------|----------|
| `firstName` | The user's first name. | Yes |
| `lastName` | The user's last name. | Yes |
- | `userType` | Determines which Prowler role the user receives (e.g., `admin`, `auditor`). If a role with that name already exists, the user receives it automatically; if it does not exist, Prowler App creates a new role with that name with read-only access (visibility over all providers, no management permissions). If `userType` is not defined, the user's existing roles are left unchanged. Role permissions can be edited in the [RBAC Management tab](/user-guide/tutorials/prowler-app-rbac). | No |
+ | `userType` | Determines which Prowler role the user receives (e.g., `admin`, `auditor`). If a role with that name already exists, the user receives it automatically; if it does not exist, Prowler Cloud creates a new role with that name with read-only access (visibility over all providers, no management permissions). If `userType` is not defined, the user's existing roles are left unchanged. Role permissions can be edited in the [RBAC Management tab](/user-guide/tutorials/prowler-app-rbac). | No |
| `organization` | The user's company name. | No |
@@ -98,9 +102,15 @@ Choose a Method:
+ **Single-Value `userType` Required**
+
+ Map `userType` to an IdP attribute that always contains a single value. If the IdP sends multiple values, Prowler Cloud uses only the first value and does not assign multiple roles or select the highest-privilege role.
+
+
+
**Dynamic Updates**
- Prowler App updates these attributes each time a user logs in. Any changes made in the Identity Provider (IdP) will be reflected when the user logs in again.
+ Prowler Cloud updates these attributes each time a user logs in. Any changes made in the Identity Provider (IdP) will be reflected when the user logs in again.
@@ -132,30 +142,31 @@ Choose a Method:

- 7. **Configure User Attributes in Okta**: Okta acts as the central source for user profile information. Prowler App maps the following Okta user profile attributes during each SAML login:
+ 7. **Configure User Attributes in Okta**: Okta acts as the central source for user profile information. Prowler Cloud maps the following Okta user profile attributes during each SAML login:
- * **First name** (`firstName`): Maps to the user's first name in Prowler App.
- * **Last name** (`lastName`): Maps to the user's last name in Prowler App.
+ * **First name** (`firstName`): Maps to the user's first name in Prowler Cloud.
+ * **Last name** (`lastName`): Maps to the user's last name in Prowler Cloud.

- * **Organization** (`organization`): Maps to the company name displayed in Prowler App. This attribute is optional.
- * **User type** (`userType`): Determines the Prowler role assigned to the user. This attribute is **case-sensitive**: if it matches the exact name of an existing role in Prowler App the user receives that role; if no role with that name exists, a new one is created with read-only access.
+ * **Organization** (`organization`): Maps to the company name displayed in Prowler Cloud. This attribute is optional.
+ * **User type** (`userType`): Determines the Prowler role assigned to the user. This attribute is **case-sensitive**: if it matches the exact name of an existing role in Prowler Cloud the user receives that role; if no role with that name exists, a new one is created with read-only access.

- To modify these values, edit the user's profile directly in the Okta admin console under the "Profile" tab. Changes are reflected in Prowler App the next time the user logs in via SAML.
+ To modify these values, edit the user's profile directly in the Okta admin console under the "Profile" tab. Changes are reflected in Prowler Cloud the next time the user logs in via SAML.
**User Type and Role Assignment**
The `userType` attribute controls which Prowler role is assigned to the user:
- * If a role with the specified name already exists in Prowler App, the user automatically receives that role.
- * If the role does not exist, Prowler App creates a new role with that exact name with read-only access: the user can see all providers and their findings but cannot manage anything. A Prowler administrator (a user whose role includes the "Manage Account" permission) can adjust its permissions afterward through the [RBAC Management tab](/user-guide/tutorials/prowler-app-rbac).
- * If `userType` is not defined in the user's Okta profile, the user's existing roles in Prowler App are left unchanged.
+ * If a role with the specified name already exists in Prowler Cloud, the user automatically receives that role.
+ * If the role does not exist, Prowler Cloud creates a new role with that exact name with read-only access: the user can see all providers and their findings but cannot manage anything. A Prowler administrator (a user whose role includes the "Manage Account" permission) can adjust its permissions afterward through the [RBAC Management tab](/user-guide/tutorials/prowler-app-rbac).
+ * If `userType` is not defined in the user's Okta profile, the user's existing roles in Prowler Cloud are left unchanged.
+ * `userType` must contain a single value. If the IdP sends multiple values, Prowler Cloud uses only the first value and does not assign multiple roles.
- **Example:** To assign the `IT` role to a user, set the `userType` value to `IT` in Okta. If a role named `IT` already exists in Prowler App, the user receives it automatically upon login. If it does not exist, Prowler App creates a new role called `IT` with read-only access, and a Prowler administrator can adjust its permissions as needed.
+ **Example:** To assign the `IT` role to a user, set the `userType` value to `IT` in Okta. If a role named `IT` already exists in Prowler Cloud, the user receives it automatically upon login. If it does not exist, Prowler Cloud creates a new role called `IT` with read-only access, and a Prowler administrator can adjust its permissions as needed.
@@ -171,11 +182,11 @@ Choose a Method:
Once the IdP is configured, it provides a **metadata XML file**. This file contains the IdP's configuration information, such as its public key and login URL.
-To complete the Prowler App configuration:
+To complete the Prowler Cloud configuration:
1. Return to the Prowler SAML configuration page.
-2. Enter the **email domain** for the organization (e.g., `mycompany.com`). Prowler App uses this to identify users who should authenticate via SAML.
+2. Enter the **email domain** for the organization (e.g., `mycompany.com`). Prowler Cloud uses this to identify users who should authenticate via SAML.
3. Upload the **metadata XML file** downloaded from the IdP.
@@ -203,7 +214,7 @@ SAML SSO can be disabled by removing the existing configuration from the integra
Once SAML SSO is configured, users can access Prowler Cloud directly from their Identity Provider's dashboard:
1. Navigate to the IdP dashboard or portal
-2. Click on the Prowler Cloud application tile
+2. Click the Prowler Cloud application tile
3. The system automatically authenticates users and redirects them to Prowler Cloud
This method is convenient for users who primarily work from the IdP portal and prefer a seamless single-click access.
@@ -218,7 +229,7 @@ Users can also initiate the login process directly from Prowler's login page:
3. Enter their email address from the configured domain

4. The system redirects users to the IdP for authentication
-5. After successful authentication, users are returned to Prowler App
+5. After successful authentication, users are returned to Prowler Cloud
This method is useful when users bookmark Prowler or navigate directly to the application.
@@ -226,11 +237,11 @@ This method is useful when users bookmark Prowler or navigate directly to the ap
## Developer and Administrator Guide
-This section provides technical details for developers and administrators of self-hosted Prowler instances.
+This section provides technical details for developers and administrators of Prowler Local Server instances.
### Environment Configuration
-For self-hosted deployments, several environment variables must be configured to ensure SAML SSO functions correctly. These variables are typically set in an `.env` file.
+For Prowler Local Server deployments, several environment variables must be configured to ensure SAML SSO functions correctly. These variables are typically set in an `.env` file.
| Variable | Description | Example |
|---------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------|
diff --git a/docs/user-guide/tutorials/prowler-app.mdx b/docs/user-guide/tutorials/prowler-app.mdx
index 5e99a41ae7..6c3131d136 100644
--- a/docs/user-guide/tutorials/prowler-app.mdx
+++ b/docs/user-guide/tutorials/prowler-app.mdx
@@ -1,34 +1,34 @@
---
title: 'Prowler Cloud'
+sidebarTitle: 'Getting Started'
---
+import { ProviderCards } from "/snippets/provider-cards.mdx"
+
**Prowler Cloud** is a web application that simplifies running Prowler. This tutorial will guide you through setting up and using it.
-We refer to **Prowler App** as the self-hosted version of **Prowler Cloud**.
+**Prowler Local Server** is the self-hosted version of **Prowler Cloud**. See [Prowler product families](/getting-started/products) for every official product name.
## Accessing Prowler Cloud and API Documentation
If you are a [Prowler Cloud](https://cloud.prowler.com/sign-in) user, you can access API docs at [https://api.prowler.com/api/v1/docs](https://api.prowler.com/api/v1/docs)
-**For Prowler App users**
+**For Prowler Local Server users**
-After [installing](/getting-started/installation/prowler-app) **Prowler App**, access it at [http://localhost:3000](http://localhost:3000).
+After [installing](/getting-started/installation/prowler-app) **Prowler Local Server**, access it at [http://localhost:3000](http://localhost:3000).
To view the auto-generated **Prowler API** documentation, navigate to [http://localhost:8080/api/v1/docs](http://localhost:8080/api/v1/docs). This documentation provides details on available endpoints, parameters, and responses.
-## **Step 1: Sign Up**
-
-### **Sign Up with Email**
-
+## Step 1: Sign Up
+### Sign Up with Email
To get started, sign up using your email and password:
-### **Sign Up with Social Login**
-
+### Sign Up with Social Login
If Social Login is enabled, you can sign up using your preferred provider (e.g., Google, GitHub).
@@ -44,16 +44,14 @@ If your email is not registered, a new account will be created using your social
See [how to configure Social Login for Prowler](/user-guide/tutorials/prowler-app-social-login) to enable this feature in your own deployments.
-## **Step 2: Log In**
-
-Once registered, log in with your email and password to access Prowler App.
+## Step 2: Log In
+Once registered, log in with your email and password to access Prowler Cloud.
Upon logging in, the Overview page will display. At this stage, no data is present: add a provider to begin scanning your cloud environment.
-## **Step 3: Add a Provider**
-
+## Step 3: Add a Provider
To perform security scans, link a cloud provider account. Prowler supports the following providers and more:
- **AWS**
@@ -77,48 +75,21 @@ Steps to add a provider:
-## **Step 4: Configure the Provider**
-
+## Step 4: Configure the Provider
Select the cloud provider to scan and configure authentication credentials. Each provider has specific requirements and authentication methods.
For detailed instructions on configuring credentials for each provider, refer to the provider-specific getting started guides:
-
-
- Configure AWS authentication using IAM Access Keys or Assumed Role credentials.
-
-
- Set up Azure authentication using Service Principal credentials.
-
-
- Configure GCP authentication with Service Account or Application Default Credentials.
-
-
- Connect OCI with API key credentials to scan compartments and regions.
-
-
- Set up Kubernetes authentication using kubeconfig files for cluster access.
-
-
- Configure M365 authentication with Application Certificate or Client Secret.
-
-
- Set up GitHub authentication using Personal Access Token, OAuth App, or GitHub App.
-
-
- Scan IaC public or private repositories for security issues.
-
-
-## **Step 5: Test Connection**
+
-After adding your credentials of your cloud account, click the `Launch` button to verify that Prowler App can successfully connect to your provider:
+## Step 5: Test Connection
+After adding your credentials of your cloud account, click the `Launch` button to verify that Prowler can successfully connect to your provider:
-## **Step 6: Scan started**
-
+## Step 6: Scan Started
After successfully adding and testing your credentials, Prowler will start scanning your cloud environment, click the `Go to Scans` button to see the progress:
@@ -127,8 +98,7 @@ After successfully adding and testing your credentials, Prowler will start scann
Prowler will automatically scan all configured providers every **24 hours**, ensuring your cloud environment stays continuously monitored.
-## **Step 7: Monitor Scan Progress**
-
+## Step 7: Monitor Scan Progress
Track the progress of your scan in the `Scans` section:
@@ -146,8 +116,7 @@ Each dashboard handles scan data differently:
When a new scan completes or a new data ingestion is processed, the dashboards automatically reflect the updated results.
-## **Step 8: Analyze the Findings**
-
+## Step 8: Analyze the Findings
While the scan is running, start exploring the findings in these sections:
- **Overview**: High-level summary of the scans.
@@ -168,8 +137,7 @@ While the scan is running, start exploring the findings in these sections:
To view all `new` findings that have not been seen prior to this scan, click the `Delta` filter and select `new`. To view all `changed` findings that have had a status change (from `PASS` to `FAIL` for example), click the `Delta` filter and select `changed`.
-## **Step 9: Download the Outputs**
-
+## Step 9: Download the Outputs
Once a scan is complete, navigate to the Scan Jobs section to download the output files generated by Prowler:
@@ -190,8 +158,7 @@ The `zip` file unpacks into a folder named like `prowler-output--
-## **Step 10: Download specified compliance report**
-
+## Step 10: Download Specified Compliance Report
Once your scan has finished, you don’t need to grab the entire ZIP—just pull down the specific compliance report you want:
- Navigate to the **Compliance** section of the UI.
diff --git a/docs/user-guide/tutorials/prowler-cloud-aws-organizations.mdx b/docs/user-guide/tutorials/prowler-cloud-aws-organizations.mdx
index d9c17aaa5f..8b2124e004 100644
--- a/docs/user-guide/tutorials/prowler-cloud-aws-organizations.mdx
+++ b/docs/user-guide/tutorials/prowler-cloud-aws-organizations.mdx
@@ -1,17 +1,20 @@
---
-title: 'AWS Organizations in Prowler Cloud'
+title: 'AWS Organizations'
description: 'Onboard all AWS accounts in your Organization through a single guided wizard'
---
import { VersionBadge } from "/snippets/version-badge.mdx"
+import { SubscriptionBanner } from "/snippets/subscription-banner.mdx"
-Prowler Cloud enables you to onboard all AWS accounts in your Organization through a single guided wizard. Instead of connecting accounts one by one, you can discover every account in your AWS Organization, select the ones you want to monitor, test connectivity, and launch scans — all from the Prowler Cloud UI.
+Prowler Cloud onboards every AWS account in your Organization through a single guided wizard. Instead of connecting accounts one by one, you can discover every account in your AWS Organization, select the ones you want to monitor, test connectivity, and launch scans — all from the Prowler Cloud UI.
-
-This feature is **exclusively available in Prowler Cloud**. For CLI-based multi-account scanning, see [AWS Organizations in Prowler CLI](/user-guide/providers/aws/organizations).
-
+
+For CLI-based multi-account scanning, see [AWS Organizations in Prowler CLI](/user-guide/providers/aws/organizations).
+
+
+To follow this guide you need an active [Prowler Cloud](https://cloud.prowler.com) account and access to your AWS Organization [management account](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html) (or a registered delegated administrator account).
## Overview
@@ -22,227 +25,19 @@ This feature is **exclusively available in Prowler Cloud**. For CLI-based multi-
| **Individual accounts** | A few AWS accounts | Connect each account one by one with its own IAM role. |
| **AWS Organizations** | 10+ accounts, or any org-managed environment | Connect once to your management account, discover all member accounts automatically, and scan them in bulk. |
-### How it works
+### How It Works
-Before using the AWS Organizations wizard, you need to deploy **two IAM roles** in your AWS environment. The onboarding follows this sequence:
+
+
+Onboarding deploys the **ProwlerScan Identity and Access Management (IAM) role** in your management account and in every member account. A **single CloudFormation stack** — launched from the wizard's **Create Stack in Management Account** button ([Step 2](#step-2-authenticate-with-your-management-account)) — creates the management account role **and** a service-managed StackSet that rolls the role out to your member accounts in one operation. Prefer to deploy the roles yourself? See [Deploy the Roles Manually](#deploy-the-roles-manually).
-
+
-## Key Concepts
+## Step 1: Start the Organization Wizard
-### What is an External ID?
-
-An **External ID** is a security token that Prowler generates unique to your tenant. When Prowler assumes the IAM role in your AWS account, it presents this External ID to prove its identity.
-
-This prevents the [confused deputy problem](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html) — a scenario where an unauthorized party could trick AWS into granting access to your account. By requiring the External ID, only your specific Prowler tenant can assume the role.
-
-You don't need to create the External ID yourself — Prowler generates it automatically and displays it in the wizard for you to copy.
-
-### Two Roles Architecture
-
-Prowler requires **two separate IAM roles** deployed in different places, each with a distinct purpose:
-
-| Role | Where it lives | What it does | How to deploy it |
-|------|---------------|--------------|------------------|
-| **ProwlerScan** (management account) | Your management (root) account only | Discovers the Organization structure **and** scans the management account. Has additional Organizations discovery permissions. | Via **Quick Create** link or **manually** in the IAM Console ([Step 1](#step-1-create-the-management-account-role)). Cannot be deployed via StackSet. |
-| **ProwlerScan** (member accounts) | Every member account | Scans the account for security findings. | Via **CloudFormation StackSet** ([Step 2](#step-2-deploy-the-cloudformation-stackset)). Automated across all accounts. |
-
-
-
-
-
-
-**Same name, different permissions.** Both roles are named `ProwlerScan` — Prowler expects a consistent role name across all accounts. The management account role has the same scanning permissions as member accounts, plus additional Organizations discovery permissions (see [Step 1](#step-1-create-the-management-account-role) for the full list).
-
-
-### What is a CloudFormation StackSet?
-
-A [CloudFormation StackSet](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html) lets you deploy the same CloudFormation template across multiple AWS accounts in a single operation. Prowler uses a StackSet to deploy the **ProwlerScan** IAM role into every member account of your organization, so you don't have to create the role manually in each account.
-
-## Prerequisites
-
-### Prowler Cloud Account
-
-You need an active [Prowler Cloud](https://cloud.prowler.com) account. Each AWS account you connect will count as a provider in your subscription. See [Billing Impact](#billing-impact) for details.
-
-### AWS Organization Enabled
-
-Your AWS environment must have [AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html) enabled. You will need access to the **management account** (or a delegated administrator account) to provide the Organization ID and IAM Role ARN.
-
-## Step 1: Create the Management Account Role
-
-The first role you need to create is the **management account role**. This role allows Prowler to discover your Organization structure — listing accounts, OUs, and hierarchy.
-
-
-**StackSets do not deploy to the management account.** Organizational CloudFormation StackSets with service-managed permissions only target member accounts — this is an AWS limitation, not a Prowler one. You must create the management account role separately, either via the Quick Create link ([Option A](#option-a-quick-create-link-fastest)) or manually ([Option B](#option-b-create-the-role-manually)).
-
-
-
-**The role must be named `ProwlerScan`** — the same name as the role deployed to member accounts via StackSet. Prowler expects a consistent role name across all accounts in the Organization. If you use a different name, connection tests and scans will fail for the management account.
-
-
-### Option A: Quick Create Link (Fastest)
-
-The Prowler wizard provides a one-click link that opens the AWS Console with the CloudFormation template pre-configured. This creates a **CloudFormation Stack** (not a StackSet) that deploys the ProwlerScan role with Organizations permissions enabled in your management account.
-
-
-**[Open Quick Create Stack in AWS Console →](https://us-east-1.console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/quickcreate?templateURL=https%3A%2F%2Fprowler-cloud-public.s3.eu-west-1.amazonaws.com%2Fpermissions%2Ftemplates%2Faws%2Fcloudformation%2Fprowler-scan-role.yml&stackName=Prowler¶m_EnableOrganizations=true)**
-
-Opens the CloudFormation Console with the Prowler scan role template and `EnableOrganizations=true` pre-filled. You will need to enter the **ExternalId** parameter manually — copy it from the Prowler wizard ([Step 4](#step-4-authenticate-with-your-management-account)).
-
-
-1. Click **[Open Quick Create Stack in AWS Console →](https://us-east-1.console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacks/quickcreate?templateURL=https%3A%2F%2Fprowler-cloud-public.s3.eu-west-1.amazonaws.com%2Fpermissions%2Ftemplates%2Faws%2Fcloudformation%2Fprowler-scan-role.yml&stackName=Prowler¶m_EnableOrganizations=true)** or use the **Create Stack in Management Account** button in the Prowler wizard (which also pre-fills the ExternalId).
-2. Enter the **ExternalId** parameter if not pre-filled.
-3. Check **"I acknowledge that AWS CloudFormation might create IAM resources with custom names"** and click **Create stack**.
-4. Wait for the stack to reach **CREATE_COMPLETE** status.
-
-Take note of the **Role ARN** from the stack's **Outputs** tab — you will need it in the wizard.
-
-### Option B: Create the Role Manually
-
-1. Sign in to the [AWS IAM Console](https://console.aws.amazon.com/iam/) in your **management account**.
-
-2. Go to **Roles > Create role** and select **Custom trust policy**.
-
-3. Paste the following trust policy. This allows Prowler Cloud to assume the role using your tenant's External ID (you will get this from the Prowler wizard in [Step 3](#step-3-start-the-organization-wizard)):
-
-```json
-{
- "Version": "2012-10-17",
- "Statement": [
- {
- "Effect": "Allow",
- "Principal": {
- "AWS": "arn:aws:iam::232136659152:root"
- },
- "Action": "sts:AssumeRole",
- "Condition": {
- "StringEquals": {
- "sts:ExternalId": ""
- },
- "StringLike": {
- "aws:PrincipalArn": "arn:aws:iam::232136659152:role/prowler*"
- }
- }
- }
- ]
-}
-```
-
-Replace `` with the External ID shown in the Prowler wizard.
-
-4. Attach the following AWS managed policies:
- - **SecurityAudit**
- - **ViewOnlyAccess**
-
- This allows Prowler to also scan the management account for security findings, just like any other account.
-
-5. Create an additional inline policy with the following permissions. These are specific to the management account and allow Prowler to discover your Organization structure:
-
-```json
-{
- "Version": "2012-10-17",
- "Statement": [
- {
- "Sid": "ProwlerOrganizationDiscovery",
- "Effect": "Allow",
- "Action": [
- "organizations:DescribeAccount",
- "organizations:DescribeOrganization",
- "organizations:ListAccounts",
- "organizations:ListAccountsForParent",
- "organizations:ListOrganizationalUnitsForParent",
- "organizations:ListRoots",
- "organizations:ListTagsForResource"
- ],
- "Resource": "*"
- },
- {
- "Sid": "ProwlerStackSetManagement",
- "Effect": "Allow",
- "Action": [
- "organizations:RegisterDelegatedAdministrator",
- "iam:CreateServiceLinkedRole"
- ],
- "Resource": "*"
- }
- ]
-}
-```
-
-
-You can optionally restrict the `Resource` field to your specific Organization ARN (e.g., `arn:aws:organizations::123456789012:organization/o-abc123def4`) instead of `"*"` to minimize the blast radius.
-
-
-6. Name the role **`ProwlerScan`** and click **Create role**. Take note of the **Role ARN** — you will need it in the Prowler wizard.
-
-The ARN follows this format: `arn:aws:iam:::role/ProwlerScan`
-
-
-The role **must** be named `ProwlerScan`. Do not use a different name.
-
-
-
-If you just created the role, it may take up to **60 seconds** for AWS to propagate it. If you get an error in the Prowler wizard, wait a moment and try again.
-
-
-## Step 2: Deploy the CloudFormation StackSet
-
-After creating the management account role, the next step is to deploy the **ProwlerScan** role to your member accounts using a CloudFormation StackSet. This is the recommended method for consistent, scalable deployment across your entire organization.
-
-The StackSet uses **service-managed permissions**, which means AWS Organizations handles the cross-account deployment automatically — you don't need to create execution roles manually in each account. The StackSet deploys the ProwlerScan IAM role in every target member account, enabling Prowler to assume that role for cross-account scanning.
-
-
-**Trusted access required:** CloudFormation StackSets must have trusted access enabled in your management account. Verify this in the AWS Console under **AWS Organizations > Settings > Trusted access for AWS CloudFormation StackSets**.
-
-
-
-**The Quick Create link creates a Stack, not a StackSet.** The link in the Prowler wizard creates a CloudFormation **Stack** that deploys the ProwlerScan role in your management account only ([Step 1](#step-1-create-the-management-account-role)). To deploy the role across **member accounts**, you must create a StackSet manually as described below. AWS does not support Quick Create links for StackSets.
-
-
-
-**[Open StackSets Console →](https://us-east-1.console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacksets/create)**
-
-Opens the CloudFormation StackSets creation page directly. You will need to paste the template URL and ExternalId manually.
-
-
-1. Click the link above or navigate to **CloudFormation > StackSets > Create StackSet** in your management account.
-2. Choose **Service-managed permissions**.
-3. Select **Amazon S3 URL** as the template source and paste the following URL:
- ```
- https://prowler-cloud-public.s3.eu-west-1.amazonaws.com/permissions/templates/aws/cloudformation/prowler-scan-role.yml
- ```
-4. Set the **ExternalId** parameter to the External ID shown in the Prowler wizard.
-5. Choose your deployment targets (entire organization or specific OUs).
-6. Select the AWS regions where you want the role deployed.
-7. Click **Create StackSet**.
-
-### Verify StackSet Deployment
-
-After deploying, verify that all stack instances completed successfully:
-
-1. In the CloudFormation Console, go to **StackSets** and select your Prowler StackSet.
-2. Click the **Stack instances** tab.
-3. Confirm that all instances show **Status: CURRENT** and **Stack status: CREATE_COMPLETE**.
-
-Deployment typically takes **2–5 minutes** for medium-sized organizations. Large organizations (500+ accounts) may take longer.
-
-
-**Prefer Terraform?** You can deploy the ProwlerScan role using Terraform instead. See the [StackSets deployment guide](/user-guide/providers/aws/organizations#deploying-prowler-iam-roles-across-aws-organizations) for the Terraform module.
-
-
-### Key Considerations
-
-- **Service-managed permissions**: Always select **Service-managed permissions** when creating the StackSet. This lets AWS Organizations manage the deployment automatically across current and future member accounts.
-- **Least privilege**: The ProwlerScan role deployed by the StackSet uses `SecurityAudit` and `ViewOnlyAccess` — AWS managed policies that grant read-only access — plus a small set of additional read-only permissions for services not covered by those policies. See the [CloudFormation template](https://prowler-cloud-public.s3.eu-west-1.amazonaws.com/permissions/templates/aws/cloudformation/prowler-scan-role.yml) for the full list. Prowler does not make any changes to your accounts.
-- **New accounts**: When you add new accounts to your AWS Organization, the StackSet automatically deploys the ProwlerScan role to them if you targeted the organization root or the relevant OU. Combined with Prowler's 6-hour automatic sync, new accounts are onboarded end-to-end without manual intervention.
-- **Management account**: Organizational StackSets **do not deploy to the management account itself**. If you want to scan the management account, you need to create the ProwlerScan role there separately using a regular CloudFormation Stack.
-
-## Step 3: Start the Organization Wizard
-
-Now that both roles are deployed — the management account role (Step 1) and the ProwlerScan role in member accounts (Step 2) — you can start the Prowler wizard.
+The Prowler wizard walks you through the entire flow: deploying both roles from a single CloudFormation stack, discovering your accounts, testing connectivity, and launching scans.
### Open the Wizard
@@ -279,29 +74,50 @@ Now that both roles are deployed — the management account role (Step 1) and th
Click **Next** to proceed to the authentication phase.
-## Step 4: Authenticate with Your Management Account
+## Step 2: Authenticate with Your Management Account
-The wizard's **Authentication Details** page guides you through three actions: deploying the roles in AWS, entering the management account Role ARN, and confirming the deployment.
+The **Authentication Details** page guides you through three actions: deploying the roles in AWS, entering the deployment account Role ARN, and confirming the deployment. The deployment account is either the management account or, when delegated administrator mode is selected, the delegated administrator account.
### External ID
-The wizard displays a **Prowler External ID** at the top — auto-generated and unique to your tenant. Click the copy icon to copy it. You will need this External ID for both the management account Stack and the member accounts StackSet.
+The wizard displays a **Prowler External ID** at the top — auto-generated and unique to your tenant. Click the copy icon to copy it. The External ID is pre-filled into the deployment link, and the single stack applies it to both the management account role and the member-account StackSet. Learn more in [What Is an External ID?](#what-is-an-external-id).
### Deploy the Roles
-The wizard provides two deployment actions:
+
-1. **Create Stack in Management Account** — opens a Quick Create link that deploys the ProwlerScan role with `EnableOrganizations=true` in your management account ([Step 1](#step-1-create-the-management-account-role)). The External ID is pre-filled.
+The wizard deploys the deployment account role and the member-account StackSet in a **single** CloudFormation Stack:
-2. **Open StackSets Console** — links to the CloudFormation StackSets console where you create a StackSet for member accounts ([Step 2](#step-2-deploy-the-cloudformation-stackset)). Copy the template URL shown in the wizard and paste the External ID manually.
+
+**Prefer to use your own role?** You do not have to use the Quick Create template. Create the ProwlerScan role yourself — through the IAM Console, Terraform, or your own CloudFormation [(Following this guide)](#deploy-the-roles-manually) — and paste its ARN into the Role ARN field below. The role must use the external ID from the earlier step and include the trust policy and permissions described in [Deploy the Roles Manually](#deploy-the-roles-manually).
+
+
+1. **Organizational Unit or Root ID** — enter the AWS OU (`ou-xxxx-yyyyyyyy`) or organization root (`r-xxxx`) you want to onboard. Prowler rolls the ProwlerScan role out to every member account under this target. Find it in the [AWS Organizations Console](https://console.aws.amazon.com/organizations/); use the **root ID** (`r-`) to cover the entire organization or an **OU ID** (`ou-`) to target a specific unit.
+
+2. *(Optional)* Check **"I'm deploying from a delegated administrator account"** if you launch the stack from a delegated administrator account instead of the management account.
+
+3. **Create Stack in Management Account** — or **Create Stack in Delegated Administrator Account** when delegated administrator mode is selected — opens a Quick Create link that deploys, in a single stack: the ProwlerScan role in the account where you launch the stack (`DeployLocalRole`, with `EnableOrganizations=true`) **and** a service-managed StackSet (`DeployStackSet`) that rolls the role out to your member accounts. The External ID, OU/Root ID, and deployment options are pre-filled.
-
+
-### Enter the Management Account Role ARN
+
+**Finding your Organizational Unit or Root ID.** In the [AWS Organizations Console](https://console.aws.amazon.com/organizations/) the root (`r-…`) and OU (`ou-…`) IDs appear in the account tree, or run these from your management account:
-Paste the **Role ARN** of the management account role you created in [Step 1](#step-1-create-the-management-account-role) into the **Management Account Role ARN** field.
+```bash
+# Root ID — deploys the role to the entire organization
+aws organizations list-roots --query 'Roots[0].Id' --output text
+
+# OU IDs under the root — to target a specific unit instead
+aws organizations list-organizational-units-for-parent --parent-id r-xxxx \
+ --query 'OrganizationalUnits[].{Name:Name,Id:Id}' --output table
+```
+
+
+### Enter the Deployment Account Role ARN
+
+Paste the **Role ARN** created by the stack above into the **Management Account Role ARN** field or, when delegated administrator mode is selected, the **Delegated Administrator Account Role ARN** field.
The ARN follows this format:
```
@@ -311,12 +127,16 @@ arn:aws:iam:::role/ProwlerScan
For example: `arn:aws:iam::123456789012:role/ProwlerScan`
-
+
+
+It may take up to **60 seconds** for AWS to generate the IAM Role ARN after the stack completes. If the wizard reports an error, wait a moment and try again.
+
+
### Confirm and Discover
-1. Check the box: **"The Stack and StackSet have been successfully deployed in AWS"**.
+1. Check the box: **"The Stack has been successfully deployed in AWS"**.
2. Click **Authenticate**.
Here's what happens behind the scenes:
@@ -324,7 +144,7 @@ Here's what happens behind the scenes:
- An asynchronous discovery is triggered to query your AWS Organization structure.
- You will see a **"Gathering AWS Accounts..."** spinner — this typically takes **30 seconds to 2 minutes** depending on your organization size.
-## Step 5: Select Accounts to Scan
+## Step 3: Select Accounts to Scan
### Understanding the Tree View
@@ -335,6 +155,7 @@ Once discovery completes, the wizard displays a **hierarchical tree view** of yo
- The tree supports up to **5 levels of nesting** (Root > OUs > Sub-OUs > Accounts).
+- If you deployed the stack for just one OU, that OU will be preselected in the tree.
- **Selecting an OU** automatically selects all accounts within it.
- **Individual overrides**: deselect specific accounts even if the parent OU is selected.
- The header shows **"X of Y accounts selected"** to track your selection.
@@ -351,14 +172,12 @@ Only **ACTIVE** accounts can be selected for scanning:
| **CLOSED** | No | Account has been closed. |
-**Your existing data is safe.** If an AWS account is already connected to Prowler as an individual provider, it will appear in the tree with a checkmark indicator.
+**Your existing data is safe.** If an AWS account is already connected to Prowler as an individual provider, it appears in the tree with a checkmark indicator.
When you proceed:
- The existing provider is **linked** to the organization — it is **not** duplicated.
- All your **historical scan data and findings are preserved** — nothing is overwritten.
- There is **no additional billing** — the existing provider is reused.
-
-This is completely safe. You are simply associating the account with the organization for easier management.
### Custom Aliases
@@ -367,14 +186,9 @@ You can edit the display name for each account before connecting. This alias is
### Blocked Accounts
-Some accounts may appear as **blocked** (grayed out, not selectable). This happens when:
-- The account is **already linked to a different organization** in Prowler (`linked_to_other_organization`).
+Some accounts may appear as **blocked** (grayed out, not selectable) when the account is **already linked to a different organization** in Prowler (`linked_to_other_organization`). Hover over the blocked account to see the specific reason.
-Hover over the blocked account to see the specific reason.
-
-## Step 6: Test Connections
-
-### How Connection Testing Works
+## Step 4: Test Connections
Click **Test Connections** to verify that Prowler can assume the **ProwlerScan** role in each selected member account.
@@ -382,157 +196,225 @@ Click **Test Connections** to verify that Prowler can assume the **ProwlerScan**
-- Each account shows a real-time status indicator:
- - **Spinner** — test in progress
- - **Green checkmark (✓)** — connection successful
- - **Red icon (✗)** — connection failed (hover to see the error)
-
-### All Tests Pass
+Each account shows a real-time status indicator:
+- **Spinner** — test in progress
+- **Green checkmark (✓)** — connection successful
+- **Red icon (✗)** — connection failed (hover to see the error)
If every account connects successfully, you automatically advance to the next step.
-### Some Tests Fail
+### When Some Tests Fail
-An error banner appears: **"There was a problem connecting to some accounts."**
-
-You have two options:
+An error banner appears: **"There was a problem connecting to some accounts."** You have two options:
**a) Fix and retry:**
1. Go to the AWS Console and verify the StackSet deployed to the failing accounts.
2. Check that the External ID in the StackSet matches the one shown in Prowler.
3. Return to Prowler and click **Test Connections** — only the **failed accounts are re-tested** (smart retry). Accounts that already passed are not tested again.
-
-
-
-
**b) Skip and continue:**
-Click **Skip Connection Validation** to proceed with only the accounts that connected successfully. The failed accounts will not be scanned.
+Click **Skip Connection Validation** to proceed with only the accounts that connected successfully. The failed accounts will not be scanned. This option is only available when at least one account connected successfully.
-
-**Skip Connection Validation** is only available when at least one account connected successfully.
-
+If **no accounts** connected successfully, you cannot proceed. Fix the underlying connection issues — see [Troubleshooting](#troubleshooting) — and retry before launching scans.
-### All Tests Fail
+## Step 5: Launch Scans
-If **no accounts** connected successfully, you cannot proceed:
+The Organizations wizard uses the same schedule controls described in [Scan Scheduling](/user-guide/tutorials/prowler-scan-scheduling#schedule-options).
-> *"No accounts connected successfully. Fix the connection errors and retry before launching scans."*
-
-You must fix the underlying connection issues before continuing. See [Updating Credentials](#updating-credentials) below.
-
-### Updating Credentials
-
-If connection tests fail, here's how to fix common issues:
-
-1. Open the [CloudFormation Console](https://console.aws.amazon.com/cloudformation/) and check that your StackSet instances show **CREATE_COMPLETE** for the failing accounts. If not, update the StackSet to include the missing OUs.
-2. Compare the **ExternalId** parameter in your StackSet with the External ID displayed in the Prowler wizard. They must match exactly.
-3. After fixing the issue in AWS, return to Prowler and click **Test Connections**. Only the previously failed accounts will be re-tested.
-
-## Step 7: Launch Scans
-
-### Choose Scan Schedule
-
-| Schedule Option | Description |
-|-----------------|-------------|
-| **Scan Daily (every 24 hours)** | Creates a recurring daily scan for all connected accounts (default). |
-| **Run a single scan (no recurring schedule)** | Launches a one-time scan. |
-
-### Launch
-
-Click **Launch scan**. A toast notification confirms: *"Scan Launched — Daily scan scheduled for X accounts"* with a link to the Scans page. You will be redirected to the **Providers** page.
-
-Scans are only launched for accounts that are accessible (passed connection testing) and were selected.
+Click **Save**, **Save and launch scan**, or **Launch scan**, depending on the selected schedule option. A toast notification confirms whether the schedule was saved, scans were launched, or both, and includes a link to the **Scans** page. Prowler then redirects to the **Providers** page. Scans launch only for accounts that passed connection testing and were selected.
-### What Happens Next
-
+After launching:
- Scans appear in the **Scans** page as they start and complete.
- Results populate the **Overview** and **Findings** pages.
-- Prowler runs an **automatic sync every 6 hours** to detect new accounts added to your Organization or accounts that have been removed. New accounts are onboarded automatically based on the parent OU configuration.
+- Prowler runs an **automatic sync every 6 hours** to detect accounts added to or removed from your Organization. New accounts under the targeted OU or root are onboarded automatically.
## Billing Impact
Each AWS account you connect through the Organizations wizard counts as one **provider** in your Prowler Cloud subscription.
- **Already-connected accounts**: if an account was already linked as a provider, adding it to the organization does **not** incur additional billing. The existing provider is reused.
-- **Large organizations**: connecting a 500-account organization will result in up to 500 providers on your subscription. Review your plan limits before proceeding.
+- **Large organizations**: connecting a 500-account organization results in up to 500 providers on your subscription. Review your plan limits before proceeding.
- **Deleted providers**: if you later remove an account, the deleted provider no longer counts toward your subscription.
-For pricing details, see [Prowler Cloud Pricing](/getting-started/products/prowler-cloud-pricing).
+For pricing details, see [Prowler Cloud Pricing](https://prowler.com/pricing).
## Troubleshooting
-### Invalid AWS Organization ID
+### Only Some Accounts Connect
-*"Must be a valid AWS Organization ID"*
+Discovery succeeds and the tree view appears, but only one account — or a handful — passes the connection test. This almost always means the ProwlerScan role reached the deployment account but not every member account.
-- Verify the Organization ID format: `o-` followed by 10–32 lowercase alphanumeric characters (e.g., `o-abc123def4`)
-- Copy it directly from the [AWS Organizations Console](https://console.aws.amazon.com/organizations/) to avoid typos
+- **Confirm the StackSet deployed.** Open the [CloudFormation Console](https://console.aws.amazon.com/cloudformation/) in the deployment account, select your Prowler StackSet, open the **Stack instances** tab, and confirm every instance shows **Status: CURRENT** and **Stack status: CREATE_COMPLETE**. Instances still in progress or in a failed state explain the missing accounts.
+- **Check the targeted OU or root.** The single stack only rolls the role out to accounts under the **Organizational Unit or Root ID** you entered in [Step 2](#step-2-authenticate-with-your-management-account). Accounts in other OUs are not covered — redeploy targeting the organization root (`r-`) or add the missing OUs.
+- **Verify the deployment account.** The role is created only in the account where you launched the stack. If you deployed from a **delegated administrator account**, confirm that account is a **registered delegated administrator** for CloudFormation StackSets (registered through AWS Organizations), not just a regular member account. A regular member account cannot create a service-managed StackSet, so only its own role is created — leaving every other account without the role.
+- **Suspended accounts** cannot be scanned. Deselect them and proceed.
-### Invalid IAM Role ARN
+### No Accounts Connect
-*"Must be a valid IAM Role ARN"*
+No account passes the connection test.
-- Verify the ARN format: `arn:aws:iam::<12-digit-account-id>:role/`
-- Copy the ARN directly from the [IAM Console](https://console.aws.amazon.com/iam/) in your management account
+- **External ID mismatch.** Compare the **ExternalId** parameter in your StackSet with the External ID shown in the Prowler wizard. They must match exactly.
+- **StackSet not deployed.** Confirm the StackSet exists and its instances reached **CREATE_COMPLETE**. If you deployed the roles manually, verify [trusted access for CloudFormation StackSets](#member-account-role-stackset) is enabled.
+- **IP-based policies.** If your accounts restrict access by IP, allow the [Prowler Cloud egress IPs](/security/networking).
-### Authentication Failed
+### Authentication Fails or Times Out
-*"Authentication failed. Please verify the StackSet deployment and Role ARN"*
+*"Authentication failed. Please verify the StackSet deployment and Role ARN"* or *"Authentication timed out"*
-- Verify the management account role exists and was created in [Step 1](#step-1-create-the-management-account-role)
-- Confirm the trust policy includes the correct External ID from the wizard
-- Check the role has all Organizations discovery permissions listed in [Step 1](#step-1-create-the-management-account-role)
-- Double-check the Role ARN format and account ID for typos
+- Verify the deployment account role exists and is named exactly `ProwlerScan`.
+- Confirm the trust policy includes the correct External ID from the wizard.
+- Check the role has the Organizations discovery permissions listed in [Deploy the Roles Manually](#management-account-role).
+- Double-check the Role ARN format and account ID for typos.
+- Retry — the role can take up to **60 seconds** to propagate, and a second attempt often succeeds. For very large organizations (500+ accounts), allow extra time for discovery.
-### Authentication Timed Out
+### Invalid Organization ID or Role ARN
-*"Authentication timed out"*
+*"Must be a valid AWS Organization ID"* or *"Must be a valid IAM Role ARN"*
-- Retry the authentication step — the second attempt often succeeds
-- Check for AWS API rate limiting on the Organizations service
-- For very large organizations (500+ accounts), allow extra time for discovery
-
-### Connection Test Fails for All Accounts
-
-No accounts pass the connection test.
-
-- Verify the CloudFormation StackSet was deployed — complete [Step 2](#step-2-deploy-the-cloudformation-stackset) and wait for stack instances to reach **CREATE_COMPLETE**
-- Check that the **ExternalId** parameter in the StackSet matches the External ID shown in the Prowler wizard
-- If your accounts use IP-based IAM policies, allow [Prowler Cloud public IPs](/user-guide/tutorials/prowler-cloud-public-ips)
-
-### Connection Test Fails for Some Accounts
-
-Some accounts show a red icon while others pass.
-
-- Expand the StackSet deployment to include the OUs containing the failing accounts
-- Suspended accounts cannot be scanned — deselect them and proceed
-- Ensure the [STS regional endpoint](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) is enabled in the account's region
-- After fixing, click **Test Connections** — only the failed accounts will be re-tested
-
-### No Accounts Connected Successfully
-
-*"No accounts connected successfully. Fix the connection errors and retry before launching scans."*
-
-- Hover over the red icon on each account to see the specific error
-- Fix the underlying issues using the guidance above
-- Click **Test Connections** to retry
+- Organization ID format: `o-` followed by 10–32 lowercase alphanumeric characters (e.g., `o-abc123def4`).
+- Role ARN format: `arn:aws:iam::<12-digit-account-id>:role/ProwlerScan`.
+- Copy both directly from the AWS Console to avoid typos.
### Failed to Apply Discovery
*"Failed to apply discovery"*
-- Check the `blocked_reasons` field for any blocked accounts
-- Retry the operation
-- If the error persists, contact [Prowler Support](mailto:support@prowler.com)
+- Check the `blocked_reasons` field for any blocked accounts and retry the operation.
+- If the error persists, contact [Prowler Support](mailto:support@prowler.com).
+
+## Deploy the Roles Manually
+
+The wizard's **Create Stack** button is the fastest path, but you can create both roles yourself — for example with Terraform or your own CloudFormation — and paste the management account Role ARN into [Step 2](#step-2-authenticate-with-your-management-account). Both roles must be named `ProwlerScan`, since Prowler expects a consistent role name across all accounts.
+
+
+**Prefer Terraform?** You can deploy the ProwlerScan role across the organization with Terraform instead of CloudFormation. See the [StackSets deployment guide](/user-guide/providers/aws/organizations#deploying-prowler-iam-roles-across-aws-organizations) for the module.
+
+
+### Management Account Role
+
+The management account role lets Prowler discover your Organization structure — listing accounts, OUs, and hierarchy — and scan the management account itself. StackSets with service-managed permissions do not deploy to the management account, so this role is always created separately from the member-account StackSet.
+
+1. Sign in to the [AWS IAM Console](https://console.aws.amazon.com/iam/) in your **management account** (or delegated administrator account).
+2. Go to **Roles > Create role** and select **Custom trust policy**.
+3. Paste the following trust policy, replacing `` with the External ID shown in the Prowler wizard:
+
+```json
+{
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Principal": {
+ "AWS": "arn:aws:iam::232136659152:root"
+ },
+ "Action": "sts:AssumeRole",
+ "Condition": {
+ "StringEquals": {
+ "sts:ExternalId": ""
+ },
+ "StringLike": {
+ "aws:PrincipalArn": "arn:aws:iam::232136659152:role/prowler*"
+ }
+ }
+ }
+ ]
+}
+```
+
+4. Attach the AWS managed policies **SecurityAudit** and **ViewOnlyAccess** so Prowler can scan the management account for security findings.
+5. Add an inline policy with the Organizations discovery permissions:
+
+```json
+{
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Sid": "ProwlerOrganizationDiscovery",
+ "Effect": "Allow",
+ "Action": [
+ "organizations:DescribeAccount",
+ "organizations:DescribeOrganization",
+ "organizations:ListAccounts",
+ "organizations:ListAccountsForParent",
+ "organizations:ListOrganizationalUnitsForParent",
+ "organizations:ListRoots",
+ "organizations:ListTagsForResource"
+ ],
+ "Resource": "*"
+ },
+ {
+ "Sid": "ProwlerStackSetManagement",
+ "Effect": "Allow",
+ "Action": [
+ "organizations:RegisterDelegatedAdministrator",
+ "iam:CreateServiceLinkedRole"
+ ],
+ "Resource": "*"
+ }
+ ]
+}
+```
+
+
+You can restrict the `Resource` field to your specific Organization ARN (e.g., `arn:aws:organizations::123456789012:organization/o-abc123def4`) instead of `"*"` to minimize the blast radius.
+
+
+6. Name the role **`ProwlerScan`** and click **Create role**. The ARN follows the format `arn:aws:iam:::role/ProwlerScan` — paste it into the wizard.
+
+### Member Account Role (StackSet)
+
+Deploy the ProwlerScan role to every member account with a [CloudFormation StackSet](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html), so you don't create the role manually in each account.
+
+
+**Trusted access required.** CloudFormation StackSets must have trusted access enabled in your management account. Verify this under **AWS Organizations > Settings > Trusted access for AWS CloudFormation StackSets**.
+
+
+1. In your management account, navigate to **CloudFormation > StackSets > Create StackSet** ([open directly](https://us-east-1.console.aws.amazon.com/cloudformation/home?region=us-east-1#/stacksets/create)).
+2. Choose **Service-managed permissions** so AWS Organizations deploys the role automatically across current and future member accounts.
+3. Select **Amazon S3 URL** as the template source and paste:
+ ```
+ https://prowler-cloud-public.s3.eu-west-1.amazonaws.com/permissions/templates/aws/cloudformation/prowler-scan-role.yml
+ ```
+4. Set the **ExternalId** parameter to the External ID shown in the Prowler wizard.
+5. Choose your deployment targets (entire organization or specific OUs) and regions, then click **Create StackSet**.
+6. Open the **Stack instances** tab and confirm every instance shows **Status: CURRENT** and **Stack status: CREATE_COMPLETE**. Deployment typically takes **2–5 minutes**; large organizations (500+ accounts) may take longer.
+
+The StackSet role uses read-only access only (`SecurityAudit`, `ViewOnlyAccess`, plus a small set of additional read-only permissions). Prowler makes no changes to your accounts. See the [CloudFormation template](https://prowler-cloud-public.s3.eu-west-1.amazonaws.com/permissions/templates/aws/cloudformation/prowler-scan-role.yml) for the full list. When you add new accounts under the targeted OU or root, the StackSet deploys the role automatically, and Prowler's 6-hour sync onboards them end-to-end.
+
+## Key Concepts
+
+### What Is an External ID?
+
+An **External ID** is a security token that Prowler generates unique to your tenant. When Prowler assumes the IAM role in your AWS account, it presents this External ID to prove its identity.
+
+This prevents the [confused deputy problem](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html) — a scenario where an unauthorized party could trick AWS into granting access to your account. By requiring the External ID, only your specific Prowler tenant can assume the role. Prowler generates it automatically and displays it in the wizard for you to copy.
+
+### Two Roles Architecture
+
+Prowler uses **two IAM roles**, both named `ProwlerScan` but deployed in different places:
+
+| Role | Where it lives | What it does |
+|------|---------------|--------------|
+| **ProwlerScan** (management account) | Your management (or delegated administrator) account | Discovers the Organization structure **and** scans that account. Includes additional Organizations discovery permissions. |
+| **ProwlerScan** (member accounts) | Every member account | Scans the account for security findings. |
+
+Both roles share the name `ProwlerScan` because Prowler expects a consistent role name across all accounts. The single CloudFormation stack in [Step 2](#step-2-authenticate-with-your-management-account) deploys both at once.
+
+
+
+
+
+### What Is a CloudFormation StackSet?
+
+A [CloudFormation StackSet](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html) deploys the same CloudFormation template across multiple AWS accounts in a single operation. Prowler uses a service-managed StackSet to deploy the **ProwlerScan** IAM role into every member account of your organization, so you don't create the role manually in each account. StackSets do not deploy to the management account, which is why that role is created separately.
## What's Next
diff --git a/docs/user-guide/tutorials/prowler-cloud-azure-management-groups.mdx b/docs/user-guide/tutorials/prowler-cloud-azure-management-groups.mdx
new file mode 100644
index 0000000000..98cfe095ce
--- /dev/null
+++ b/docs/user-guide/tutorials/prowler-cloud-azure-management-groups.mdx
@@ -0,0 +1,11 @@
+---
+title: 'Azure Management Groups'
+description: 'Onboard all Azure subscriptions in your management groups through a single guided wizard'
+tag: "Coming Soon"
+---
+
+Onboarding Azure management groups through a single guided wizard is coming soon to Prowler Cloud.
+
+Today, Azure subscriptions are onboarded individually. See [Getting Started with Azure](/user-guide/providers/azure/getting-started-azure) and [Bulk Provider Provisioning](/user-guide/tutorials/bulk-provider-provisioning) to automate onboarding multiple subscriptions.
+
+Keep an eye on the [changelog](https://github.com/prowler-cloud/prowler/releases) for updates.
diff --git a/docs/user-guide/tutorials/prowler-cloud-gcp-organizations.mdx b/docs/user-guide/tutorials/prowler-cloud-gcp-organizations.mdx
new file mode 100644
index 0000000000..c0c11747a9
--- /dev/null
+++ b/docs/user-guide/tutorials/prowler-cloud-gcp-organizations.mdx
@@ -0,0 +1,11 @@
+---
+title: 'GCP Organizations'
+description: 'Onboard all GCP projects in your organization through a single guided wizard'
+tag: "Coming Soon"
+---
+
+Onboarding a full GCP organization through a single guided wizard is coming soon to Prowler Cloud.
+
+Today, GCP projects are onboarded individually. See [Getting Started with GCP](/user-guide/providers/gcp/getting-started-gcp) and [Bulk Provider Provisioning](/user-guide/tutorials/bulk-provider-provisioning) to automate onboarding multiple projects.
+
+Keep an eye on the [changelog](https://github.com/prowler-cloud/prowler/releases) for updates.
diff --git a/docs/user-guide/tutorials/prowler-cloud-lighthouse-multi-llm.mdx b/docs/user-guide/tutorials/prowler-cloud-lighthouse-multi-llm.mdx
new file mode 100644
index 0000000000..0cb251df1f
--- /dev/null
+++ b/docs/user-guide/tutorials/prowler-cloud-lighthouse-multi-llm.mdx
@@ -0,0 +1,82 @@
+---
+title: 'Using Multiple LLM Providers'
+sidebarTitle: 'Multiple LLM Providers'
+---
+
+import { SubscriptionBanner } from "/snippets/subscription-banner.mdx"
+
+Lighthouse AI on Prowler Cloud supports multiple Large Language Model (LLM) providers, so teams can choose the option that best fits their infrastructure, compliance requirements, and cost considerations. This guide explains how to configure and manage providers for Lighthouse AI on Prowler Cloud.
+
+
+
+For a feature overview, see [Lighthouse AI on Prowler Cloud](/getting-started/products/prowler-cloud-lighthouse).
+
+## Supported Providers
+
+- **OpenAI:** GPT models, including the default GPT-5.5.
+- **Amazon Bedrock:** AWS-hosted access to Claude, Llama, Titan, and other models.
+- **OpenAI Compatible:** Any service exposing an OpenAI-compatible API endpoint, such as OpenRouter.
+
+## Model Requirements
+
+Lighthouse AI requires models that support all of the following:
+
+- **Text input:** Ability to receive text prompts.
+- **Text output:** Ability to generate text responses.
+- **Tool calling:** Ability to invoke tools to retrieve data from Prowler.
+
+Models without these capabilities are not going to work well.
+
+## Configuring Providers
+
+Navigate to **Configuration** → **Lighthouse AI** to see the available providers, each with its own connection option.
+
+To connect a provider:
+
+1. Click the desired provider.
+2. Enter the required credentials.
+3. Click **Save**. The connection is validated automatically before the provider becomes available.
+
+
+
+The required information differs per provider:
+
+
+
+ - **API Key:** OpenAI API key (starts with `sk-` or `sk-proj-`), created from the [OpenAI platform](https://platform.openai.com/api-keys).
+
+ Confirm the OpenAI account has sufficient credits and that the default GPT-5.5 model is not blocked in the organization settings.
+
+
+ Connect using either an Amazon Bedrock API key or AWS IAM credentials.
+
+ **Amazon Bedrock API key**
+ - **Bedrock API Key:** The key generated from Amazon Bedrock.
+ - **AWS Region:** Region where Bedrock is available.
+
+ **AWS IAM Access Keys**
+ - **AWS Access Key ID** and **AWS Secret Access Key** for the IAM user.
+ - **AWS Region:** Region where Bedrock is available.
+ - The IAM user requires the `AmazonBedrockLimitedAccess` managed policy.
+
+
+ Connect to any service exposing an OpenAI-compatible API endpoint that Prowler Cloud can reach over the Internet.
+
+ - **API Key:** API key from the compatible service.
+ - **Base URL:** API endpoint URL including the version (for example, `https://openrouter.ai/api/v1`).
+
+ ### Example: OpenRouter
+
+ 1. Create an account at [OpenRouter](https://openrouter.ai/).
+ 2. Generate an API key from the OpenRouter dashboard.
+ 3. Enter the API key and set the base URL to `https://openrouter.ai/api/v1`.
+
+
+
+## Model Recommendations
+
+GPT-5.5 is the default and recommended model for Lighthouse AI on Prowler Cloud. Models from Amazon Bedrock and OpenAI-compatible endpoints can also be used, but performance is not guaranteed. Ensure any selected model supports text input, text output, and tool calling.
+
+## Getting Help
+
+For issues or suggestions with Lighthouse AI on Prowler Cloud, request support at [support.prowler.com](https://support.prowler.com) or [reach out through our Slack channel](https://goto.prowler.com/slack).
diff --git a/docs/user-guide/tutorials/prowler-cloud-public-ips.mdx b/docs/user-guide/tutorials/prowler-cloud-public-ips.mdx
deleted file mode 100644
index f3b285056c..0000000000
--- a/docs/user-guide/tutorials/prowler-cloud-public-ips.mdx
+++ /dev/null
@@ -1,29 +0,0 @@
----
-title: 'Prowler Cloud Public IPs'
----
-
-## Overview
-
-Prowler Cloud uses a dedicated egress IPv4 address for all outbound connections to customer infrastructure. This enables organizations to implement network-level security controls by whitelisting Prowler's IP address.
-
-## Use Cases
-
-Whitelisting Prowler's egress IP address enables:
-
-- **Credential Usage Control**: Restrict where cloud provider credentials can be used from across AWS, Azure, GCP, and other providers
-- **Kubernetes Security**: Limit inbound HTTPS traffic to clusters by allowing only Prowler's IP address
-- **Compliance Requirements**: Meet security policies requiring allowlisting of external services
-
-## Query the Egress IP Address
-
-Retrieve Prowler Cloud's current egress IP address using the following command:
-
-```bash
-dig egress.prowler.com +short
-```
-
-This command returns the IPv4 address that Prowler Cloud uses for all outbound connections to customer infrastructure.
-
-
-The egress IP address is stable, but it is recommended to periodically verify it remains current by querying `egress.prowler.com`.
-
diff --git a/docs/user-guide/tutorials/prowler-import-findings.mdx b/docs/user-guide/tutorials/prowler-import-findings.mdx
index d4c8f8a74d..530cd160ee 100644
--- a/docs/user-guide/tutorials/prowler-import-findings.mdx
+++ b/docs/user-guide/tutorials/prowler-import-findings.mdx
@@ -1,19 +1,19 @@
---
title: 'Import Findings'
+sidebarTitle: 'Import Findings'
description: 'Upload OCSF scan results to Prowler Cloud from external sources or the CLI'
---
import { VersionBadge } from "/snippets/version-badge.mdx"
+import { SubscriptionBanner } from "/snippets/subscription-banner.mdx"
Findings Ingestion enables uploading OCSF (Open Cybersecurity Schema Framework) scan results to Prowler Cloud. This feature supports importing findings from Prowler CLI output files that use the [Detection Finding](https://schema.ocsf.io/classes/detection_finding) class.
-
-This feature is available exclusively in **Prowler Cloud** and **Prowler Enterprise** with a [paid subscription](https://prowler.com/pricing).
-
+
-## OCSF Detection Finding format
+## OCSF Detection Finding Format
The ingestion API accepts `.ocsf.json` files containing a JSON array of OCSF Detection Finding records. Each finding represents a security check result from Prowler.
@@ -130,11 +130,11 @@ The ingestion API accepts `.ocsf.json` files containing a JSON array of OCSF Det
Only **Detection Finding** (`class_uid: 2004`) records are accepted. Other OCSF classes are not supported for ingestion.
-## Required permissions
+## Required Permissions
The **Manage Ingestions** RBAC permission controls access to the ingestion endpoints. Without this permission, findings cannot be submitted via the API or `--push-to-cloud`.
-For more information about RBAC permissions, refer to the [Prowler App RBAC documentation](/user-guide/tutorials/prowler-app-rbac).
+For more information about RBAC permissions, refer to the [Prowler Cloud RBAC documentation](/user-guide/tutorials/prowler-app-rbac).
## Using the CLI
@@ -145,7 +145,7 @@ The `--push-to-cloud` flag uploads scan results directly to Prowler Cloud after
- A valid Prowler Cloud API key (see [API Keys](/user-guide/tutorials/prowler-app-api-keys))
- The `PROWLER_CLOUD_API_KEY` environment variable configured
-### Basic usage
+### Basic Usage
```bash
export PROWLER_CLOUD_API_KEY="pk_your_api_key_here"
@@ -153,7 +153,7 @@ export PROWLER_CLOUD_API_KEY="pk_your_api_key_here"
prowler aws --push-to-cloud
```
-### Combining with output formats
+### Combining with Output Formats
When using `--push-to-cloud` with custom output formats that exclude OCSF, Prowler generates a temporary OCSF file for upload:
@@ -169,7 +169,7 @@ When default output formats include OCSF, Prowler reuses the existing file. Defa
prowler aws --services accessanalyzer --push-to-cloud -o /tmp/scan-output
```
-### CLI output examples
+### CLI Output Examples
**Successful upload:**
```
@@ -228,7 +228,7 @@ curl -X POST \
https://api.prowler.com/api/v1/ingestions
```
-### Submit an ingestion batch
+### Submit an Ingestion Batch
Upload a `.ocsf.json` file containing a JSON array of OCSF Detection Finding records. See [OCSF Detection Finding format](#ocsf-detection-finding-format) for the expected structure.
@@ -266,7 +266,7 @@ curl -X POST \
}
```
-### Get ingestion status
+### Get Ingestion Status
Monitor the progress of an ingestion job.
@@ -304,7 +304,7 @@ curl -X GET \
}
```
-### List ingestion jobs
+### List Ingestion Jobs
Retrieve a list of ingestion jobs for the tenant.
@@ -332,7 +332,7 @@ curl -X GET \
"https://api.prowler.com/api/v1/ingestions?filter[status]=completed&page[size]=10"
```
-### Get ingestion errors
+### Get Ingestion Errors
Retrieve error details for a specific ingestion job.
@@ -346,7 +346,7 @@ curl -X GET \
https://api.prowler.com/api/v1/ingestions/3650fef9-8e5f-4808-a95f-74f0afae8499/errors
```
-## Ingestion status values
+## Ingestion Status Values
| Status | Description |
|--------|-------------|
@@ -355,7 +355,7 @@ curl -X GET \
| `completed` | All records processed successfully |
| `failed` | Job encountered errors during processing |
-## CI/CD integration
+## CI/CD Integration
Automate findings ingestion in CI/CD pipelines by setting the API key as a secret.
@@ -391,7 +391,7 @@ prowler_scan:
PROWLER_CLOUD_API_KEY: $PROWLER_CLOUD_API_KEY
```
-## Billing impact
+## Billing Impact
Each unique cloud account discovered in ingested OCSF findings counts as one **provider** in the Prowler Cloud subscription.
diff --git a/docs/user-guide/tutorials/prowler-scan-scheduling.mdx b/docs/user-guide/tutorials/prowler-scan-scheduling.mdx
new file mode 100644
index 0000000000..f909ed2fa0
--- /dev/null
+++ b/docs/user-guide/tutorials/prowler-scan-scheduling.mdx
@@ -0,0 +1,107 @@
+---
+title: 'Scan Scheduling'
+sidebarTitle: 'Scheduling'
+description: 'Create, edit, and monitor recurring scans in Prowler Cloud and Prowler Private Cloud.'
+---
+
+import { VersionBadge } from "/snippets/version-badge.mdx"
+import { SubscriptionBanner } from "/snippets/subscription-banner.mdx"
+
+
+
+Scan Scheduling lets Prowler run recurring scans for connected providers. Use it to keep findings, compliance results, and resource inventory up to date without launching every scan manually.
+
+
+
+## Prerequisites
+
+Before creating or editing scan schedules, ensure that:
+
+* At least one provider is connected.
+* The user role includes the **Manage Scans** permission, configured through Role-Based Access Control (RBAC). See [RBAC Administrative Permissions](/user-guide/tutorials/prowler-app-rbac#rbac-administrative-permissions) for details.
+
+## Schedule Options
+
+A Prowler Cloud or Prowler Private Cloud subscription supports the following custom recurring schedule options. Prowler Local Server runs a daily scan automatically and does not expose custom cadence controls.
+
+| Schedule Option | Description | Prowler Cloud & Prowler Private Cloud | Prowler Local Server |
+|-----------------|-------------|---------------------------------------|----------------------|
+| Daily | Runs one scan every day at the selected time. | Yes | Automatic |
+| Every 48 hours | Runs one scan every 48 hours, anchored to the selected time. | Yes | — |
+| Weekly | Runs one scan every week on the selected day and time. | Yes | — |
+| Monthly | Runs one scan every month on the selected day, from day 1 to day 28. | Yes | — |
+
+The scan time is always selected on the hour (for example, 14:00); minutes cannot be set. The schedule time uses the browser timezone when the schedule is saved. Prowler displays the next scheduled scan in that timezone.
+
+## Create a Schedule From Scans
+
+To create a schedule from the **Scans** page:
+
+1. Navigate to **Scans**.
+2. Click **Launch Scan**.
+3. Select a connected provider.
+4. Select **On a schedule**.
+5. Choose the **Scan Time** and **Repeats** values.
+6. Optional: select **Launch an initial scan now for immediate findings** to run a scan immediately after saving the recurring schedule.
+7. Click **Save Schedule**.
+
+
+
+
+
+After the schedule is saved, Prowler shows a confirmation toast with a link to the **Scheduled** tab.
+
+## Edit Schedules From Providers
+
+The **Providers** page shows each provider's current schedule in the **Scan Schedule** column. Providers without a recurring schedule show **None**.
+
+
+
+
+
+To edit a provider schedule:
+
+1. Navigate to **Providers**.
+2. Open the provider row actions menu.
+3. Click **Edit Scan Schedule**.
+4. Update the schedule fields.
+5. Click **Save**.
+
+
+
+
+
+To stop automatic scans for a provider, click **Remove Scan Schedule** in the edit modal. Removing a schedule stops future automatic scans; existing completed scan results remain available.
+
+## Bulk Edit Schedules
+
+Use bulk schedule editing when several providers need the same recurring cadence.
+
+To bulk edit provider schedules:
+
+1. Navigate to **Providers**.
+2. Select the provider rows that should receive the same schedule.
+3. Open the selected-row actions menu.
+4. Click **Edit Scan Schedule (N)**, where **N** is the number of selected providers.
+5. Save the schedule.
+
+For AWS Organizations and Organizational Unit rows, **Edit Scan Schedule** applies the schedule to the connected child providers in that group.
+
+
+Bulk schedule edits apply one schedule to every selected provider. If the wrong providers are selected, Prowler applies the same cadence to unintended providers. To recover, reopen bulk edit with the correct selection or update affected provider schedules individually.
+
+
+## Review Scheduled Scans
+
+To review upcoming scheduled scans:
+
+1. Navigate to **Scans**.
+2. Click the **Scheduled** tab.
+
+The **Scheduled** tab shows configured schedules, next scan time, and last scan time. Pending rows represent configured schedules that have not started their next scan yet.
+
+
+
+
+
+To edit a schedule from this tab, open the row actions menu and click **Edit Scan Schedule**.
diff --git a/mcp_server/.env.template b/mcp_server/.env.template
index 11b8caa724..10aabd84cf 100644
--- a/mcp_server/.env.template
+++ b/mcp_server/.env.template
@@ -1,3 +1,3 @@
-PROWLER_APP_API_KEY="pk_your_api_key_here"
+PROWLER_API_KEY="pk_your_api_key_here"
API_BASE_URL="https://api.prowler.com/api/v1"
PROWLER_MCP_TRANSPORT_MODE="stdio"
diff --git a/mcp_server/AGENTS.md b/mcp_server/AGENTS.md
index a82cc42e33..1d3d808e6a 100644
--- a/mcp_server/AGENTS.md
+++ b/mcp_server/AGENTS.md
@@ -25,7 +25,7 @@ The Prowler MCP Server provides AI agents access to the Prowler ecosystem throug
## CRITICAL RULES
### Tool Implementation
-- ALWAYS: Extend `BaseTool` ABC for Prowler App tools (auto-registration)
+- ALWAYS: Extend `BaseTool` ABC for Prowler tools (auto-registration)
- ALWAYS: Use `@mcp.tool()` decorator for Hub/Docs tools
- NEVER: Manually register BaseTool subclasses
- NEVER: Import tools directly in server.py
@@ -56,7 +56,7 @@ await prowler_mcp_server.import_server(docs_mcp_server, prefix="prowler_docs")
### Tool Naming
- `prowler_hub_*` - Catalog and compliance (no auth)
- `prowler_docs_*` - Documentation search (no auth)
-- `prowler_app_*` - Cloud/App management (auth required)
+- `prowler_*` - Prowler Cloud, Private Cloud & Local Server management (auth required)
---
diff --git a/mcp_server/CHANGELOG.md b/mcp_server/CHANGELOG.md
index 8f1438a3bb..5898f816c9 100644
--- a/mcp_server/CHANGELOG.md
+++ b/mcp_server/CHANGELOG.md
@@ -2,6 +2,16 @@
All notable changes to the **Prowler MCP Server** are documented in this file.
+
+
+## [0.8.0] (Prowler v5.35.0)
+
+### 🔄 Changed
+
+- Core Prowler tool namespace from the `prowler_app_*` prefix to `prowler_*` [(#12017)](https://github.com/prowler-cloud/prowler/pull/12017)
+
+---
+
## [0.7.2] (Prowler v5.28.1)
### 🐞 Fixed
diff --git a/mcp_server/Dockerfile b/mcp_server/Dockerfile
index c2759b20de..195bfe1eae 100644
--- a/mcp_server/Dockerfile
+++ b/mcp_server/Dockerfile
@@ -25,7 +25,7 @@ RUN --mount=type=cache,target=/root/.cache/uv \
# =============================================================================
# Final stage - Minimal runtime environment
# =============================================================================
-FROM python:3.13.14-alpine3.23@sha256:b0513989fa9be54569cac73f48a60320b74bb0f9ffa886568eea7e48a2432c04
+FROM python:3.13.14-alpine3.23@sha256:9fdbf2e3e82628351513560b121e2ee6ce31cac212be9e070c5a5e2769fb5e76
LABEL maintainer="https://github.com/prowler-cloud"
diff --git a/mcp_server/README.md b/mcp_server/README.md
index e990f0f363..c0e4fdb0fe 100644
--- a/mcp_server/README.md
+++ b/mcp_server/README.md
@@ -6,9 +6,9 @@
## Key Capabilities
-### Prowler Cloud and Prowler App (Self-Managed)
+### Prowler Cloud, Prowler Private Cloud & Prowler Local Server
-Full access to Prowler Cloud platform and self-managed Prowler App for:
+Full access to your Prowler data (Prowler Cloud, Prowler Private Cloud, or Prowler Local Server) for:
- **Findings Analysis**: Query, filter, and analyze security findings across all your cloud environments
- **Finding Groups Analysis**: Triage findings grouped by check ID and drill down into affected resources
- **Provider Management**: Create, configure, and manage your configured Prowler providers (AWS, Azure, GCP, etc.)
@@ -49,7 +49,7 @@ For comprehensive guides and tutorials, see the official documentation:
Prowler MCP Server can be used in three ways:
-### 1. Prowler Cloud MCP Server (Recommended)
+### 1. Hosted Prowler MCP (Recommended)
**Use Prowler's managed MCP server at `https://mcp.prowler.com/mcp`**
@@ -126,7 +126,7 @@ For complete tool descriptions and parameters, see the [Tools Reference](https:/
### Tool Naming Convention
All tools follow a consistent naming pattern with prefixes:
-- `prowler_app_*` - Prowler Cloud and App (Self-Managed) management tools
+- `prowler_*` - Prowler Cloud, Prowler Private Cloud & Prowler Local Server management tools
- `prowler_hub_*` - Prowler Hub catalog and compliance tools
- `prowler_docs_*` - Prowler documentation search and retrieval
@@ -146,7 +146,7 @@ prowler_mcp_server/
**Key Features:**
- **Modular Design**: Three independent sub-servers with prefixed namespacing
-- **Auto-Discovery**: Prowler App tools are automatically discovered and registered
+- **Auto-Discovery**: Prowler tools are automatically discovered and registered
- **LLM Optimization**: Response models minimize token usage by excluding empty values
- **Dual Transport**: Supports both STDIO (local) and HTTP (remote) modes
@@ -174,17 +174,17 @@ The Prowler MCP Server enables powerful workflows through AI assistants:
## Requirements
-**For Prowler Cloud MCP Server:**
-- Prowler Cloud account and API key (only for Prowler Cloud/App features)
+**For the hosted Prowler MCP:**
+- Prowler Cloud account and API key (only for Prowler features)
**For self-hosted STDIO/HTTP Mode:**
- Python 3.12+ or Docker
- Network access to:
- `https://hub.prowler.com` (for Prowler Hub)
- `https://docs.prowler.com` (for Prowler Documentation)
- - Prowler Cloud API or self-hosted Prowler App API (for Prowler Cloud/App features)
+ - Prowler Cloud API or Prowler Local Server API (for Prowler features)
-> **No Authentication Required**: Prowler Hub and Prowler Documentation features work without authentication. A Prowler API key is only required to access Prowler Cloud or Prowler App (Self-Managed) features.
+> **No Authentication Required**: Prowler Hub and Prowler Documentation features work without authentication. A Prowler API key is only required to access Prowler features (Prowler Cloud, Prowler Private Cloud, or Prowler Local Server).
## Configuring MCP Hosts
@@ -200,7 +200,7 @@ For developers looking to extend the MCP server with new tools or features:
## Related Products
- **[Prowler Hub](https://hub.prowler.com)**: Browse security checks and compliance frameworks
-- **[Prowler Cloud](https://cloud.prowler.com)**: Managed Prowler platform
+- **[Prowler Cloud](https://cloud.prowler.com)**: Fully managed Prowler in the cloud
- **[Lighthouse AI](https://docs.prowler.com/getting-started/products/prowler-lighthouse-ai)**: AI security analyst
## License
diff --git a/tests/config/__init__.py b/mcp_server/changelog.d/.gitkeep
similarity index 100%
rename from tests/config/__init__.py
rename to mcp_server/changelog.d/.gitkeep
diff --git a/mcp_server/changelog.d/README.md b/mcp_server/changelog.d/README.md
new file mode 100644
index 0000000000..0853174f30
--- /dev/null
+++ b/mcp_server/changelog.d/README.md
@@ -0,0 +1,10 @@
+# Changelog fragments
+
+Each PR adds one small file here instead of editing `CHANGELOG.md` directly, so concurrent PRs never conflict.
+
+- Filename: `..md`, e.g. `my-new-check.added.md` (slug is free-form: letters, digits, `.`, `_`, `-`)
+- `` is one of: `added`, `changed`, `deprecated`, `removed`, `fixed`, `security`
+- Content: one line with the changelog entry text, without the PR link and without a trailing period (the PR link is attached automatically at release time)
+- A PR adds as many fragment files as entries it needs, freely mixing types (one file per entry); same-type entries just use different slugs
+
+Fragments are compiled into `CHANGELOG.md` when a release is prepared. Full conventions: `skills/prowler-changelog/SKILL.md`.
diff --git a/mcp_server/prowler_mcp_server/__init__.py b/mcp_server/prowler_mcp_server/__init__.py
index fe7af2dcea..1956a6ec41 100644
--- a/mcp_server/prowler_mcp_server/__init__.py
+++ b/mcp_server/prowler_mcp_server/__init__.py
@@ -5,7 +5,7 @@ This package provides MCP tools for accessing:
- Prowler Hub: All security artifacts (detections, remediations and frameworks) supported by Prowler
"""
-__version__ = "0.5.0"
+__version__ = "0.8.0"
__author__ = "Prowler Team"
__email__ = "engineering@prowler.com"
diff --git a/mcp_server/prowler_mcp_server/prowler_app/models/__init__.py b/mcp_server/prowler_mcp_server/prowler_app/models/__init__.py
index 899ab4e866..1b15e35ac9 100644
--- a/mcp_server/prowler_mcp_server/prowler_app/models/__init__.py
+++ b/mcp_server/prowler_mcp_server/prowler_app/models/__init__.py
@@ -1,4 +1,4 @@
-"""Pydantic models for Prowler App MCP Server."""
+"""Pydantic models for Prowler MCP Server."""
from prowler_mcp_server.prowler_app.models.base import MinimalSerializerMixin
from prowler_mcp_server.prowler_app.models.findings import (
diff --git a/mcp_server/prowler_mcp_server/prowler_app/models/finding_groups.py b/mcp_server/prowler_mcp_server/prowler_app/models/finding_groups.py
index ae8431ba63..c2429012c3 100644
--- a/mcp_server/prowler_mcp_server/prowler_app/models/finding_groups.py
+++ b/mcp_server/prowler_mcp_server/prowler_app/models/finding_groups.py
@@ -228,7 +228,7 @@ class FindingGroupResource(MinimalSerializerMixin):
resource: FindingGroupResourceInfo = Field(description="Affected resource")
provider: FindingGroupProviderInfo = Field(description="Affected provider")
finding_id: str = Field(
- description="Finding UUID to use with prowler_app_get_finding_details"
+ description="Finding UUID to use with prowler_get_finding_details"
)
status: FindingStatus = Field(description="Finding status for this resource")
severity: FindingSeverity = Field(description="Finding severity")
diff --git a/mcp_server/prowler_mcp_server/prowler_app/tools/__init__.py b/mcp_server/prowler_mcp_server/prowler_app/tools/__init__.py
index 4d740b6efe..8b5be76076 100644
--- a/mcp_server/prowler_mcp_server/prowler_app/tools/__init__.py
+++ b/mcp_server/prowler_mcp_server/prowler_app/tools/__init__.py
@@ -1,4 +1,4 @@
-"""Domain-specific tools for Prowler App MCP Server.
+"""Domain-specific tools for Prowler MCP Server.
Each module in this package contains a BaseTool subclass that registers
and implements tools for a specific domain (findings, providers, scans, etc.).
diff --git a/mcp_server/prowler_mcp_server/prowler_app/tools/attack_paths.py b/mcp_server/prowler_mcp_server/prowler_app/tools/attack_paths.py
index b08bbfe01f..5bd66760fa 100644
--- a/mcp_server/prowler_mcp_server/prowler_app/tools/attack_paths.py
+++ b/mcp_server/prowler_mcp_server/prowler_app/tools/attack_paths.py
@@ -1,4 +1,4 @@
-"""Attack Paths tools for Prowler App MCP Server.
+"""Attack Paths tools for Prowler MCP Server.
This module provides tools for analyzing Attack Paths data from Neo4j graph database.
Attack Paths help identify security risks by tracing potential attack vectors
@@ -22,16 +22,16 @@ class AttackPathsTools(BaseTool):
"""Tools for Attack Paths analysis.
Provides tools for:
- - prowler_app_list_attack_paths_scans: Find completed scans ready for analysis
- - prowler_app_list_attack_paths_queries: Discover available queries for a scan
- - prowler_app_run_attack_paths_query: Execute query and analyze attack paths
+ - prowler_list_attack_paths_scans: Find completed scans ready for analysis
+ - prowler_list_attack_paths_queries: Discover available queries for a scan
+ - prowler_run_attack_paths_query: Execute query and analyze attack paths
"""
async def list_attack_paths_scans(
self,
provider_id: list[str] = Field(
default=[],
- description="Filter by Prowler's internal UUID(s) (v4) for specific provider(s). Use `prowler_app_search_providers` tool to find provider IDs",
+ description="Filter by Prowler's internal UUID(s) (v4) for specific provider(s). Use `prowler_search_providers` tool to find provider IDs",
),
provider_type: list[str] = Field(
default=[],
@@ -73,8 +73,8 @@ class AttackPathsTools(BaseTool):
Workflow:
1. Use this tool to find completed attack paths scans
- 2. Use prowler_app_list_attack_paths_queries to see available queries for a scan
- 3. Use prowler_app_run_attack_paths_query to execute analysis
+ 2. Use prowler_list_attack_paths_queries to see available queries for a scan
+ 3. Use prowler_run_attack_paths_query to execute analysis
"""
try:
# Validate pagination
@@ -113,7 +113,7 @@ class AttackPathsTools(BaseTool):
async def list_attack_paths_queries(
self,
scan_id: str = Field(
- description="UUID of a COMPLETED attack paths scan. Use `prowler_app_list_attack_paths_scans` with state=['completed'] to find scan IDs"
+ description="UUID of a COMPLETED attack paths scan. Use `prowler_list_attack_paths_scans` with state=['completed'] to find scan IDs"
),
) -> list[dict[str, Any]]:
"""Discover available Attack Paths queries for a completed scan.
@@ -133,9 +133,9 @@ class AttackPathsTools(BaseTool):
- aws-ec2-instances-internet-exposed: Find internet-exposed EC2 instances
Workflow:
- 1. Use prowler_app_list_attack_paths_scans to find a completed scan
+ 1. Use prowler_list_attack_paths_scans to find a completed scan
2. Use this tool to discover available queries
- 3. Use prowler_app_run_attack_paths_query with query_id and any required parameters
+ 3. Use prowler_run_attack_paths_query with query_id and any required parameters
"""
try:
api_response = await self.api_client.get(
@@ -158,7 +158,7 @@ class AttackPathsTools(BaseTool):
description="UUID of a COMPLETED attack paths scan. The scan must be in 'completed' state"
),
query_id: str = Field(
- description="Query ID to execute (e.g., 'aws-internet-exposed-ec2-sensitive-s3-access'). Use `prowler_app_list_attack_paths_queries` to discover available queries"
+ description="Query ID to execute (e.g., 'aws-internet-exposed-ec2-sensitive-s3-access'). Use `prowler_list_attack_paths_queries` to discover available queries"
),
parameters: dict[str, str] = Field(
default_factory=dict,
@@ -194,7 +194,7 @@ class AttackPathsTools(BaseTool):
Workflow:
1. Ensure scan is completed
- 2. List available queries (use prowler_app_list_attack_paths_queries)
+ 2. List available queries (use prowler_list_attack_paths_queries)
3. Execute this tool with appropriate parameters
4. Analyze the returned graph for security insights
"""
@@ -231,7 +231,7 @@ class AttackPathsTools(BaseTool):
async def get_attack_paths_cartography_schema(
self,
scan_id: str = Field(
- description="UUID of a COMPLETED attack paths scan. Use `prowler_app_list_attack_paths_scans` with state=['completed'] to find scan IDs"
+ description="UUID of a COMPLETED attack paths scan. Use `prowler_list_attack_paths_scans` with state=['completed'] to find scan IDs"
),
) -> dict[str, Any]:
"""Retrieve the Cartography graph schema for a completed attack paths scan.
@@ -253,10 +253,10 @@ class AttackPathsTools(BaseTool):
- schema_content: Full Cartography schema markdown with node/relationship definitions
Workflow:
- 1. Use prowler_app_list_attack_paths_scans to find a completed scan
+ 1. Use prowler_list_attack_paths_scans to find a completed scan
2. Use this tool to get the schema for the scan's provider
3. Use the schema to craft custom openCypher queries
- 4. Execute queries with prowler_app_run_attack_paths_query
+ 4. Execute queries with prowler_run_attack_paths_query
"""
try:
api_response = await self.api_client.get(
diff --git a/mcp_server/prowler_mcp_server/prowler_app/tools/compliance.py b/mcp_server/prowler_mcp_server/prowler_app/tools/compliance.py
index 360dd5510d..33cdd22a69 100644
--- a/mcp_server/prowler_mcp_server/prowler_app/tools/compliance.py
+++ b/mcp_server/prowler_mcp_server/prowler_app/tools/compliance.py
@@ -1,4 +1,4 @@
-"""Compliance framework tools for Prowler App MCP Server.
+"""Compliance framework tools for Prowler MCP Server.
This module provides tools for viewing compliance status and requirement details
across all cloud providers.
@@ -50,7 +50,7 @@ class ComplianceTools(BaseTool):
if not scans_data:
raise ValueError(
f"No completed scans found for provider {provider_id}. "
- "Run a scan first using prowler_app_trigger_scan."
+ "Run a scan first using prowler_trigger_scan."
)
scan_id = scans_data[0]["id"]
@@ -60,11 +60,11 @@ class ComplianceTools(BaseTool):
self,
scan_id: str | None = Field(
default=None,
- description="UUID of a specific scan to get compliance data for. Required if provider_id is not specified. Use `prowler_app_list_scans` to find scan IDs.",
+ description="UUID of a specific scan to get compliance data for. Required if provider_id is not specified. Use `prowler_list_scans` to find scan IDs.",
),
provider_id: str | None = Field(
default=None,
- description="Prowler's internal UUID (v4) for a specific provider. If provided without scan_id, the tool will automatically find the latest completed scan for this provider. Use `prowler_app_search_providers` tool to find provider IDs.",
+ description="Prowler's internal UUID (v4) for a specific provider. If provided without scan_id, the tool will automatically find the latest completed scan for this provider. Use `prowler_search_providers` tool to find provider IDs.",
),
) -> dict[str, Any]:
"""Get high-level compliance overview across all frameworks for a specific scan.
@@ -90,11 +90,11 @@ class ComplianceTools(BaseTool):
Workflow:
1. Use this tool to get an overview of all compliance frameworks
- 2. Use prowler_app_get_compliance_framework_state_details with a specific compliance_id to see which requirements failed
+ 2. Use prowler_get_compliance_framework_state_details with a specific compliance_id to see which requirements failed
"""
if not scan_id and not provider_id:
return {
- "error": "Either scan_id or provider_id must be provided. Use prowler_app_search_providers to find provider IDs or prowler_app_list_scans to find scan IDs."
+ "error": "Either scan_id or provider_id must be provided. Use prowler_search_providers to find provider IDs or prowler_list_scans to find scan IDs."
}
elif scan_id and provider_id:
return {
@@ -254,7 +254,7 @@ class ComplianceTools(BaseTool):
async def get_compliance_framework_state_details(
self,
compliance_id: str = Field(
- description="Compliance framework ID to get details for (e.g., 'cis_1.5_aws', 'pci_dss_v4.0_aws'). You can get compliance IDs from prowler_app_get_compliance_overview or consulting Prowler Hub/Prowler Documentation that you can also find in form of tools in this MCP Server",
+ description="Compliance framework ID to get details for (e.g., 'cis_1.5_aws', 'pci_dss_v4.0_aws'). You can get compliance IDs from prowler_get_compliance_overview or consulting Prowler Hub/Prowler Documentation that you can also find in form of tools in this MCP Server",
),
scan_id: str | None = Field(
default=None,
@@ -262,14 +262,14 @@ class ComplianceTools(BaseTool):
),
provider_id: str | None = Field(
default=None,
- description="Prowler's internal UUID (v4) for a specific provider. If provided without scan_id, the tool will automatically find the latest completed scan for this provider. Use `prowler_app_search_providers` tool to find provider IDs.",
+ description="Prowler's internal UUID (v4) for a specific provider. If provided without scan_id, the tool will automatically find the latest completed scan for this provider. Use `prowler_search_providers` tool to find provider IDs.",
),
) -> dict[str, Any]:
"""Get detailed requirement-level breakdown for a specific compliance framework.
IMPORTANT: This tool returns DETAILED requirement information for a single compliance framework,
focusing on FAILED requirements and their associated FAILED finding IDs.
- Use this after prowler_app_get_compliance_overview to drill down into specific frameworks.
+ Use this after prowler_get_compliance_overview to drill down into specific frameworks.
The markdown report includes:
@@ -280,7 +280,7 @@ class ComplianceTools(BaseTool):
2. Failed Requirements Breakdown:
- Each failed requirement's ID and description
- Associated failed finding IDs for each failed requirement
- - Use prowler_app_get_finding_details with these finding IDs for more details and remediation guidance
+ - Use prowler_get_finding_details with these finding IDs for more details and remediation guidance
Default behavior:
- Requires either scan_id OR provider_id
@@ -289,14 +289,14 @@ class ComplianceTools(BaseTool):
- Only shows failed requirements with their associated failed finding IDs
Workflow:
- 1. Use prowler_app_get_compliance_overview to identify frameworks with failures
+ 1. Use prowler_get_compliance_overview to identify frameworks with failures
2. Use this tool with the compliance_id to see failed requirements and their finding IDs
- 3. Use prowler_app_get_finding_details with the finding IDs to get remediation guidance
+ 3. Use prowler_get_finding_details with the finding IDs to get remediation guidance
"""
# Validate that either scan_id or provider_id is provided
if not scan_id and not provider_id:
return {
- "error": "Either scan_id or provider_id must be provided. Use prowler_app_search_providers to find provider IDs or prowler_app_list_scans to find scan IDs."
+ "error": "Either scan_id or provider_id must be provided. Use prowler_search_providers to find provider IDs or prowler_list_scans to find scan IDs."
}
# Resolve provider_id to latest scan_id if needed
@@ -395,7 +395,7 @@ class ComplianceTools(BaseTool):
report_lines.append("**Failed Finding IDs**: None found")
report_lines.append("")
report_lines.append(
- "*Use `prowler_app_get_finding_details` with these finding IDs to get remediation guidance.*"
+ "*Use `prowler_get_finding_details` with these finding IDs to get remediation guidance.*"
)
report_lines.append("")
diff --git a/mcp_server/prowler_mcp_server/prowler_app/tools/finding_groups.py b/mcp_server/prowler_mcp_server/prowler_app/tools/finding_groups.py
index 905a352740..05adf8db2b 100644
--- a/mcp_server/prowler_mcp_server/prowler_app/tools/finding_groups.py
+++ b/mcp_server/prowler_mcp_server/prowler_app/tools/finding_groups.py
@@ -1,4 +1,4 @@
-"""Finding Groups tools for Prowler App MCP Server.
+"""Finding Groups tools for Prowler MCP Server.
This module provides read-only tools for finding group triage and drill-downs.
"""
@@ -233,8 +233,8 @@ class FindingGroupsTools(BaseTool):
`date_to`, this uses `/finding-groups` with a maximum 2-day date window.
Use this tool to find noisy or high-impact checks, then call
- prowler_app_get_finding_group_details for complete counters or
- prowler_app_list_finding_group_resources to drill into affected resources.
+ prowler_get_finding_group_details for complete counters or
+ prowler_list_finding_group_resources to drill into affected resources.
"""
try:
self.api_client.validate_page_size(page_size)
@@ -423,7 +423,7 @@ class FindingGroupsTools(BaseTool):
Default behavior returns FAIL, unmuted resources so the result is
actionable. Set `include_muted=True` to include accepted/suppressed
resources too. Each row includes nested resource and provider data plus
- `finding_id`. Use `prowler_app_get_finding_details(finding_id)` to
+ `finding_id`. Use `prowler_get_finding_details(finding_id)` to
retrieve complete remediation guidance for a specific resource finding.
"""
try:
diff --git a/mcp_server/prowler_mcp_server/prowler_app/tools/findings.py b/mcp_server/prowler_mcp_server/prowler_app/tools/findings.py
index ec492c6a43..b556101cab 100644
--- a/mcp_server/prowler_mcp_server/prowler_app/tools/findings.py
+++ b/mcp_server/prowler_mcp_server/prowler_app/tools/findings.py
@@ -1,4 +1,4 @@
-"""Security Findings tools for Prowler App MCP Server.
+"""Security Findings tools for Prowler MCP Server.
This module provides tools for searching, viewing, and analyzing security findings
across all cloud providers.
@@ -92,7 +92,7 @@ class FindingsTools(BaseTool):
"""Search and filter security findings across all cloud providers with rich filtering capabilities.
IMPORTANT: This tool returns LIGHTWEIGHT findings. Use this for fast searching and filtering across many findings.
- For complete details use prowler_app_get_finding_details on specific findings.
+ For complete details use prowler_get_finding_details on specific findings.
Default behavior:
- Returns latest findings from most recent scans (no date parameters needed)
@@ -111,7 +111,7 @@ class FindingsTools(BaseTool):
Workflow:
1. Use this tool to search and filter findings by severity, status, provider, service, region, etc.
- 2. Use prowler_app_get_finding_details with the finding 'id' to get complete information about the finding
+ 2. Use prowler_get_finding_details with the finding 'id' to get complete information about the finding
"""
# Validate page_size parameter
self.api_client.validate_page_size(page_size)
@@ -187,9 +187,9 @@ class FindingsTools(BaseTool):
"""Retrieve comprehensive details about a specific security finding by its ID.
IMPORTANT: This tool returns COMPLETE finding details.
- Use this after finding a specific finding via prowler_app_search_security_findings
+ Use this after finding a specific finding via prowler_search_security_findings
- This tool provides ALL information that prowler_app_search_security_findings returns PLUS:
+ This tool provides ALL information that prowler_search_security_findings returns PLUS:
1. Check Metadata (information about the check script that generated the finding):
- title: Human-readable phrase used to summarize the check
@@ -217,7 +217,7 @@ class FindingsTools(BaseTool):
- resource_ids: List of UUIDs for cloud resources associated with this finding
Workflow:
- 1. Use prowler_app_search_security_findings to browse and filter findings
+ 1. Use prowler_search_security_findings to browse and filter findings
2. Use this tool with the finding 'id' to get remediation guidance and complete context
"""
params = {
diff --git a/mcp_server/prowler_mcp_server/prowler_app/tools/muting.py b/mcp_server/prowler_mcp_server/prowler_app/tools/muting.py
index 639f1ec3b7..37e1504165 100644
--- a/mcp_server/prowler_mcp_server/prowler_app/tools/muting.py
+++ b/mcp_server/prowler_mcp_server/prowler_app/tools/muting.py
@@ -1,4 +1,4 @@
-"""Muting tools for Prowler App MCP Server.
+"""Muting tools for Prowler MCP Server.
This module provides tools for managing finding muting in Prowler, including:
- Mutelist management (pattern-based bulk muting)
@@ -43,7 +43,7 @@ class MutingTools(BaseTool):
Workflow:
1. Use this tool to check if a mutelist is configured
2. Examine current muting patterns before making updates
- 3. Use prowler_app_set_mutelist to create or update the configuration
+ 3. Use prowler_set_mutelist to create or update the configuration
"""
self.logger.info("Retrieving mutelist configuration...")
@@ -61,7 +61,7 @@ class MutingTools(BaseTool):
if len(data) == 0:
return {
"error": "No mutelist found",
- "message": "No mutelist configuration exists for this tenant. Use prowler_app_set_mutelist to create one.",
+ "message": "No mutelist configuration exists for this tenant. Use prowler_set_mutelist to create one.",
}
# Return the first (and only) mutelist
@@ -116,10 +116,10 @@ Structure:
- Exceptions: Accounts, Regions, Resources to exclude from muting
Workflow:
- 1. Use prowler_app_get_mutelist to check existing configuration
+ 1. Use prowler_get_mutelist to check existing configuration
2. Build configuration object following Prowler mutelist format
3. Use this tool to create or update the mutelist
- 4. Verify with prowler_app_get_mutelist
+ 4. Verify with prowler_get_mutelist
"""
self.logger.info("Setting mutelist configuration...")
@@ -171,12 +171,12 @@ Structure:
"""Remove the mutelist configuration from the tenant.
WARNING: This is a destructive operation that cannot be undone.
- - The mutelist will need to be re-created with prowler_app_set_mutelist
+ - The mutelist will need to be re-created with prowler_set_mutelist
- New findings from future scans will NOT be muted by the deleted mutelist
- Previously muted findings remain muted (deletion doesn't un-mute them)
Workflow:
- 1. Use prowler_app_get_mutelist to confirm what will be deleted
+ 1. Use prowler_get_mutelist to confirm what will be deleted
2. Use this tool to permanently remove the mutelist
3. New scans will no longer apply mutelist-based muting
"""
@@ -229,7 +229,7 @@ Structure:
"""Search and filter mute rules with pagination support.
IMPORTANT: This tool returns LIGHTWEIGHT mute rules without the full list of finding UIDs.
- Use prowler_app_get_mute_rule to get complete details including all finding UIDs and creator information.
+ Use prowler_get_mute_rule to get complete details including all finding UIDs and creator information.
Default behavior:
- Returns all mute rules (both enabled and disabled)
@@ -237,15 +237,15 @@ Structure:
- Includes basic rule information without full finding UID lists
Each mute rule includes:
- - Core identification: id (UUID for prowler_app_get_mute_rule), name
+ - Core identification: id (UUID for prowler_get_mute_rule), name
- Contextual information: reason, enabled status
- State tracking: finding_count (number of findings currently muted)
- Temporal data: inserted_at, updated_at timestamps
Workflow:
1. Use this tool to search and filter mute rules by name, enabled status, or keywords
- 2. Use prowler_app_get_mute_rule with the mute rule 'id' to get complete details including all finding UIDs
- 3. Use prowler_app_update_mute_rule or prowler_app_delete_mute_rule to modify rules
+ 2. Use prowler_get_mute_rule with the mute rule 'id' to get complete details including all finding UIDs
+ 3. Use prowler_update_mute_rule or prowler_delete_mute_rule to modify rules
"""
self.logger.info("Listing mute rules...")
self.api_client.validate_page_size(page_size)
@@ -289,17 +289,17 @@ Structure:
"""Retrieve comprehensive details about a specific mute rule by its ID.
IMPORTANT: This tool returns COMPLETE mute rule details including the full list of finding UIDs.
- Use this after finding a rule via prowler_app_list_mute_rules.
+ Use this after finding a rule via prowler_list_mute_rules.
- This tool provides ALL information that prowler_app_list_mute_rules returns PLUS:
+ This tool provides ALL information that prowler_list_mute_rules returns PLUS:
- finding_uids: Complete list of finding UIDs that are muted by this rule
- user_creator_id: UUID of the user who created the rule (audit trail)
Workflow:
- 1. Use prowler_app_list_mute_rules to find rules by name or filter criteria
+ 1. Use prowler_list_mute_rules to find rules by name or filter criteria
2. Use this tool with the rule 'id' to get complete details
3. Examine finding_uids list to understand which findings are muted
- 4. Use prowler_app_update_mute_rule or prowler_app_delete_mute_rule to modify if needed
+ 4. Use prowler_update_mute_rule or prowler_delete_mute_rule to modify if needed
"""
self.logger.info(f"Retrieving mute rule {rule_id}...")
@@ -323,7 +323,7 @@ Structure:
description="Reason for muting these findings. Document why this security issue is acceptable or intentional (e.g., 'Development environment with controlled access', 'Legacy application requires IMDSv1')."
),
finding_ids: list[str] = Field(
- description="List of finding IDs (UUIDs) to mute. Get these from the prowler_app_search_security_findings tool. Must provide at least 1 finding ID."
+ description="List of finding IDs (UUIDs) to mute. Get these from the prowler_search_security_findings tool. Must provide at least 1 finding ID."
),
) -> dict[str, Any]:
"""Create a new mute rule to mute specific findings with documentation and audit trail.
@@ -337,15 +337,15 @@ Structure:
- Records creator for audit trail
The mute rule includes:
- - Core identification: id (UUID for prowler_app_get_mute_rule), name, reason
+ - Core identification: id (UUID for prowler_get_mute_rule), name, reason
- Configuration: enabled status, finding_uids list
- Audit trail: user_creator_id (UUID of the Prowler user from the tenant that created the rule), timestamps when the rule was created and last modified
Workflow:
- 1. Use prowler_app_search_security_findings to identify findings to mute
+ 1. Use prowler_search_security_findings to identify findings to mute
2. Use this tool with finding IDs, descriptive name, and documented reason
- 3. Verify with prowler_app_get_mute_rule to confirm rule creation
- 4. Check findings are muted with prowler_app_search_security_findings (filter by muted=true)
+ 3. Verify with prowler_get_mute_rule to confirm rule creation
+ 4. Check findings are muted with prowler_search_security_findings (filter by muted=true)
"""
self.logger.info(f"Creating mute rule '{name}'...")
@@ -399,9 +399,9 @@ Structure:
- enabled: Toggle rule active status (doesn't affect already-muted findings)
Workflow:
- 1. Use prowler_app_get_mute_rule to see current rule state
+ 1. Use prowler_get_mute_rule to see current rule state
2. Use this tool to update name, reason, or enabled status
- 3. Verify changes with prowler_app_get_mute_rule
+ 3. Verify changes with prowler_get_mute_rule
"""
self.logger.info(f"Updating mute rule {rule_id}...")
@@ -451,9 +451,9 @@ Structure:
- Cannot be undone - rule must be recreated to restore
Workflow:
- 1. Use prowler_app_get_mute_rule to review what will be deleted
+ 1. Use prowler_get_mute_rule to review what will be deleted
2. Use this tool to permanently remove the rule
- 3. Verify deletion with prowler_app_list_mute_rules (rule should no longer appear)
+ 3. Verify deletion with prowler_list_mute_rules (rule should no longer appear)
"""
self.logger.info(f"Deleting mute rule {rule_id}...")
diff --git a/mcp_server/prowler_mcp_server/prowler_app/tools/providers.py b/mcp_server/prowler_mcp_server/prowler_app/tools/providers.py
index b22d57d7b9..3ba417d677 100644
--- a/mcp_server/prowler_mcp_server/prowler_app/tools/providers.py
+++ b/mcp_server/prowler_mcp_server/prowler_app/tools/providers.py
@@ -1,4 +1,4 @@
-"""Provider Management tools for Prowler App MCP Server.
+"""Provider Management tools for Prowler MCP Server.
This module provides tools for managing provider connections,
including searching, connecting, and deleting providers.
@@ -19,9 +19,9 @@ class ProvidersTools(BaseTool):
"""Tools for provider management operations
Provides tools for:
- - prowler_app_search_providers: Search and view configured providers with their connection status
- - prowler_app_connect_provider: Connect or register a provider for security scanning in Prowler
- - prowler_app_delete_provider: Permanently remove a provider from Prowler
+ - prowler_search_providers: Search and view configured providers with their connection status
+ - prowler_connect_provider: Connect or register a provider for security scanning in Prowler
+ - prowler_delete_provider: Permanently remove a provider from Prowler
"""
async def search_providers(
@@ -145,7 +145,7 @@ class ProvidersTools(BaseTool):
) -> dict[str, Any]:
"""Register a provider to be scanned with Prowler.
- This tool will register a provider in Prowler App, even if the UID is wrong.
+ This tool will register a provider in Prowler, even if the UID is wrong.
If the provider is already registered, it will be updated with the new provided alias or credentials if provided.
If credentials are provided, they will be added to the indicated provider, if the provider does not exist, it will be created and the credentials will be added to it.
If the connection test is successful, the provider will be connected.
@@ -292,13 +292,13 @@ class ProvidersTools(BaseTool):
async def delete_provider(
self,
provider_id: str = Field(
- description="Prowler's internal UUID (v4) for the provider to permanently remove, generated when the provider was registered in the system. Use `prowler_app_search_providers` tool to find the provider_id if you only know the alias or the provider's own identifier (provider_uid)"
+ description="Prowler's internal UUID (v4) for the provider to permanently remove, generated when the provider was registered in the system. Use `prowler_search_providers` tool to find the provider_id if you only know the alias or the provider's own identifier (provider_uid)"
),
) -> dict[str, Any]:
"""Permanently remove a registered provider from Prowler.
WARNING: This is a destructive operation that cannot be undone. The provider will need to be
- re-added with prowler_app_connect_provider if you want to scan it again.
+ re-added with prowler_connect_provider if you want to scan it again.
The tool always returns the deletion status and message.
"""
diff --git a/mcp_server/prowler_mcp_server/prowler_app/tools/resources.py b/mcp_server/prowler_mcp_server/prowler_app/tools/resources.py
index 011e013b91..88fcca25ae 100644
--- a/mcp_server/prowler_mcp_server/prowler_app/tools/resources.py
+++ b/mcp_server/prowler_mcp_server/prowler_app/tools/resources.py
@@ -1,4 +1,4 @@
-"""Cloud Resources tools for Prowler App MCP Server.
+"""Cloud Resources tools for Prowler MCP Server.
This module provides tools for searching, viewing, and analyzing cloud resources
across all providers.
@@ -86,7 +86,7 @@ class ResourcesTools(BaseTool):
IMPORTANT: This tool returns LIGHTWEIGHT resource information. Use this for fast searching
and filtering across many resources. For complete configuration details, metadata, and finding
- relationships, use prowler_app_get_resource on specific resources of interest.
+ relationships, use prowler_get_resource on specific resources of interest.
This is the primary tool for browsing resources with rich filtering capabilities.
Returns current state by default (latest scan per provider). Specify dates to query
@@ -102,16 +102,16 @@ class ResourcesTools(BaseTool):
- With dates: queries historical resource state (2-day maximum range between date_from and date_to)
Each resource includes:
- - Core identification: id (UUID for prowler_app_get_resource), uid, name
+ - Core identification: id (UUID for prowler_get_resource), uid, name
- Location context: region, service, type
- Security context: failed_findings_count (number of active security issues)
- Tags: tags associated with the resource
Useful Workflow:
1. Use this tool to search and filter resources by provider, region, service, tags, etc.
- 2. Use prowler_app_get_resource with the resource 'id' to get complete configuration and metadata
- 3. Use prowler_app_search_security_findings to find security issues for specific resources
- 4. Use prowler_app_get_finding_details to get details about the security issues for specific resources
+ 2. Use prowler_get_resource with the resource 'id' to get complete configuration and metadata
+ 3. Use prowler_search_security_findings to find security issues for specific resources
+ 4. Use prowler_get_finding_details to get details about the security issues for specific resources
"""
# Validate page_size parameter
self.api_client.validate_page_size(page_size)
@@ -177,15 +177,15 @@ class ResourcesTools(BaseTool):
async def get_resource(
self,
resource_id: str = Field(
- description="Prowler's internal UUID (v4) for the resource to retrieve, generated when the resource was discovered in the system. Use `prowler_app_list_resources` tool to find the right ID"
+ description="Prowler's internal UUID (v4) for the resource to retrieve, generated when the resource was discovered in the system. Use `prowler_list_resources` tool to find the right ID"
),
) -> dict[str, Any]:
"""Retrieve comprehensive details about a specific resource by its ID.
IMPORTANT: This tool provides COMPLETE resource details with all available information.
- Use this after finding a specific resource via prowler_app_list_resources.
+ Use this after finding a specific resource via prowler_list_resources.
- This tool provides ALL information that prowler_app_list_resources returns PLUS:
+ This tool provides ALL information that prowler_list_resources returns PLUS:
1. Configuration Details:
- metadata: Provider-specific configuration (tags, policies, encryption settings, network rules)
@@ -197,12 +197,12 @@ class ResourcesTools(BaseTool):
3. Security Relationships:
- finding_ids: Prowler's internal UUIDs (v4) of all security findings associated with this resource
- - Use prowler_app_get_finding_details on these IDs to get remediation guidance
+ - Use prowler_get_finding_details on these IDs to get remediation guidance
Useful Workflow:
- 1. Use prowler_app_list_resources to browse and filter across many resources
+ 1. Use prowler_list_resources to browse and filter across many resources
2. Use this tool to drill down into specific resources of interest
- 3. Use prowler_app_get_finding_details to get details about the security issues for specific resources
+ 3. Use prowler_get_finding_details to get details about the security issues for specific resources
"""
params = {}
@@ -348,7 +348,7 @@ class ResourcesTools(BaseTool):
async def get_resource_events(
self,
resource_id: str = Field(
- description="Prowler's internal UUID (v4) for the resource. Use `prowler_app_list_resources` to find the right ID, or get it from a finding's resource relationship via `prowler_app_get_finding_details`."
+ description="Prowler's internal UUID (v4) for the resource. Use `prowler_list_resources` to find the right ID, or get it from a finding's resource relationship via `prowler_get_finding_details`."
),
lookback_days: int = Field(
default=90,
@@ -386,8 +386,8 @@ class ResourcesTools(BaseTool):
- Identifying unauthorized or unexpected modifications
Workflows:
- 1. Resource browsing: prowler_app_list_resources → find resource → this tool for event history
- 2. Incident investigation: prowler_app_get_finding_details → get resource ID from finding → this tool to identify who caused the issue, what they changed, and when
+ 1. Resource browsing: prowler_list_resources → find resource → this tool for event history
+ 2. Incident investigation: prowler_get_finding_details → get resource ID from finding → this tool to identify who caused the issue, what they changed, and when
"""
params = {
"lookback_days": lookback_days,
diff --git a/mcp_server/prowler_mcp_server/prowler_app/tools/scans.py b/mcp_server/prowler_mcp_server/prowler_app/tools/scans.py
index 1df636ffc0..21d1431b71 100644
--- a/mcp_server/prowler_mcp_server/prowler_app/tools/scans.py
+++ b/mcp_server/prowler_mcp_server/prowler_app/tools/scans.py
@@ -1,4 +1,4 @@
-"""Security Scans tools for Prowler App MCP Server.
+"""Security Scans tools for Prowler MCP Server.
This module provides tools for managing and monitoring Prowler security scans.
"""
@@ -20,18 +20,18 @@ class ScansTools(BaseTool):
"""Tools for security scan operations.
Provides tools for:
- - prowler_app_list_scans: Search and filter scans with rich filtering capabilities
- - prowler_app_get_scan: Get comprehensive details about a specific scan
- - prowler_app_trigger_scan: Trigger manual security scans for providers
- - prowler_app_schedule_daily_scan: Schedule automated daily scans for continuous monitoring
- - prowler_app_update_scan: Update scan names for better organization
+ - prowler_list_scans: Search and filter scans with rich filtering capabilities
+ - prowler_get_scan: Get comprehensive details about a specific scan
+ - prowler_trigger_scan: Trigger manual security scans for providers
+ - prowler_schedule_daily_scan: Schedule automated daily scans for continuous monitoring
+ - prowler_update_scan: Update scan names for better organization
"""
async def list_scans(
self,
provider_id: list[str] = Field(
default=[],
- description="Filter by Prowler's internal UUID(s) (v4) for specific provider(s), generated when the provider was registered. Use `prowler_app_search_providers` tool to find provider IDs",
+ description="Filter by Prowler's internal UUID(s) (v4) for specific provider(s), generated when the provider was registered. Use `prowler_search_providers` tool to find provider IDs",
),
provider_type: list[str] = Field(
default=[],
@@ -56,7 +56,7 @@ class ScansTools(BaseTool):
),
trigger: Literal["manual", "scheduled"] | None = Field(
default=None,
- description="Filter by how the scan was initiated. Options: 'manual' (user-initiated via prowler_app_trigger_scan), 'scheduled' (automated via prowler_app_schedule_daily_scan)",
+ description="Filter by how the scan was initiated. Options: 'manual' (user-initiated via prowler_trigger_scan), 'scheduled' (automated via prowler_schedule_daily_scan)",
),
name: str | None = Field(
default=None,
@@ -75,7 +75,7 @@ class ScansTools(BaseTool):
IMPORTANT: This tool returns LIGHTWEIGHT scan information. Use this for fast searching and filtering
across many scans. For complete scan details including progress, duration, and resource counts,
- use prowler_app_get_scan on specific scans of interest.
+ use prowler_get_scan on specific scans of interest.
Default behavior:
- Returns all scans
@@ -83,15 +83,15 @@ class ScansTools(BaseTool):
- Includes all scan states (available, scheduled, executing, completed, failed, cancelled)
Each scan includes:
- - Core identification: id (UUID for prowler_app_get_scan), name
+ - Core identification: id (UUID for prowler_get_scan), name
- Execution context: state, trigger (manual/scheduled)
- Temporal data: started_at, completed_at
- Provider relationship: provider_id
Workflow:
1. Use this tool to search and filter scans by provider, state, or date range
- 2. Use prowler_app_get_scan with the scan 'id' to get progress, duration, and resource counts
- 3. Use prowler_app_search_security_findings filtered by scan dates to analyze scan results
+ 2. Use prowler_get_scan with the scan 'id' to get progress, duration, and resource counts
+ 3. Use prowler_search_security_findings filtered by scan dates to analyze scan results
"""
# Validate pagination
self.api_client.validate_page_size(page_size)
@@ -128,15 +128,15 @@ class ScansTools(BaseTool):
async def get_scan(
self,
scan_id: str = Field(
- description="Prowler's internal UUID (v4) for the scan to retrieve, generated when the scan was created (e.g., '123e4567-e89b-12d3-a456-426614174000'). Use `prowler_app_list_scans` tool to find scan IDs"
+ description="Prowler's internal UUID (v4) for the scan to retrieve, generated when the scan was created (e.g., '123e4567-e89b-12d3-a456-426614174000'). Use `prowler_list_scans` tool to find scan IDs"
),
) -> dict[str, Any]:
"""Retrieve comprehensive details about a specific scan by its ID.
IMPORTANT: This tool returns COMPLETE scan details.
- Use this after finding a specific scan via prowler_app_list_scans.
+ Use this after finding a specific scan via prowler_list_scans.
- This tool provides ALL information that prowler_app_list_scans returns PLUS:
+ This tool provides ALL information that prowler_list_scans returns PLUS:
1. Execution Details:
- progress: Scan completion progress as percentage (0-100%)
@@ -155,9 +155,9 @@ class ScansTools(BaseTool):
- Understanding scan scheduling patterns
Workflow:
- 1. Use prowler_app_list_scans to browse and filter scans
+ 1. Use prowler_list_scans to browse and filter scans
2. Use this tool with the scan 'id' to monitor progress or view detailed results
- 3. For completed scans, use prowler_app_search_security_findings filtered by date to analyze findings
+ 3. For completed scans, use prowler_search_security_findings filtered by date to analyze findings
"""
# Fetch scan with all fields
params = {
@@ -172,7 +172,7 @@ class ScansTools(BaseTool):
async def trigger_scan(
self,
provider_id: str = Field(
- description="Prowler's internal UUID (v4) for the provider to scan, generated when the provider was registered in the system (e.g., '4d0e2614-6385-4fa7-bf0b-c2e2f75c6877'). Use `prowler_app_search_providers` tool to find the provider ID"
+ description="Prowler's internal UUID (v4) for the provider to scan, generated when the provider was registered in the system (e.g., '4d0e2614-6385-4fa7-bf0b-c2e2f75c6877'). Use `prowler_search_providers` tool to find the provider ID"
),
name: str | None = Field(
default=None,
@@ -182,14 +182,14 @@ class ScansTools(BaseTool):
"""Trigger a manual security scan for a provider.
IMPORTANT: This tool returns immediately once the scan is created.
- The scan will continue running in the background. Use `prowler_app_get_scan`
+ The scan will continue running in the background. Use `prowler_get_scan`
with the returned scan ID to monitor progress and check when it completes.
Example Useful Workflow:
- 1. Use `prowler_app_search_providers` to find the provider_id you want to scan
+ 1. Use `prowler_search_providers` to find the provider_id you want to scan
2. Use this tool to trigger the scan
- 3. Use `prowler_app_get_scan` with the returned scan 'id' to monitor progress
- 4. Once completed, use `prowler_app_search_security_findings` to analyze results
+ 3. Use `prowler_get_scan` with the returned scan 'id' to monitor progress
+ 4. Once completed, use `prowler_search_security_findings` to analyze results
"""
try:
# Build request data
@@ -231,7 +231,7 @@ class ScansTools(BaseTool):
return ScanCreationResult(
scan=scan_info,
status="success",
- message=f"Scan {scan_id} created successfully. The scan may take some time to complete. Use prowler_app_get_scan tool with this ID to monitor progress.",
+ message=f"Scan {scan_id} created successfully. The scan may take some time to complete. Use prowler_get_scan tool with this ID to monitor progress.",
).model_dump()
except Exception as e:
@@ -245,7 +245,7 @@ class ScansTools(BaseTool):
async def schedule_daily_scan(
self,
provider_id: str = Field(
- description="Prowler's internal UUID (v4) for the provider to scan, generated when the provider was registered in the system (e.g., '4d0e2614-6385-4fa7-bf0b-c2e2f75c6877'). Use `prowler_app_search_providers` tool to find the provider ID"
+ description="Prowler's internal UUID (v4) for the provider to scan, generated when the provider was registered in the system (e.g., '4d0e2614-6385-4fa7-bf0b-c2e2f75c6877'). Use `prowler_search_providers` tool to find the provider ID"
),
) -> dict[str, Any]:
"""Schedule automated daily scans for a provider for continuous security monitoring.
@@ -256,17 +256,17 @@ class ScansTools(BaseTool):
you're not actively using the system.
IMPORTANT: This tool returns immediately once the daily schedule is created.
- The schedule will be set up in the background. Use `prowler_app_list_scans`
+ The schedule will be set up in the background. Use `prowler_list_scans`
filtered by provider_id and trigger='scheduled' to view scheduled scans.
IMPORTANT: This creates a PERSISTENT schedule. The provider will be scanned
automatically every 24 hours until the provider is deleted.
Example Useful Workflow:
- 1. Use `prowler_app_search_providers` to find the provider_id you want to monitor
+ 1. Use `prowler_search_providers` to find the provider_id you want to monitor
2. Use this tool to create the daily schedule
- 3. Use `prowler_app_list_scans` filtered by provider_id to view scheduled and completed scans
- 4. Monitor findings over time with `prowler_app_search_security_findings`
+ 3. Use `prowler_list_scans` filtered by provider_id to view scheduled and completed scans
+ 4. Monitor findings over time with `prowler_search_security_findings`
"""
self.logger.info(f"Creating daily schedule for provider {provider_id}")
task_response = await self.api_client.post(
@@ -285,7 +285,7 @@ class ScansTools(BaseTool):
)
if task_state == "available":
- return_message = "Daily schedule created successfully. The schedule is being set up in the background. Use prowler_app_list_scans with provider_id filter to view scheduled scans."
+ return_message = "Daily schedule created successfully. The schedule is being set up in the background. Use prowler_list_scans with provider_id filter to view scheduled scans."
else:
return_message = "Daily schedule creation failed. Please try again later."
@@ -297,7 +297,7 @@ class ScansTools(BaseTool):
async def update_scan(
self,
scan_id: str = Field(
- description="Prowler's internal UUID (v4) for the scan to update, generated when the scan was created (e.g., '123e4567-e89b-12d3-a456-426614174000'). Use `prowler_app_list_scans` tool to find the scan ID if you only know the provider or scan name. Returns an error if the scan ID is invalid or not found."
+ description="Prowler's internal UUID (v4) for the scan to update, generated when the scan was created (e.g., '123e4567-e89b-12d3-a456-426614174000'). Use `prowler_list_scans` tool to find the scan ID if you only know the provider or scan name. Returns an error if the scan ID is invalid or not found."
),
name: str = Field(
description="New human-friendly name for the scan (3-100 characters). Use descriptive names to improve organization and tracking, e.g., 'Production Security Audit - Q4 2025', 'Post-Deployment Compliance Check'. IMPORTANT: Only the scan name can be updated - other attributes (state, progress, duration) are read-only and managed by the system."
@@ -309,7 +309,7 @@ class ScansTools(BaseTool):
(state, progress, duration, etc.) are read-only and managed by the system.
Example Useful Workflow:
- 1. Use `prowler_app_list_scans` to find the scan you want to rename
+ 1. Use `prowler_list_scans` to find the scan you want to rename
2. Use this tool with the scan 'id' and new name
"""
api_response = await self.api_client.patch(
diff --git a/mcp_server/prowler_mcp_server/prowler_app/utils/api_client.py b/mcp_server/prowler_mcp_server/prowler_app/utils/api_client.py
index a6aacc3ce1..187364bee1 100644
--- a/mcp_server/prowler_mcp_server/prowler_app/utils/api_client.py
+++ b/mcp_server/prowler_mcp_server/prowler_app/utils/api_client.py
@@ -1,4 +1,4 @@
-"""Shared API client utilities for Prowler App tools."""
+"""Shared API client utilities for Prowler tools."""
import asyncio
from datetime import datetime, timedelta
diff --git a/mcp_server/prowler_mcp_server/prowler_app/utils/auth.py b/mcp_server/prowler_mcp_server/prowler_app/utils/auth.py
index 72c06000df..eff5d3a117 100644
--- a/mcp_server/prowler_mcp_server/prowler_app/utils/auth.py
+++ b/mcp_server/prowler_mcp_server/prowler_app/utils/auth.py
@@ -10,7 +10,7 @@ from prowler_mcp_server.lib.logger import logger
class ProwlerAppAuth:
- """Handles authentication for Prowler App API using API keys or JWT tokens."""
+ """Handles authentication for Prowler API using API keys or JWT tokens."""
def __init__(
self,
@@ -18,19 +18,23 @@ class ProwlerAppAuth:
base_url: str = os.getenv("API_BASE_URL", "https://api.prowler.com/api/v1"),
):
self.base_url = base_url.rstrip("/")
- logger.info(f"Using Prowler App API base URL: {self.base_url}")
+ logger.info(f"Using Prowler API base URL: {self.base_url}")
self.mode = mode
self.access_token: str | None = None
self.api_key: str | None = None
if mode == "stdio": # STDIO mode
- self.api_key = os.getenv("PROWLER_APP_API_KEY")
+ # PROWLER_API_KEY is the current variable; PROWLER_APP_API_KEY is kept
+ # as a backward-compatible fallback so existing setups keep working.
+ self.api_key = os.getenv("PROWLER_API_KEY") or os.getenv(
+ "PROWLER_APP_API_KEY"
+ )
if not self.api_key:
- raise ValueError("PROWLER_APP_API_KEY environment variable is required")
+ raise ValueError("PROWLER_API_KEY environment variable is required")
if not self.api_key.startswith("pk_"):
- raise ValueError("Prowler App API key format is incorrect")
+ raise ValueError("Prowler API key format is incorrect")
def _parse_jwt(self, token: str) -> dict | None:
"""Parse JWT token and return payload
diff --git a/mcp_server/prowler_mcp_server/prowler_app/utils/tool_loader.py b/mcp_server/prowler_mcp_server/prowler_app/utils/tool_loader.py
index b85c13af35..3a00474b5f 100644
--- a/mcp_server/prowler_mcp_server/prowler_app/utils/tool_loader.py
+++ b/mcp_server/prowler_mcp_server/prowler_app/utils/tool_loader.py
@@ -13,18 +13,27 @@ from prowler_mcp_server.lib.logger import logger
from prowler_mcp_server.prowler_app.tools.base import BaseTool
-def load_all_tools(mcp: FastMCP) -> None:
- """Auto-discover and load all BaseTool subclasses from the tools package.
+def load_all_tools(
+ mcp: FastMCP,
+ tools_package: str = "prowler_mcp_server.prowler_app.tools",
+) -> None:
+ """Auto-discover and load all BaseTool subclasses from a tools package.
This function:
- 1. Dynamically imports all Python modules in the tools package
- 2. Discovers all concrete BaseTool subclasses
+ 1. Dynamically imports all Python modules in the given tools package
+ 2. Discovers all concrete BaseTool subclasses defined in that package
3. Instantiates each tool class
4. Registers all tools with the provided FastMCP instance
+ ``BaseTool.__subclasses__()`` returns every subclass in the process, so the
+ discovered classes are filtered by ``__module__`` prefix. This keeps sibling
+ sub-servers (e.g. ``prowler_app`` and ``prowler_cloud``) from cross-registering
+ each other's tools, regardless of import order.
+
Args:
mcp: The FastMCP instance to register tools with
- TOOLS_PACKAGE: The package path containing tool modules (default: prowler_mcp_server.prowler_app.tools)
+ tools_package: The package path containing tool modules
+ (default: prowler_mcp_server.prowler_app.tools)
Example:
from fastmcp import FastMCP
@@ -33,7 +42,7 @@ def load_all_tools(mcp: FastMCP) -> None:
app = FastMCP("prowler-app")
load_all_tools(app)
"""
- TOOLS_PACKAGE = "prowler_mcp_server.prowler_app.tools"
+ TOOLS_PACKAGE = tools_package
logger.info(f"Auto-discovering tools from package: {TOOLS_PACKAGE}")
# Import the tools package
@@ -59,11 +68,14 @@ def load_all_tools(mcp: FastMCP) -> None:
except Exception as e:
logger.error(f"Failed to import module {module_name}: {e}")
- # Discover all concrete BaseTool subclasses
+ # Discover all concrete BaseTool subclasses defined in this package only.
+ # __subclasses__() is process-wide, so filter by module to avoid sibling
+ # sub-servers cross-registering each other's tools.
concrete_tools = [
tool_class
for tool_class in BaseTool.__subclasses__()
if not getattr(tool_class, "__abstractmethods__", None)
+ and tool_class.__module__.startswith(TOOLS_PACKAGE)
]
logger.info(f"Discovered {len(concrete_tools)} tool classes")
diff --git a/mcp_server/prowler_mcp_server/server.py b/mcp_server/prowler_mcp_server/server.py
index 7c85641dee..a46ca12672 100644
--- a/mcp_server/prowler_mcp_server/server.py
+++ b/mcp_server/prowler_mcp_server/server.py
@@ -19,15 +19,15 @@ def setup_main_server():
except Exception as e:
logger.error(f"Failed to mount Prowler Hub server: {e}")
- # Mount Prowler App tools with prowler_app_ namespace
+ # Mount core Prowler tools with prowler_ namespace
try:
- logger.info("Mounting Prowler App server...")
+ logger.info("Mounting Prowler tools server...")
from prowler_mcp_server.prowler_app.server import app_mcp_server
- prowler_mcp_server.mount(app_mcp_server, namespace="prowler_app")
- logger.info("Successfully mounted Prowler App server")
+ prowler_mcp_server.mount(app_mcp_server, namespace="prowler")
+ logger.info("Successfully mounted Prowler tools server")
except Exception as e:
- logger.error(f"Failed to mount Prowler App server: {e}")
+ logger.error(f"Failed to mount Prowler tools server: {e}")
# Mount Prowler Documentation tools with prowler_docs_ namespace
try:
diff --git a/mcp_server/pyproject.toml b/mcp_server/pyproject.toml
index 63aefdf931..f27e08b743 100644
--- a/mcp_server/pyproject.toml
+++ b/mcp_server/pyproject.toml
@@ -19,11 +19,13 @@ description = "MCP server for Prowler ecosystem"
name = "prowler-mcp"
readme = "README.md"
requires-python = ">=3.12"
-version = "0.5.0"
+version = "0.8.0"
[project.scripts]
prowler-mcp = "prowler_mcp_server.main:main"
+[tool.pytest]
+
[tool.pytest.ini_options]
testpaths = ["tests"]
diff --git a/mcp_server/towncrier.toml b/mcp_server/towncrier.toml
new file mode 100644
index 0000000000..528e6129ec
--- /dev/null
+++ b/mcp_server/towncrier.toml
@@ -0,0 +1,39 @@
+[tool.towncrier]
+directory = "changelog.d"
+filename = "CHANGELOG.md"
+start_string = "\n"
+title_format = "## [{version}] ({name})"
+issue_format = "[(#{issue})](https://github.com/prowler-cloud/prowler/pull/{issue})"
+template = "../.github/towncrier/template.md.jinja"
+underlines = ["", "", ""]
+ignore = [".gitkeep", "README.md"]
+
+[[tool.towncrier.type]]
+directory = "added"
+name = "🚀 Added"
+showcontent = true
+
+[[tool.towncrier.type]]
+directory = "changed"
+name = "🔄 Changed"
+showcontent = true
+
+[[tool.towncrier.type]]
+directory = "deprecated"
+name = "⚠️ Deprecated"
+showcontent = true
+
+[[tool.towncrier.type]]
+directory = "removed"
+name = "❌ Removed"
+showcontent = true
+
+[[tool.towncrier.type]]
+directory = "fixed"
+name = "🐞 Fixed"
+showcontent = true
+
+[[tool.towncrier.type]]
+directory = "security"
+name = "🔐 Security"
+showcontent = true
diff --git a/mcp_server/uv.lock b/mcp_server/uv.lock
index 3258767442..a9afbeafd7 100644
--- a/mcp_server/uv.lock
+++ b/mcp_server/uv.lock
@@ -676,7 +676,7 @@ wheels = [
[[package]]
name = "prowler-mcp"
-version = "0.5.0"
+version = "0.8.0"
source = { editable = "." }
dependencies = [
{ name = "fastmcp" },
diff --git a/permissions/prowler-additions-policy.json b/permissions/prowler-additions-policy.json
index c0da045603..6c58f6e184 100644
--- a/permissions/prowler-additions-policy.json
+++ b/permissions/prowler-additions-policy.json
@@ -4,6 +4,8 @@
{
"Action": [
"account:Get*",
+ "amplify:ListApps",
+ "amplify:ListBranches",
"appstream:Describe*",
"appstream:List*",
"backup:List*",
@@ -15,6 +17,9 @@
"codebuild:BatchGet*",
"codebuild:ListReportGroups",
"cognito-idp:GetUserPoolMfaConfig",
+ "datapipeline:DescribePipelines",
+ "datapipeline:GetPipelineDefinition",
+ "datapipeline:ListPipelines",
"dlm:Get*",
"drs:Describe*",
"ds:Get*",
@@ -39,6 +44,8 @@
"rolesanywhere:ListTagsForResource",
"rolesanywhere:ListTrustAnchors",
"s3:GetAccountPublicAccessBlock",
+ "s3:GetObjectAcl",
+ "s3:ListBucket",
"shield:DescribeProtection",
"shield:GetSubscriptionState",
"securityhub:BatchImportFindings",
diff --git a/permissions/templates/cloudformation/prowler-scan-role.yml b/permissions/templates/cloudformation/prowler-scan-role.yml
index a7d91b0071..c9eee71950 100644
--- a/permissions/templates/cloudformation/prowler-scan-role.yml
+++ b/permissions/templates/cloudformation/prowler-scan-role.yml
@@ -1,27 +1,24 @@
AWSTemplateFormatVersion: "2010-09-09"
-# You can invoke CloudFormation and pass the principal ARN from a command line like this:
-# aws cloudformation create-stack \
-# --capabilities CAPABILITY_IAM --capabilities CAPABILITY_NAMED_IAM \
-# --template-body "file://prowler-scan-role.yaml" \
-# --stack-name "ProwlerScanRole" \
-# --parameters "ParameterKey=ExternalId,ParameterValue=ProvidedExternalID"
-
Description: |
- This template creates the ProwlerScan IAM Role in this account with
- all read-only permissions to scan your account for security issues.
+ This template creates the ProwlerScan IAM Role either locally in this account or across
+ multiple accounts via StackSets. It can deploy both simultaneously or just one option.
+ The role includes all read-only permissions to scan your accounts for security issues.
Contains two AWS managed policies (SecurityAudit and ViewOnlyAccess) and an inline policy.
- It sets the trust policy on that IAM Role to permit Prowler to assume that role.
This template is designed to be used in Prowler Cloud, but can also be used in other Prowler deployments.
+
If you are deploying this template to be used in Prowler Cloud please do not edit the AccountId, IAMPrincipal and ExternalId parameters.
+
Parameters:
+ # Core Prowler IAM Role Parameters
ExternalId:
Description: |
- This is the External ID that Prowler will use to assume the role ProwlerScan IAM Role.
+ This is the External ID that Prowler will use to assume the ProwlerScan IAM Role.
Type: String
MinLength: 1
AllowedPattern: ".+"
ConstraintDescription: "ExternalId must not be empty."
+
AccountId:
Description: |
AWS Account ID that will assume the role created, if you are deploying this template to be used in Prowler Cloud please do not edit this.
@@ -31,11 +28,13 @@ Parameters:
MaxLength: 12
AllowedPattern: "[0-9]{12}"
ConstraintDescription: "AccountId must be a valid AWS Account ID."
+
IAMPrincipal:
Description: |
The IAM principal type and name that will be allowed to assume the role created, leave an * for all the IAM principals in your AWS account. If you are deploying this template to be used in Prowler Cloud please do not edit this.
Type: String
Default: role/prowler*
+
EnableOrganizations:
Description: |
Enable AWS Organizations discovery permissions. Set to true only when deploying this role in the management account.
@@ -45,6 +44,7 @@ Parameters:
AllowedValues:
- true
- false
+
EnableS3Integration:
Description: |
Enable S3 integration for storing Prowler scan reports.
@@ -53,25 +53,102 @@ Parameters:
AllowedValues:
- true
- false
+
S3IntegrationBucketName:
Description: |
The S3 bucket name where Prowler will store scan reports for your cloud providers.
Type: String
Default: ""
+
S3IntegrationBucketAccountId:
Description: |
The AWS Account ID owner of the S3 Bucket.
Type: String
Default: ""
+ # Deployment Control Parameters
+ DeployStackSet:
+ Description: |
+ Set to true to deploy the ProwlerScan role across multiple accounts using StackSets.
+ Requires delegated administrator permissions for CloudFormation StackSets.
+ Type: String
+ Default: false
+ AllowedValues:
+ - true
+ - false
+
+ DeployLocalRole:
+ Description: |
+ Set to true to deploy the ProwlerScan role in this account (the account where this template is deployed).
+ Can be used independently or in conjunction with StackSet deployment.
+ Type: String
+ Default: true
+ AllowedValues:
+ - true
+ - false
+
+ # StackSet Configuration Parameters
+ AWSOrganizationalUnitId:
+ Description: |
+ AWS Organizations OU to deploy this stackset to (e.g., ou-xxxx-yyyyyyyy or r-xxxx for root).
+ Only required if DeployStackSet is true.
+ Type: String
+ Default: ""
+ AllowedPattern: '^(ou-[a-z0-9]{4,32}-[a-z0-9]{8,32}|r-[a-z0-9]{4,32})?$'
+
+ RetainStacksOnAccountRemoval:
+ Description: |
+ When an account is removed from the Organization or OU, should the ProwlerScan role remain in that account?
+ False (Recommended for security): Automatically deletes the role when accounts leave, following principle of least privilege.
+ True: Retains the role even after account removal, useful if accounts may temporarily leave and rejoin.
+ Type: String
+ Default: false
+ AllowedValues:
+ - true
+ - false
+
+ DeployFromDelegatedAdmin:
+ Description: |
+ Is this StackSet being deployed from a Delegated Administrator account (not the Organization Management Account)?
+ True: Deploying from a delegated admin account - uses CallAs: DELEGATED_ADMIN.
+ False: Deploying from the Organization Management Account - omits CallAs property.
+ Only required if DeployStackSet is true.
+ Type: String
+ Default: false
+ AllowedValues:
+ - true
+ - false
+
+ FailureTolerancePercentage:
+ Description: |
+ The percentage of accounts in which stack operations can fail before CloudFormation stops the operation.
+ Only applies when DeployStackSet is true.
+ Type: Number
+ Default: 10
+ MinValue: 0
+ MaxValue: 100
+
Conditions:
OrganizationsEnabled: !Equals [!Ref EnableOrganizations, true]
S3IntegrationEnabled: !Equals [!Ref EnableS3Integration, true]
+ DeployStackSetEnabled: !Equals [!Ref DeployStackSet, true]
+ DeployLocalRoleEnabled: !Equals [!Ref DeployLocalRole, true]
+ UseDelegatedAdmin: !Equals [!Ref DeployFromDelegatedAdmin, true]
+Rules:
+ S3IntegrationRequiresParams:
+ RuleCondition: !Equals [!Ref EnableS3Integration, "true"]
+ Assertions:
+ - Assert: !Not [!Equals [!Ref S3IntegrationBucketName, ""]]
+ AssertDescription: "S3IntegrationBucketName is required when EnableS3Integration is true."
+ - Assert: !Not [!Equals [!Ref S3IntegrationBucketAccountId, ""]]
+ AssertDescription: "S3IntegrationBucketAccountId is required when EnableS3Integration is true."
Resources:
+ # Local ProwlerScan Role (deployed in this account)
ProwlerScan:
Type: AWS::IAM::Role
+ Condition: DeployLocalRoleEnabled
Properties:
RoleName: ProwlerScan
AssumeRolePolicyDocument:
@@ -88,8 +165,8 @@ Resources:
"aws:PrincipalArn": !Sub "arn:${AWS::Partition}:iam::${AccountId}:${IAMPrincipal}"
MaxSessionDuration: 3600
ManagedPolicyArns:
- - "arn:aws:iam::aws:policy/SecurityAudit"
- - "arn:aws:iam::aws:policy/job-function/ViewOnlyAccess"
+ - !Sub "arn:${AWS::Partition}:iam::aws:policy/SecurityAudit"
+ - !Sub "arn:${AWS::Partition}:iam::aws:policy/job-function/ViewOnlyAccess"
Policies:
- PolicyName: ProwlerScan
PolicyDocument:
@@ -99,9 +176,12 @@ Resources:
Effect: Allow
Action:
- "account:Get*"
+ - "amplify:ListApps"
+ - "amplify:ListBranches"
- "appstream:Describe*"
- "appstream:List*"
- "backup:List*"
+ - "backup:Get*"
- "bedrock:List*"
- "bedrock:Get*"
- "cloudtrail:GetInsightSelectors"
@@ -109,6 +189,9 @@ Resources:
- "codebuild:BatchGet*"
- "codebuild:ListReportGroups"
- "cognito-idp:GetUserPoolMfaConfig"
+ - "datapipeline:DescribePipelines"
+ - "datapipeline:GetPipelineDefinition"
+ - "datapipeline:ListPipelines"
- "dlm:Get*"
- "drs:Describe*"
- "ds:Get*"
@@ -124,6 +207,7 @@ Resources:
- "glue:GetConnections"
- "glue:GetSecurityConfiguration*"
- "glue:SearchTables"
+ - "glue:GetMLTransforms"
- "lambda:GetFunction*"
- "logs:FilterLogEvents"
- "lightsail:GetRelationalDatabases"
@@ -134,7 +218,6 @@ Resources:
- "s3:GetAccountPublicAccessBlock"
- "shield:DescribeProtection"
- "shield:GetSubscriptionState"
- - "securityhub:BatchImportFindings"
- "securityhub:GetFindings"
- "servicecatalog:Describe*"
- "servicecatalog:List*"
@@ -145,15 +228,20 @@ Resources:
- "tag:GetTagKeys"
- "wellarchitected:List*"
Resource: "*"
+ - Sid: AllowSecurityHubImportFindings
+ Effect: Allow
+ Action:
+ - "securityhub:BatchImportFindings"
+ Resource: "*"
- Sid: AllowAPIGatewayReadOnly
Effect: Allow
Action:
- "apigateway:GET"
Resource:
- - "arn:*:apigateway:*::/restapis/*"
- - "arn:*:apigateway:*::/apis/*"
- - "arn:*:apigateway:*::/domainnames"
- - "arn:*:apigateway:*::/domainnames/*"
+ - !Sub "arn:${AWS::Partition}:apigateway:*::/restapis/*"
+ - !Sub "arn:${AWS::Partition}:apigateway:*::/apis/*"
+ - !Sub "arn:${AWS::Partition}:apigateway:*::/domainnames"
+ - !Sub "arn:${AWS::Partition}:apigateway:*::/domainnames/*"
- !If
- OrganizationsEnabled
- PolicyName: ProwlerOrganizations
@@ -175,8 +263,12 @@ Resources:
Effect: Allow
Action:
- "organizations:RegisterDelegatedAdministrator"
- - "iam:CreateServiceLinkedRole"
Resource: "*"
+ - Sid: AllowCreateStackSetSLR
+ Effect: Allow
+ Action:
+ - "iam:CreateServiceLinkedRole"
+ Resource: !Sub "arn:${AWS::Partition}:iam::*:role/aws-service-role/member.org.stacksets.cloudformation.amazonaws.com/*"
- !Ref AWS::NoValue
- !If
- S3IntegrationEnabled
@@ -219,12 +311,287 @@ Resources:
- Key: "Name"
Value: "ProwlerScan"
+ # StackSet for deploying ProwlerScan role across multiple accounts
+ ProwlerScanStackSet:
+ Type: AWS::CloudFormation::StackSet
+ Condition: DeployStackSetEnabled
+ Properties:
+ StackSetName: !Sub "${AWS::StackName}-ProwlerScan-StackSet"
+ Description: Organizational StackSet to Deploy ProwlerScan IAM Role across accounts
+ PermissionModel: SERVICE_MANAGED
+ CallAs: !If [UseDelegatedAdmin, DELEGATED_ADMIN, !Ref "AWS::NoValue"]
+ Capabilities:
+ - CAPABILITY_NAMED_IAM
+ AutoDeployment:
+ Enabled: True
+ RetainStacksOnAccountRemoval: !Ref RetainStacksOnAccountRemoval
+ OperationPreferences:
+ FailureTolerancePercentage: !Ref FailureTolerancePercentage
+ MaxConcurrentPercentage: 100
+ Parameters:
+ - ParameterKey: ExternalId
+ ParameterValue: !Ref ExternalId
+ - ParameterKey: AccountId
+ ParameterValue: !Ref AccountId
+ - ParameterKey: IAMPrincipal
+ ParameterValue: !Ref IAMPrincipal
+ - ParameterKey: EnableOrganizations
+ ParameterValue: !Ref EnableOrganizations
+ - ParameterKey: EnableS3Integration
+ ParameterValue: !Ref EnableS3Integration
+ - ParameterKey: S3IntegrationBucketName
+ ParameterValue: !Ref S3IntegrationBucketName
+ - ParameterKey: S3IntegrationBucketAccountId
+ ParameterValue: !Ref S3IntegrationBucketAccountId
+ StackInstancesGroup:
+ - DeploymentTargets:
+ OrganizationalUnitIds:
+ - !Ref AWSOrganizationalUnitId
+ Regions:
+ - us-east-1
+ TemplateBody: |
+ AWSTemplateFormatVersion: "2010-09-09"
+
+ Description: |
+ This template creates the ProwlerScan IAM Role in this account with
+ all read-only permissions to scan your account for security issues.
+ Contains two AWS managed policies (SecurityAudit and ViewOnlyAccess) and an inline policy.
+ It sets the trust policy on that IAM Role to permit Prowler to assume that role.
+ This template is designed to be used in Prowler Cloud, but can also be used in other Prowler deployments.
+
+ ** DEPLOYED VIA SERVICE-MANAGED STACKSET **
+ This stack was automatically deployed across your organization using CloudFormation StackSets
+ with SERVICE_MANAGED permissions. It will auto-deploy to new accounts and can be centrally managed.
+
+ Parameters:
+ ExternalId:
+ Description: |
+ This is the External ID that Prowler will use to assume the role ProwlerScan IAM Role.
+ Type: String
+ MinLength: 1
+ AllowedPattern: ".+"
+ ConstraintDescription: "ExternalId must not be empty."
+ AccountId:
+ Description: |
+ AWS Account ID that will assume the role created, if you are deploying this template to be used in Prowler Cloud please do not edit this.
+ Type: String
+ Default: "232136659152"
+ MinLength: 12
+ MaxLength: 12
+ AllowedPattern: "[0-9]{12}"
+ ConstraintDescription: "AccountId must be a valid AWS Account ID."
+ IAMPrincipal:
+ Description: |
+ The IAM principal type and name that will be allowed to assume the role created, leave an * for all the IAM principals in your AWS account. If you are deploying this template to be used in Prowler Cloud please do not edit this.
+ Type: String
+ Default: role/prowler*
+ EnableOrganizations:
+ Description: |
+ Enable AWS Organizations discovery permissions. Set to true only when deploying this role in the management account.
+ This adds read-only Organizations permissions (e.g. ListAccounts, DescribeOrganization) and StackSet management permissions.
+ Type: String
+ Default: false
+ AllowedValues:
+ - true
+ - false
+ EnableS3Integration:
+ Description: |
+ Enable S3 integration for storing Prowler scan reports.
+ Type: String
+ Default: false
+ AllowedValues:
+ - true
+ - false
+ S3IntegrationBucketName:
+ Description: |
+ The S3 bucket name where Prowler will store scan reports for your cloud providers.
+ Type: String
+ Default: ""
+ S3IntegrationBucketAccountId:
+ Description: |
+ The AWS Account ID owner of the S3 Bucket.
+ Type: String
+ Default: ""
+
+ Conditions:
+ OrganizationsEnabled: !Equals [!Ref EnableOrganizations, true]
+ S3IntegrationEnabled: !Equals [!Ref EnableS3Integration, true]
+
+ Resources:
+ ProwlerScan:
+ Type: AWS::IAM::Role
+ Properties:
+ RoleName: ProwlerScan
+ AssumeRolePolicyDocument:
+ Version: "2012-10-17"
+ Statement:
+ - Effect: Allow
+ Principal:
+ AWS: !Sub "arn:${AWS::Partition}:iam::${AccountId}:root"
+ Action: "sts:AssumeRole"
+ Condition:
+ StringEquals:
+ "sts:ExternalId": !Sub ${ExternalId}
+ StringLike:
+ "aws:PrincipalArn": !Sub "arn:${AWS::Partition}:iam::${AccountId}:${IAMPrincipal}"
+ MaxSessionDuration: 3600
+ ManagedPolicyArns:
+ - !Sub "arn:${AWS::Partition}:iam::aws:policy/SecurityAudit"
+ - !Sub "arn:${AWS::Partition}:iam::aws:policy/job-function/ViewOnlyAccess"
+ Policies:
+ - PolicyName: ProwlerScan
+ PolicyDocument:
+ Version: "2012-10-17"
+ Statement:
+ - Sid: AllowMoreReadOnly
+ Effect: Allow
+ Action:
+ - "account:Get*"
+ - "appstream:Describe*"
+ - "appstream:List*"
+ - "backup:List*"
+ - "backup:Get*"
+ - "bedrock:List*"
+ - "bedrock:Get*"
+ - "cloudtrail:GetInsightSelectors"
+ - "codeartifact:List*"
+ - "codebuild:BatchGet*"
+ - "codebuild:ListReportGroups"
+ - "cognito-idp:GetUserPoolMfaConfig"
+ - "dlm:Get*"
+ - "drs:Describe*"
+ - "ds:Get*"
+ - "ds:Describe*"
+ - "ds:List*"
+ - "dynamodb:GetResourcePolicy"
+ - "ec2:GetEbsEncryptionByDefault"
+ - "ec2:GetSnapshotBlockPublicAccessState"
+ - "ec2:GetInstanceMetadataDefaults"
+ - "ecr:Describe*"
+ - "ecr:GetRegistryScanningConfiguration"
+ - "elasticfilesystem:DescribeBackupPolicy"
+ - "glue:GetConnections"
+ - "glue:GetSecurityConfiguration*"
+ - "glue:SearchTables"
+ - "glue:GetMLTransforms"
+ - "lambda:GetFunction*"
+ - "logs:FilterLogEvents"
+ - "lightsail:GetRelationalDatabases"
+ - "macie2:GetMacieSession"
+ - "macie2:GetAutomatedDiscoveryConfiguration"
+ - "s3:GetAccountPublicAccessBlock"
+ - "shield:DescribeProtection"
+ - "shield:GetSubscriptionState"
+ - "securityhub:GetFindings"
+ - "servicecatalog:Describe*"
+ - "servicecatalog:List*"
+ - "ssm:GetDocument"
+ - "ssm-incidents:List*"
+ - "states:ListTagsForResource"
+ - "support:Describe*"
+ - "tag:GetTagKeys"
+ - "wellarchitected:List*"
+ Resource: "*"
+ - Sid: AllowSecurityHubImportFindings
+ Effect: Allow
+ Action:
+ - "securityhub:BatchImportFindings"
+ Resource: "*"
+ - Sid: AllowAPIGatewayReadOnly
+ Effect: Allow
+ Action:
+ - "apigateway:GET"
+ Resource:
+ - !Sub "arn:${AWS::Partition}:apigateway:*::/restapis/*"
+ - !Sub "arn:${AWS::Partition}:apigateway:*::/apis/*"
+ - !Sub "arn:${AWS::Partition}:apigateway:*::/domainnames"
+ - !Sub "arn:${AWS::Partition}:apigateway:*::/domainnames/*"
+ - !If
+ - OrganizationsEnabled
+ - PolicyName: ProwlerOrganizations
+ PolicyDocument:
+ Version: "2012-10-17"
+ Statement:
+ - Sid: AllowOrganizationsReadOnly
+ Effect: Allow
+ Action:
+ - "organizations:DescribeAccount"
+ - "organizations:DescribeOrganization"
+ - "organizations:ListAccounts"
+ - "organizations:ListAccountsForParent"
+ - "organizations:ListOrganizationalUnitsForParent"
+ - "organizations:ListRoots"
+ - "organizations:ListTagsForResource"
+ Resource: "*"
+ - Sid: AllowStackSetManagement
+ Effect: Allow
+ Action:
+ - "organizations:RegisterDelegatedAdministrator"
+ Resource: "*"
+ - Sid: AllowCreateStackSetSLR
+ Effect: Allow
+ Action:
+ - "iam:CreateServiceLinkedRole"
+ Resource: !Sub "arn:${AWS::Partition}:iam::*:role/aws-service-role/member.org.stacksets.cloudformation.amazonaws.com/*"
+ - !Ref AWS::NoValue
+ - !If
+ - S3IntegrationEnabled
+ - PolicyName: S3Integration
+ PolicyDocument:
+ Version: "2012-10-17"
+ Statement:
+ - Effect: Allow
+ Action:
+ - "s3:PutObject"
+ Resource:
+ - !Sub "arn:${AWS::Partition}:s3:::${S3IntegrationBucketName}/*"
+ Condition:
+ StringEquals:
+ "s3:ResourceAccount": !Sub ${S3IntegrationBucketAccountId}
+ - Effect: Allow
+ Action:
+ - "s3:ListBucket"
+ Resource:
+ - !Sub "arn:${AWS::Partition}:s3:::${S3IntegrationBucketName}"
+ Condition:
+ StringEquals:
+ "s3:ResourceAccount": !Sub ${S3IntegrationBucketAccountId}
+ - Effect: Allow
+ Action:
+ - "s3:DeleteObject"
+ Resource:
+ - !Sub "arn:${AWS::Partition}:s3:::${S3IntegrationBucketName}/*test-prowler-connection.txt"
+ Condition:
+ StringEquals:
+ "s3:ResourceAccount": !Sub ${S3IntegrationBucketAccountId}
+ - !Ref AWS::NoValue
+ Tags:
+ - Key: "Service"
+ Value: "https://prowler.com"
+ - Key: "Support"
+ Value: "support@prowler.com"
+ - Key: "CloudFormation"
+ Value: "true"
+ - Key: "Name"
+ Value: "ProwlerScan"
+
+ Outputs:
+ ProwlerScanRoleArn:
+ Description: "ARN of the ProwlerScan IAM Role"
+ Value: !GetAtt ProwlerScan.Arn
+ Export:
+ Name: !Sub "${AWS::StackName}-ProwlerScanRoleArn"
+
Metadata:
- AWS::CloudFormation::StackName: "Prowler"
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
- default: Required
+ default: Deployment Options
+ Parameters:
+ - DeployLocalRole
+ - DeployStackSet
+ - Label:
+ default: Required Prowler Configuration
Parameters:
- ExternalId
- AccountId
@@ -232,14 +599,27 @@ Metadata:
- EnableOrganizations
- EnableS3Integration
- Label:
- default: Optional
+ default: Optional S3 Integration
Parameters:
- S3IntegrationBucketName
- S3IntegrationBucketAccountId
+ - Label:
+ default: StackSet Configuration (Required if DeployStackSet is true)
+ Parameters:
+ - AWSOrganizationalUnitId
+ - DeployFromDelegatedAdmin
+ - RetainStacksOnAccountRemoval
+ - FailureTolerancePercentage
Outputs:
- ProwlerScanRoleArn:
- Description: "ARN of the ProwlerScan IAM Role"
+ LocalProwlerScanRoleArn:
+ Condition: DeployLocalRoleEnabled
+ Description: "ARN of the ProwlerScan IAM Role deployed locally in this account"
Value: !GetAtt ProwlerScan.Arn
Export:
Name: !Sub "${AWS::StackName}-ProwlerScanRoleArn"
+
+ StackSetId:
+ Condition: DeployStackSetEnabled
+ Description: "StackSet ID for the ProwlerScan role deployment across accounts"
+ Value: !Ref ProwlerScanStackSet
diff --git a/prowler/CHANGELOG.md b/prowler/CHANGELOG.md
index 1d6dd42262..408c76d3e1 100644
--- a/prowler/CHANGELOG.md
+++ b/prowler/CHANGELOG.md
@@ -2,12 +2,127 @@
All notable changes to the **Prowler SDK** are documented in this file.
-## [5.32.0] (Prowler UNRELEASED)
+
+
+## [5.35.0] (Prowler v5.35.0)
### 🚀 Added
+- `excluded_checks` and `excluded_services` in scan configurations to narrow the execution scope [(#12028)](https://github.com/prowler-cloud/prowler/pull/12028)
+
+### 🔐 Security
+
+- Jira tenant information requests validate site names and do not follow redirects [(#12012)](https://github.com/prowler-cloud/prowler/pull/12012)
+
+---
+
+## [5.34.0] (Prowler v5.34.0)
+
+### 🚀 Added
+
+- `elbv2_listener_pqc_tls_enabled` check for AWS provider, verifying that ELBv2 listeners use post-quantum TLS policies [(#11254)](https://github.com/prowler-cloud/prowler/pull/11254)
+- `iaas_server_public_ip_attached` check for STACKIT provider, flagging IaaS servers that have a public IP address directly attached to a network interface [(#11549)](https://github.com/prowler-cloud/prowler/pull/11549)
+- Changelog fragment workflow for SDK, API, UI, and MCP Server releases, including PR attribution, fragment validation, release compilation, and preserved section ordering [(#11572)](https://github.com/prowler-cloud/prowler/pull/11572)
+- E2E Networks provider with 27 checks across compute nodes, networking, security groups, load balancers, block/file storage, and managed databases [(#11654)](https://github.com/prowler-cloud/prowler/pull/11654)
+- `datapipeline_pipeline_no_secrets_in_definition` check for AWS provider, scanning Data Pipeline object fields, parameter objects, and parameter values for hardcoded secrets with Kingfisher [(#11821)](https://github.com/prowler-cloud/prowler/pull/11821)
+- `amplify_app_no_secrets_in_environment` check for AWS provider, scanning Amplify app and branch environment variables and build settings for hardcoded secrets [(#11825)](https://github.com/prowler-cloud/prowler/pull/11825)
+- `ec2_ami_account_block_public_access` check for AWS provider, verifying AMI block public access is enabled at the account level in each Region so AMIs cannot be shared publicly [(#11828)](https://github.com/prowler-cloud/prowler/pull/11828)
+- `core_readonly_root_filesystem_enabled` check for Kubernetes provider, verifying that every container in each Pod explicitly sets `readOnlyRootFilesystem: true` in its security context [(#11835)](https://github.com/prowler-cloud/prowler/pull/11835)
+- `core_minimize_hostpath_volume_mounts` check for Kubernetes provider, detecting Pods that use `hostPath` volumes [(#11837)](https://github.com/prowler-cloud/prowler/pull/11837)
+- `app_function_ensure_http_is_redirected_to_https` check for Azure provider, verifying that Function Apps enforce HTTPS-only traffic [(#11929)](https://github.com/prowler-cloud/prowler/pull/11929)
+
+### 🔄 Changed
+
+- Add missing trailing newlines to compliance, region, and fixture data files for POSIX compliance [(#11765)](https://github.com/prowler-cloud/prowler/pull/11765)
+- Oracle Cloud API key authentication now uses an internal bootstrap region when no explicit scan region filter is provided [(#11853)](https://github.com/prowler-cloud/prowler/pull/11853)
+- Redesign the local dashboard sidebar and informational pages [(#11972)](https://github.com/prowler-cloud/prowler/pull/11972)
+
+---
+
+## [5.33.2] (Prowler v5.33.2)
+
+### 🐞 Fixed
+
+- EC2 AMI loading now targets Amazon-owned AMIs used by audited instances, reducing AWS API calls during EC2 scans [(#11958)](https://github.com/prowler-cloud/prowler/pull/11958)
+- `ec2_instance_account_imdsv2_enabled` findings now use regional resource ARNs, preventing findings from different AWS Regions from collapsing into one resource [(#11966)](https://github.com/prowler-cloud/prowler/pull/11966)
+
+---
+
+## [5.33.1] (Prowler v5.33.1)
+
+### 🐞 Fixed
+
+- ECS task definition resource limits now select the latest task definitions by registration date instead of relying on ARN ordering [(#11891)](https://github.com/prowler-cloud/prowler/pull/11891)
+- `dlm_ebs_snapshot_lifecycle_policy_exists` no longer initializes the full EC2 inventory just to detect EBS snapshots, avoiding slow scans when checking DLM lifecycle policies [(#11900)](https://github.com/prowler-cloud/prowler/pull/11900)
+- `dms_instance_no_public_access` no longer initializes the full EC2 service when there are no DMS replication instances [(#11902)](https://github.com/prowler-cloud/prowler/pull/11902)
+- `organizations_scp_check_deny_regions` no longer reports false `FAIL` for AWS Organizations that restrict regions with Allow-based SCPs; the Allow path now checks the statement `Effect` instead of an always-false comparison that made it unreachable [(#11915)](https://github.com/prowler-cloud/prowler/pull/11915)
+- Jira issue creation failures now preserve safe structured response details from Jira [(#11925)](https://github.com/prowler-cloud/prowler/pull/11925)
+- Azure Function App optional permission failures now log as warnings, and Function App environment variable fields use the correct spelling internally [(#11926)](https://github.com/prowler-cloud/prowler/pull/11926)
+
+---
+
+## [5.33.0] (Prowler v5.33.0)
+
+### 🐞 Fixed
+
+- Azure resource group scoped scans now keep subscription entries when scoped resource listing fails, clarify helper documentation and test organization, and align the resource group documentation example with the described values [(#11796)](https://github.com/prowler-cloud/prowler/pull/11796)
+- Azure `postgresql_flexible_server_log_retention_days_greater_3` check now queries the `logfiles.retention_days` configuration parameter instead of `log_retention_days` (which only exists on the retired Single Server), fixing false `FAIL` results on every Flexible Server regardless of the actual retention value [(#11761)](https://github.com/prowler-cloud/prowler/pull/11761)
+
+---
+
+## [5.32.1] (Prowler v5.32.1)
+
+### 🐞 Fixed
+
+- `KeyError: 'MANUAL'` crash while rendering the compliance summary table (e.g. CIS Microsoft 365) when a framework has manual, checks-less requirements with a Level 1/Level 2 profile; `MANUAL` findings are now skipped in the PASS/FAIL section tally instead of raising [(#11822)](https://github.com/prowler-cloud/prowler/issues/11822)
+
+---
+
+## [5.32.0] (Prowler v5.32.0)
+
+### 🚀 Added
+
+- `exchange_application_access_policy_restricts_mailbox_apps` check for M365 provider, verifying every service principal with Microsoft Graph application-level Exchange mailbox permissions is restricted by an Exchange Online Application Access Policy, preventing tenant-wide mailbox access by unscoped applications [(#11247)](https://github.com/prowler-cloud/prowler/pull/11247)
+- Per-requirement configuration validation for compliance frameworks via `ConfigRequirements`, so a requirement is reported as FAIL when its configurable checks ran with a configuration too loose to satisfy it (applied across all compliance outputs: CSV, OCSF, and console tables) [(#11669)](https://github.com/prowler-cloud/prowler/pull/11669)
- `entra_conditional_access_policy_explicitly_targets_azure_devops` check for M365 provider, verifying at least one enabled Conditional Access policy explicitly includes the Azure DevOps cloud application instead of relying on a broad "All cloud apps" policy [(#11182)](https://github.com/prowler-cloud/prowler/pull/11182)
- `entra_conditional_access_policy_no_exclusion_gaps` check for M365 provider, verifying every user, group, role, or application excluded from an enabled Conditional Access policy stays in scope of another enabled policy [(#11577)](https://github.com/prowler-cloud/prowler/pull/11577)
+- `entra_conditional_access_policy_groups_management_restricted` check for M365 provider, verifying every security group referenced by an enabled or report-only Conditional Access policy is management-restricted or role-assignable [(#11342)](https://github.com/prowler-cloud/prowler/pull/11342)
+- `stepfunctions_statemachine_encrypted_with_cmk` check for AWS provider, verifying that each Step Functions state machine uses a customer-managed KMS key for encryption at rest rather than the default AWS-owned key [(#11538)](https://github.com/prowler-cloud/prowler/pull/11538)
+- CIS Controls v8.1 universal compliance framework mapping existing checks across 18 providers (AWS, Azure, GCP, Kubernetes, M365, GitHub, AlibabaCloud, OracleCloud, GoogleWorkspace, Okta, Cloudflare, Vercel, MongoDB Atlas, OpenStack, Linode, StackIT, NHN, and Scaleway) to the 18 CIS Critical Security Controls and their Safeguards [(#11700)](https://github.com/prowler-cloud/prowler/pull/11700)
+- CIS Microsoft 365 Foundations Benchmark v7.0.0 compliance framework for the M365 provider [(#11699)](https://github.com/prowler-cloud/prowler/pull/11699)
+- `waf_regional_webacl_logging_enabled` check for AWS provider, verifying that each AWS WAF Classic Regional Web ACL has logging enabled to a Kinesis Data Firehose stream [(#11539)](https://github.com/prowler-cloud/prowler/pull/11539)
+- `sdk_only` provider property (default `true`) and `Provider.get_app_providers()`, so a provider (built-in or external) stays CLI/SDK-only and hidden from the app unless it declares `sdk_only = False` [(#11427)](https://github.com/prowler-cloud/prowler/pull/11427)
+- `Provider.get_scan_arguments()`, `Provider.get_connection_arguments()` and `Provider.get_credentials_schema()` contract methods, so a provider persisted as a stored uid plus a secret dict can be constructed and validated programmatically (to be consumed by the API in a later change) [(#11578)](https://github.com/prowler-cloud/prowler/pull/11578)
+- Okta API request throttling to proactively stay under rate limits, configurable via `okta_requests_per_second` in the config file and the `--okta-requests-per-second` CLI flag, plus configurable retries via `okta_max_retries` / `--okta-retries-max-attempts` as a safety net [(#11702)](https://github.com/prowler-cloud/prowler/pull/11702)
+- CIS Amazon Web Services Foundations Benchmark v7.0.0 compliance framework for the AWS provider, adding the new Organizations section (2.1.1-2.1.6), resource policy (2.21), web front-end access logging (4.10), and VPC Endpoints (6.8) recommendations [(#11707)](https://github.com/prowler-cloud/prowler/pull/11707)
+- CIS Microsoft Azure Foundations Benchmark v6.0.0 compliance framework for the Azure provider [(#11708)](https://github.com/prowler-cloud/prowler/pull/11708)
+- CIS Google Cloud Platform Foundation Benchmark v5.0.0 compliance framework for the GCP provider [(#11714)](https://github.com/prowler-cloud/prowler/pull/11714)
+- CIS Kubernetes Benchmark v2.0.1 compliance framework for the Kubernetes provider [(#11722)](https://github.com/prowler-cloud/prowler/pull/11722)
+- CIS GitHub Benchmark v1.2.0 compliance framework for the GitHub provider [(#11719)](https://github.com/prowler-cloud/prowler/pull/11719)
+- AWS Bedrock AgentCore privilege escalation paths in the IAM privilege escalation checks, covering Runtime, Harness, Code Interpreter and Custom Browser [(#11726)](https://github.com/prowler-cloud/prowler/pull/11726)
+- `--scan-secrets-validate` flag and `aws.secrets_validate` configuration option to optionally validate the secrets discovered by the secret-scanning checks against the provider APIs; secrets confirmed to be live are reported as critical [(#11694)](https://github.com/prowler-cloud/prowler/pull/11694)
+- `apigateway_restapi_no_secrets_in_stage_variables` check for AWS provider, scanning API Gateway REST API stage variables for hardcoded secrets such as passwords, API keys, and tokens [(#11188)](https://github.com/prowler-cloud/prowler/pull/11188)
+- `s3_bucket_object_public` check for AWS provider, spot-checking a configurable sample of object ACLs in each bucket and flagging objects granted to the AllUsers or AuthenticatedUsers groups; disabled by default and opted into via the `s3_bucket_object_public_enabled` configuration option [(#9517)](https://github.com/prowler-cloud/prowler/pull/9517)
+- Azure provider now supports `--azure-resource-group` to scope resource-level checks to specific resource groups across all accessible subscriptions [(#10657)](https://github.com/prowler-cloud/prowler/pull/10657)
+
+### 🔄 Changed
+
+- Replaced the `detect-secrets` library with [Kingfisher](https://github.com/mongodb/kingfisher) as the engine for the secret-scanning checks; scans run fully offline by default and obvious placeholder values are no longer reported as findings [(#11694)](https://github.com/prowler-cloud/prowler/pull/11694)
+- Removed the `detect_secrets_plugins` configuration option, which is no longer used by the new secret-scanning engine [(#11694)](https://github.com/prowler-cloud/prowler/pull/11694)
+- `awslambda_function_no_secrets_in_code` now supports a `secrets_ignore_files` audit-config option to skip files inside the deployment package by glob pattern (e.g. `*.deps.json`), suppressing .NET dependency-manifest false positives without masking real secrets [(#11222)](https://github.com/prowler-cloud/prowler/pull/11222)
+- AWS scans for EBS snapshots, Backup recovery points, CloudWatch log groups, Lambda functions, ECS task definitions, and CodeArtifact packages now support configurable resource analysis limits via `aws.max_scanned_resources_per_service`; limits are disabled by default and only positive values cap analyzed resources [(#11228)](https://github.com/prowler-cloud/prowler/pull/11228)
+
+### 🐞 Fixed
+
+- GitHub `repository_has_codeowners_file` check no longer flags archived repositories, since they are read-only and cannot be updated without first being unarchived, making the finding not actionable [(#11735)](https://github.com/prowler-cloud/prowler/pull/11735)
+- Report secret-scanning checks as `MANUAL` instead of `PASS` when the scanner fails (non-zero exit, timeout, unparseable output or missing binary), so a scanner failure is no longer indistinguishable from "no secrets found" [(#11694)](https://github.com/prowler-cloud/prowler/pull/11694)
+- Avoid a false `FAIL` in `cloudwatch_log_group_no_secrets_in_logs` when a multiline event's secrets are all removed by `secrets_ignore_patterns` during the rescan [(#11694)](https://github.com/prowler-cloud/prowler/pull/11694)
+- Key the `cloudwatch_log_group_no_secrets_in_logs` secret scan by log group ARN instead of name, so same-named log groups and streams in different regions no longer collide and reuse each other's findings [(#11694)](https://github.com/prowler-cloud/prowler/pull/11694)
+- Compliance frameworks contributed by several external packages under the same provider are now merged instead of overwritten, so every entry-point directory a provider contributes is discovered [(#11578)](https://github.com/prowler-cloud/prowler/pull/11578)
+- Azure PostgreSQL flexible server collection no longer drops the remaining servers in a subscription when one server fails to collect; the `connection_throttle.enable` parameter (removed in PostgreSQL 16+) is treated as absent only when the Azure SDK reports it as not found, so unexpected lookup failures are not silently reported as throttling disabled [(#11595)](https://github.com/prowler-cloud/prowler/pull/11595)
+- Azure `keyvault_logging_enabled` now accepts Key Vault diagnostic settings that enable the explicit `AuditEvent` category, avoiding false failures when Azure returns category-based logs without category groups [(#11660)](https://github.com/prowler-cloud/prowler/pull/11660)
+- GitHub default branch protection checks now evaluate repository rulesets in addition to classic branch protection, avoiding false positives for repositories that enforce protection through rulesets [(#11723)](https://github.com/prowler-cloud/prowler/pull/11723)
+- Okta, Alibaba Cloud and OpenStack scan-config sections are now validated against a registered schema instead of being silently accepted, so their configurable thresholds (session/idle timeouts, retention days, image-sharing and secret-scanning settings) log a warning and fall back to the built-in default whenever a value is out of range [(#11725)](https://github.com/prowler-cloud/prowler/pull/11725)
---
@@ -284,7 +399,6 @@ All notable changes to the **Prowler SDK** are documented in this file.
- `bedrock_prompt_management_exists` check for AWS provider [(#10878)](https://github.com/prowler-cloud/prowler/pull/10878)
- 8 Gmail attachment safety and spoofing protection checks for Google Workspace provider using the Cloud Identity Policy API [(#10980)](https://github.com/prowler-cloud/prowler/pull/10980)
- `bedrock_prompt_encrypted_with_cmk` check for AWS provider [(#10905)](https://github.com/prowler-cloud/prowler/pull/10905)
-
### 🔄 Changed
- Azure Network Watcher flow log checks now require workspace-backed Traffic Analytics for `network_flow_log_captured_sent` and align metadata with VNet-compatible flow log guidance [(#10645)](https://github.com/prowler-cloud/prowler/pull/10645)
diff --git a/prowler/__main__.py b/prowler/__main__.py
index d4c925f74f..12f4b24cac 100644
--- a/prowler/__main__.py
+++ b/prowler/__main__.py
@@ -140,6 +140,7 @@ from prowler.providers.azure.models import AzureOutputOptions
from prowler.providers.cloudflare.models import CloudflareOutputOptions
from prowler.providers.common.provider import Provider
from prowler.providers.common.quick_inventory import run_provider_quick_inventory
+from prowler.providers.e2enetworks.models import E2eNetworksOutputOptions
from prowler.providers.gcp.models import GCPOutputOptions
from prowler.providers.github.models import GithubOutputOptions
from prowler.providers.googleworkspace.models import GoogleWorkspaceOutputOptions
@@ -432,6 +433,10 @@ def prowler():
output_options = VercelOutputOptions(
args, bulk_checks_metadata, global_provider.identity
)
+ elif provider == "e2enetworks":
+ output_options = E2eNetworksOutputOptions(
+ args, bulk_checks_metadata, global_provider.identity
+ )
elif provider == "okta":
output_options = OktaOutputOptions(
args, bulk_checks_metadata, global_provider.identity
diff --git a/tests/config/schema/__init__.py b/prowler/changelog.d/.gitkeep
similarity index 100%
rename from tests/config/schema/__init__.py
rename to prowler/changelog.d/.gitkeep
diff --git a/prowler/changelog.d/README.md b/prowler/changelog.d/README.md
new file mode 100644
index 0000000000..0853174f30
--- /dev/null
+++ b/prowler/changelog.d/README.md
@@ -0,0 +1,10 @@
+# Changelog fragments
+
+Each PR adds one small file here instead of editing `CHANGELOG.md` directly, so concurrent PRs never conflict.
+
+- Filename: `..md`, e.g. `my-new-check.added.md` (slug is free-form: letters, digits, `.`, `_`, `-`)
+- `` is one of: `added`, `changed`, `deprecated`, `removed`, `fixed`, `security`
+- Content: one line with the changelog entry text, without the PR link and without a trailing period (the PR link is attached automatically at release time)
+- A PR adds as many fragment files as entries it needs, freely mixing types (one file per entry); same-type entries just use different slugs
+
+Fragments are compiled into `CHANGELOG.md` when a release is prepared. Full conventions: `skills/prowler-changelog/SKILL.md`.
diff --git a/prowler/changelog.d/grouped-jira-dispatch.changed.md b/prowler/changelog.d/grouped-jira-dispatch.changed.md
new file mode 100644
index 0000000000..8dd2e43ab5
--- /dev/null
+++ b/prowler/changelog.d/grouped-jira-dispatch.changed.md
@@ -0,0 +1 @@
+Jira output rendering supports grouped Finding Group issues with caller-provided links and capped or uncapped finding copy
diff --git a/prowler/compliance/alibabacloud/cis_2.0_alibabacloud.json b/prowler/compliance/alibabacloud/cis_2.0_alibabacloud.json
index 7cda08efbb..9a05c1997f 100644
--- a/prowler/compliance/alibabacloud/cis_2.0_alibabacloud.json
+++ b/prowler/compliance/alibabacloud/cis_2.0_alibabacloud.json
@@ -109,6 +109,14 @@
],
"Checks": [
"ram_user_console_access_unused"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "ram_user_console_access_unused",
+ "ConfigKey": "max_console_access_days",
+ "Operator": "lte",
+ "Value": 90
+ }
]
},
{
@@ -841,6 +849,14 @@
],
"Checks": [
"sls_logstore_retention_period"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "sls_logstore_retention_period",
+ "ConfigKey": "min_log_retention_days",
+ "Operator": "gte",
+ "Value": 365
+ }
]
},
{
@@ -1353,6 +1369,14 @@
],
"Checks": [
"rds_instance_sql_audit_retention"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "rds_instance_sql_audit_retention",
+ "ConfigKey": "min_rds_audit_retention_days",
+ "Operator": "gte",
+ "Value": 180
+ }
]
},
{
@@ -1551,6 +1575,14 @@
],
"Checks": [
"cs_kubernetes_cluster_check_recent"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "cs_kubernetes_cluster_check_recent",
+ "ConfigKey": "max_cluster_check_days",
+ "Operator": "lte",
+ "Value": 7
+ }
]
},
{
diff --git a/prowler/compliance/alibabacloud/prowler_threatscore_alibabacloud.json b/prowler/compliance/alibabacloud/prowler_threatscore_alibabacloud.json
index ca7a030dc2..0bfd47df7e 100644
--- a/prowler/compliance/alibabacloud/prowler_threatscore_alibabacloud.json
+++ b/prowler/compliance/alibabacloud/prowler_threatscore_alibabacloud.json
@@ -47,6 +47,14 @@
"Checks": [
"ram_user_console_access_unused"
],
+ "ConfigRequirements": [
+ {
+ "Check": "ram_user_console_access_unused",
+ "ConfigKey": "max_console_access_days",
+ "Operator": "lte",
+ "Value": 90
+ }
+ ],
"Attributes": [
{
"Title": "Inactive users disabled for console access",
@@ -399,6 +407,14 @@
"LevelOfRisk": 3,
"Weight": 10
}
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "cs_kubernetes_cluster_check_weekly",
+ "ConfigKey": "max_cluster_check_days",
+ "Operator": "lte",
+ "Value": 7
+ }
]
},
{
@@ -695,6 +711,14 @@
"Checks": [
"rds_instance_sql_audit_retention"
],
+ "ConfigRequirements": [
+ {
+ "Check": "rds_instance_sql_audit_retention",
+ "ConfigKey": "min_rds_audit_retention_days",
+ "Operator": "gte",
+ "Value": 180
+ }
+ ],
"Attributes": [
{
"Title": "RDS SQL audit retention configured",
diff --git a/prowler/compliance/aws/asd_essential_eight_aws.json b/prowler/compliance/aws/asd_essential_eight_aws.json
index 00b39817e3..dd39c44268 100644
--- a/prowler/compliance/aws/asd_essential_eight_aws.json
+++ b/prowler/compliance/aws/asd_essential_eight_aws.json
@@ -13,6 +13,14 @@
"config_recorder_all_regions_enabled",
"inspector2_is_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "1 Patch applications",
@@ -260,6 +268,14 @@
"config_recorder_all_regions_enabled",
"inspector2_is_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "2 Patch operating systems",
@@ -742,6 +758,14 @@
"accessanalyzer_enabled",
"accessanalyzer_enabled_without_findings"
],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "4 Restrict administrative privileges",
diff --git a/prowler/compliance/aws/aws_account_security_onboarding_aws.json b/prowler/compliance/aws/aws_account_security_onboarding_aws.json
index 1d038537f0..1910bac223 100644
--- a/prowler/compliance/aws/aws_account_security_onboarding_aws.json
+++ b/prowler/compliance/aws/aws_account_security_onboarding_aws.json
@@ -37,6 +37,26 @@
"guardduty_is_enabled",
"accessanalyzer_enabled",
"macie_is_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "securityhub_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ },
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ },
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -259,6 +279,20 @@
"Checks": [
"guardduty_is_enabled",
"guardduty_is_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ },
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -514,6 +548,14 @@
"Checks": [
"accessanalyzer_enabled",
"accessanalyzer_enabled_without_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -530,6 +572,20 @@
"securityhub_enabled",
"accessanalyzer_enabled",
"accessanalyzer_enabled_without_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "securityhub_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ },
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -666,6 +722,14 @@
],
"Checks": [
"securityhub_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "securityhub_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -680,6 +744,14 @@
],
"Checks": [
"securityhub_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "securityhub_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -694,6 +766,14 @@
],
"Checks": [
"securityhub_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "securityhub_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -708,6 +788,14 @@
],
"Checks": [
"securityhub_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "securityhub_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -722,6 +810,14 @@
],
"Checks": [
"securityhub_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "securityhub_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -736,6 +832,14 @@
],
"Checks": [
"config_recorder_all_regions_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -762,6 +866,14 @@
],
"Checks": [
"config_recorder_all_regions_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -777,6 +889,14 @@
"Checks": [
"guardduty_is_enabled",
"guardduty_centrally_managed"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -792,6 +912,14 @@
"Checks": [
"guardduty_is_enabled",
"guardduty_no_high_severity_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -807,6 +935,14 @@
"Checks": [
"guardduty_is_enabled",
"guardduty_no_high_severity_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -822,6 +958,14 @@
"Checks": [
"guardduty_is_enabled",
"guardduty_no_high_severity_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -837,6 +981,14 @@
"Checks": [
"guardduty_is_enabled",
"guardduty_no_high_severity_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -852,6 +1004,14 @@
"Checks": [
"guardduty_is_enabled",
"guardduty_no_high_severity_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -867,6 +1027,14 @@
"Checks": [
"guardduty_is_enabled",
"guardduty_no_high_severity_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -882,6 +1050,14 @@
"Checks": [
"guardduty_is_enabled",
"guardduty_no_high_severity_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -897,6 +1073,14 @@
"Checks": [
"guardduty_is_enabled",
"guardduty_no_high_severity_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -912,6 +1096,14 @@
"Checks": [
"guardduty_is_enabled",
"guardduty_no_high_severity_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
diff --git a/prowler/compliance/aws/aws_ai_security_framework_aws.json b/prowler/compliance/aws/aws_ai_security_framework_aws.json
index c6a0a8504b..9b87f7464d 100644
--- a/prowler/compliance/aws/aws_ai_security_framework_aws.json
+++ b/prowler/compliance/aws/aws_ai_security_framework_aws.json
@@ -404,6 +404,14 @@
"Checks": [
"accessanalyzer_enabled",
"accessanalyzer_enabled_without_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -860,6 +868,20 @@
"guardduty_lambda_protection_enabled",
"guardduty_rds_protection_enabled",
"guardduty_ec2_malware_protection_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ },
+ {
+ "Check": "guardduty_delegated_admin_enabled_all_regions",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -894,6 +916,14 @@
],
"Checks": [
"securityhub_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "securityhub_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -964,6 +994,14 @@
"Checks": [
"config_recorder_all_regions_enabled",
"config_recorder_using_aws_service_role"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -1157,4 +1195,4 @@
"Checks": []
}
]
-}
\ No newline at end of file
+}
diff --git a/prowler/compliance/aws/aws_foundational_security_best_practices_aws.json b/prowler/compliance/aws/aws_foundational_security_best_practices_aws.json
index cea7ad1655..b58a74bcaa 100644
--- a/prowler/compliance/aws/aws_foundational_security_best_practices_aws.json
+++ b/prowler/compliance/aws/aws_foundational_security_best_practices_aws.json
@@ -20,6 +20,14 @@
"SectionDescription": "This section contains recommendations for configuring ACM resources.",
"Service": "ACM"
}
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "acm_certificates_expiration_check",
+ "ConfigKey": "days_to_expire_threshold",
+ "Operator": "gte",
+ "Value": 30
+ }
]
},
{
@@ -29,6 +37,17 @@
"Checks": [
"acm_certificates_with_secure_key_algorithms"
],
+ "ConfigRequirements": [
+ {
+ "Check": "acm_certificates_with_secure_key_algorithms",
+ "ConfigKey": "insecure_key_algorithms",
+ "Operator": "superset",
+ "Value": [
+ "RSA-1024",
+ "P-192"
+ ]
+ }
+ ],
"Attributes": [
{
"ItemId": "ACM.2",
@@ -777,6 +796,14 @@
"Checks": [
"config_recorder_all_regions_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"ItemId": "Config.1",
@@ -892,6 +919,14 @@
"Checks": [
"documentdb_cluster_backup_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "documentdb_cluster_backup_enabled",
+ "ConfigKey": "minimum_backup_retention_period",
+ "Operator": "gte",
+ "Value": 7
+ }
+ ],
"Attributes": [
{
"ItemId": "DocumentDB.2",
@@ -1959,6 +1994,14 @@
"SectionDescription": "This section contains recommendations for configuring ELB resources.",
"Service": "ELB"
}
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "elb_is_in_multiple_az",
+ "ConfigKey": "elb_min_azs",
+ "Operator": "gte",
+ "Value": 2
+ }
]
},
{
@@ -1993,6 +2036,14 @@
"SectionDescription": "This section contains recommendations for configuring ELB resources.",
"Service": "ELB"
}
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "elbv2_is_in_multiple_az",
+ "ConfigKey": "elbv2_min_azs",
+ "Operator": "gte",
+ "Value": 2
+ }
]
},
{
@@ -2370,6 +2421,14 @@
"Checks": [
"guardduty_is_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"ItemId": "GuardDuty.1",
@@ -2547,6 +2606,20 @@
"iam_user_accesskey_unused",
"iam_user_console_access_unused"
],
+ "ConfigRequirements": [
+ {
+ "Check": "iam_user_accesskey_unused",
+ "ConfigKey": "max_unused_access_keys_days",
+ "Operator": "lte",
+ "Value": 90
+ },
+ {
+ "Check": "iam_user_console_access_unused",
+ "ConfigKey": "max_console_access_days",
+ "Operator": "lte",
+ "Value": 90
+ }
+ ],
"Attributes": [
{
"ItemId": "IAM.8",
@@ -2635,6 +2708,20 @@
"iam_user_accesskey_unused",
"iam_user_console_access_unused"
],
+ "ConfigRequirements": [
+ {
+ "Check": "iam_user_accesskey_unused",
+ "ConfigKey": "max_unused_access_keys_days",
+ "Operator": "lte",
+ "Value": 45
+ },
+ {
+ "Check": "iam_user_console_access_unused",
+ "ConfigKey": "max_console_access_days",
+ "Operator": "lte",
+ "Value": 45
+ }
+ ],
"Attributes": [
{
"ItemId": "IAM.22",
@@ -2791,6 +2878,40 @@
"SectionDescription": "This section contains recommendations for configuring Lambda resources.",
"Service": "Lambda"
}
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "awslambda_function_using_supported_runtimes",
+ "ConfigKey": "obsolete_lambda_runtimes",
+ "Operator": "superset",
+ "Value": [
+ "java8",
+ "go1.x",
+ "provided",
+ "python3.6",
+ "python2.7",
+ "python3.7",
+ "python3.8",
+ "nodejs4.3",
+ "nodejs4.3-edge",
+ "nodejs6.10",
+ "nodejs",
+ "nodejs8.10",
+ "nodejs10.x",
+ "nodejs12.x",
+ "nodejs14.x",
+ "nodejs16.x",
+ "dotnet5.0",
+ "dotnet6",
+ "dotnet7",
+ "dotnetcore1.0",
+ "dotnetcore2.0",
+ "dotnetcore2.1",
+ "dotnetcore3.1",
+ "ruby2.5",
+ "ruby2.7"
+ ]
+ }
]
},
{
@@ -2951,6 +3072,14 @@
"Checks": [
"neptune_cluster_backup_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "neptune_cluster_backup_enabled",
+ "ConfigKey": "minimum_backup_retention_period",
+ "Operator": "gte",
+ "Value": 7
+ }
+ ],
"Attributes": [
{
"ItemId": "Neptune.5",
diff --git a/prowler/compliance/aws/aws_foundational_technical_review_aws.json b/prowler/compliance/aws/aws_foundational_technical_review_aws.json
index 691a8ba7f1..9d8e3cfdc8 100644
--- a/prowler/compliance/aws/aws_foundational_technical_review_aws.json
+++ b/prowler/compliance/aws/aws_foundational_technical_review_aws.json
@@ -176,6 +176,14 @@
"iam_user_with_temporary_credentials",
"guardduty_is_enabled",
"guardduty_no_high_severity_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
diff --git a/prowler/compliance/aws/aws_well_architected_framework_security_pillar_aws.json b/prowler/compliance/aws/aws_well_architected_framework_security_pillar_aws.json
index 4c4eaee252..9dd009afb3 100644
--- a/prowler/compliance/aws/aws_well_architected_framework_security_pillar_aws.json
+++ b/prowler/compliance/aws/aws_well_architected_framework_security_pillar_aws.json
@@ -585,6 +585,14 @@
"cloudtrail_multi_region_enabled",
"vpc_flow_logs_enabled",
"config_recorder_all_regions_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -646,6 +654,20 @@
"guardduty_no_high_severity_findings",
"macie_is_enabled",
"guardduty_is_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "securityhub_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ },
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -778,6 +800,14 @@
"guardduty_is_enabled",
"vpc_flow_logs_enabled",
"apigateway_restapi_authorizers_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -1151,6 +1181,7 @@
"elb_insecure_ssl_ciphers",
"elb_ssl_listeners",
"elbv2_insecure_ssl_ciphers",
+ "elbv2_listener_pqc_tls_enabled",
"cloudfront_distributions_pqc_tls_enabled",
"apigateway_domain_name_pqc_tls_enabled",
"transfer_server_pqc_ssh_kex_enabled",
diff --git a/prowler/compliance/aws/c5_aws.json b/prowler/compliance/aws/c5_aws.json
index 8847469154..269a5ce308 100644
--- a/prowler/compliance/aws/c5_aws.json
+++ b/prowler/compliance/aws/c5_aws.json
@@ -382,6 +382,14 @@
"cloudtrail_multi_region_enabled",
"config_recorder_all_regions_enabled",
"s3_multi_region_access_point_public_access_block"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -2234,6 +2242,14 @@
"vpc_different_regions",
"autoscaling_group_multiple_az",
"storagegateway_gateway_fault_tolerant"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -2261,6 +2277,14 @@
"organizations_scp_check_deny_regions",
"s3_multi_region_access_point_public_access_block",
"vpc_different_regions"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -2308,6 +2332,14 @@
"organizations_scp_check_deny_regions",
"s3_multi_region_access_point_public_access_block",
"vpc_different_regions"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -2978,6 +3010,14 @@
"guardduty_is_enabled",
"athena_workgroup_enforce_configuration",
"shield_advanced_protection_in_global_accelerators"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -3481,6 +3521,14 @@
"cloudtrail_cloudwatch_logging_enabled",
"guardduty_is_enabled",
"guardduty_no_high_severity_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -4299,6 +4347,14 @@
"guardduty_no_high_severity_findings",
"guardduty_rds_protection_enabled",
"guardduty_s3_protection_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -4920,6 +4976,17 @@
"elbv2_nlb_tls_termination_enabled",
"transfer_server_in_transit_encryption_enabled",
"kafka_cluster_mutual_tls_authentication_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "acm_certificates_with_secure_key_algorithms",
+ "ConfigKey": "insecure_key_algorithms",
+ "Operator": "superset",
+ "Value": [
+ "RSA-1024",
+ "P-192"
+ ]
+ }
]
},
{
@@ -4946,6 +5013,17 @@
"elbv2_nlb_tls_termination_enabled",
"transfer_server_in_transit_encryption_enabled",
"kafka_cluster_mutual_tls_authentication_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "acm_certificates_with_secure_key_algorithms",
+ "ConfigKey": "insecure_key_algorithms",
+ "Operator": "superset",
+ "Value": [
+ "RSA-1024",
+ "P-192"
+ ]
+ }
]
},
{
@@ -5220,6 +5298,14 @@
"rds_instance_default_admin",
"accessanalyzer_enabled",
"efs_access_point_enforce_user_identity"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -5737,6 +5823,14 @@
"Checks": [
"accessanalyzer_enabled",
"accessanalyzer_enabled_without_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -6100,6 +6194,17 @@
"cloudfront_distributions_origin_traffic_encrypted",
"glue_development_endpoints_job_bookmark_encryption_enabled",
"cloudtrail_kms_encryption_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "acm_certificates_with_secure_key_algorithms",
+ "ConfigKey": "insecure_key_algorithms",
+ "Operator": "superset",
+ "Value": [
+ "RSA-1024",
+ "P-192"
+ ]
+ }
]
},
{
@@ -6196,6 +6301,17 @@
"elb_ssl_listeners_use_acm_certificate",
"iam_no_expired_server_certificates_stored",
"rds_instance_certificate_expiration"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "acm_certificates_with_secure_key_algorithms",
+ "ConfigKey": "insecure_key_algorithms",
+ "Operator": "superset",
+ "Value": [
+ "RSA-1024",
+ "P-192"
+ ]
+ }
]
},
{
@@ -6307,6 +6423,17 @@
"elb_ssl_listeners_use_acm_certificate",
"iam_no_expired_server_certificates_stored",
"rds_instance_certificate_expiration"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "acm_certificates_with_secure_key_algorithms",
+ "ConfigKey": "insecure_key_algorithms",
+ "Operator": "superset",
+ "Value": [
+ "RSA-1024",
+ "P-192"
+ ]
+ }
]
},
{
@@ -6393,6 +6520,14 @@
"sns_topics_not_publicly_accessible",
"sqs_queues_not_publicly_accessible",
"vpc_peering_routing_tables_with_least_privilege"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -6412,6 +6547,14 @@
"ec2_instance_profile_attached",
"accessanalyzer_enabled",
"accessanalyzer_enabled_without_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -6587,6 +6730,17 @@
"kms_cmk_not_multi_region",
"kms_key_not_publicly_accessible",
"ec2_ebs_volume_encryption"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "acm_certificates_with_secure_key_algorithms",
+ "ConfigKey": "insecure_key_algorithms",
+ "Operator": "superset",
+ "Value": [
+ "RSA-1024",
+ "P-192"
+ ]
+ }
]
},
{
@@ -6809,6 +6963,17 @@
"secretsmanager_not_publicly_accessible",
"secretsmanager_secret_rotated_periodically",
"secretsmanager_secret_unused"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "acm_certificates_with_secure_key_algorithms",
+ "ConfigKey": "insecure_key_algorithms",
+ "Operator": "superset",
+ "Value": [
+ "RSA-1024",
+ "P-192"
+ ]
+ }
]
},
{
@@ -6842,6 +7007,17 @@
],
"Checks": [
"acm_certificates_with_secure_key_algorithms"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "acm_certificates_with_secure_key_algorithms",
+ "ConfigKey": "insecure_key_algorithms",
+ "Operator": "superset",
+ "Value": [
+ "RSA-1024",
+ "P-192"
+ ]
+ }
]
},
{
@@ -6915,6 +7091,17 @@
"secretsmanager_secret_rotated_periodically",
"secretsmanager_secret_unused",
"acm_certificates_with_secure_key_algorithms"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "acm_certificates_with_secure_key_algorithms",
+ "ConfigKey": "insecure_key_algorithms",
+ "Operator": "superset",
+ "Value": [
+ "RSA-1024",
+ "P-192"
+ ]
+ }
]
},
{
@@ -6937,6 +7124,17 @@
"secretsmanager_secret_rotated_periodically",
"secretsmanager_secret_unused",
"acm_certificates_with_secure_key_algorithms"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "acm_certificates_with_secure_key_algorithms",
+ "ConfigKey": "insecure_key_algorithms",
+ "Operator": "superset",
+ "Value": [
+ "RSA-1024",
+ "P-192"
+ ]
+ }
]
},
{
@@ -8042,6 +8240,14 @@
"cloudtrail_multi_region_enabled",
"cloudtrail_multi_region_enabled_logging_management_events",
"cloudtrail_log_file_validation_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -8810,6 +9016,14 @@
"guardduty_is_enabled",
"cloudtrail_log_file_validation_enabled",
"ssmincidents_enabled_with_plans"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -9732,6 +9946,14 @@
"accessanalyzer_enabled_without_findings",
"cloudfront_distributions_s3_origin_access_control",
"cloudtrail_logs_s3_bucket_access_logging_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -10367,6 +10589,14 @@
"Checks": [
"accessanalyzer_enabled",
"accessanalyzer_enabled_without_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -10457,6 +10687,14 @@
"ec2_instance_profile_attached",
"iam_role_cross_account_readonlyaccess_policy",
"iam_securityaudit_role_created"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
diff --git a/prowler/compliance/aws/ccc_aws.json b/prowler/compliance/aws/ccc_aws.json
index 003e9e17a0..ef31bfe1ea 100644
--- a/prowler/compliance/aws/ccc_aws.json
+++ b/prowler/compliance/aws/ccc_aws.json
@@ -49,6 +49,7 @@
"elb_insecure_ssl_ciphers",
"elb_ssl_listeners",
"elbv2_insecure_ssl_ciphers",
+ "elbv2_listener_pqc_tls_enabled",
"cloudfront_distributions_pqc_tls_enabled",
"apigateway_domain_name_pqc_tls_enabled",
"transfer_server_pqc_ssh_kex_enabled",
@@ -275,6 +276,17 @@
"acm_certificates_expiration_check",
"acm_certificates_with_secure_key_algorithms",
"acm_certificates_transparency_logs_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "acm_certificates_with_secure_key_algorithms",
+ "ConfigKey": "insecure_key_algorithms",
+ "Operator": "superset",
+ "Value": [
+ "RSA-1024",
+ "P-192"
+ ]
+ }
]
},
{
@@ -794,6 +806,17 @@
],
"Checks": [
"acm_certificates_with_secure_key_algorithms"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "acm_certificates_with_secure_key_algorithms",
+ "ConfigKey": "insecure_key_algorithms",
+ "Operator": "superset",
+ "Value": [
+ "RSA-1024",
+ "P-192"
+ ]
+ }
]
},
{
@@ -1504,6 +1527,14 @@
"iam_policy_no_full_access_to_kms",
"iam_policy_no_full_access_to_cloudtrail",
"iam_policy_attached_only_to_group_or_roles"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -1666,6 +1697,14 @@
"cloudwatch_changes_to_network_route_tables_alarm_configured",
"cloudwatch_changes_to_vpcs_alarm_configured",
"config_recorder_all_regions_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -1791,6 +1830,14 @@
"cloudtrail_threat_detection_enumeration",
"guardduty_is_enabled",
"guardduty_no_high_severity_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -4311,6 +4358,14 @@
],
"Checks": [
"acm_certificates_expiration_check"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "acm_certificates_expiration_check",
+ "ConfigKey": "days_to_expire_threshold",
+ "Operator": "gte",
+ "Value": 30
+ }
]
},
{
@@ -6176,6 +6231,20 @@
"Checks": [
"iam_user_accesskey_unused",
"iam_user_console_access_unused"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "iam_user_accesskey_unused",
+ "ConfigKey": "max_unused_access_keys_days",
+ "Operator": "lte",
+ "Value": 90
+ },
+ {
+ "Check": "iam_user_console_access_unused",
+ "ConfigKey": "max_console_access_days",
+ "Operator": "lte",
+ "Value": 90
+ }
]
},
{
@@ -6272,6 +6341,14 @@
"cloudwatch_log_metric_filter_root_usage",
"cloudwatch_log_metric_filter_sign_in_without_mfa",
"guardduty_is_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "guardduty_is_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
@@ -6374,6 +6451,14 @@
"Checks": [
"accessanalyzer_enabled",
"accessanalyzer_enabled_without_findings"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
]
},
{
diff --git a/prowler/compliance/aws/cis_1.4_aws.json b/prowler/compliance/aws/cis_1.4_aws.json
index 3efc29fd5b..b373a04665 100644
--- a/prowler/compliance/aws/cis_1.4_aws.json
+++ b/prowler/compliance/aws/cis_1.4_aws.json
@@ -75,6 +75,20 @@
"iam_user_accesskey_unused",
"iam_user_console_access_unused"
],
+ "ConfigRequirements": [
+ {
+ "Check": "iam_user_accesskey_unused",
+ "ConfigKey": "max_unused_access_keys_days",
+ "Operator": "lte",
+ "Value": 45
+ },
+ {
+ "Check": "iam_user_console_access_unused",
+ "ConfigKey": "max_console_access_days",
+ "Operator": "lte",
+ "Value": 45
+ }
+ ],
"Attributes": [
{
"Section": "1 Identity and Access Management",
@@ -265,6 +279,14 @@
"Checks": [
"accessanalyzer_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "1 Identity and Access Management",
@@ -736,6 +758,14 @@
"Checks": [
"config_recorder_all_regions_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "3 Logging",
diff --git a/prowler/compliance/aws/cis_1.5_aws.json b/prowler/compliance/aws/cis_1.5_aws.json
index f7307bb7f4..6a60d786a2 100644
--- a/prowler/compliance/aws/cis_1.5_aws.json
+++ b/prowler/compliance/aws/cis_1.5_aws.json
@@ -75,6 +75,20 @@
"iam_user_accesskey_unused",
"iam_user_console_access_unused"
],
+ "ConfigRequirements": [
+ {
+ "Check": "iam_user_accesskey_unused",
+ "ConfigKey": "max_unused_access_keys_days",
+ "Operator": "lte",
+ "Value": 45
+ },
+ {
+ "Check": "iam_user_console_access_unused",
+ "ConfigKey": "max_console_access_days",
+ "Operator": "lte",
+ "Value": 45
+ }
+ ],
"Attributes": [
{
"Section": "1 Identity and Access Management",
@@ -265,6 +279,14 @@
"Checks": [
"accessanalyzer_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "1 Identity and Access Management",
@@ -802,6 +824,14 @@
"Checks": [
"config_recorder_all_regions_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "3 Logging",
@@ -1054,6 +1084,14 @@
"Checks": [
"securityhub_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "securityhub_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "4 Monitoring",
diff --git a/prowler/compliance/aws/cis_2.0_aws.json b/prowler/compliance/aws/cis_2.0_aws.json
index 4f8c4b2c23..e255bd43e1 100644
--- a/prowler/compliance/aws/cis_2.0_aws.json
+++ b/prowler/compliance/aws/cis_2.0_aws.json
@@ -75,6 +75,20 @@
"iam_user_accesskey_unused",
"iam_user_console_access_unused"
],
+ "ConfigRequirements": [
+ {
+ "Check": "iam_user_accesskey_unused",
+ "ConfigKey": "max_unused_access_keys_days",
+ "Operator": "lte",
+ "Value": 45
+ },
+ {
+ "Check": "iam_user_console_access_unused",
+ "ConfigKey": "max_console_access_days",
+ "Operator": "lte",
+ "Value": 45
+ }
+ ],
"Attributes": [
{
"Section": "1 Identity and Access Management",
@@ -265,6 +279,14 @@
"Checks": [
"accessanalyzer_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "1 Identity and Access Management",
@@ -802,6 +824,14 @@
"Checks": [
"config_recorder_all_regions_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "3 Logging",
@@ -1054,6 +1084,14 @@
"Checks": [
"securityhub_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "securityhub_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "4 Monitoring",
diff --git a/prowler/compliance/aws/cis_3.0_aws.json b/prowler/compliance/aws/cis_3.0_aws.json
index dd4c75a2f7..5540bc40cf 100644
--- a/prowler/compliance/aws/cis_3.0_aws.json
+++ b/prowler/compliance/aws/cis_3.0_aws.json
@@ -75,6 +75,20 @@
"iam_user_accesskey_unused",
"iam_user_console_access_unused"
],
+ "ConfigRequirements": [
+ {
+ "Check": "iam_user_accesskey_unused",
+ "ConfigKey": "max_unused_access_keys_days",
+ "Operator": "lte",
+ "Value": 45
+ },
+ {
+ "Check": "iam_user_console_access_unused",
+ "ConfigKey": "max_console_access_days",
+ "Operator": "lte",
+ "Value": 45
+ }
+ ],
"Attributes": [
{
"Section": "1 Identity and Access Management",
@@ -265,6 +279,14 @@
"Checks": [
"accessanalyzer_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "1 Identity and Access Management",
@@ -756,6 +778,14 @@
"Checks": [
"config_recorder_all_regions_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "3 Logging",
@@ -1008,6 +1038,14 @@
"Checks": [
"securityhub_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "securityhub_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "4 Monitoring",
diff --git a/prowler/compliance/aws/cis_4.0_aws.json b/prowler/compliance/aws/cis_4.0_aws.json
index 0c40f8ac09..c8787ef409 100644
--- a/prowler/compliance/aws/cis_4.0_aws.json
+++ b/prowler/compliance/aws/cis_4.0_aws.json
@@ -254,6 +254,20 @@
"iam_user_accesskey_unused",
"iam_user_console_access_unused"
],
+ "ConfigRequirements": [
+ {
+ "Check": "iam_user_accesskey_unused",
+ "ConfigKey": "max_unused_access_keys_days",
+ "Operator": "lte",
+ "Value": 45
+ },
+ {
+ "Check": "iam_user_console_access_unused",
+ "ConfigKey": "max_console_access_days",
+ "Operator": "lte",
+ "Value": 45
+ }
+ ],
"Attributes": [
{
"Section": "1 Identity and Access Management",
@@ -431,6 +445,14 @@
"Checks": [
"accessanalyzer_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "1 Identity and Access Management",
@@ -750,6 +772,14 @@
"Checks": [
"config_recorder_all_regions_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "3 Logging",
@@ -1234,6 +1264,14 @@
"Checks": [
"securityhub_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "securityhub_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "4 Monitoring",
diff --git a/prowler/compliance/aws/cis_5.0_aws.json b/prowler/compliance/aws/cis_5.0_aws.json
index e870878c6b..0c8d46e170 100644
--- a/prowler/compliance/aws/cis_5.0_aws.json
+++ b/prowler/compliance/aws/cis_5.0_aws.json
@@ -232,6 +232,20 @@
"iam_user_accesskey_unused",
"iam_user_console_access_unused"
],
+ "ConfigRequirements": [
+ {
+ "Check": "iam_user_accesskey_unused",
+ "ConfigKey": "max_unused_access_keys_days",
+ "Operator": "lte",
+ "Value": 45
+ },
+ {
+ "Check": "iam_user_console_access_unused",
+ "ConfigKey": "max_console_access_days",
+ "Operator": "lte",
+ "Value": 45
+ }
+ ],
"Attributes": [
{
"Section": "1 Identity and Access Management",
@@ -409,6 +423,14 @@
"Checks": [
"accessanalyzer_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "1 Identity and Access Management",
@@ -728,6 +750,14 @@
"Checks": [
"config_recorder_all_regions_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "3 Logging",
@@ -1212,6 +1242,14 @@
"Checks": [
"securityhub_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "securityhub_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "4 Monitoring",
diff --git a/prowler/compliance/aws/cis_6.0_aws.json b/prowler/compliance/aws/cis_6.0_aws.json
index 643c192b7b..7ad62a4b65 100644
--- a/prowler/compliance/aws/cis_6.0_aws.json
+++ b/prowler/compliance/aws/cis_6.0_aws.json
@@ -232,6 +232,20 @@
"iam_user_accesskey_unused",
"iam_user_console_access_unused"
],
+ "ConfigRequirements": [
+ {
+ "Check": "iam_user_accesskey_unused",
+ "ConfigKey": "max_unused_access_keys_days",
+ "Operator": "lte",
+ "Value": 45
+ },
+ {
+ "Check": "iam_user_console_access_unused",
+ "ConfigKey": "max_console_access_days",
+ "Operator": "lte",
+ "Value": 45
+ }
+ ],
"Attributes": [
{
"Section": "2 Identity and Access Management",
@@ -409,6 +423,14 @@
"Checks": [
"accessanalyzer_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "2 Identity and Access Management",
@@ -728,6 +750,14 @@
"Checks": [
"config_recorder_all_regions_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "4 Logging",
@@ -1212,6 +1242,14 @@
"Checks": [
"securityhub_enabled"
],
+ "ConfigRequirements": [
+ {
+ "Check": "securityhub_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
"Attributes": [
{
"Section": "5 Monitoring",
diff --git a/prowler/compliance/aws/cis_7.0_aws.json b/prowler/compliance/aws/cis_7.0_aws.json
new file mode 100644
index 0000000000..a927c375bb
--- /dev/null
+++ b/prowler/compliance/aws/cis_7.0_aws.json
@@ -0,0 +1,1610 @@
+{
+ "Framework": "CIS",
+ "Name": "CIS Amazon Web Services Foundations Benchmark v7.0.0",
+ "Version": "7.0",
+ "Provider": "AWS",
+ "Description": "The CIS Amazon Web Services Foundations Benchmark provides prescriptive guidance for configuring security options for a subset of Amazon Web Services with an emphasis on foundational, testable, and architecture agnostic settings.",
+ "Requirements": [
+ {
+ "Id": "2.1.1",
+ "Description": "Ensure centralized root access in AWS Organizations",
+ "Checks": [
+ "iam_root_credentials_management_enabled"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Manual",
+ "Description": "Ensure centralized root access management is enabled to manage and secure root user credentials for member accounts in AWS Organizations. This allows the management account and an optional delegated administrator account to centrally delete, prevent recovery of, and if necessary, perform short-lived, scoped root-required actions in member accounts without maintaining long-term root user credentials in each account.",
+ "RationaleStatement": "The AWS account root user is a powerful, default administrative identity that is difficult to manage safely across many accounts. When each member account manages its own root credentials, organizations often end up with numerous long-lived root passwords, access keys, and MFA devices that are hard to inventory, rotate, and protect. Centralized root access management lets security teams remove or avoid creating root user credentials in member accounts, centrally review and manage any remaining root credentials, and perform necessary root-only tasks via short-term, task-scoped root sessions. This significantly reduces privileged credential sprawl, supports least privilege and dedicated administrator models, and improves visibility and auditability of root-level activity across the organization.",
+ "ImpactStatement": "Enabling centralized root access management changes how root user access is obtained and used in member accounts, but it does not automatically remove existing root credentials. Organizations must plan when and how to delete or disable any existing root passwords, access keys, signing certificates, and MFA devices in member accounts and update any workflows that still rely on direct root sign-in. Security and operations teams will need to use centrally initiated, short-lived root sessions for exceptional tasks that truly require root. This may require procedural changes and additional training, but it significantly reduces long-lived privileged credential sprawl across the organization.",
+ "RemediationProcedure": "1. Sign in to the AWS Management Console with the management account. 2. In the console search bar, type Organizations and open AWS Organizations. - On the Overview page, confirm that an Organization exists and that this account is listed as the Management account. 3. In AWS Organizations, choose Services. Locate AWS Identity and Access Management in the list and, if it is not already enabled, choose Enable trusted access and confirm. - This allows IAM to integrate with AWS Organizations to manage root access centrally. 4. In the console search bar, type IAM and open IAM. In the left navigation pane, choose Root access management. If you see Root access management is disabled, choose Enable. - In the enable dialog, confirm that you want to - \"Root credentials management\" and if desired - \"Privileged root actions in member accounts\" - In the Delegated administrator field, enter the account ID of the account that will manage root user access and take privileged actions on member accounts. AWS recommends using an account intended for security or management purposes, not a general workload account. - When you enable centralized root access in the console, IAM also enables trusted access for IAM in AWS Organizations if it isn't already enabled. - Choose Enable to save the configuration.",
+ "AuditProcedure": "1. Sign in to the AWS Management Console with the management account. 2. In the console search bar, type Organizations and open AWS Organizations. - On the Overview page, confirm that an Organization exists and that this account is listed as the Management account. 3. In AWS Organizations, choose Services. - Confirm that AWS Identity and Access Management appears in the list of services with trusted access enabled. 4. In the console search bar, type IAM and open IAM. In the left navigation pane, choose Root access management. Check the status banner. - If you see that Root access management is enabled and the feature card shows that root credentials management is turned on for member accounts, the organization has centralized root access management enabled. - If you see Root access management is disabled with an option to Enable, centralized root access is not yet enabled. 5. (Optional) On the same Root access management page, review the Delegated administrator information (if shown). - Confirm that the delegated account (if present) is a security or management-focused account, not a general workload account.",
+ "AdditionalInformation": "",
+ "References": "",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.1.2",
+ "Description": "Ensure authorization guardrails for all AWS Organization accounts",
+ "Checks": [],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Manual",
+ "Description": "Ensure that one or more baseline authorization policies such as Service Control Policies (SCPs) and/or Resource Control Policies (RCPs) are attached to all member accounts in AWS Organizations in accordance with organizational security requirements. Authorization policies act as preventive permission guardrails: SCPs define the maximum available permissions for IAM principals within accounts, while RCPs define the maximum available permissions for resources within accounts. These policies can enforce security invariants such as preventing disabling of key security services, restricting use of unapproved AWS Regions, or blocking external access to sensitive resources.",
+ "RationaleStatement": "Authorization policies do not grant permissions but instead set organization-wide limits on what actions principals can perform (SCPs) and what access can be granted to resources (RCPs), regardless of local IAM or resource-based policies. Without baseline guardrail authorization policies, each account can grant excessive or inconsistent permissions that disable logging, weaken security services, allow use of unapproved Regions and services, or permit unintended external access to resources. Attaching standard authorization policies to all member accounts enforces preventive, centralized control over high-risk actions and access patterns, supports least-privilege and role-based access control at scale, and helps ensure that all accounts and resources operate within the organization's defined security baseline.",
+ "ImpactStatement": "Enforcing baseline authorization policies for all member accounts can initially block some existing patterns, such as use of unapproved Regions, disabling security services, or granting broader permissions than the guardrails allow. Teams may need to adjust IAM policies, deployment pipelines, and exception processes so legitimate use cases remain possible within the new guardrails. This can introduce short-term operational overhead and require careful testing, especially when attaching new policies at the root or OU level.",
+ "RemediationProcedure": "Design or confirm baseline guardrail SCPs. 1. From the AWS Organizations console, go to Policies → Service control policies. - If you already have standard guardrail SCPs that implement your security baseline, note their names. - If you do not have such policies, choose Create policy and create at least one baseline guardrail SCP that encodes non-negotiable security requirements. 2. Do the same step as above but for RCPs if needed. From the AWS Organizations console, go to Policies → Resource control policies. 3. Attach guardrail authorization policies to the root and/or OUs. In AWS Organizations, choose AWS accounts, then select the Root of the organization. - Go to the Policies tab, then within section for Service control policies, choose Attach, and select the baseline guardrail SCP(s) you identified or created in step 1. - If using RCPs, then within section for Resource control policies, choose Attach, and select the baseline guardrail RCP(s) you identified or created in step 2. - If your design uses different guardrails per OU (for example, stricter policies for production OU), select each OU in turn and attach the appropriate guardrail SCPs and RCPs to those OUs. - AWS recommends testing authorization policies in a staging OU before attaching them broadly to the root to avoid unintended service disruption.",
+ "AuditProcedure": "Pre-requisite: you must run these CLI commands in the management account for the AWS Organization. 1. Before auditing, document or confirm your organization's baseline guardrail requirements. Common examples include: - Prevent disabling CloudTrail, AWS Config, GuardDuty, or Security Hub - Restrict usage to approved AWS Regions only - Protect central security or logging roles from modification - Deny external principal access to sensitive resources 2. List all SCPs and RCPs in the organization: ``` aws organizations list-policies --filter SERVICE_CONTROL_POLICY aws organizations list-policies --filter RESOURCE_CONTROL_POLICY ``` This returns a list of SCP/RCP policy IDs and names. 3. For each SCP/RCP, retrieve and review the policy document to determine if it implements your baseline guardrail requirements: ``` aws organizations describe-policy --policy-id ``` Review the `Content` field in the output to confirm the policy enforces organizational security requirements. If no SCPs/RCPs exist that implement your documented baseline guardrail requirements, note this as a gap and proceed to remediation. 4. List all accounts in the organization and note the account IDs: ``` aws organizations list-accounts --query 'Accounts[?Status==`ACTIVE`].[Id,Name]' --output table ``` 5. For each baseline guardrail Authorization policy identified in Step 2, list the accounts and OUs to which it is attached: ``` aws organizations list-targets-for-policy --policy-id ``` The output shows `TargetId` values representing accounts, OUs, or the root. 6. Compare the list of attached targets to your full account list. - If the policy is attached to the root, all accounts in the organization inherit it and this policy passes for coverage. - If the policy is attached to specific OUs, verify that all active member accounts belong to those OUs. - If the policy is attached to individual accounts, verify that all active member accounts are included. The environment passes this recommendation if: - All baseline guardrail authorization policies required by organizational security requirements exist. - Each baseline guardrail authorization policy is attached to all active member accounts either directly or via OU/root inheritance.",
+ "AdditionalInformation": "",
+ "References": "",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.1.3",
+ "Description": "Ensure Organizations management account is not used for workloads",
+ "Checks": [],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Manual",
+ "Description": "Ensure that the AWS Organizations management account is used only for organizational governance tasks and does not host production workloads, applications, or business data. The management account is the most privileged account in an AWS Organization and performs sensitive administrative functions such as creating and managing member accounts, applying service control policies (SCPs), and managing consolidated billing. Workloads, applications, and associated data should be deployed in dedicated member accounts, not in the management account.",
+ "RationaleStatement": "The management account has unique privileges that cannot be restricted by SCPs, making it the highest-risk account in an organization. Deploying workloads or storing business data in the management account increases the attack surface and blast radius of a compromise. If a workload vulnerability or misconfiguration occurs in the management account, it could grant attackers access to organization-wide administrative capabilities.",
+ "ImpactStatement": "Restricting the management account to governance-only use may require creating new member accounts, redesigning existing account boundaries, and migrating workloads and data out of the management account. This can introduce short-term complexity and operational overhead. However, it reduces the blast radius of a compromise, simplifies security controls in the most privileged account, and aligns the environment with AWS multi-account and workload-isolation best practices.",
+ "RemediationProcedure": "1. Inventory all workload resources currently in the management account (compute, storage, databases, application services). 2. For each class of workload resource (for example, production, non-production, shared services), create or confirm dedicated member accounts within the organization and place them into the appropriate OUs. 3. For each workload resource, design a migration plan to the appropriate member account. - Execute the migrations in phases, starting with lower-risk environments (for example, development/test) before production. 4. Review and adjust IAM roles and permissions in the management account so that only personnel responsible for organization governance and security have access 5. Update architecture diagrams, runbooks, and onboarding processes to state that new workloads must be deployed only into designated workload accounts, not the management account.",
+ "AuditProcedure": "1. Confirm which AWS account is the management account for the organization (for example, via AWS Organizations \"Overview\" page or organizational documentation). 2. Ensure you have read-only access to review resources in this account. 3. Use your organization's standard discovery methods (for example, AWS Config, CMDB/asset inventory, or CSPM) to obtain a list of services and resources running in the management account. - At a minimum, identify compute, storage, database, and application services (for example, EC2, Lambda, ECS, S3, RDS, DynamoDB, API Gateway, load balancers). 4. For each identified resource, determine whether it is: - Governance/security: resources that support centralized management, logging, audit, or security (for example, org-wide CloudTrail, Config aggregator, Security Hub or GuardDuty delegated admin, billing/cost tooling). - Workload/business: resources that support business applications, production or non-production workloads, or customer-facing systems. 5. If any workload/business resources are present in the management account, record this as a gap and document the affected services and resource types",
+ "AdditionalInformation": "",
+ "References": "",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.1.4",
+ "Description": "Ensure Organizational Units are structured by environment and sensitivity",
+ "Checks": [],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Manual",
+ "Description": "Ensure that AWS Organizations Organizational Units (OUs) are structured primarily by environment (for example, production, non-production, sandbox) and sensitivity (for example, security, logging, shared services, regulated workloads), rather than mirroring the corporate org chart. OUs should group accounts that share similar security requirements and controls so that appropriate authorization policies and other guardrails can be applied consistently at the OU level.",
+ "RationaleStatement": "A clear OU structure based on environment and sensitivity makes it easier to apply consistent guardrails and centralized security controls to accounts that have similar risk profiles and compliance needs. Poorly defined or ad-hoc OU structures complicate policy management, increase the chance of misapplied controls, and can lead to mixing workloads with different data sensitivities under the same set of controls.",
+ "ImpactStatement": "Restructuring OUs by environment and sensitivity can require moving accounts, changing inherited policies, and updating automation that assumes existing OU paths. This may introduce short-term operational overhead, including policy revalidation, testing of workloads under new guardrails, and coordination with application and platform teams to avoid unintended service disruption.",
+ "RemediationProcedure": "1. Work with security, platform, and application teams to agree on a small set of top-level OUs such as: - Security / Management - Shared Services / Infrastructure - Prod - Non-Prod (dev, test, staging) - You may also define dedicated OUs for highly regulated workloads. 2. In the AWS Organizations console (management account), navigate to AWS Accounts. Under the root, create the agreed top-level OUs. If needed, create child OUs under these. 3. Export or list all existing accounts and their current OUs. Create a simple mapping from each account to its target OU based on environment and sensitivity. 4. In the AWS Organizations console (management account), navigate to AWS Accounts. Move accounts into the new environment/sensitivity-based OUs according to your mapping. - Start with low-risk accounts (for example, sandbox and non-production) to validate effects of inherited policies and guardrails before moving production and high-sensitivity accounts. 5. After accounts have been moved, remove old OUs that no longer reflect the target structure. - Ensure no active accounts remain directly under the root unless explicitly justified and documented. 6. Update architecture docs, onboarding runbooks, and account request processes to require new accounts to be created in the correct OU based on environment and sensitivity.",
+ "AuditProcedure": "1. From the management account, use AWS Organizations console to obtain: - The full OU hierarchy (root, top-level and child OUs). - The list of accounts in each OU. 2. Review top-level and key OUs and determine whether they are clearly aligned to: - Environment (for example, production, non-production, sandbox). - Sensitivity/function (for example, security, logging, shared services, regulated). - Note any OUs whose purpose is unclear or that appear to be organized mainly by department or owner rather than environment/sensitivity. 3. For each environment/sensitivity OU, select a sample of accounts and verify that their primary workloads match the OU's stated purpose. - Note any accounts that mix production and non-production workloads in the same OU when separate OUs are defined. - Note any accounts that place highly sensitive or regulated workloads in OUs that are intended for lower-sensitivity use.",
+ "AdditionalInformation": "",
+ "References": "",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.1.5",
+ "Description": "Ensure delegated admin manages AWS Organizations policies",
+ "Checks": [
+ "organizations_delegated_administrators"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Manual",
+ "Description": "Ensure that a dedicated member account is configured as a delegated administrator for AWS Organizations to manage organization policies (SCPs, RCPs, tag policies, backup policies, AI opt-out policies) and other Organizations features, instead of performing these tasks directly from the management account. The delegated administrator for AWS Organizations is configured via a resource-based delegation policy in the management account, which grants specific member accounts limited permissions to perform Organizations policy and account management actions across the organization. This allows policy management, OU operations, and other governance tasks to be handled from purpose-built accounts without requiring broad access to the management account.",
+ "RationaleStatement": "The management account has unique and high privileges to manage AWS Organizations (for example, creating/deleting accounts, managing org structures) and is not subject to guardrails like SCPs. Without a delegated administrator for Organizations, all policy management, OU changes, and account governance must be performed directly from the management account. This results in concentrating operational activity in the most powerful account. Configuring a dedicated member account as a delegated administrator for Organizations policy management distributes these tasks to a purpose-built AWS account that can be protected by SCPs and other controls, reduces the number of users and roles that need management-account access, and supports separation of duties while maintaining centralized control over organization-wide features.",
+ "ImpactStatement": "Configuring a delegated administrator for AWS Organizations requires creating or identifying a dedicated member account for policy management and granting it specific permissions via a resource-based delegation policy. Existing workflows, automation, and user access patterns that currently perform Organizations policy tasks directly from the management account must be updated to use the delegated account instead. This introduces short-term operational overhead and testing to ensure policy creation, attachment, and management continue to function correctly from the new account.",
+ "RemediationProcedure": "1. Identify a dedicated member account for governance/policy management (for example, create a new \"Policy Management\" account or use an existing Security account) 2. You must be in the management account with permissions to manage Organizations resource policies. Navigate to AWS Organizations console, then click on Settings and browse to \"Delegated administrator for AWS Organizations\" section. 3. If no policy exists, click on Delegate. If a policy exists, choose Edit policy. - In the policy editor, paste or construct a delegation policy statement mentioning the Principal as the AWS account Root which is being delegated access to, and the Actions with the list of least-privileged permissions that could be performed by the delegated AWS account. - Save and validate the delegation policy. 4. Sign in to the delegated administrator account and open the AWS Organizations console. - Confirm that policy management (Policies, Attach/Detach, etc.) is accessible and that users/roles in this account can perform Organizations tasks without management-account access. 5. Grant IAM roles/users in the delegated admin account only the permissions needed for Organizations policy management. 6. Update procedures so that routine Organizations policy tasks are performed from the delegated account, reserving the management account for tasks that only it can perform",
+ "AuditProcedure": "1. Sign in to the AWS Organizations console. From the AWS Accounts section, verify that this is the management account for the organization. 2. In the AWS Organizations console, navigate to Settings. Scroll to the Delegated administrator for AWS Organizations section 3. Review the delegation policy status: - If a delegation policy is configured and shows one or more member accounts registered to manage Organizations policies, proceed to step 4. - If no delegation policy is configured or the section shows No delegated administrator (or equivalent), the audit fails because Organizations management is performed directly from the management account. 4. In the Delegated administrator section, note the account IDs registered for Organizations policy management. Confirm that the delegated accounts are purpose-built governance, security, or policy management accounts, not general workload, sandbox, or development accounts. 5. View the delegation policy details to confirm it grants appropriate least-privilege permissions for policy types (for example, SCPs, tag policies, backup policies) and actions (CreatePolicy, AttachPolicy, UpdatePolicy, etc.).",
+ "AdditionalInformation": "",
+ "References": "",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.1.6",
+ "Description": "Ensure delegated admins manage AWS Organizations-integrated services",
+ "Checks": [
+ "organizations_delegated_administrators"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Manual",
+ "Description": "Ensure that AWS services (such as AWS CloudTrail) which integrate with AWS Organizations and support delegated administration are managed through delegated administrator member accounts instead of directly from the Organizations management account. For each such service, the management account should enable trusted access and register a purpose-built member account as the delegated administrator, so that this account can perform service-level administration across all organization accounts.",
+ "RationaleStatement": "The management account has unique and high privileges to manage AWS Organizations (for example, creating/deleting accounts, managing org structures) and is not subject to guardrails like SCPs. Without delegated administrators, organization-wide security, logging, and management services must be operated directly from the management account, concentrating operational activity and credentials in the most privileged account in the organization. Registering member accounts as delegated administrators for AWS services distributes service-specific administration to dedicated security, logging, or operations accounts that can be restricted by SCPs, monitored like other workload accounts, and aligned with team responsibilities, while reducing day-to-day use of the management account.",
+ "ImpactStatement": "Configuring a delegated administrator for AWS Services that integrate with AWS Organizations requires creating or identifying a dedicated member account for policy management and granting it specific permissions. Existing workflows, automation, and user access patterns that currently perform tasks directly from the management account must be updated to use the delegated account instead. This introduces short-term operational overhead and testing to ensure policy creation, attachment, and management continue to function correctly from the new account.",
+ "RemediationProcedure": "Note: This remediation section uses AWS CloudTrail as a concrete example. You must perform similar procedure for all other AWS services that integrate with AWS Organizations and support delegated administration that are in use in your environment. 1. In the management account, verify that trusted access for CloudTrail is enabled in AWS Organizations (AWS Organizations → Services). 2. In the management account CloudTrail console, choose Settings in the left navigation pane. Scroll to Organization delegated administrators. 3. Click on \"Register administrator\" - Enter the account ID of the designated Logging or Security account. - Click on Register administrator. CloudTrail will automatically create the necessary service-linked roles and register the account. 4. In the delegated administrator account, open the CloudTrail console and confirm that the organization trail is visible and administrative actions are accessible. 5. Update operational runbooks so that routine CloudTrail administration is performed from the delegated admin account, not the management account.",
+ "AuditProcedure": "Note: This audit uses AWS CloudTrail as a concrete example. You must perform similar audits for all other AWS services that integrate with AWS Organizations and support delegated administration that are in use in your environment. 1. Sign in to the management account and open the CloudTrail console. 2. In the left navigation pane, choose Trails. - Verify that there is at least one organization trail (trail with Apply trail to all accounts in my organization or equivalent setting enabled) - If CloudTrail is only configured as single-account trails and no organization trail is in use, note that delegated admin for CloudTrail is not in scope and this recommendation is not applicable for CloudTrail in this environment. 3. In the same management account CloudTrail console, choose Settings in the left navigation pane, and scroll to the Organization delegated administrators section. 4. Verify the configuration for Organization delegated administrators: - Verify that at least one member account ID (not the management account) is listed as a delegated administrator for CloudTrail. - Verify that the account(s) are appropriate for security/logging operations (for example, a named Security or Logging account, not a sandbox or general workload account). - If the section shows \"No delegated administrators\" when an organization trail is in use, CloudTrail is effectively administered from the management account and this is a gap.",
+ "AdditionalInformation": "",
+ "References": "",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.2",
+ "Description": "Maintain current AWS account contact details",
+ "Checks": [
+ "account_maintain_current_contact_details"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Manual",
+ "Description": "Ensure contact email and telephone details for AWS accounts are current and map to more than one individual in your organization. An AWS account supports a number of contact details, and AWS will use these to contact the account owner if activity judged to be in breach of the Acceptable Use Policy or indicative of a likely security compromise is observed by the AWS Abuse team. Contact details should not be for a single individual, as circumstances may arise where that individual is unavailable. Email contact details should point to a mail alias which forwards email to multiple individuals within the organization; where feasible, phone contact details should point to a PABX hunt group or other call-forwarding system.",
+ "RationaleStatement": "If an AWS account is observed to be behaving in a prohibited or suspicious manner, AWS will attempt to contact the account owner by email and phone using the contact details listed. If this is unsuccessful and the account behavior needs urgent mitigation, proactive measures may be taken, including throttling of traffic between the account exhibiting suspicious behavior and the AWS API endpoints and the Internet. This will result in impaired service to and from the account in question, so it is in both the customers' and AWS's best interests that prompt contact can be established. This is best achieved by setting AWS account contact details to point to resources which have multiple individuals as recipients, such as email aliases and PABX hunt groups.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "This activity can only be performed via the AWS Console, with a user who has permission to read and write Billing information (aws-portal:\\*Billing). **From Console:** 1. Sign in to the AWS Management Console and open the `Billing and Cost Management` console at https://console.aws.amazon.com/billing/home#/. 2. On the navigation bar, choose your account name, and then choose `Account`. 3. On the `Account Settings` page, next to `Account Settings`, choose `Edit`. 4. Next to the field that you need to update, choose `Edit`. 5. After you have entered your changes, choose `Save changes`. 6. After you have made your changes, choose `Done`. 7. To edit your contact information, under `Contact Information`, choose `Edit`. 8. For the fields that you want to change, type your updated information, and then choose `Update`. **From Command Line:** 1. Run the following command: ``` aws account put-contact-information --contact-information '{\"AddressLine1\": \"\", \"AddressLine2\": \"\", \"City\": \"\", \"CompanyName\": \"\", \"CountryCode\": \"\", \"FullName\": \"\", \"PhoneNumber\": \"\", \"PostalCode\": \"\", \"StateOrRegion\": \"\"}' ```",
+ "AuditProcedure": "This activity can only be performed via the AWS Console, with a user who has permission to read and write Billing information (aws-portal:\\*Billing). 1. Sign in to the AWS Management Console and open the `Billing and Cost Management` console at https://console.aws.amazon.com/billing/home#/. 2. On the navigation bar, choose your account name, and then choose `Account`. 3. On the `Account Settings` page, review and verify the current details. 4. Under `Contact Information`, review and verify the current details.",
+ "AdditionalInformation": "",
+ "References": "https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/manage-account-payment.html#contact-info",
+ "DefaultValue": "By default, AWS account contact information (email and telephone) is set to the values provided at account creation. These usually reference a single individual rather than a shared alias or group contact."
+ }
+ ]
+ },
+ {
+ "Id": "2.3",
+ "Description": "Ensure security contact information is registered",
+ "Checks": [
+ "account_security_contact_information_is_registered"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Manual",
+ "Description": "AWS provides customers with the option of specifying the contact information for account's security team. It is recommended that this information be provided.",
+ "RationaleStatement": "Specifying security-specific contact information will help ensure that security advisories sent by AWS reach the team in your organization that is best equipped to respond to them.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "Perform the following to establish security contact information: **From Console:** 1. Click on your account name at the top right corner of the console. 2. From the drop-down menu Click `My Account` 3. Scroll down to the `Alternate Contacts` section 4. Enter contact information in the `Security` section **From Command Line:** Run the following command with the following input parameters: --email-address, --name, and --phone-number. ``` aws account put-alternate-contact --alternate-contact-type SECURITY ``` **Note:** Consider specifying an internal email distribution list to ensure emails are regularly monitored by more than one individual.",
+ "AuditProcedure": "Perform the following to determine if security contact information is present: **From Console:** 1. Click on your account name at the top right corner of the console 2. From the drop-down menu Click `My Account` 3. Scroll down to the `Alternate Contacts` section 4. Ensure contact information is specified in the `Security` section **From Command Line:** 1. Run the following command: ``` aws account get-alternate-contact --alternate-contact-type SECURITY ``` 2. Ensure proper contact information is specified for the `Security` contact.",
+ "AdditionalInformation": "",
+ "References": "",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.4",
+ "Description": "Ensure no 'root' user account access key exists",
+ "Checks": [
+ "iam_no_root_access_key"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "The 'root' user account is the most privileged user in an AWS account. AWS Access Keys provide programmatic access to a given AWS account. It is recommended that all access keys associated with the 'root' user account be deleted.",
+ "RationaleStatement": "Deleting access keys associated with the 'root' user account limits vectors by which the account can be compromised. Additionally, deleting the 'root' access keys encourages the creation and use of role based accounts that are least privileged.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "Perform the following to delete active 'root' user access keys. **From Console:** 1. Sign in to the AWS Management Console as 'root' and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/). 2. Click on `` at the top right and select `My Security Credentials` from the drop down list. 3. On the pop out screen Click on `Continue to Security Credentials`. 4. Click on `Access Keys` (Access Key ID and Secret Access Key). 5. If there are active keys, under `Status`, click `Delete` (Note: Deleted keys cannot be recovered). Note: While a key can be made inactive, this inactive key will still show up in the CLI command from the audit procedure, and may lead to the root user being falsely flagged as being non-compliant.",
+ "AuditProcedure": "Perform the following to determine if the 'root' user account has access keys: **From Console:** 1. Login to the AWS Management Console. 2. Click `Services`. 3. Click `IAM`. 4. Click on `Credential Report`. 5. This will download a `.csv` file which contains credential usage for all IAM users within an AWS Account - open this file. 6. For the `` user, ensure the `access_key_1_active` and `access_key_2_active` fields are set to `FALSE`. **From Command Line:** Run the following command: ``` aws iam get-account-summary | grep AccountAccessKeysPresent ``` If no 'root' access keys exist the output will show `AccountAccessKeysPresent: 0,`. If the output shows a 1, then 'root' keys exist and should be deleted.",
+ "AdditionalInformation": "- IAM User account root for us-gov cloud regions is not enabled by default. However, on request to AWS support enables 'root' access only through access-keys (CLI, API methods) for us-gov cloud region. - Implement regular checks and alerts for any creation of new root access keys to promptly address any unauthorized or accidental creation.",
+ "References": "http://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html:http://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html:http://docs.aws.amazon.com/IAM/latest/APIReference/API_GetAccountSummary.html:https://aws.amazon.com/blogs/security/an-easier-way-to-determine-the-presence-of-aws-account-access-keys/",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.5",
+ "Description": "Ensure MFA is enabled for the 'root' user account",
+ "Checks": [
+ "iam_root_mfa_enabled"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "The 'root' user account is the most privileged user in an AWS account. Multi-factor Authentication (MFA) adds an extra layer of protection on top of a username and password. With MFA enabled, when a user signs in to an AWS website, they will be prompted for their username and password as well as for an authentication code from their AWS MFA device. **Note:** When virtual MFA is used for 'root' accounts, it is recommended that the device used is NOT a personal device, but rather a dedicated mobile device (tablet or phone) that is kept charged and secured, independent of any individual personal devices (non-personal virtual MFA). This lessens the risks of losing access to the MFA due to device loss, device trade-in, or if the individual owning the device is no longer employed at the company. Where an AWS Organization is using centralized root access, root credentials can be removed from member accounts. In that case it is neither possible nor necessary to configure root MFA in the member account.",
+ "RationaleStatement": "Enabling MFA provides increased security for console access as it requires the authenticating principal to possess a device that emits a time-sensitive key and have knowledge of a credential.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "**Note:** To manage MFA devices for the 'root' AWS account, you must use your 'root' account credentials to sign in to AWS. You cannot manage MFA devices for the 'root' account using other credentials. Perform the following to establish MFA for the 'root' user account: 1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/). 2. Choose `Dashboard` , and under `Security Status` , expand `Activate MFA` on your root account. 3. Choose `Activate MFA` 4. In the wizard, choose `A virtual MFA` device and then choose `Next Step` . 5. IAM generates and displays configuration information for the virtual MFA device, including a QR code graphic. The graphic is a representation of the 'secret configuration key' that is available for manual entry on devices that do not support QR codes. 6. Open your virtual MFA application. (For a list of apps that you can use for hosting virtual MFA devices, see [Virtual MFA Applications](http://aws.amazon.com/iam/details/mfa/#Virtual_MFA_Applications).) If the virtual MFA application supports multiple accounts (multiple virtual MFA devices), choose the option to create a new account (a new virtual MFA device). 7. Determine whether the MFA app supports QR codes, and then do one of the following: - Use the app to scan the QR code. For example, you might choose the camera icon or choose an option similar to Scan code, and then use the device's camera to scan the code. - In the Manage MFA Device wizard, choose Show secret key for manual configuration, and then type the secret configuration key into your MFA application. When you are finished, the virtual MFA device starts generating one-time passwords. In the Manage MFA Device wizard, in the Authentication Code 1 box, type the one-time password that currently appears in the virtual MFA device. Wait up to 30 seconds for the device to generate a new one-time password. Then type the second one-time password into the Authentication Code 2 box. Choose Assign Virtual MFA.",
+ "AuditProcedure": "Perform the following to determine if the 'root' user account is enabled and has MFA setup: **From Console:** 1. Login to the AWS Management Console 2. Click `Services` 3. Click `IAM` 4. Click on `Credential Report` 5. This will download a `.csv` file which contains credential usage for all IAM users within an AWS Account - open this file 6. For the `` user, ensure the `mfa_active` field is set to `TRUE` or the `password_enabled` field is set to `FALSE` **From Command Line:** 1. Run the following command: ``` aws iam get-account-summary | grep AccountMFAEnabled aws iam get-account-summary | grep AccountPasswordPresent ``` 2. Ensure the AccountMFAEnabled property is set to 1 or the AccountPasswordPresent property is set to 0",
+ "AdditionalInformation": "IAM User account root for us-gov cloud regions does not have console access. This recommendation is not applicable for us-gov cloud regions.",
+ "References": "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#id_root-user_manage_mfa:https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_enable_virtual.html#enable-virt-mfa-for-root:https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-enable-root-access.html",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.6",
+ "Description": "Ensure hardware MFA is enabled for the 'root' user account",
+ "Checks": [
+ "iam_root_hardware_mfa_enabled"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Manual",
+ "Description": "The 'root' user account is the most privileged user in an AWS account. MFA adds an extra layer of protection on top of a user name and password. With MFA enabled, when a user signs in to an AWS website, they will be prompted for their user name and password as well as for an authentication code from their AWS MFA device. For Level 2, it is recommended that the 'root' user account be protected with a hardware MFA. Where an AWS Organization is using centralized root access, root credentials can be removed from member accounts. In that case it is neither possible nor necessary to configure root MFA in the member account.",
+ "RationaleStatement": "A hardware MFA has a smaller attack surface than a virtual MFA. For example, a hardware MFA does not suffer the attack surface introduced by the mobile smartphone on which a virtual MFA resides. **Note**: Using hardware MFA for numerous AWS accounts may create a logistical device management issue. If this is the case, consider implementing this Level 2 recommendation selectively for the highest security AWS accounts, while applying the Level 1 recommendation to the remaining accounts.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "**Note:** To manage MFA devices for the AWS 'root' user account, you must use your 'root' account credentials to sign in to AWS. You cannot manage MFA devices for the 'root' account using other credentials. Perform the following to establish a hardware MFA for the 'root' user account: 1. Open the AWS Management Console and sign in using your root user credentials. 2. On the right side of the navigation bar, choose your account name, and choose Security credentials. 3. In the Multi-Factor Authentication (MFA) section, choose Assign MFA device. 4. In the wizard, type a Device name, choose Authenticator app, and then choose Next. IAM generates and displays configuration information for the virtual MFA device, including a QR code graphic. The graphic is a representation of the secret configuration key that is available for manual entry on devices that do not support QR codes. 5. Open the virtual MFA app on the device. If the virtual MFA app supports multiple virtual MFA devices or accounts, choose the option to create a new virtual MFA device or account. 6. The easiest way to configure the app is to use the app to scan the QR code. If you cannot scan the code, you can type the configuration information manually. The QR code and secret configuration key generated by IAM are tied to your AWS account. To use the QR code to configure the virtual MFA device, from the wizard, choose Show QR code. Then follow the app instructions for scanning the code. For example, you might need to choose the camera icon or choose a command like Scan account barcode, and then use the device's camera to scan the QR code. To manual entry secret key on devices, in the Set up device wizard, choose Show secret key, and then type the secret key into your MFA app. 7. In the wizard, in the MFA code 1 box, type the one-time password that currently appears in the virtual MFA device. Wait up to 30 seconds for the device to generate a new one-time password. Then type the second one-time password into the MFA code 2 box. Choose Add MFA. Remediation for this recommendation is not available through AWS CLI.",
+ "AuditProcedure": "Perform the following to determine if the 'root' user account has a hardware MFA setup: 1. Run the following command to determine if the 'root' account has MFA setup: ``` aws iam get-account-summary | grep \"AccountMFAEnabled\" aws iam get-account-summary | grep \"AccountPasswordPresent\" ``` The `AccountMFAEnabled` property is set to `1` will ensure that the 'root' user account has MFA (Virtual or Hardware) Enabled. `AccountPasswordPresent` set to `0` indicates that the `root` console credential has been removed. If `AccountMFAEnabled` property is set to `0` and `AccountPasswordPresent` is set to `1` the account is not compliant with this recommendation. 2. If `AccountMFAEnabled` property is set to `1`, determine 'root' account has Hardware MFA enabled. Run the following command to list all virtual MFA devices: ``` aws iam list-virtual-mfa-devices ``` If the output contains one MFA with the following Serial Number, it means the MFA is virtual, not hardware and the account is not compliant with this recommendation: `SerialNumber: arn:aws:iam::__:mfa/root-account-mfa-device`",
+ "AdditionalInformation": "IAM User account 'root' for us-gov cloud regions does not have console access. This control is not applicable for us-gov cloud regions.",
+ "References": "CCE-78911-5:https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_enable_virtual.html:https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_enable_physical.html#enable-hw-mfa-for-root:https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-enable-root-access.html:https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html",
+ "DefaultValue": "By default, the AWS root user does not have a hardware MFA device assigned. MFA must be explicitly configured, and if enabled by default it will be virtual (software-based), not hardware."
+ }
+ ]
+ },
+ {
+ "Id": "2.7",
+ "Description": "Eliminate use of the 'root' user for administrative and daily tasks",
+ "Checks": [
+ "iam_avoid_root_usage"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Manual",
+ "Description": "With the creation of an AWS account, a 'root user' is created that cannot be disabled or deleted. That user has unrestricted access to and control over all resources in the AWS account. It is highly recommended that the use of this account be avoided for everyday tasks.",
+ "RationaleStatement": "The 'root user' has unrestricted access to and control over all account resources. Use of it is inconsistent with the principles of least privilege and separation of duties, and can lead to unnecessary harm due to error or account compromise.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "If you find that the 'root' user account is being used for daily activities, including administrative tasks that do not require the 'root' user: 1. Change the 'root' user password. 2. Deactivate or delete any access keys associated with the 'root' user. Remember, anyone who has 'root' user credentials for your AWS account has unrestricted access to and control of all the resources in your account, including billing information.",
+ "AuditProcedure": "**From Console:** 1. Login to the AWS Management Console at `https://console.aws.amazon.com/iam/`. 2. In the left pane, click `Credential Report`. 3. Click on `Download Report`. 4. Open or Save the file locally. 5. Locate the `` under the user column. 6. Review `password_last_used, access_key_1_last_used_date, access_key_2_last_used_date` to determine when the 'root user' was last used. **From Command Line:** Run the following CLI commands to provide a credential report for determining the last time the 'root user' was used: ``` aws iam generate-credential-report ``` ``` aws iam get-credential-report --query 'Content' --output text | base64 -d | cut -d, -f1,5,11,16 | grep -B1 '' ``` Review `password_last_used`, `access_key_1_last_used_date`, `access_key_2_last_used_date` to determine when the _root user_ was last used. **Note:** There are a few conditions under which the use of the 'root' user account is required. Please see the reference links for all of the tasks that require use of the 'root' user.",
+ "AdditionalInformation": "The 'root' user for us-gov cloud regions is not enabled by default. However, on request to AWS support, they can enable the 'root' user and grant access only through access-keys (CLI, API methods) for us-gov cloud region. If the 'root' user for us-gov cloud regions is enabled, this recommendation is applicable. Monitoring usage of the 'root' user can be accomplished by implementing recommendation 3.3 Ensure a log metric filter and alarm exist for usage of the 'root' user.",
+ "References": "https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html:https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html:https://docs.aws.amazon.com/general/latest/gr/aws_tasks-that-require-root.html",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.8",
+ "Description": "Ensure IAM password policy requires minimum length of 14 or greater",
+ "Checks": [
+ "iam_password_policy_minimum_length_14"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "Password policies are, in part, used to enforce password complexity requirements. IAM password policies can be used to ensure passwords are at least a given length. It is recommended that the password policy require a minimum password length 14.",
+ "RationaleStatement": "Setting a password complexity policy increases account resiliency against brute force login attempts.",
+ "ImpactStatement": "Enforcing a minimum password length of 14 characters enhances security by making passwords more resistant to brute force attacks. However, it may require users to create longer and potentially more complex passwords, which could impact user convenience.",
+ "RemediationProcedure": "Perform the following to set the password policy as prescribed: **From Console:** 1. Login to AWS Console (with appropriate permissions to View Identity Access Management Account Settings) 2. Go to IAM Service on the AWS Console 3. Click on Account Settings on the Left Pane 4. Set Minimum password length to `14` or greater. 5. Click Apply password policy **From Command Line:** ``` aws iam update-account-password-policy --minimum-password-length 14 ``` Note: All commands starting with aws iam update-account-password-policy can be combined into a single command.",
+ "AuditProcedure": "Perform the following to ensure the password policy is configured as prescribed: **From Console:** 1. Login to AWS Console (with appropriate permissions to View Identity Access Management Account Settings) 2. Go to IAM Service on the AWS Console 3. Click on Account Settings on the Left Pane 4. Ensure Minimum password length is set to 14 or greater. **From Command Line:** ``` aws iam get-account-password-policy ``` Ensure the output of the above command includes MinimumPasswordLength: 14 (or higher)",
+ "AdditionalInformation": "Ensure the password policy also includes requirements for password complexity, such as the inclusion of uppercase letters, lowercase letters, numbers, and special characters: ``` aws iam update-account-password-policy --require-uppercase-characters --require-lowercase-characters --require-numbers --require-symbols ```",
+ "References": "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_account-policy.html:https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#configure-strong-password-policy",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.9",
+ "Description": "Ensure IAM password policy prevents password reuse",
+ "Checks": [
+ "iam_password_policy_reuse_24"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "IAM password policies can prevent the reuse of a given password by the same user. It is recommended that the password policy prevent the reuse of passwords.",
+ "RationaleStatement": "Preventing password reuse increases account resiliency against brute force login attempts.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "Perform the following to set the password policy as prescribed: **From Console:** 1. Login to AWS Console (with appropriate permissions to View Identity Access Management Account Settings) 2. Go to IAM Service on the AWS Console 3. Click on Account Settings on the Left Pane 4. Check Prevent password reuse 5. Set Number of passwords to remember is set to `24` **From Command Line:** ``` aws iam update-account-password-policy --password-reuse-prevention 24 ``` Note: All commands starting with aws iam update-account-password-policy can be combined into a single command.",
+ "AuditProcedure": "Perform the following to ensure the password policy is configured as prescribed: **From Console:** 1. Login to AWS Console (with appropriate permissions to View Identity Access Management Account Settings) 2. Go to IAM Service on the AWS Console 3. Click on Account Settings on the Left Pane 4. Ensure Prevent password reuse is checked 5. Ensure Number of passwords to remember is set to 24 **From Command Line:** ``` aws iam get-account-password-policy ``` Ensure the output of the above command includes PasswordReusePrevention: 24",
+ "AdditionalInformation": "",
+ "References": "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_account-policy.html:https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#configure-strong-password-policy",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.10",
+ "Description": "Ensure multi-factor authentication (MFA) is enabled for all IAM users that have a console password",
+ "Checks": [
+ "iam_user_mfa_enabled_console_access"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "Multi-Factor Authentication (MFA) adds an extra layer of authentication assurance beyond traditional credentials. With MFA enabled, when a user signs in to the AWS Console, they will be prompted for their user name and password as well as for an authentication code from their physical or virtual MFA token. It is recommended that MFA be enabled for all accounts that have a console password.",
+ "RationaleStatement": "Enabling MFA provides increased security for console access as it requires the authenticating principal to possess a device that displays a time-sensitive key and have knowledge of a credential.",
+ "ImpactStatement": "AWS will soon end support for SMS multi-factor authentication (MFA). New customers are not allowed to use this feature. We recommend that existing customers switch to an alternative method of MFA.",
+ "RemediationProcedure": "Perform the following to enable MFA: **From Console:** 1. Sign in to the AWS Management Console and open the IAM console at 'https://console.aws.amazon.com/iam/' 2. In the left pane, select `Users`. 3. In the `User Name` list, choose the name of the intended MFA user. 4. Choose the `Security Credentials` tab, and then choose `Manage MFA Device`. 5. In the `Manage MFA Device wizard`, choose `Virtual MFA` device, and then choose `Continue`. IAM generates and displays configuration information for the virtual MFA device, including a QR code graphic. The graphic is a representation of the 'secret configuration key' that is available for manual entry on devices that do not support QR codes. 6. Open your virtual MFA application. (For a list of apps that you can use for hosting virtual MFA devices, see Virtual MFA Applications at https://aws.amazon.com/iam/details/mfa/#Virtual_MFA_Applications). If the virtual MFA application supports multiple accounts (multiple virtual MFA devices), choose the option to create a new account (a new virtual MFA device). 7. Determine whether the MFA app supports QR codes, and then do one of the following: - Use the app to scan the QR code. For example, you might choose the camera icon or choose an option similar to Scan code, and then use the device's camera to scan the code. - In the Manage MFA Device wizard, choose Show secret key for manual configuration, and then type the secret configuration key into your MFA application. When you are finished, the virtual MFA device starts generating one-time passwords. 8. In the `Manage MFA Device wizard`, in the `MFA Code 1 box`, type the `one-time password` that currently appears in the virtual MFA device. Wait up to 30 seconds for the device to generate a new one-time password. Then type the second `one-time password` into the `MFA Code 2 box`. 9. Click `Assign MFA`.",
+ "AuditProcedure": "Perform the following to determine if a MFA device is enabled for all IAM users having a console password: **From Console:** 1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/). 2. In the left pane, select `Users` 3. If the `MFA` or `Password age` columns are not visible in the table, click the gear icon at the upper right corner of the table and ensure a checkmark is next to both, then click `Close`. 4. Ensure that for each user where the `Password age` column shows a password age, the `MFA` column shows `Virtual`, `U2F Security Key`, or `Hardware`. **From Command Line:** 1. Run the following command (OSX/Linux/UNIX) to generate a list of all IAM users along with their password and MFA status: ``` aws iam generate-credential-report ``` ``` aws iam get-credential-report --query 'Content' --output text | base64 -d | cut -d, -f1,4,8 ``` 2. The output of this command will produce a table similar to the following: ``` user,password_enabled,mfa_active elise,false,false brandon,true,true rakesh,false,false helene,false,false paras,true,true anitha,false,false ``` 3. For any column having `password_enabled` set to `true` , ensure `mfa_active` is also set to `true.`",
+ "AdditionalInformation": "**Forced IAM User Self-Service Remediation** Amazon has published a pattern that requires users to set up MFA through self-service before they gain access to their complete set of permissions. Until they complete this step, they cannot access their full permissions. This pattern can be used for new AWS accounts. It can also be applied to existing accounts; it is recommended that users receive instructions and a grace period to complete MFA enrollment before active enforcement on existing AWS accounts.",
+ "References": "https://tools.ietf.org/html/rfc6238:https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html:https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#enable-mfa-for-privileged-users:https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_enable_virtual.html:https://blogs.aws.amazon.com/security/post/Tx2SJJYE082KBUK/How-to-Delegate-Management-of-Multi-Factor-Authentication-to-AWS-IAM-Users",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.11",
+ "Description": "Ensure credentials unused for 45 days or more are disabled",
+ "Checks": [
+ "iam_user_accesskey_unused",
+ "iam_user_console_access_unused"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "iam_user_accesskey_unused",
+ "ConfigKey": "max_unused_access_keys_days",
+ "Operator": "lte",
+ "Value": 45
+ },
+ {
+ "Check": "iam_user_console_access_unused",
+ "ConfigKey": "max_console_access_days",
+ "Operator": "lte",
+ "Value": 45
+ }
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "AWS IAM users can access AWS resources using different types of credentials, such as passwords or access keys. It is recommended that all credentials that have been unused for 45 days or more be deactivated or removed.",
+ "RationaleStatement": "Disabling or removing unnecessary credentials will reduce the window of opportunity for credentials associated with a compromised or abandoned account to be used.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "**From Console:** Perform the following to manage Unused Password (IAM user console access) 1. Login to the AWS Management Console: 2. Click `Services` 3. Click `IAM` 4. Click on `Users` 5. Click on `Security Credentials` 6. Select user whose `Console last sign-in` is greater than 45 days 7. Click `Security credentials` 8. In section `Sign-in credentials`, `Console password` click `Manage` 9. Under Console Access select `Disable` 10. Click `Apply` Perform the following to deactivate Access Keys: 1. Login to the AWS Management Console: 2. Click `Services` 3. Click `IAM` 4. Click on `Users` 5. Click on `Security Credentials` 6. Select any access keys that are over 45 days old and that have been used and - Click on `Make Inactive` 7. Select any access keys that are over 45 days old and that have not been used and - Click the X to `Delete`",
+ "AuditProcedure": "Perform the following to determine if unused credentials exist: **From Console:** 1. Login to the AWS Management Console 2. Click `Services` 3. Click `IAM` 4. Click on `Users` 5. Click the `Settings` (gear) icon. 6. Select `Console last sign-in`, `Access key last used`, and `Access Key Id` 7. Click on `Close` 8. Check and ensure that `Console last sign-in` is less than 45 days ago. **Note** - `Never` means the user has never logged in. 9. Check and ensure that `Access key age` is less than 45 days and that `Access key last used` does not say `None` If the user hasn't signed into the Console in the last 45 days or Access keys are over 45 days old refer to the remediation. **From Command Line:** **Download Credential Report:** 1. Run the following commands: ``` aws iam generate-credential-report aws iam get-credential-report --query 'Content' --output text | base64 -d | cut -d, -f1,4,5,6,9,10,11,14,15,16 | grep -v '^' ``` **Ensure unused credentials do not exist:** 2. For each user having `password_enabled` set to `TRUE` , ensure `password_last_used_date` is less than `45` days ago. - When `password_enabled` is set to `TRUE` and `password_last_used` is set to `No_Information` , ensure `password_last_changed` is less than 45 days ago. 3. For each user having an `access_key_1_active` or `access_key_2_active` to `TRUE` , ensure the corresponding `access_key_n_last_used_date` is less than `45` days ago. - When a user having an `access_key_x_active` (where x is 1 or 2) to `TRUE` and corresponding access_key_x_last_used_date is set to `N/A`, ensure `access_key_x_last_rotated` is less than 45 days ago.",
+ "AdditionalInformation": " is excluded in the audit since the root account should not be used for day-to-day business and would likely be unused for more than 45 days.",
+ "References": "https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#remove-credentials:https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_finding-unused.html:https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_admin-change-user.html:https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.12",
+ "Description": "Ensure access keys are rotated every 90 days or less",
+ "Checks": [
+ "iam_rotate_access_key_90_days"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "Access keys consist of an access key ID and secret access key, which are used to sign programmatic requests that you make to AWS. AWS users need their own access keys to make programmatic calls to AWS from the AWS Command Line Interface (AWS CLI), Tools for Windows PowerShell, the AWS SDKs, or direct HTTP calls using the APIs for individual AWS services. It is recommended that all access keys be rotated regularly.",
+ "RationaleStatement": "Rotating access keys will reduce the window of opportunity for an access key that is associated with a compromised or terminated account to be used. Access keys should be rotated to ensure that data cannot be accessed with an old key which might have been lost, cracked, or stolen.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "Perform the following to rotate access keys: **From Console:** 1. Go to the Management Console (https://console.aws.amazon.com/iam) 2. Click on `Users` 3. Click on `Security Credentials` 4. As an Administrator - Click on `Make Inactive` for keys that have not been rotated in `90` Days 5. As an IAM User - Click on `Make Inactive` or `Delete` for keys which have not been rotated or used in `90` Days 6. Click on `Create Access Key` 7. Update programmatic calls with new Access Key credentials **From Command Line:** 1. While the first access key is still active, create a second access key, which is active by default. Run the following command: ``` aws iam create-access-key --user-name ``` At this point, the user has two active access keys. 2. Update all applications and tools to use the new access key. 3. Determine whether the first access key is still in use by using this command: ``` aws iam get-access-key-last-used --access-key-id ``` 4. One approach is to wait several days and then check the old access key for any use before proceeding. Even if step 3 indicates no use of the old key, it is recommended that you do not immediately delete the first access key. Instead, change the state of the first access key to Inactive using this command: ``` aws iam update-access-key --user-name --access-key-id --status Inactive ``` 5. Use only the new access key to confirm that your applications are working. Any applications and tools that still use the original access key will stop working at this point because they no longer have access to AWS resources. If you find such an application or tool, you can switch its state back to Active to reenable the first access key. Then return to step 2 and update this application to use the new key. 6. After you wait some period of time to ensure that all applications and tools have been updated, you can delete the first access key with this command: ``` aws iam delete-access-key --user-name --access-key-id ```",
+ "AuditProcedure": "Perform the following to determine if access keys are rotated as prescribed: **From Console:** 1. Go to the Management Console (https://console.aws.amazon.com/iam) 2. Click on `Users` 3. For each user, go to `Security Credentials` 4. Review each key under `Access Keys` 5. For each key that shows `Active` for status, ensure that `Created` is less than or equal to `90 days ago`. **From Command Line:** ``` aws iam generate-credential-report aws iam get-credential-report --query 'Content' --output text | base64 -d ``` The `access_key_1_last_rotated` and the `access_key_2_last_rotated` fields in this file notes the date and time, in ISO 8601 date-time format, when the user's access key was created or last changed. If the user does not have an active access key, the value in this field is N/A (not applicable).",
+ "AdditionalInformation": "",
+ "References": "CCE-78902-4:https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#rotate-credentials:https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_finding-unused.html:https://docs.aws.amazon.com/general/latest/gr/managing-aws-access-keys.html:https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html",
+ "DefaultValue": "By default, AWS does not enforce access key rotation. Access keys remain valid until they are manually deactivated or deleted."
+ }
+ ]
+ },
+ {
+ "Id": "2.13",
+ "Description": "Ensure IAM users receive permissions only through groups",
+ "Checks": [
+ "iam_policy_attached_only_to_group_or_roles"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "IAM users are granted access to services, functions, and data through IAM policies. There are four ways to define policies for a user: 1) Edit the user policy directly, also known as an inline or user policy; 2) attach a policy directly to a user; 3) add the user to an IAM group that has an attached policy; 4) add the user to an IAM group that has an inline policy. Only the third implementation is recommended.",
+ "RationaleStatement": "Assigning IAM policies solely through groups unifies permissions management into a single, flexible layer that is consistent with organizational functional roles. By unifying permissions management, the likelihood of excessive permissions is reduced.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "**From Console:** Perform the following to create an IAM group and assign a policy to it: 1. Sign in to the AWS Management Console and open the IAM console at https://console.aws.amazon.com/iam/. 2. In the navigation pane, click `Groups` and then click `Create New Group`. 3. In the `Group Name` box, type the name of the group and then click `Next Step`. 4. In the list of policies, select the check box for each policy that you want to apply to all members of the group. Then click `Next Step`. 5. Click `Create Group`. Perform the following to add a user to a given group: 1. Sign in to the AWS Management Console and open the IAM console at https://console.aws.amazon.com/iam/. 2. In the navigation pane, click `Groups`. 3. Select the group to add a user to. 4. Click `Add Users To Group`. 5. Select the users to be added to the group. 6. Click `Add Users`. Perform the following to remove a direct association between a user and policy: 1. Sign in to the AWS Management Console and open the IAM console at https://console.aws.amazon.com/iam/. 2. In the left navigation pane, click on Users. 3. For each user: - Select the user - Click on the `Permissions` tab - Expand `Permissions policies` - Click `X` for each policy; then click Detach or Remove (depending on policy type) **From Command Line:** 1. Create the IAM user group: ``` aws iam create-group --group-name ``` 2. Attach the policy to the IAM user group: ``` aws iam attach-group-policy --group-name --policy-arn ``` 3. Perform the following to add a user to a given group: ``` aws iam add-user-to-group --user-name --group-name ``` 4. Perform the following to remove a direct association between a user and policy: ``` aws iam detach-user-policy --user-name --policy-arn ``` 5. Delete an inline policy from an IAM user: ``` aws iam delete-user-policy --user-name --policy-name ```",
+ "AuditProcedure": "Perform the following to determine if an inline policy is set or a policy is directly attached to users: 1. Run the following to get a list of IAM users: ``` aws iam list-users --query 'Users[*].UserName' --output text ``` 2. For each user returned, run the following command to determine if any policies are attached to them: ``` aws iam list-attached-user-policies --user-name aws iam list-user-policies --user-name ``` 3. If any policies are returned, the user has an inline policy or direct policy attachment.",
+ "AdditionalInformation": "",
+ "References": "http://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html:http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html:CCE-78912-3",
+ "DefaultValue": "By default, AWS allows IAM policies to be attached directly to users, groups, or roles. There is no restriction preventing direct user policies unless explicitly enforced by organizational standards."
+ }
+ ]
+ },
+ {
+ "Id": "2.14",
+ "Description": "Ensure IAM policies that allow full \"*:*\" administrative privileges are not attached",
+ "Checks": [
+ "iam_aws_attached_policy_no_administrative_privileges",
+ "iam_customer_attached_policy_no_administrative_privileges"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "IAM policies are the means by which privileges are granted to users, groups, or roles. It is recommended and considered standard security advice to grant least privilege—that is, granting only the permissions required to perform a task. Determine what users need to do, and then craft policies for them that allow the users to perform only those tasks, instead of granting full administrative privileges.",
+ "RationaleStatement": "It's more secure to start with a minimum set of permissions and grant additional permissions as necessary, rather than starting with permissions that are too lenient and then attempting to tighten them later. Providing full administrative privileges instead of restricting access to the minimum set of permissions required for the user exposes resources to potentially unwanted actions. IAM policies that contain a statement with `Effect: Allow` and `Action: *` over `Resource: *` should be removed.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "**From Console:** Perform the following to detach the policy that has full administrative privileges: 1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/). 2. In the navigation pane, click Policies and then search for the policy name found in the audit step. 3. Select the policy that needs to be deleted. 4. In the policy action menu, select `Detach`. 5. Select all Users, Groups, Roles that have this policy attached. 6. Click `Detach Policy`. 7. Select the newly detached policy and select `Delete`. **From Command Line:** Perform the following to detach the policy that has full administrative privileges as found in the audit step: 1. Lists all IAM users, groups, and roles that the specified managed policy is attached to. ``` aws iam list-entities-for-policy --policy-arn ``` 2. Detach the policy from all IAM Users: ``` aws iam detach-user-policy --user-name --policy-arn ``` 3. Detach the policy from all IAM Groups: ``` aws iam detach-group-policy --group-name --policy-arn ``` 4. Detach the policy from all IAM Roles: ``` aws iam detach-role-policy --role-name --policy-arn ```",
+ "AuditProcedure": "Perform the following to determine existing policies: **From Command Line:** 1. Run the following to get a list of IAM policies: ``` aws iam list-policies --only-attached --output text ``` 2. For each policy returned, run the following command to determine if any policy is allowing full administrative privileges on the account: ``` aws iam get-policy-version --policy-arn --version-id ``` 3. In the output, the policy should not contain any Statement block with `Effect: Allow` and `Action` set to `*` and `Resource` set to `*`.",
+ "AdditionalInformation": "",
+ "References": "https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html:https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html:https://docs.aws.amazon.com/cli/latest/reference/iam/index.html#cli-aws-iam",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.15",
+ "Description": "Ensure a support role has been created to manage incidents with AWS Support",
+ "Checks": [
+ "iam_support_role_created"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "AWS provides a support center that can be used for incident notification and response, as well as technical support and customer services. Create an IAM Role, with the appropriate policy assigned, to allow authorized users to manage incidents with AWS Support.",
+ "RationaleStatement": "By implementing least privilege for access control, an IAM Role will require an appropriate IAM Policy to allow Support Center Access in order to manage Incidents with AWS Support.",
+ "ImpactStatement": "All AWS Support plans include an unlimited number of account and billing support cases, with no long-term contracts. Support billing calculations are performed on a per-account basis for all plans. Enterprise Support plan customers have the option to include multiple enabled accounts in an aggregated monthly billing calculation. Monthly charges for the Business and Enterprise support plans are based on each month's AWS usage charges, subject to a monthly minimum, billed in advance. When assigning rights, keep in mind that other policies may grant access to Support as well. This may include AdministratorAccess and other policies including customer managed policies. Utilizing the AWS managed 'AWSSupportAccess' role is one simple way of ensuring that this permission is properly granted. To better support the principle of separation of duties, it would be best to only attach this role where necessary.",
+ "RemediationProcedure": "**From Command Line:** 1. Create an IAM role for managing incidents with AWS: - Create a trust relationship policy document that allows to manage AWS incidents, and save it locally as /tmp/TrustPolicy.json: ``` { Version: 2012-10-17, Statement: [ { Effect: Allow, Principal: { AWS: }, Action: sts:AssumeRole } ] } ``` 2. Create the IAM role using the above trust policy: ``` aws iam create-role --role-name --assume-role-policy-document file:///tmp/TrustPolicy.json ``` 3. Attach 'AWSSupportAccess' managed policy to the created IAM role: ``` aws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/AWSSupportAccess --role-name ```",
+ "AuditProcedure": "**From Command Line:** 1. List IAM policies, filter for the 'AWSSupportAccess' managed policy, and note the Arn element value: ``` aws iam list-policies --query Policies[?PolicyName == 'AWSSupportAccess'] ``` 2. Check if the 'AWSSupportAccess' policy is attached to any role: ``` aws iam list-entities-for-policy --policy-arn arn:aws:iam::aws:policy/AWSSupportAccess ``` 3. In the output, ensure `PolicyRoles` does not return empty. 'Example: Example: PolicyRoles: [ ]' If it returns empty refer to the remediation below.",
+ "AdditionalInformation": "AWSSupportAccess policy is a global AWS resource. It has same ARN as `arn:aws:iam::aws:policy/AWSSupportAccess` for every account.",
+ "References": "https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html:https://aws.amazon.com/premiumsupport/pricing/:https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-policies.html:https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/attach-role-policy.html:https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-entities-for-policy.html",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.16",
+ "Description": "Ensure IAM instance roles are used for AWS resource access from instances",
+ "Checks": [
+ "ec2_instance_profile_attached"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Automated",
+ "Description": "AWS access from within AWS instances can be done by either encoding AWS keys into AWS API calls or by assigning the instance to a role which has an appropriate permissions policy for the required access. AWS Access means accessing the APIs of AWS in order to access AWS resources or manage AWS account resources.",
+ "RationaleStatement": "AWS IAM roles reduce the risks associated with sharing and rotating credentials that can be used outside of AWS itself. Compromised credentials can be used from outside the AWS account to which they provide access. In contrast, to leverage role permissions, an attacker would need to gain and maintain access to a specific instance to use the privileges associated with it. Additionally, if credentials are encoded into compiled applications or other hard-to-change mechanisms, they are even less likely to be properly rotated due to the risks of service disruption. As time passes, credentials that cannot be rotated are more likely to be known by an increasing number of individuals who no longer work for the organization that owns the credentials.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "**From Console:** 1. Sign in to the AWS Management Console and navigate to the EC2 dashboard at `https://console.aws.amazon.com/ec2/`. 2. In the left navigation panel, choose `Instances`. 3. Select the EC2 instance you want to modify. 4. Click `Actions`. 5. Click `Security`. 6. Click `Modify IAM role`. 7. Click `Create new IAM role` if a new IAM role is required. 8. Select the IAM role you want to attach to your instance in the `IAM role` dropdown. 9. Click `Update IAM role`. 10. Repeat steps 3 to 9 for each EC2 instance in your AWS account that requires an IAM role to be attached. **From Command Line:** 1. Run the `describe-instances` command to list all EC2 instance IDs in the selected AWS region: ``` aws ec2 describe-instances --region --query 'Reservations[*].Instances[*].InstanceId' ``` 2. Run the `associate-iam-instance-profile` command to attach an instance profile (which is attached to an IAM role) to the EC2 instance: ``` aws ec2 associate-iam-instance-profile --region --instance-id --iam-instance-profile Name=Instance-Profile-Name ``` 3. Run the `describe-instances` command again for the recently modified EC2 instance. The command output should return the instance profile ARN and ID: ``` aws ec2 describe-instances --region --instance-id --query 'Reservations[*].Instances[*].IamInstanceProfile' ``` 4. Repeat steps 2 and 3 for each EC2 instance in your AWS account that requires an IAM role to be attached.",
+ "AuditProcedure": "First, check if the instance has any API secrets stored using Secret Scanning. Currently, AWS does not have a solution for this. You can use open-source tools like TruffleHog to scan for secrets in the EC2 instance. If a secret is found, then assign the role to the instance. **From Console:** 1. Sign in to the AWS Management Console and navigate to the EC2 dashboard at `https://console.aws.amazon.com/ec2/`. 2. In the left navigation panel, choose `Instances`. 3. Select the EC2 instance you want to examine. 4. Select `Actions`. 5. Select `View details`. 6. Select `Security` in the lower panel. - If the value for **Instance profile arn** is an instance profile ARN, then an instance profile (that contains an IAM role) is attached. - If the value for **IAM Role** is blank, no role is attached. - If the value for **IAM Role** contains a role, a role is attached. - If the value for **IAM Role** is No roles attached to instance profile: , then an instance profile is attached to the instance, but it does not contain an IAM role. 7. Repeat steps 3 to 6 for each EC2 instance in your AWS account. **From Command Line:** 1. Run the `describe-instances` command to list all EC2 instance IDs in the selected AWS region: ``` aws ec2 describe-instances --region --query 'Reservations[*].Instances[*].InstanceId' ``` 2. Run the `describe-instances` command again for each EC2 instance using the `IamInstanceProfile` identifier in the query filter to check if an IAM role is attached: ``` aws ec2 describe-instances --region --instance-id --query 'Reservations[*].Instances[*].IamInstanceProfile' ``` 3. If an IAM role is attached, the command output will show the IAM instance profile ARN and ID. 4. Repeat steps 2 and 3 for each EC2 instance in your AWS account.",
+ "AdditionalInformation": "",
+ "References": "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html:https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.17",
+ "Description": "Ensure that all expired SSL/TLS certificates stored in AWS IAM are removed",
+ "Checks": [
+ "iam_no_expired_server_certificates_stored"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "To enable HTTPS connections to your website or application in AWS, you need an SSL/TLS server certificate. You can use AWS Certificate Manager (ACM) or IAM to store and deploy server certificates. Use IAM as a certificate manager only when you must support HTTPS connections in a region that is not supported by ACM. IAM securely encrypts your private keys and stores the encrypted version in IAM SSL certificate storage. IAM supports deploying server certificates in all regions, but you must obtain your certificate from an external provider for use with AWS. You cannot upload an ACM certificate to IAM. Additionally, you cannot manage your certificates from the IAM Console.",
+ "RationaleStatement": "Removing expired SSL/TLS certificates eliminates the risk that an invalid certificate will be deployed accidentally to a resource such as AWS Elastic Load Balancer (ELB), which can damage the credibility of the application/website behind the ELB. As a best practice, it is recommended to delete expired certificates.",
+ "ImpactStatement": "Deleting the certificate could have implications for your application if you are using an expired server certificate with Elastic Load Balancing, CloudFront, etc. You must make configurations in the respective services to ensure there is no interruption in application functionality.",
+ "RemediationProcedure": "**From Console:** Removing expired certificates via AWS Management Console is not currently supported. To delete SSL/TLS certificates stored in IAM through the AWS API, use the Command Line Interface (CLI). **From Command Line:** To delete an expired certificate, run the following command by replacing with the name of the certificate to delete: ``` aws iam delete-server-certificate --server-certificate-name ``` When the preceding command is successful, it does not return any output.",
+ "AuditProcedure": "**From Console:** Getting the certificate expiration information via the AWS Management Console is not currently supported. To request information about the SSL/TLS certificates stored in IAM through the AWS API, use the Command Line Interface (CLI). **From Command Line:** Run the `list-server-certificates` command to list all the IAM-stored server certificates: ``` aws iam list-server-certificates ``` The command output should return an array that contains all the SSL/TLS certificates currently stored in IAM and their metadata (name, ID, expiration date, etc): ``` { ServerCertificateMetadataList: [ { ServerCertificateId: EHDGFRW7EJFYTE88D, ServerCertificateName: MyServerCertificate, Expiration: 2018-07-10T23:59:59Z, Path: /, Arn: arn:aws:iam::012345678910:server-certificate/MySSLCertificate, UploadDate: 2018-06-10T11:56:08Z } ] } ``` Verify the `ServerCertificateName` and `Expiration` parameter value (expiration date) for each SSL/TLS certificate returned by the list-server-certificates command and determine if there are any expired server certificates currently stored in AWS IAM. If so, use the AWS API to remove them. If this command returns: ``` { { ServerCertificateMetadataList: [] } ``` This means that there are no expired certificates; it **does not** mean that no certificates exist.",
+ "AdditionalInformation": "",
+ "References": "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html:https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-server-certificate.html",
+ "DefaultValue": "By default, expired certificates will not be deleted."
+ }
+ ]
+ },
+ {
+ "Id": "2.18",
+ "Description": "Ensure that IAM External Access Analyzer is enabled for all regions",
+ "Checks": [
+ "accessanalyzer_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "accessanalyzer_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "Enable the IAM External Access Analyzer regarding all resources in each active AWS region. IAM Access Analyzer is a technology introduced at AWS reinvent 2019. After the Analyzer is enabled in IAM, scan results are displayed on the console showing the accessible resources. Scans show resources that other accounts and federated users can access, such as KMS keys and IAM roles. The results allow you to determine whether an unintended user is permitted, making it easier for administrators to monitor least privilege access. Access Analyzer analyzes only the policies that are applied to resources in the same AWS Region.",
+ "RationaleStatement": "AWS IAM External Access Analyzer helps you identify the resources in your organization and accounts, such as Amazon S3 buckets or IAM roles, that are shared with external entities. This allows you to identify unintended access to your resources and data. Access Analyzer identifies resources that are shared with external principals by using logic-based reasoning to analyze the resource-based policies in your AWS environment. IAM External Access Analyzer continuously monitors all policies for S3 buckets, IAM roles, KMS (Key Management Service) keys, AWS Lambda functions, Amazon SQS (Simple Queue Service) queues and more",
+ "ImpactStatement": "",
+ "RemediationProcedure": "**From Console:** Perform the following to enable IAM Access Analyzer for IAM policies: 1. Open the IAM console at `https://console.aws.amazon.com/iam/.` 2. Choose `Access analyzer`. 3. Choose `Create external access analyzer`. 4. On the `Create analyzer` page, confirm that the `Region` displayed is the Region where you want to enable Access Analyzer. 5. Optionally enter a name for the analyzer. 6. Optionally add any tags that you want to apply to the analyzer. 7. Choose `Create Analyzer`. 8. Repeat these step for each active region. **From Command Line:** Run the following command: ``` aws accessanalyzer list-analyzers --type ORGANIZATION ``` Repeat this command for each active region. **Note:** The IAM Access Analyzer is successfully configured only when the account you use has the necessary permissions.",
+ "AuditProcedure": "**From Console:** 1. Open the IAM console at `https://console.aws.amazon.com/iam/` 2. Under `Access analyzer` choose `Analyzer Settings` 3. On the `Analyzer Settings` page, there will be a list of analyzers. 4. Look for analyzers where the `Finding type` is `External Access`. **From Command Line:** 1. Run the following command: ``` aws accessanalyzer list-analyzers --type ORGANIZATION | grep status ``` 2. Ensure that at least one Analyzer's `status` is set to `ACTIVE`. 3. Repeat the steps above for each active region. If an Access Analyzer is not listed for each region or the status is not set to active refer to the remediation procedure below.",
+ "AdditionalInformation": "",
+ "References": "https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html:https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-getting-started.html:https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/get-analyzer.html:https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/create-analyzer.html",
+ "DefaultValue": "By default, IAM External Access Analyzer is not enabled in any region. An analyzer must be explicitly created and activated for each region where monitoring is required."
+ }
+ ]
+ },
+ {
+ "Id": "2.19",
+ "Description": "Ensure IAM users are managed centrally via identity federation or AWS Organizations for multi-account environments",
+ "Checks": [
+ "iam_check_saml_providers_sts"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Manual",
+ "Description": "In multi-account environments, IAM user centralization facilitates greater user control. User access beyond the initial account is then provided via role assumption. Centralization of users can be accomplished through federation with an external identity provider or through the use of AWS Organizations.",
+ "RationaleStatement": "Centralizing IAM user management to a single identity store reduces complexity and thus the likelihood of access management errors.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "The remediation procedure will vary based on each individual organization's implementation of identity federation and/or AWS Organizations, with the acceptance criteria that no non-service IAM users and non-root accounts are present outside the account providing centralized IAM user management.",
+ "AuditProcedure": "For multi-account AWS environments with an external identity provider: 1. Determine the master account for identity federation or IAM user management 2. Login to that account through the AWS Management Console 3. Click `Services` 4. Click `IAM` 5. Click `Identity providers` 6. Verify the configuration For multi-account AWS environments with an external identity provider, as well as for those implementing AWS Organizations without an external identity provider: 1. Determine all accounts that should not have local users present 2. Log into the AWS Management Console 3. Switch role into each identified account 4. Click `Services` 5. Click `IAM` 6. Click `Users` 7. Confirm that no IAM users representing individuals are present",
+ "AdditionalInformation": "",
+ "References": "",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.20",
+ "Description": "Ensure access to AWSCloudShellFullAccess is restricted",
+ "Checks": [
+ "iam_policy_cloudshell_admin_not_attached"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Manual",
+ "Description": "AWS CloudShell is a convenient way of running CLI commands against AWS services; a managed IAM policy ('AWSCloudShellFullAccess') provides full access to CloudShell, which allows file upload and download capability between a user's local system and the CloudShell environment. Within the CloudShell environment, a user has sudo permissions and can access the internet. Therefore, it is feasible to install file transfer software, for example, and move data from CloudShell to external internet servers.",
+ "RationaleStatement": "Access to this policy should be restricted, as it presents a potential channel for data exfiltration by malicious cloud admins who are given full permissions to the service. AWS documentation describes how to create a more restrictive IAM policy that denies file transfer permissions.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "**From Console** 1. Open the IAM console at https://console.aws.amazon.com/iam/ 2. In the left pane, select Policies 3. Search for and select AWSCloudShellFullAccess 4. On the Entities attached tab, for each item, check the box and select Detach",
+ "AuditProcedure": "**From Console** 1. Open the IAM console at https://console.aws.amazon.com/iam/ 2. In the left pane, select Policies 3. Search for and select AWSCloudShellFullAccess 4. On the Entities attached tab, ensure that there are no entities using this policy **From Command Line** 1. List IAM policies, filter for the 'AWSCloudShellFullAccess' managed policy, and note the Arn element value: ``` aws iam list-policies --query Policies[?PolicyName == 'AWSCloudShellFullAccess'] ``` 2. Check if the 'AWSCloudShellFullAccess' policy is attached to any role: ``` aws iam list-entities-for-policy --policy-arn arn:aws:iam::aws:policy/AWSCloudShellFullAccess ``` 3. In the output, ensure PolicyRoles returns empty. 'Example: Example: PolicyRoles: [ ]' If it does not return empty, refer to the remediation below. **Note:** Keep in mind that other policies may grant access.",
+ "AdditionalInformation": "",
+ "References": "https://docs.aws.amazon.com/cloudshell/latest/userguide/sec-auth-with-identities.html",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "2.21",
+ "Description": "Ensure AWS resource policies do not allow unrestricted access using 'Principal': '*'",
+ "Checks": [
+ "s3_bucket_policy_public_write_access",
+ "sqs_queues_not_publicly_accessible",
+ "sns_topics_not_publicly_accessible",
+ "awslambda_function_not_publicly_accessible",
+ "kms_key_not_publicly_accessible",
+ "glacier_vaults_policy_public_access",
+ "secretsmanager_not_publicly_accessible",
+ "eventbridge_bus_exposed"
+ ],
+ "Attributes": [
+ {
+ "Section": "2 Identity and Access Management",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Manual",
+ "Description": "Ensure AWS resource-based policies, such as Amazon S3 bucket policies, Amazon SQS queue policies, Amazon SNS topic policies, and AWS Lambda resource policies, do not grant unrestricted access using \"Principal\": \"*\" with \"Effect\": \"Allow\" unless the policy includes restrictive conditions that limit access to specific trusted identities, accounts, services, or network boundaries.",
+ "RationaleStatement": "Resource-based policies are evaluated alongside identity-based IAM policies during authorization decisions. When a policy statement specifies \"Principal\": \"*\" with \"Effect\": \"Allow\", it grants the specified permissions to any AWS principal unless additional conditions restrict the request. This may unintentionally allow access from users, roles, or services in any AWS account. Such broad access significantly increases the risk of unauthorized data access, resource abuse, or data exfiltration.",
+ "ImpactStatement": "Unrestricted resource-based policies may expose data or services to unauthorized access, potentially leading to data breaches, service misuse, or unintended public exposure.",
+ "RemediationProcedure": "If a resource policy contains `\"Principal\": \"*\"` with `\"Effect\": \"Allow\"` and lacks sufficient restrictions, modify the policy to limit access. **OPTION 1 - Restrict the Principal:** Replace the wildcard principal (`\"Principal\": \"*\"`) with a specific account, role, user, or service. Example Non-Compliant Policy: ``` {\"Version\": \"2012-10-17\", \"Statement\": [{\"Sid\": \"AllowPublicAccess\", \"Effect\": \"Allow\", \"Principal\": \"*\", \"Action\": \"sqs:SendMessage\", \"Resource\": \"arn:aws:sqs:us-east-1:123456789012:my-queue\"}]} ``` Steps: 1. Retrieve the current policy: ``` aws sqs get-queue-attributes --queue-url https://sqs.us-east-1.amazonaws.com/123456789012/my-queue --attribute-names Policy --query 'Attributes.Policy' ``` 2. Update the policy with a specific principal: ``` aws sqs set-queue-attributes --queue-url https://sqs.us-east-1.amazonaws.com/123456789012/my-queue --attributes '{\"Policy\": \"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[{\\\"Sid\\\":\\\"AllowSpecificAccount\\\",\\\"Effect\\\":\\\"Allow\\\",\\\"Principal\\\":{\\\"AWS\\\":\\\"arn:aws:iam::345678901234:root\\\"},\\\"Action\\\":\\\"sqs:SendMessage\\\",\\\"Resource\\\":\\\"arn:aws:sqs:us-east-1:123456789012:my-queue\\\"}]}\"}' ``` Resulting Compliant Policy: ``` {\"Version\": \"2012-10-17\", \"Statement\": [{\"Sid\": \"AllowSpecificAccount\", \"Effect\": \"Allow\", \"Principal\": {\"AWS\": \"arn:aws:iam::345678901234:root\"}, \"Action\": \"sqs:SendMessage\", \"Resource\": \"arn:aws:sqs:us-east-1:123456789012:my-queue\"}]} ``` **OPTION 2 - Restrict Using Conditions:** If a wildcard principal is required, add restrictive conditions. Example compliant policy: ``` {\"Version\": \"2012-10-17\", \"Statement\": [{\"Sid\": \"AllowServiceIntegration\", \"Effect\": \"Allow\", \"Principal\": \"*\", \"Action\": \"sqs:SendMessage\", \"Resource\": \"arn:aws:sqs:us-east-1:123456789012:my-queue\", \"Condition\": {\"StringEquals\": {\"aws:SourceAccount\": \"345678901234\"}}}]} ```",
+ "AuditProcedure": "1. Identify resources that support resource-based policies within the AWS account, such as S3 buckets, SQS queues, SNS topics, and Lambda functions. 2. Retrieve the resource policies for each resource. Example CLI commands: SQS Queue Policies: ``` aws sqs get-queue-attributes --queue-url https://sqs.region.amazonaws.com/account/QUEUE --attribute-names Policy ``` S3 Bucket Policies: ``` aws s3api get-bucket-policy --bucket YOUR-BUCKET-NAME ``` SNS Topic Policies: ``` aws sns get-topic-attributes --topic-arn TOPIC-ARN --query \"Attributes.Policy\" --output text ``` 3. Inspect the retrieved policies and identify statements containing: - `\"Effect\": \"Allow\"` AND `\"Principal\": \"*\"` OR - `\"Principal\": {\"AWS\": \"*\"}` 4. Evaluate whether the statement includes restrictive conditions such as: - `aws:SourceArn` - `aws:SourceAccount` - `aws:PrincipalArn` - Other service-specific condition keys 5. Determine audit status: - Compliant: Wildcard principals are present only when restrictive conditions limit access to trusted principals or services - Non-Compliant: Wildcard principals are used without sufficient restrictions",
+ "AdditionalInformation": "",
+ "References": "",
+ "DefaultValue": "By default, AWS does not prevent the use of \"Principal\": \"*\" in resource-based policies. Policies may allow unrestricted access unless explicitly restricted through policy definitions or organizational controls. It is the responsibility of the customer to ensure that resource policies are properly scoped and do not grant unintended public or cross-account access."
+ }
+ ]
+ },
+ {
+ "Id": "3.1.1",
+ "Description": "Ensure S3 Bucket Policy is set to deny HTTP requests",
+ "Checks": [
+ "s3_bucket_secure_transport_policy"
+ ],
+ "Attributes": [
+ {
+ "Section": "3 Storage",
+ "SubSection": "3.1 Simple Storage Service (S3)",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Automated",
+ "Description": "At the Amazon S3 bucket level, you can configure permissions through a bucket policy, making the objects accessible only through HTTPS.",
+ "RationaleStatement": "By default, Amazon S3 allows both HTTP and HTTPS requests. To ensure that access to Amazon S3 objects is only permitted through HTTPS, you must explicitly deny HTTP requests. Bucket policies that allow HTTPS requests without explicitly denying HTTP requests will not comply with this recommendation.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "**From Console:** 1. Login to the AWS Management Console and open the Amazon S3 console using https://console.aws.amazon.com/s3/. 2. Select the check box next to the Bucket. 3. Click on 'Permissions'. 4. Click 'Bucket Policy'. 5. Add either of the following to the existing policy, filling in the required information: ``` { Sid: , Effect: Deny, Principal: *, Action: s3:*, Resource: arn:aws:s3:::/*, Condition: { Bool: { aws:SecureTransport: false } } } ``` or ``` { Sid: , Effect: Deny, Principal: *, Action: s3:*, Resource: [ arn:aws:s3:::, arn:aws:s3:::/* ], Condition: { NumericLessThan: { s3:TlsVersion: 1.2 } } } ``` 6. Save 7. Repeat for all the buckets in your AWS account that contain sensitive data. **From Console** Using AWS Policy Generator: 1. Repeat steps 1-4 above. 2. Click on `Policy Generator` at the bottom of the Bucket Policy Editor. 3. Select Policy Type `S3 Bucket Policy`. 4. Add Statements: - `Effect` = Deny - `Principal` = * - `AWS Service` = Amazon S3 - `Actions` = * - `Amazon Resource Name` = 5. Generate Policy. 6. Copy the text and add it to the Bucket Policy. **From Command Line:** 1. Export the bucket policy to a json file: ``` aws s3api get-bucket-policy --bucket --query Policy --output text > policy.json ``` 2. Modify the policy.json file by adding either of the following: ``` { Sid: , Effect: Deny, Principal: *, Action: s3:*, Resource: arn:aws:s3:::/*, Condition: { Bool: { aws:SecureTransport: false } } } ``` or ``` { Sid: , Effect: Deny, Principal: *, Action: s3:*, Resource: [ arn:aws:s3:::, arn:aws:s3:::/* ], Condition: { NumericLessThan: { s3:TlsVersion: 1.2 } } } ``` 3. Apply this modified policy back to the S3 bucket: ``` aws s3api put-bucket-policy --bucket --policy file://policy.json ```",
+ "AuditProcedure": "To allow access to HTTPS, you can use a bucket policy with the effect `allow` and a condition that checks for the key `aws:SecureTransport: true`. This means that HTTPS requests are allowed, but it does not deny HTTP requests. To explicitly deny HTTP access, ensure that there is also a bucket policy with the effect `deny` that contains the key `aws:SecureTransport: false`. You may also require TLS by setting a policy to deny any version lower than the one you wish to require, using the condition `NumericLessThan` and the key `s3:TlsVersion: 1.2`. **From Console:** 1. Login to the AWS Management Console and open the Amazon S3 console using https://console.aws.amazon.com/s3/. 2. Select the check box next to the Bucket. 3. Click on 'Permissions', then click on `Bucket Policy`. 4. Ensure that a policy is listed that matches either: ``` { Sid: , Effect: Deny, Principal: *, Action: s3:*, Resource: arn:aws:s3:::/*, Condition: { Bool: { aws:SecureTransport: false } } } ``` or ``` { Sid: , Effect: Deny, Principal: *, Action: s3:*, Resource: [ arn:aws:s3:::, arn:aws:s3:::/* ], Condition: { NumericLessThan: { s3:TlsVersion: 1.2 } } } ``` `` and `` will be specific to your account, and TLS version will be site/policy specific to your organisation. 5. Repeat for all the buckets in your AWS account. **From Command Line:** 1. List all of the S3 Buckets ``` aws s3 ls ``` 2. Using the list of buckets, run this command on each of them: ``` aws s3api get-bucket-policy --bucket | grep aws:SecureTransport ``` or ``` aws s3api get-bucket-policy --bucket | grep s3:TlsVersion ``` NOTE : If an error is thrown by the CLI, it means no policy has been configured for the specified S3 bucket, and that by default it is allowing both HTTP and HTTPS requests. 3. Confirm that `aws:SecureTransport` is set to false (such as `aws:SecureTransport:false`) or that `s3:TlsVersion` has a site-specific value. 4. Confirm that the policy line has Effect set to Deny 'Effect:Deny'",
+ "AdditionalInformation": "",
+ "References": "https://aws.amazon.com/premiumsupport/knowledge-center/s3-bucket-policy-for-config-rule/:https://aws.amazon.com/blogs/security/how-to-use-bucket-policies-and-apply-defense-in-depth-to-help-secure-your-amazon-s3-data/:https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-policy.html",
+ "DefaultValue": "Both HTTP and HTTPS requests are allowed."
+ }
+ ]
+ },
+ {
+ "Id": "3.1.2",
+ "Description": "Ensure MFA Delete is enabled on S3 buckets",
+ "Checks": [
+ "s3_bucket_no_mfa_delete"
+ ],
+ "Attributes": [
+ {
+ "Section": "3 Storage",
+ "SubSection": "3.1 Simple Storage Service (S3)",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Manual",
+ "Description": "Once MFA Delete is enabled on your sensitive and classified S3 bucket, it requires the user to provide two forms of authentication.",
+ "RationaleStatement": "Adding MFA delete to an S3 bucket requires additional authentication when you change the version state of your bucket or delete an object version, adding another layer of security in the event your security credentials are compromised or unauthorized access is granted.",
+ "ImpactStatement": "Enabling MFA delete on an S3 bucket could require additional administrator oversight. Enabling MFA delete may impact other services that automate the creation and/or deletion of S3 buckets.",
+ "RemediationProcedure": "Perform the steps below to enable MFA delete on an S3 bucket: **Note:** - You cannot enable MFA Delete using the AWS Management Console; you must use the AWS CLI or API. - You must use your 'root' account to enable MFA Delete on S3 buckets. **From Command line:** 1. Run the s3api `put-bucket-versioning` command: ``` aws s3api put-bucket-versioning --profile my-root-profile --bucket Bucket_Name --versioning-configuration Status=Enabled,MFADelete=Enabled --mfa “arn:aws:iam::aws_account_id:mfa/root-account-mfa-device passcode” ```",
+ "AuditProcedure": "Perform the steps below to confirm that MFA delete is configured on an S3 bucket: **From Console:** 1. Login to the S3 console at `https://console.aws.amazon.com/s3/`. 2. Click the `check` box next to the name of the bucket you want to confirm. 3. In the window under `Properties`: - Confirm that Versioning is `Enabled` - Confirm that MFA Delete is `Enabled` **From Command Line:** 1. Run the `get-bucket-versioning` command: ``` aws s3api get-bucket-versioning --bucket my-bucket ``` Example output: ``` EnabledEnabled ``` If the console or CLI output does not show that Versioning and MFA Delete are `enabled`, please refer to the remediation below.",
+ "AdditionalInformation": "",
+ "References": "https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html#MultiFactorAuthenticationDelete:https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMFADelete.html:https://aws.amazon.com/blogs/security/securing-access-to-aws-using-mfa-part-3/:https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_lost-or-broken.html",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "3.1.3",
+ "Description": "Ensure all data in Amazon S3 has been discovered, classified, and secured when necessary",
+ "Checks": [
+ "macie_is_enabled"
+ ],
+ "Attributes": [
+ {
+ "Section": "3 Storage",
+ "SubSection": "3.1 Simple Storage Service (S3)",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Manual",
+ "Description": "Amazon S3 buckets can contain sensitive data that, for security purposes, should be discovered, monitored, classified, and protected. Macie, along with other third-party tools, can automatically provide an inventory of Amazon S3 buckets.",
+ "RationaleStatement": "Using a cloud service or third-party software to continuously monitor and automate the process of data discovery and classification for S3 buckets through machine learning and pattern matching is a strong defense in protecting that information. Amazon Macie is a fully managed data security and privacy service that uses machine learning and pattern matching to discover and protect your sensitive data in AWS.",
+ "ImpactStatement": "There is a cost associated with using Amazon Macie, and there is typically a cost associated with third-party tools that perform similar processes and provide protection.",
+ "RemediationProcedure": "Perform the steps below to enable and configure Amazon Macie: **From Console:** 1. Log on to the Macie console at `https://console.aws.amazon.com/macie/`. 2. Click `Get started`. 3. Click `Enable Macie`. Set up a repository for sensitive data discovery results: 1. In the left pane, under Settings, click `Discovery results`. 2. Make sure `Create bucket` is selected. 3. Create a bucket and enter a name for it. The name must be unique across all S3 buckets, and it must start with a lowercase letter or a number. 4. Click `Advanced`. 5. For block all public access, make sure `Yes` is selected. 6. For KMS encryption, specify the AWS KMS key that you want to use to encrypt the results. The key must be a symmetric customer master key (CMK) that is in the same region as the S3 bucket. 7. Click `Save`. Create a job to discover sensitive data: 1. In the left pane, click `S3 buckets`. Macie displays a list of all the S3 buckets for your account. 2. Check the box for each bucket that you want Macie to analyze as part of the job. 3. Click `Create job`. 4. Click `Quick create`. 5. For the Name and Description step, enter a name and, optionally, a description of the job. 6. Click `Next`. 7. For the Review and create step, click `Submit`. Review your findings: 1. In the left pane, click `Findings`. 2. To view the details of a specific finding, choose any field other than the check box for the finding. If you are using a third-party tool to manage and protect your S3 data, follow the vendor documentation for implementing and configuring that tool.",
+ "AuditProcedure": "Perform the following steps to determine if Macie is running: **From Console:** 1. Login to the Macie console at https://console.aws.amazon.com/macie/. 2. In the left hand pane, click on `By job` under findings. 3. Confirm that you have a job set up for your S3 buckets. When you log into the Macie console, if you are not taken to the summary page and do not have a job set up and running, then refer to the remediation procedure below. If you are using a third-party tool to manage and protect your S3 data, you meet this recommendation.",
+ "AdditionalInformation": "",
+ "References": "https://aws.amazon.com/macie/getting-started/:https://docs.aws.amazon.com/workspaces/latest/adminguide/data-protection.html:https://docs.aws.amazon.com/macie/latest/user/data-classification.html",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "3.1.4",
+ "Description": "Ensure that S3 is configured with 'Block Public Access' enabled",
+ "Checks": [
+ "s3_bucket_level_public_access_block",
+ "s3_account_level_public_access_blocks"
+ ],
+ "Attributes": [
+ {
+ "Section": "3 Storage",
+ "SubSection": "3.1 Simple Storage Service (S3)",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "Amazon S3 provides `Block public access (bucket settings)` and `Block public access (account settings)` to help you manage public access to Amazon S3 resources. By default, S3 buckets and objects are created with public access disabled. However, an IAM principal with sufficient S3 permissions can enable public access at the bucket and/or object level. While enabled, `Block public access (bucket settings)` prevents an individual bucket and its contained objects from becoming publicly accessible. Similarly, `Block public access (account settings)` prevents all buckets and their contained objects from becoming publicly accessible across the entire account.",
+ "RationaleStatement": "Amazon S3 `Block public access (bucket settings)` prevents the accidental or malicious public exposure of data contained within the respective bucket(s). Amazon S3 `Block public access (account settings)` prevents the accidental or malicious public exposure of data contained within all buckets of the respective AWS account. Whether to block public access to all or some buckets is an organizational decision that should be based on data sensitivity, least privilege, and use case.",
+ "ImpactStatement": "When you apply Block Public Access settings to an account, the settings apply to all AWS regions globally. The settings may not take effect in all regions immediately or simultaneously, but they will eventually propagate to all regions.",
+ "RemediationProcedure": "**If utilizing Block Public Access (bucket settings)** **From Console:** 1. Login to the AWS Management Console and open the Amazon S3 console using https://console.aws.amazon.com/s3/. 2. Select the check box next to a bucket. 3. Click 'Edit public access settings'. 4. Click 'Block all public access' 5. Repeat for all the buckets in your AWS account that contain sensitive data. **From Command Line:** 1. List all of the S3 buckets: ``` aws s3 ls ``` 2. Enable Block Public Access on a specific bucket: ``` aws s3api put-public-access-block --bucket --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true ``` **If utilizing Block Public Access (account settings)** **From Console:** If the output reads `true` for the separate configuration settings, then Block Public Access is enabled on the account. 1. Login to the AWS Management Console and open the Amazon S3 console using https://console.aws.amazon.com/s3/. 2. Click `Block Public Access (account settings)`. 3. Click `Edit` to change the block public access settings for all the buckets in your AWS account. 4. Update the settings and click `Save`. For details about each setting, pause on the `i` icons. 5. When you're asked for confirmation, enter `confirm`. Then click `Confirm` to save your changes. **From Command Line:** To enable Block Public Access for this account, run the following command: ``` aws s3control put-public-access-block --public-access-block-configuration BlockPublicAcls=true, IgnorePublicAcls=true, BlockPublicPolicy=true, RestrictPublicBuckets=true --account-id ```",
+ "AuditProcedure": "**If utilizing Block Public Access (bucket settings)** **From Console:** 1. Login to the AWS Management Console and open the Amazon S3 console using https://console.aws.amazon.com/s3/. 2. Select the check box next to a bucket. 3. Click on 'Edit public access settings'. 4. Ensure that the block public access settings are configured appropriately for this bucket. 5. Repeat for all the buckets in your AWS account. **From Command Line:** 1. List all of the S3 buckets: ``` aws s3 ls ``` 2. Find the public access settings for a specific bucket: ``` aws s3api get-public-access-block --bucket ``` Output if Block Public Access is enabled: ``` { PublicAccessBlockConfiguration: { BlockPublicAcls: true, IgnorePublicAcls: true, BlockPublicPolicy: true, RestrictPublicBuckets: true } } ``` If the output reads `false` for the separate configuration settings, then proceed with the remediation. **If utilizing Block Public Access (account settings)** **From Console:** 1. Login to the AWS Management Console and open the Amazon S3 console using https://console.aws.amazon.com/s3/. 2. Choose `Block public access (account settings)`. 3. Ensure that the block public access settings are configured appropriately for your AWS account. **From Command Line:** To check the block public access settings for this account, run the following command: `aws s3control get-public-access-block --account-id --region ` Output if Block Public Access is enabled: ``` { PublicAccessBlockConfiguration: { IgnorePublicAcls: true, BlockPublicPolicy: true, BlockPublicAcls: true, RestrictPublicBuckets: true } } ``` If the output reads `false` for the separate configuration settings, then proceed with the remediation.",
+ "AdditionalInformation": "",
+ "References": "https://docs.aws.amazon.com/AmazonS3/latest/user-guide/block-public-access-account.html",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "3.2.1",
+ "Description": "Ensure that encryption-at-rest is enabled for RDS instances",
+ "Checks": [
+ "rds_instance_storage_encrypted"
+ ],
+ "Attributes": [
+ {
+ "Section": "3 Storage",
+ "SubSection": "3.2 Relational Database Service (RDS)",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "Amazon RDS encrypted DB instances use the industry-standard AES-256 encryption algorithm to encrypt your data on the server that hosts your Amazon RDS DB instances. After your data is encrypted, Amazon RDS handles the authentication of access and the decryption of your data transparently, with minimal impact on performance.",
+ "RationaleStatement": "Databases are likely to hold sensitive and critical data; therefore, it is highly recommended to implement encryption to protect your data from unauthorized access or disclosure. With RDS encryption enabled, the data stored on the instance's underlying storage, the automated backups, read replicas, and snapshots are all encrypted.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "**From Console:** 1. Login to the AWS Management Console and open the RDS dashboard at https://console.aws.amazon.com/rds/. 2. In the left navigation panel, click on `Databases`. 3. Select the Database instance that needs to be encrypted. 4. Click the `Actions` button placed at the top right and select `Take Snapshot`. 5. On the Take Snapshot page, enter the name of the database for which you want to take a snapshot in the `Snapshot Name` field and click on `Take Snapshot`. 6. Select the newly created snapshot, click the `Action` button placed at the top right, and select `Copy snapshot` from the Action menu. 7. On the Make Copy of DB Snapshot page, perform the following: - In the `New DB Snapshot Identifier` field, enter a name for the new snapshot. - Check `Copy Tags`. The new snapshot must have the same tags as the source snapshot. - Select `Yes` from the `Enable Encryption` dropdown list to enable encryption. You can choose to use the AWS default encryption key or a custom key from the Master Key dropdown list. 8. Click `Copy Snapshot` to create an encrypted copy of the selected instance's snapshot. 9. Select the new Snapshot Encrypted Copy and click the `Action` button located at the top right. Then, select the `Restore Snapshot` option from the Action menu. This will restore the encrypted snapshot to a new database instance. 10. On the Restore DB Instance page, enter a unique name for the new database instance in the DB Instance Identifier field. 11. Review the instance configuration details and click `Restore DB Instance`. 12. As the new instance provisioning process is completed, you can update the application configuration to refer to the endpoint of the new encrypted database instance. Once the database endpoint is changed at the application level, you can remove the unencrypted instance. **From Command Line:** 1. Run the `describe-db-instances` command to list the names of all RDS database instances in the selected AWS region. The command output should return database instance identifiers: ``` aws rds describe-db-instances --query 'DBInstances[*].DBInstanceIdentifier' ``` 2. Check if the specified RDS instance is encrypted. If it shows false, it means it is not yet encrypted: ``` aws rds describe-db-instances --region --db-instance-identifier --query 'DBInstances[*].StorageEncrypted' ``` 3. Run the `create-db-snapshot` command to create a snapshot for a selected database instance. The command output will return the `new snapshot` with name DB Snapshot Name: ``` aws rds create-db-snapshot --region --db-snapshot-identifier --db-instance-identifier ``` 4. Now run the `list-aliases` command to list the KMS key aliases available in a specified region. The command output should return each `key alias currently available`. For our RDS encryption activation process, locate the ID of the AWS default KMS key: ``` aws kms list-aliases --region ``` 5. Run the `copy-db-snapshot` command using the default KMS key ID for the RDS instances returned earlier to create an encrypted copy of the database instance snapshot. The command output will return the `encrypted instance snapshot configuration`: ``` aws rds copy-db-snapshot --region --source-db-snapshot-identifier --target-db-snapshot-identifier --copy-tags --kms-key-id ``` 6. Run the `restore-db-instance-from-db-snapshot` command to restore the encrypted snapshot created in the previous step to a new database instance. If successful, the command output should return the configuration of the new encrypted database instance. If using the default VPC for the database network: ``` aws rds restore-db-instance-from-db-snapshot --region --db-instance-identifier --db-snapshot-identifier ``` If you created your own VPC and Subnets, you need to create a DB subnet group: ``` aws rds create-db-subnet-group --db-subnet-group-name --db-subnet-group-description --subnet-ids '[\"\",\"\",\"\"]' ``` Restore the encrypted snapshot to an RDS database instance using the specified DB subnet group. The new instance will be encrypted using the KMS key specified during the snapshot copy: ``` aws rds restore-db-instance-from-db-snapshot --region --db-subnet-group-name --db-instance-identifier --db-snapshot-identifier ``` 7. Run the `describe-db-instances` command to list all RDS database names available in the selected AWS region. The output will return the database instance identifier names. Select the encrypted database name that we just created, `db-name-encrypted`: ``` aws rds describe-db-instances --region --query 'DBInstances[*].DBInstanceIdentifier' ``` 8. Run the `describe-db-instances` command again using the RDS instance identifier returned earlier to determine if the selected database instance is encrypted. The command output should indicate that the encryption status is `True`: ``` aws rds describe-db-instances --region --db-instance-identifier --query 'DBInstances[*].StorageEncrypted' ```",
+ "AuditProcedure": "**From Console:** 1. Login to the AWS Management Console and open the RDS dashboard at https://console.aws.amazon.com/rds/. 2. In the navigation pane, under RDS dashboard, click `Databases`. 3. Select the RDS instance that you want to examine. 4. Click `Instance Name` to see details, then select the `Configuration` tab. 5. Under Configuration Details, in the Storage pane, search for the `Encryption Enabled` status. 6. If the current status is set to `Disabled`, encryption is not enabled for the selected RDS database instance. 7. Repeat steps 2 to 6 to verify the encryption status of other RDS instances in the same region. 8. Change the region from the top of the navigation bar, and repeat the audit steps for other regions. **From Command Line:** 1. Run the `describe-db-instances` command to list all the RDS database instance names available in the selected AWS region. The output will return each database instance identifier (name): ``` aws rds describe-db-instances --region --query 'DBInstances[*].DBInstanceIdentifier' ``` 2. Run the `describe-db-instances` command again, using an RDS instance identifier returned from step 1, to determine if the selected database instance is encrypted. The output should return the encryption status `True` or `False`: ``` aws rds describe-db-instances --region --db-instance-identifier --query 'DBInstances[*].StorageEncrypted' ``` 3. If the StorageEncrypted parameter value is `False`, encryption is not enabled for the selected RDS database instance. 4. Repeat steps 1 to 3 to audit each RDS instance, and change the region to verify RDS instances in other regions.",
+ "AdditionalInformation": "",
+ "References": "https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.Encryption.html:https://aws.amazon.com/blogs/database/selecting-the-right-encryption-options-for-amazon-rds-and-amazon-aurora-database-engines/#:~:text=With%20RDS%2Dencrypted%20resources%2C%20data,transparent%20to%20your%20database%20engine.:https://aws.amazon.com/rds/features/security/:https://docs.aws.amazon.com/cli/latest/reference/rds/create-db-subnet-group.html",
+ "DefaultValue": "By default, Amazon RDS instances are created without encryption at rest. Encryption must be explicitly enabled at instance creation or by restoring from an encrypted snapshot."
+ }
+ ]
+ },
+ {
+ "Id": "3.2.2",
+ "Description": "Ensure the Auto Minor Version Upgrade feature is enabled for RDS instances",
+ "Checks": [
+ "rds_instance_minor_version_upgrade_enabled"
+ ],
+ "Attributes": [
+ {
+ "Section": "3 Storage",
+ "SubSection": "3.2 Relational Database Service (RDS)",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "Ensure that RDS database instances have the Auto Minor Version Upgrade flag enabled to automatically receive minor engine upgrades during the specified maintenance window. This way, RDS instances can obtain new features, bug fixes, and security patches for their database engines.",
+ "RationaleStatement": "AWS RDS will occasionally deprecate minor engine versions and provide new ones for upgrades. When the last version number within a release is replaced, the changed version is considered minor. With the Auto Minor Version Upgrade feature enabled, version upgrades will occur automatically during the specified maintenance window, allowing your RDS instances to receive new features, bug fixes, and security patches for their database engines.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "**From Console:** 1. Log in to the AWS management console and navigate to the RDS dashboard at https://console.aws.amazon.com/rds/. 2. In the left navigation panel, click `Databases`. 3. Select the RDS instance that you want to update. 4. Click on the `Modify` button located at the top right side. 5. On the `Modify DB Instance: ` page, In the `Maintenance` section, select `Auto minor version upgrade` and click the `Yes` radio button. 6. At the bottom of the page, click `Continue`, and check `Apply Immediately` to apply the changes immediately, or select `Apply during the next scheduled maintenance window` to avoid any downtime. 7. Review the changes and click `Modify DB Instance`. The instance status should change from available to modifying and back to available. Once the feature is enabled, the `Auto Minor Version Upgrade` status should change to `Yes`. **From Command Line:** 1. Run the `describe-db-instances` command to list all RDS database instance names available in the selected AWS region: ``` aws rds describe-db-instances --region --query 'DBInstances[*].DBInstanceIdentifier' ``` 2. The command output should return each database instance identifier. 3. Run the `modify-db-instance` command to modify the configuration of a selected RDS instance. This command will apply the changes immediately. Remove `--apply-immediately` to apply changes during the next scheduled maintenance window and avoid any downtime: ``` aws rds modify-db-instance --region --db-instance-identifier --auto-minor-version-upgrade --apply-immediately ``` 4. The command output should reveal the new configuration metadata for the RDS instance, including the `AutoMinorVersionUpgrade` parameter value. 5. Run the `describe-db-instances` command to check if the Auto Minor Version Upgrade feature has been successfully enabled: ``` aws rds describe-db-instances --region --db-instance-identifier --query 'DBInstances[*].AutoMinorVersionUpgrade' ``` 6. The command output should return the feature's current status set to `true`, indicating that the feature is `enabled`, and that the minor engine upgrades will be applied to the selected RDS instance.",
+ "AuditProcedure": "**From Console:** 1. Log in to the AWS management console and navigate to the RDS dashboard at https://console.aws.amazon.com/rds/. 2. In the left navigation panel, click `Databases`. 3. Select the RDS instance that you want to examine. 4. Click on the `Maintenance and backups` panel. 5. Under the `Maintenance` section, search for the Auto Minor Version Upgrade status. - If the current status is `Disabled`, it means that the feature is not enabled, and the minor engine upgrades released will not be applied to the selected RDS instance. **From Command Line:** 1. Run the `describe-db-instances` command to list all RDS database names available in the selected AWS region: ``` aws rds describe-db-instances --region --query 'DBInstances[*].DBInstanceIdentifier' ``` 2. The command output should return each database instance identifier. 3. Run the `describe-db-instances` command again using a RDS instance identifier returned earlier to determine the Auto Minor Version Upgrade status for the selected instance: ``` aws rds describe-db-instances --region --db-instance-identifier --query 'DBInstances[*].AutoMinorVersionUpgrade' ``` 4. The command output should return the current status of the feature. If the current status is set to `true`, the feature is enabled and the minor engine upgrades will be applied to the selected RDS instance.",
+ "AdditionalInformation": "",
+ "References": "https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_RDS_Managing.html:https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Upgrading.html:https://aws.amazon.com/rds/faqs/",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "3.2.3",
+ "Description": "Ensure that RDS instances are not publicly accessible",
+ "Checks": [
+ "rds_instance_no_public_access"
+ ],
+ "Attributes": [
+ {
+ "Section": "3 Storage",
+ "SubSection": "3.2 Relational Database Service (RDS)",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "Ensure and verify that the RDS database instances provisioned in your AWS account restrict unauthorized access in order to minimize security risks. To restrict access to any RDS database instance, you must disable the Publicly Accessible flag for the database and update the VPC security group associated with the instance.",
+ "RationaleStatement": "Ensure that no public-facing RDS database instances are provisioned in your AWS account, and restrict unauthorized access in order to minimize security risks. When the RDS instance allows unrestricted access (0.0.0.0/0), anyone and anything on the Internet can establish a connection to your database, which can increase the opportunity for malicious activities such as brute force attacks, PostgreSQL injections, or DoS/DDoS attacks.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "**From Console:** 1. Log in to the AWS management console and navigate to the RDS dashboard at https://console.aws.amazon.com/rds/. 2. Under the navigation panel, on the RDS dashboard, click `Databases`. 3. Select the RDS instance that you want to update. 4. Click `Modify` from the dashboard top menu. 5. On the Modify DB Instance panel, under the `Connectivity` section, click on `Additional connectivity configuration` and update the value for `Publicly Accessible` to `Not publicly accessible` to restrict public access. 6. Follow the below steps to update subnet configurations: - Select the `Connectivity and security` tab, and click the VPC attribute value inside the `Networking` section. - Select the `Details` tab from the VPC dashboard's bottom panel and click the Route table configuration attribute value. - On the Route table details page, select the Routes tab from the dashboard's bottom panel and click `Edit routes`. - On the Edit routes page, update the Destination of Target which is set to `igw-xxxxx` and click `Save` routes. 7. On the Modify DB Instance panel, click `Continue`, and in the Scheduling of modifications section, perform one of the following actions based on your requirements: - Select `Apply during the next scheduled maintenance window` to apply the changes automatically during the next scheduled maintenance window. - Select `Apply immediately` to apply the changes right away. With this option, any pending modifications will be asynchronously applied as soon as possible, regardless of the maintenance window setting for this RDS database instance. Note that any changes available in the pending modifications queue are also applied. If any of the pending modifications require downtime, choosing this option can cause unexpected downtime for the application. 8. Repeat steps 3-7 for each RDS instance in the current region. 9. Change the AWS region from the navigation bar to repeat the process for other regions. **From Command Line:** 1. Run the `describe-db-instances` command to list all available RDS database identifiers in the selected AWS region: ``` aws rds describe-db-instances --region --query 'DBInstances[*].DBInstanceIdentifier' ``` 2. The command output should return each database instance identifier. 3. Run the `modify-db-instance` command to modify the configuration of a selected RDS instance, disabling the `Publicly Accessible` flag for that instance. This command uses the `apply-immediately` flag. If you want to avoid any downtime, the `--no-apply-immediately` flag can be used: ``` aws rds modify-db-instance --region --db-instance-identifier --no-publicly-accessible --apply-immediately ``` 4. The command output should reveal the `PubliclyAccessible` configuration under pending values, to be applied at the specified time. 5. Updating the Internet Gateway destination via the AWS CLI is not currently supported. To update information about the Internet Gateway, please use the AWS Console procedure. 6. Repeat steps 1-5 for each RDS instance provisioned in the current region. 7. Change the AWS region by using the --region filter to repeat the process for other regions.",
+ "AuditProcedure": "**From Console:** 1. Log in to the AWS management console and navigate to the RDS dashboard at https://console.aws.amazon.com/rds/. 2. Under the navigation panel, on the RDS dashboard, click `Databases`. 3. Select the RDS instance that you want to examine. 4. Click `Instance Name` from the dashboard, under `Connectivity and Security`. 5. In the `Security` section, check if the Publicly Accessible flag status is set to `Yes`. 6. Follow the steps below to check database subnet access: - In the `networking` section, click the subnet link under `Subnets`. - The link will redirect you to the VPC Subnets page. - Select the subnet listed on the page and click the `Route Table` tab from the dashboard bottom panel. - If the route table contains any entries with the destination CIDR block set to `0.0.0.0/0` and an `Internet Gateway` attached, the selected RDS database instance was provisioned inside a public subnet; therefore, it is not running within a logically isolated environment and can be accessed from the Internet. 7. Repeat steps 3-6 to determine the configuration of other RDS database instances provisioned in the current region. 8. Change the AWS region from the navigation bar and repeat the audit process for other regions. **From Command Line:** 1. Run the `describe-db-instances` command to list all available RDS database names in the selected AWS region: ``` aws rds describe-db-instances --region --query 'DBInstances[*].DBInstanceIdentifier' ``` 2. The command output should return each database instance `identifier`. 3. Run the `describe-db-instances` command again, using the `PubliclyAccessible` parameter as a query filter to reveal the status of the database instance's Publicly Accessible flag: ``` aws rds describe-db-instances --region --db-instance-identifier --query 'DBInstances[*].PubliclyAccessible' ``` 4. Check the Publicly Accessible parameter status. If the Publicly Accessible flag is set to `Yes`, then the selected RDS database instance is publicly accessible and insecure. Follow the steps mentioned below to check database subnet access. 5. Run the `describe-db-instances` command again using the RDS database instance identifier that you want to check, along with the appropriate filtering to describe the VPC subnet(s) associated with the selected instance: ``` aws rds describe-db-instances --region --db-instance-identifier --query 'DBInstances[*].DBSubnetGroup.Subnets[]' ``` - The command output should list the subnets available in the selected database subnet group. 6. Run the `describe-route-tables` command using the ID of the subnet returned in the previous step to describe the routes of the VPC route table associated with the selected subnet: ``` aws ec2 describe-route-tables --region --filters Name=association.subnet-id,Values= --query 'RouteTables[*].Routes[]' ``` - If the command returns the route table associated with the database instance subnet ID, check the values of the `GatewayId` and `DestinationCidrBlock` attributes returned in the output. If the route table contains any entries with the `GatewayId` value set to `igw-xxxxxxxx` and the `DestinationCidrBlock` value set to `0.0.0.0/0`, the selected RDS database instance was provisioned within a public subnet. - Or, if the command returns empty results, the route table is implicitly associated with the subnet; therefore, the audit process continues with the next step. 7. Run the `describe-db-instances` command again using the RDS database instance identifier that you want to check, along with the appropriate filtering to describe the VPC ID associated with the selected instance: ``` aws rds describe-db-instances --region --db-instance-identifier --query 'DBInstances[*].DBSubnetGroup.VpcId' ``` - The command output should show the VPC ID in the selected database subnet group. 8. Now run the `describe-route-tables` command using the ID of the VPC returned in the previous step to describe the routes of the VPC's main route table that is implicitly associated with the selected subnet: ``` aws ec2 describe-route-tables --region --filters Name=vpc-id,Values= Name=association.main,Values=true --query 'RouteTables[*].Routes[]' ``` - The command output returns the VPC main route table implicitly associated with the database instance subnet ID. Check the values of the `GatewayId` and `DestinationCidrBlock` attributes returned in the output. If the route table contains any entries with the `GatewayId` value set to `igw-xxxxxxxx` and the `DestinationCidrBlock` value set to `0.0.0.0/0`, the selected RDS database instance was provisioned inside a public subnet; therefore, it is not running within a logically isolated environment and does not adhere to AWS security best practices.",
+ "AdditionalInformation": "",
+ "References": "https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.html:https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Scenario2.html:https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.WorkingWithRDSInstanceinaVPC.html:https://aws.amazon.com/rds/faqs/",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "3.2.4",
+ "Description": "Ensure Multi-AZ deployments are used for enhanced availability in Amazon RDS",
+ "Checks": [
+ "rds_cluster_multi_az",
+ "rds_instance_multi_az"
+ ],
+ "Attributes": [
+ {
+ "Section": "3 Storage",
+ "SubSection": "3.2 Relational Database Service (RDS)",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Manual",
+ "Description": "Amazon RDS offers Multi-AZ deployments that provide enhanced availability and durability for your databases, using synchronous replication to replicate data to a standby instance in a different Availability Zone (AZ). In the event of an infrastructure failure, Amazon RDS automatically fails over to the standby to minimize downtime and ensure business continuity.",
+ "RationaleStatement": "Database availability is crucial for maintaining service uptime, particularly for applications that are critical to the business. Implementing Multi-AZ deployments with Amazon RDS ensures that your databases are protected against unplanned outages due to hardware failures, network issues, or other disruptions. This configuration enhances both the availability and durability of your database, making it a highly recommended practice for production environments.",
+ "ImpactStatement": "Multi-AZ deployments may increase costs due to the additional resources required to maintain a standby instance; however, the benefits of increased availability and reduced risk of downtime outweigh these costs for critical applications.",
+ "RemediationProcedure": "**From Console:** 1. Login to the AWS Management Console and open the RDS dashboard at [AWS RDS Console](https://console.aws.amazon.com/rds/). 2. In the left navigation pane, click on `Databases`. 3. Select the database instance that needs Multi-AZ deployment to be enabled. 4. Click the `Modify` button at the top right. 5. Scroll down to the `Availability & Durability` section. 6. Under `Multi-AZ deployment`, select `Yes` to enable. 7. Review the changes and click `Continue`. 8. On the `Review` page, choose `Apply immediately` to make the change without waiting for the next maintenance window, or `Apply during the next scheduled maintenance window`. 9. Click `Modify DB Instance` to apply the changes. **From Command Line:** 1. Run the following command to modify the RDS instance and enable Multi-AZ: ``` aws rds modify-db-instance --region --db-instance-identifier --multi-az --apply-immediately ``` 2. Confirm that the Multi-AZ deployment is enabled by running the following command: ``` aws rds describe-db-instances --region --db-instance-identifier --query 'DBInstances[*].MultiAZ' ``` - The output should return `True`, indicating that Multi-AZ is enabled. 3. Repeat the procedure for other instances as necessary.",
+ "AuditProcedure": "**From Console:** 1. Login to the AWS Management Console and open the RDS dashboard at [AWS RDS Console](https://console.aws.amazon.com/rds/). 2. In the navigation pane, under `Databases`, select the RDS instance you want to examine. 3. Click the `Instance Name` to see details, then navigate to the `Configuration` tab. 4. Under the `Availability & Durability` section, check the `Multi-AZ` status. - If Multi-AZ deployment is enabled, it will display `Yes`. - If it is disabled, the status will display `No`. 5. Repeat steps 2-4 to verify the Multi-AZ status of other RDS instances in the same region. 6. Change the region from the top of the navigation bar and repeat the audit for other regions. **From Command Line:** 1. Run the following command to list all RDS instances in the selected AWS region: ``` aws rds describe-db-instances --region --query 'DBInstances[*].DBInstanceIdentifier' ``` 2. Run the following command using the instance identifier returned earlier to check the Multi-AZ status: ``` aws rds describe-db-instances --region --db-instance-identifier --query 'DBInstances[*].MultiAZ' ``` - If the output is `True`, Multi-AZ is enabled. - If the output is `False`, Multi-AZ is not enabled. 3. Repeat steps 1 and 2 to audit each RDS instance, and change regions to verify in other regions.",
+ "AdditionalInformation": "",
+ "References": "",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "3.3.1",
+ "Description": "Ensure that encryption is enabled for EFS file systems",
+ "Checks": [
+ "efs_encryption_at_rest_enabled"
+ ],
+ "Attributes": [
+ {
+ "Section": "3 Storage",
+ "SubSection": "3.3 Elastic File System (EFS)",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Automated",
+ "Description": "EFS data should be encrypted at rest using AWS KMS (Key Management Service).",
+ "RationaleStatement": "Data should be encrypted at rest to reduce the risk of a data breach via direct access to the storage device.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "**It is important to note that EFS file system data-at-rest encryption must be turned on when creating the file system. If an EFS file system has been created without data-at-rest encryption enabled, then you must create another EFS file system with the correct configuration and transfer the data.** **Steps to create an EFS file system with data encrypted at rest:** **From Console:** 1. Login to the AWS Management Console and Navigate to the `Elastic File System (EFS)` dashboard. 2. Select `File Systems` from the left navigation panel. 3. Click the `Create File System` button from the dashboard top menu to start the file system setup process. 4. On the `Configure file system access` configuration page, perform the following actions: - Choose an appropriate VPC from the VPC dropdown list. - Within the `Create mount targets` section, check the boxes for all of the Availability Zones (AZs) within the selected VPC. These will be your mount targets. - Click `Next step` to continue. 5. Perform the following on the `Configure optional settings` page: - Create `tags` to describe your new file system. - Choose `performance mode` based on your requirements. - Check the `Enable encryption` box and choose `aws/elasticfilesystem` from the `Select KMS master key` dropdown list to enable encryption for the new file system, using the default master key provided and managed by AWS KMS. - Click `Next step` to continue. 6. Review the file system configuration details on the `review and create` page and then click `Create File System` to create your new AWS EFS file system. 7. Copy the data from the old unencrypted EFS file system onto the newly created encrypted file system. 8. Remove the unencrypted file system as soon as your data migration to the newly created encrypted file system is completed. 9. Change the AWS region from the navigation bar and repeat the entire process for the other AWS regions. **From CLI:** 1. Run the `describe-file-systems` command to view the configuration information for the selected unencrypted file system identified in the Audit steps: ``` aws efs describe-file-systems --region --file-system-id ``` 2. The command output should return the configuration information. 3. To provision a new AWS EFS file system, you need to generate a universally unique identifier (UUID) to create the token required by the `create-file-system` command. To create the required token, you can use a randomly generated UUID from https://www.uuidgenerator.net. 4. Run the `create-file-system` command using the unique token created at the previous step: ``` aws efs create-file-system --region --creation-token --performance-mode generalPurpose --encrypted ``` 5. The command output should return the new file system configuration metadata. 6. Run the `create-mount-target` command using the EFS file system ID returned from step 4 as the identifier and the ID of the Availability Zone (AZ) that will represent the mount target: ``` aws efs create-mount-target --region --file-system-id --subnet-id ``` 7. The command output should return the new mount target metadata. 8. Now you can mount your file system from an EC2 instance. 9. Copy the data from the old unencrypted EFS file system to the newly created encrypted file system. 10. Remove the unencrypted file system as soon as your data migration to the newly created encrypted file system is completed: ``` aws efs delete-file-system --region --file-system-id ``` 11. Change the AWS region by updating the --region and repeat the entire process for the other AWS regions.",
+ "AuditProcedure": "**From Console:** 1. Login to the AWS Management Console and Navigate to the Elastic File System (EFS) dashboard. 2. Select `File Systems` from the left navigation panel. 3. Each item on the list has a visible Encrypted field that displays data at rest encryption status. 4. Validate that this field reads `Encrypted` for all EFS file systems in all AWS regions. **From CLI:** 1. Run the `describe-file-systems` command using custom query filters to list the identifiers of all AWS EFS file systems currently available within the selected region: ``` aws efs describe-file-systems --region --output table --query 'FileSystems[*].FileSystemId' ``` 2. The command output should return a table with the requested file system IDs. 3. Run the `describe-file-systems` command using the ID of the file system that you want to examine as `file-system-id` and the necessary query filters: ``` aws efs describe-file-systems --region --file-system-id --query 'FileSystems[*].Encrypted' ``` 4. The command output should return the file system encryption status as `true` or `false`. If the returned value is `false`, the selected AWS EFS file system is not encrypted and if the returned value is `true`, the selected AWS EFS file system is encrypted.",
+ "AdditionalInformation": "",
+ "References": "https://docs.aws.amazon.com/efs/latest/ug/encryption-at-rest.html:https://awscli.amazonaws.com/v2/documentation/api/latest/reference/efs/index.html#efs",
+ "DefaultValue": "EFS file system data is encrypted at rest by default when creating a file system through the Console. However, encryption at rest is not enabled by default when creating a new file system using the AWS CLI, API, or SDKs."
+ }
+ ]
+ },
+ {
+ "Id": "4.1",
+ "Description": "Ensure CloudTrail is enabled in all regions",
+ "Checks": [
+ "cloudtrail_multi_region_enabled"
+ ],
+ "Attributes": [
+ {
+ "Section": "4 Logging",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Manual",
+ "Description": "AWS CloudTrail is a web service that records AWS API calls for your account and delivers log files to you. The recorded information includes the identity of the API caller, the time of the API call, the source IP address of the API caller, the request parameters, and the response elements returned by the AWS service. CloudTrail provides a history of AWS API calls for an account, including API calls made via the Management Console, SDKs, command line tools, and higher-level AWS services (such as CloudFormation).",
+ "RationaleStatement": "The AWS API call history produced by CloudTrail enables security analysis, resource change tracking, and compliance auditing. Additionally, - ensuring that a multi-region trail exists will help detect unexpected activity occurring in otherwise unused regions - ensuring that a multi-region trail exists will ensure that `Global Service Logging` is enabled for a trail by default to capture recordings of events generated on AWS global services - for a multi-region trail, ensuring that management events are configured for all types of Read/Writes ensures the recording of management operations that are performed on all resources in an AWS account",
+ "ImpactStatement": "S3 lifecycle features can be used to manage the accumulation and management of logs over time. See the following AWS resource for more information on these features: 1. https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lifecycle-mgmt.html",
+ "RemediationProcedure": "Perform the following to enable global (Multi-region) CloudTrail logging: **From Console:** 1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/cloudtrail](https://console.aws.amazon.com/cloudtrail). 2. Click on `Trails` in the left navigation pane. 3. Click `Get Started Now` if it is presented, then: - Click `Add new trail`. - Enter a trail name in the `Trail name` box. - A trail created in the console is a multi-region trail by default. - Specify an S3 bucket name in the `S3 bucket` box. - Specify the AWS KMS alias under the `Log file SSE-KMS encryption` section, or create a new key. - Click `Next`. 4. Ensure the `Management events` check box is selected. 5. Ensure both `Read` and `Write` are checked under API activity. 6. Click `Next`. 7. Review your trail settings and click `Create trail`. **From Command Line:** Create a multi-region trail: ``` aws cloudtrail create-trail --name --bucket-name --is-multi-region-trail ``` Enable multi-region on an existing trail: ``` aws cloudtrail update-trail --name --is-multi-region-trail ``` **Note:** Creating a CloudTrail trail via the CLI without providing any overriding options configures all `read` and `write` `Management Events` to be logged by default.",
+ "AuditProcedure": "Perform the following to determine if CloudTrail is enabled for all regions: **From Console:** 1. Sign in to the AWS Management Console and open the CloudTrail console at [https://console.aws.amazon.com/cloudtrail](https://console.aws.amazon.com/cloudtrail) 2. Click on `Trails` in the left navigation pane - You will be presented with a list of trails across all regions 3. Ensure that at least one Trail has `Yes` specified in the `Multi-region trail` column 4. Click on a trail via the link in the `Name` column 5. Ensure `Logging` is set to `ON` 6. Ensure `Multi-region trail` is set to `Yes` 7. In the section `Management Events`, ensure that `API activity` set to `ALL` **From Command Line:** 1. List all trails: ``` aws cloudtrail describe-trails ``` 2. Ensure `IsMultiRegionTrail` is set to `true`: ``` aws cloudtrail get-trail-status --name ``` 3. Ensure `IsLogging` is set to `true`: ``` aws cloudtrail get-event-selectors --trail-name ``` 4. Ensure there is at least one `fieldSelector` for a trail that equals `Management`: - This should NOT output any results for Field: readOnly. If either `true` or `false` is returned, one of the checkboxes (`read` or `write`) is not selected. Example of correct output: ``` TrailARN: , AdvancedEventSelectors: [ { Name: Management events selector, FieldSelectors: [ { Field: eventCategory, Equals: [ Management ] ```",
+ "AdditionalInformation": "",
+ "References": "https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-concepts.html#cloudtrail-concepts-management-events:https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-management-and-data-events-with-cloudtrail.html?icmpid=docs_cloudtrail_console#logging-management-events:https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-supported-services.html#cloud-trail-supported-services-data-events",
+ "DefaultValue": "Not Enabled"
+ }
+ ]
+ },
+ {
+ "Id": "4.2",
+ "Description": "Ensure CloudTrail log file validation is enabled",
+ "Checks": [
+ "cloudtrail_log_file_validation_enabled"
+ ],
+ "Attributes": [
+ {
+ "Section": "4 Logging",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Automated",
+ "Description": "CloudTrail log file validation creates a digitally signed digest file containing a hash of each log that CloudTrail writes to S3. These digest files can be used to determine whether a log file was changed, deleted, or remained unchanged after CloudTrail delivered the log. It is recommended that file validation be enabled for all CloudTrails.",
+ "RationaleStatement": "Enabling log file validation will provide additional integrity checks for CloudTrail logs.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "Perform the following to enable log file validation on a given trail: **From Console:** 1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/cloudtrail](https://console.aws.amazon.com/cloudtrail). 2. Click on `Trails` in the left navigation pane. 3. Click on the target trail. 4. Within the `General details` section, click `edit`. 5. Under `Advanced settings`, check the `enable` box under `Log file validation`. 6. Click `Save changes`. **From Command Line:** Enable log file validation on a trail: ``` aws cloudtrail update-trail --name --enable-log-file-validation ``` Note that periodic validation of logs using these digests can be carried out by running the following command: ``` aws cloudtrail validate-logs --trail-arn --start-time --end-time ```",
+ "AuditProcedure": "Perform the following on each trail to determine if log file validation is enabled: **From Console:** 1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/cloudtrail](https://console.aws.amazon.com/cloudtrail). 2. Click on `Trails` in the left navigation pane. 3. For every trail: - Click on a trail via the link in the `Name` column. - Under the `General details` section, ensure `Log file validation` is set to `Enabled`. **From Command Line:** List all trails: ``` aws cloudtrail describe-trails ``` Ensure `LogFileValidationEnabled` is set to `true` for each trail.",
+ "AdditionalInformation": "",
+ "References": "https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-log-file-validation-enabling.html",
+ "DefaultValue": "Not Enabled"
+ }
+ ]
+ },
+ {
+ "Id": "4.3",
+ "Description": "Ensure AWS Config is enabled in all regions",
+ "Checks": [
+ "config_recorder_all_regions_enabled"
+ ],
+ "ConfigRequirements": [
+ {
+ "Check": "config_recorder_all_regions_enabled",
+ "ConfigKey": "mute_non_default_regions",
+ "Operator": "eq",
+ "Value": false
+ }
+ ],
+ "Attributes": [
+ {
+ "Section": "4 Logging",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Automated",
+ "Description": "AWS Config is a web service that performs configuration management of supported AWS resources within your account and delivers log files to you. The recorded information includes the configuration items (AWS resources), relationships between configuration items (AWS resources), and any configuration changes between resources. It is recommended that AWS Config be enabled in all regions.",
+ "RationaleStatement": "The AWS configuration item history captured by AWS Config enables security analysis, resource change tracking, and compliance auditing.",
+ "ImpactStatement": "Enabling AWS Config in all regions provides comprehensive visibility into resource configurations, enhancing security and compliance monitoring. However, this may incur additional costs and require proper configuration management.",
+ "RemediationProcedure": "To implement AWS Config configuration: **From Console:** 1. Select the region you want to focus on in the top right of the console. 2. Click `Services`. 3. Click `Config`. 4. If a Config Recorder is enabled in this region, navigate to the Settings page from the navigation menu on the left-hand side. If a Config Recorder is not yet enabled in this region, select Get Started. 5. Select Record all resources supported in this region. 6. Choose to include global resources (IAM resources). 7. Specify an S3 bucket in the same account or in another managed AWS account. 8. Create an SNS Topic from the same AWS account or another managed AWS account. **From Command Line:** 1. Ensure there is an appropriate S3 bucket, SNS topic, and IAM role per the [AWS Config Service prerequisites](http://docs.aws.amazon.com/config/latest/developerguide/gs-cli-prereq.html). 2. Run this command to create a new configuration recorder: ``` aws configservice put-configuration-recorder --configuration-recorder name=,roleARN=arn:aws:iam:::role/ --recording-group allSupported=true,includeGlobalResourceTypes=true ``` 3. Create a delivery channel configuration file locally which specifies the channel attributes, populated from the prerequisites set up previously: ``` { name: , s3BucketName: , snsTopicARN: arn:aws:sns:::, configSnapshotDeliveryProperties: { deliveryFrequency: Twelve_Hours } } ``` 4. Run this command to create a new delivery channel, referencing the json configuration file made in the previous step: ``` aws configservice put-delivery-channel --delivery-channel file://.json ``` 5. Start the configuration recorder by running the following command: ``` aws configservice start-configuration-recorder --configuration-recorder-name ```",
+ "AuditProcedure": "Process to evaluate AWS Config configuration per region: **From Console:** 1. Sign in to the AWS Management Console and open the AWS Config console at [https://console.aws.amazon.com/config/](https://console.aws.amazon.com/config/). 1. On the top right of the console select the target region. 1. If a Config Recorder is enabled in this region, you should navigate to the Settings page from the navigation menu on the left-hand side. If a Config Recorder is not yet enabled in this region, proceed to the remediation steps. 1. Ensure Record all resources supported in this region is checked. 1. Ensure Include global resources (e.g., AWS IAM resources) is checked, unless it is enabled in another region (this is only required in one region). 1. Ensure the correct S3 bucket has been defined. 1. Ensure the correct SNS topic has been defined. 1. Repeat steps 2 to 7 for each region. **From Command Line:** 1. Run this command to show all AWS Config Recorders and their properties: ``` aws configservice describe-configuration-recorders ``` 2. Evaluate the output to ensure that all recorders have a `recordingGroup` object which includes `allSupported: true`. Additionally, ensure that at least one recorder has `includeGlobalResourceTypes: true`. **Note:** There is one more parameter, ResourceTypes, in the recordingGroup object. We don't need to check it, as whenever we set allSupported to true, AWS enforces the resource types to be empty (ResourceTypes: []). Sample output: ``` { ConfigurationRecorders: [ { recordingGroup: { allSupported: true, resourceTypes: [], includeGlobalResourceTypes: true }, roleARN: arn:aws:iam:::role/service-role/, name: default } ] } ``` 3. Run this command to show the status for all AWS Config Recorders: ``` aws configservice describe-configuration-recorder-status ``` 4. In the output, find recorders with `name` key matching the recorders that were evaluated in step 2. Ensure that they include `recording: true` and `lastStatus: SUCCESS`.",
+ "AdditionalInformation": "",
+ "References": "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/describe-configuration-recorder-status.html:https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/describe-configuration-recorders.html:https://docs.aws.amazon.com/config/latest/developerguide/gs-cli-prereq.html",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "4.4",
+ "Description": "Ensure that server access logging is enabled on the CloudTrail S3 bucket",
+ "Checks": [
+ "cloudtrail_logs_s3_bucket_access_logging_enabled"
+ ],
+ "Attributes": [
+ {
+ "Section": "4 Logging",
+ "Profile": "Level 1",
+ "AssessmentStatus": "Manual",
+ "Description": "Server access logging generates a log that contains access records for each request made to your S3 bucket. An access log record contains details about the request, such as the request type, the resources specified in the request worked, and the time and date the request was processed. It is recommended that server access logging be enabled on the CloudTrail S3 bucket.",
+ "RationaleStatement": "By enabling server access logging on target S3 buckets, it is possible to capture all events that may affect objects within any target bucket. Configuring the logs to be placed in a separate bucket allows access to log information that can be useful in security and incident response workflows.",
+ "ImpactStatement": "",
+ "RemediationProcedure": "Perform the following to enable server access logging: **From Console:** 1. Sign in to the AWS Management Console and open the S3 console at [https://console.aws.amazon.com/s3](https://console.aws.amazon.com/s3). 2. Under `All Buckets` click on the target S3 bucket. 3. Click on `Properties` in the top right of the console. 4. Under `Bucket: `, click `Logging`. 5. Configure bucket logging: - Check the `Enabled` box. - Select a Target Bucket from the list. - Enter a Target Prefix. 6. Click `Save`. **From Command Line:** 1. Get the name of the S3 bucket that CloudTrail is logging to: ``` aws cloudtrail describe-trails --region --query trailList[*].S3BucketName ``` 2. Copy and add the target bucket name at ``, the prefix for the log file at ``, and optionally add an email address in the following template, then save it as `.json`: ``` { LoggingEnabled: { TargetBucket: , TargetPrefix: , TargetGrants: [ { Grantee: { Type: AmazonCustomerByEmail, EmailAddress: }, Permission: FULL_CONTROL } ] } } ``` 3. Run the `put-bucket-logging` command with bucket name and `.json` as input; for more information, refer to [put-bucket-logging](https://docs.aws.amazon.com/cli/latest/reference/s3api/put-bucket-logging.html): ``` aws s3api put-bucket-logging --bucket --bucket-logging-status file://.json ```",
+ "AuditProcedure": "Perform the following ensure that the CloudTrail S3 bucket has access logging is enabled: **From Console:** 1. Go to the Amazon CloudTrail console at [https://console.aws.amazon.com/cloudtrail/home](https://console.aws.amazon.com/cloudtrail/home). 2. In the API activity history pane on the left, click `Trails`. 3. In the Trails pane, note the bucket names in the S3 bucket column. 4. Sign in to the AWS Management Console and open the S3 console at [https://console.aws.amazon.com/s3](https://console.aws.amazon.com/s3). 5. Under `All Buckets` click on a target S3 bucket. 6. Click on `Properties` in the top right of the console. 7. Under `Bucket: `, click `Logging`. 8. Ensure `Enabled` is checked. **From Command Line:** 1. Get the name of the S3 bucket that CloudTrail is logging to: ``` aws cloudtrail describe-trails --query 'trailList[*].S3BucketName' ``` 2. Ensure logging is enabled on the bucket: ``` aws s3api get-bucket-logging --bucket ``` Ensure the command does not return an empty output. Sample output for a bucket with logging enabled: ``` { LoggingEnabled: { TargetPrefix: , TargetBucket: } } ```",
+ "AdditionalInformation": "",
+ "References": "https://docs.aws.amazon.com/AmazonS3/latest/dev/ServerLogs.html:https://docs.aws.amazon.com/AmazonS3/latest/userguide/enable-server-access-logging.html",
+ "DefaultValue": "Logging is disabled."
+ }
+ ]
+ },
+ {
+ "Id": "4.5",
+ "Description": "Ensure CloudTrail logs are encrypted at rest using KMS CMKs",
+ "Checks": [
+ "cloudtrail_kms_encryption_enabled"
+ ],
+ "Attributes": [
+ {
+ "Section": "4 Logging",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Automated",
+ "Description": "AWS CloudTrail is a web service that records AWS API calls for an account and makes those logs available to users and resources in accordance with IAM policies. AWS Key Management Service (KMS) is a managed service that helps create and control the encryption keys used to encrypt account data, and uses Hardware Security Modules (HSMs) to protect the security of encryption keys. CloudTrail logs can be configured to leverage server side encryption (SSE) and KMS customer-created master keys (CMK) to further protect CloudTrail logs. It is recommended that CloudTrail be configured to use SSE-KMS.",
+ "RationaleStatement": "Configuring CloudTrail to use SSE-KMS provides additional confidentiality controls on log data, as a given user must have S3 read permission on the corresponding log bucket and must be granted decrypt permission by the CMK policy.",
+ "ImpactStatement": "Customer-created keys incur an additional cost. See https://aws.amazon.com/kms/pricing/ for more information.",
+ "RemediationProcedure": "Perform the following to configure CloudTrail to use SSE-KMS: **From Console:** 1. Sign in to the AWS Management Console and open the CloudTrail console at [https://console.aws.amazon.com/cloudtrail](https://console.aws.amazon.com/cloudtrail). 2. In the left navigation pane, choose `Trails`. 3. Click on a trail. 4. Under the `S3` section, click the edit button (pencil icon). 5. Click `Advanced`. 6. Select an existing CMK from the `KMS key Id` drop-down menu. - **Note:** Ensure the CMK is located in the same region as the S3 bucket. - **Note:** You will need to apply a KMS key policy on the selected CMK in order for CloudTrail, as a service, to encrypt and decrypt log files using the CMK provided. View the AWS documentation for [editing the selected CMK Key policy](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/create-kms-key-policy-for-cloudtrail.html). 7. Click `Save`. 8. You will see a notification message stating that you need to have decryption permissions on the specified KMS key to decrypt log files. 9. Click `Yes`. **From Command Line:** Run the following command to specify a KMS key ID to use with a trail: ``` aws cloudtrail update-trail --name --kms-key-id ``` Run the following command to attach a key policy to a specified KMS key: ``` aws kms put-key-policy --key-id --policy ```",
+ "AuditProcedure": "Perform the following to determine if CloudTrail is configured to use SSE-KMS: **From Console:** 1. Sign in to the AWS Management Console and open the CloudTrail console at [https://console.aws.amazon.com/cloudtrail](https://console.aws.amazon.com/cloudtrail). 2. In the left navigation pane, choose `Trails`. 3. Select a trail. 4. In the `General details` section, select `Edit` to edit the trail configuration. 5. Ensure the box at `Log file SSE-KMS encryption` is checked and that a valid `AWS KMS alias` of a KMS key is entered in the respective text box. **From Command Line:** 1. Run the following command: ``` aws cloudtrail describe-trails ``` 2. For each trail listed, SSE-KMS is enabled if the trail has a `KmsKeyId` property defined.",
+ "AdditionalInformation": "Three statements that need to be added to the CMK policy: 1. Enable CloudTrail to describe CMK properties: ``` { \"Sid\": \"Allow CloudTrail access\", \"Effect\": \"Allow\", \"Principal\": { \"Service\": \"cloudtrail.amazonaws.com\" }, \"Action\": \"kms:DescribeKey\", \"Resource\": \"*\" } ``` 2. Granting encrypt permissions: ``` { \"Sid\": \"Allow CloudTrail to encrypt logs\", \"Effect\": \"Allow\", \"Principal\": { \"Service\": \"cloudtrail.amazonaws.com\" }, \"Action\": \"kms:GenerateDataKey*\", \"Resource\": \"*\", \"Condition\": { \"StringLike\": { \"kms:EncryptionContext:aws:cloudtrail:arn\": [ \"arn:aws:cloudtrail:*:aws-account-id:trail/*\" ] } } } ``` 3. Granting decrypt permissions: ``` { \"Sid\": \"Enable CloudTrail log decrypt permissions\", \"Effect\": \"Allow\", \"Principal\": { \"AWS\": \"arn:aws:iam::aws-account-id:user/username\" }, \"Action\": \"kms:Decrypt\", \"Resource\": \"*\", \"Condition\": { \"Null\": { \"kms:EncryptionContext:aws:cloudtrail:arn\": \"false\" } } } ```",
+ "References": "https://docs.aws.amazon.com/awscloudtrail/latest/userguide/encrypting-cloudtrail-log-files-with-aws-kms.html:https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html:CCE-78919-8:https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/update-trail.html:https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/put-key-policy.html",
+ "DefaultValue": "By default, CloudTrail logs are not encrypted with a KMS CMK. Logs may be encrypted with SSE-S3, but this does not provide the same level of control or auditing as KMS CMKs."
+ }
+ ]
+ },
+ {
+ "Id": "4.6",
+ "Description": "Ensure rotation for customer-created symmetric CMKs is enabled",
+ "Checks": [
+ "kms_cmk_rotation_enabled"
+ ],
+ "Attributes": [
+ {
+ "Section": "4 Logging",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Automated",
+ "Description": "AWS Key Management Service (KMS) allows customers to rotate the backing key, which is key material stored within the KMS that is tied to the key ID of the customer-created customer master key (CMK). The backing key is used to perform cryptographic operations such as encryption and decryption. Automated key rotation currently retains all prior backing keys so that decryption of encrypted data can occur transparently. It is recommended that CMK key rotation be enabled for symmetric keys. Key rotation cannot be enabled for any asymmetric CMK.",
+ "RationaleStatement": "Rotating encryption keys helps reduce the potential impact of a compromised key, as data encrypted with a new key cannot be accessed with a previous key that may have been exposed. Keys should be rotated every year or upon an event that could result in the compromise of that key.",
+ "ImpactStatement": "Creation, management, and storage of CMKs may require additional time from an administrator.",
+ "RemediationProcedure": "**From Console:** 1. Sign in to the AWS Management Console and open the KMS console at: [https://console.aws.amazon.com/kms](https://console.aws.amazon.com/kms). 2. In the left navigation pane, click `Customer-managed keys`. 3. Select a key with `Key spec = SYMMETRIC_DEFAULT` that does not have automatic rotation enabled. 4. Select the `Key rotation` tab. 5. Check the `Automatically rotate this KMS key every year` box. 6. Click `Save`. 7. Repeat steps 3–6 for all customer-managed CMKs that do not have automatic rotation enabled. **From Command Line:** 1. Run the following command to enable key rotation: ``` aws kms enable-key-rotation --key-id ```",
+ "AuditProcedure": "**From Console:** 1. Sign in to the AWS Management Console and open the KMS console at: [https://console.aws.amazon.com/kms](https://console.aws.amazon.com/kms). 2. In the left navigation pane, click `Customer-managed keys`. 3. Select a customer-managed CMK where `Key spec = SYMMETRIC_DEFAULT`. 4. Select the `Key rotation` tab. 5. Ensure the `Automatically rotate this KMS key every year` box is checked. 6. Repeat steps 3–5 for all customer-managed CMKs where `Key spec = SYMMETRIC_DEFAULT`. **From Command Line:** 1. Run the following command to get a list of all keys and their associated `KeyIds`: ``` aws kms list-keys ``` 2. For each key, note the KeyId and run the following command: ``` describe-key --key-id ``` 3. If the response contains `KeySpec = SYMMETRIC_DEFAULT`, run the following command: ``` aws kms get-key-rotation-status --key-id ``` 4. Ensure `KeyRotationEnabled` is set to `true`. 5. Repeat steps 2–4 for all remaining CMKs.",
+ "AdditionalInformation": "",
+ "References": "https://aws.amazon.com/kms/pricing/:https://csrc.nist.gov/publications/detail/sp/800-57-part-1/rev-5/final",
+ "DefaultValue": ""
+ }
+ ]
+ },
+ {
+ "Id": "4.7",
+ "Description": "Ensure VPC flow logging is enabled in all VPCs",
+ "Checks": [
+ "vpc_flow_logs_enabled"
+ ],
+ "Attributes": [
+ {
+ "Section": "4 Logging",
+ "Profile": "Level 2",
+ "AssessmentStatus": "Automated",
+ "Description": "VPC Flow Logs is a feature that enables you to capture information about the IP traffic going to and from network interfaces in your VPC. After you've created a flow log, you can view and retrieve its data in Amazon CloudWatch Logs. It is recommended that VPC Flow Logs be enabled for packet Rejects for VPCs.",
+ "RationaleStatement": "VPC Flow Logs provide visibility into network traffic that traverses the VPC and can be used to detect anomalous traffic or gain insights during security workflows.",
+ "ImpactStatement": "By default, CloudWatch Logs will store logs indefinitely unless a specific retention period is defined for the log group. When choosing the number of days to retain, keep in mind that the average time it takes for an organization to realize they have been breached is 210 days (at the time of this writing). Since additional time is required to research a breach, a minimum retention policy of 365 days allows for detection and investigation. You may also wish to archive the logs to a cheaper storage service rather than simply deleting them. See the following AWS resource to manage CloudWatch Logs retention periods: 1. https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/SettingLogRetention.html",
+ "RemediationProcedure": "Perform the following to enable VPC Flow Logs: **From Console:** 1. Sign into the management console. 2. Select `Services`, then select `VPC`. 3. In the left navigation pane, select `Your VPCs`. 4. Select a VPC. 5. In the right pane, select the `Flow Logs` tab. 6. If no Flow Log exists, click `Create Flow Log`. 7. For Filter, select `Reject`. 8. Enter a `Role` and `Destination Log Group`. 9. Click `Create Log Flow`. 10. Click on `CloudWatch Logs Group`. **Note:** Setting the filter to Reject will dramatically reduce the accumulation of logging data for this recommendation and provide sufficient information for the purposes of breach detection, research, and remediation. However, during periods of least privilege security group engineering, setting the filter to All can be very helpful in discovering existing traffic flows required for the proper operation of an already running environment. **From Command Line:** 1. Create a policy document, name it `role_policy_document.json`, and paste the following content: ``` { Version: 2012-10-17, Statement: [ { Sid: test, Effect: Allow, Principal: { Service: ec2.amazonaws.com }, Action: sts:AssumeRole } ] } ``` 2. Create another policy document, name it `iam_policy.json`, and paste the following content: ``` { Version: 2012-10-17, Statement: [ { Effect: Allow, Action:[ logs:CreateLogGroup, logs:CreateLogStream, logs:DescribeLogGroups, logs:DescribeLogStreams, logs:PutLogEvents, logs:GetLogEvents, logs:FilterLogEvents ], Resource: * } ] } ``` 3. Run the following command to create an IAM role: ``` aws iam create-role --role-name --assume-role-policy-document file://role_policy_document.json ``` 4. Run the following command to create an IAM policy: ``` aws iam create-policy --policy-name --policy-document file://iam-policy.json ``` 5. Run the `attach-group-policy` command, using the IAM policy ARN returned from the previous step to attach the policy to the IAM role: ``` aws iam attach-group-policy --policy-arn arn:aws:iam::