From 1eda94140dc027317a1ac72f2351cbc198d3cbe0 Mon Sep 17 00:00:00 2001 From: Hugo Pereira Brito <101209179+HugoPBrito@users.noreply.github.com> Date: Mon, 23 Mar 2026 09:45:08 +0000 Subject: [PATCH 01/15] fix(sdk): use case-insensitive comparison for Azure VM backup checks (#10395) --- prowler/CHANGELOG.md | 8 ++ .../vm/vm_backup_enabled/vm_backup_enabled.py | 3 +- ...ufficient_daily_backup_retention_period.py | 3 +- .../vm_backup_enabled_test.py | 79 ++++++++++++++++ ...ient_daily_backup_retention_period_test.py | 94 +++++++++++++++++++ 5 files changed, 185 insertions(+), 2 deletions(-) diff --git a/prowler/CHANGELOG.md b/prowler/CHANGELOG.md index 9c57c2bece..a0061fb196 100644 --- a/prowler/CHANGELOG.md +++ b/prowler/CHANGELOG.md @@ -2,6 +2,14 @@ All notable changes to the **Prowler SDK** are documented in this file. +## [5.21.2] (Prowler UNRELEASED) + +### 🐞 Fixed + +- Azure `vm_backup_enabled` and `vm_sufficient_daily_backup_retention_period` checks now compare VM names case-insensitively to avoid false negatives when Azure stores backup item names in a different case [(#10373)](https://github.com/prowler-cloud/prowler/pull/10373) + +--- + ## [5.21.0] (Prowler v5.21.0) ### 🚀 Added diff --git a/prowler/providers/azure/services/vm/vm_backup_enabled/vm_backup_enabled.py b/prowler/providers/azure/services/vm/vm_backup_enabled/vm_backup_enabled.py index e9da4662ed..d5865937f9 100644 --- a/prowler/providers/azure/services/vm/vm_backup_enabled/vm_backup_enabled.py +++ b/prowler/providers/azure/services/vm/vm_backup_enabled/vm_backup_enabled.py @@ -31,7 +31,8 @@ class vm_backup_enabled(Check): for backup_item in vault.backup_protected_items.values(): if ( backup_item.workload_type == DataSourceType.VM - and backup_item.name.split(";")[-1] == vm.resource_name + and backup_item.name.split(";")[-1].lower() + == vm.resource_name.lower() ): found = True found_vault_name = vault.name diff --git a/prowler/providers/azure/services/vm/vm_sufficient_daily_backup_retention_period/vm_sufficient_daily_backup_retention_period.py b/prowler/providers/azure/services/vm/vm_sufficient_daily_backup_retention_period/vm_sufficient_daily_backup_retention_period.py index 221df85351..444cfcfa3b 100644 --- a/prowler/providers/azure/services/vm/vm_sufficient_daily_backup_retention_period/vm_sufficient_daily_backup_retention_period.py +++ b/prowler/providers/azure/services/vm/vm_sufficient_daily_backup_retention_period/vm_sufficient_daily_backup_retention_period.py @@ -27,7 +27,8 @@ class vm_sufficient_daily_backup_retention_period(Check): for backup_item in vault.backup_protected_items.values(): if ( backup_item.workload_type == DataSourceType.VM - and backup_item.name.split(";")[-1] == vm.resource_name + and backup_item.name.split(";")[-1].lower() + == vm.resource_name.lower() ): backup_found = True policy_id = backup_item.backup_policy_id diff --git a/tests/providers/azure/services/vm/vm_backup_enabled/vm_backup_enabled_test.py b/tests/providers/azure/services/vm/vm_backup_enabled/vm_backup_enabled_test.py index 23394addca..a99be2ea54 100644 --- a/tests/providers/azure/services/vm/vm_backup_enabled/vm_backup_enabled_test.py +++ b/tests/providers/azure/services/vm/vm_backup_enabled/vm_backup_enabled_test.py @@ -221,6 +221,85 @@ class Test_vm_backup_enabled: == f"VM {vm_name} in subscription {AZURE_SUBSCRIPTION_ID} is not protected by Azure Backup." ) + def test_vm_protected_by_backup_case_insensitive(self): + vm_id = str(uuid4()) + vm_name = "vmtest" + vault_id = str(uuid4()) + vault_name = "vault1" + mock_vm_client = mock.MagicMock() + mock_recovery_client = mock.MagicMock() + with ( + mock.patch( + "prowler.providers.common.provider.Provider.get_global_provider", + return_value=set_mocked_azure_provider(), + ), + mock.patch( + "prowler.providers.azure.services.vm.vm_backup_enabled.vm_backup_enabled.vm_client", + new=mock_vm_client, + ), + mock.patch( + "prowler.providers.azure.services.vm.vm_backup_enabled.vm_backup_enabled.recovery_client", + new=mock_recovery_client, + ), + ): + from azure.mgmt.recoveryservicesbackup.activestamp.models import ( + DataSourceType, + ) + + from prowler.providers.azure.services.recovery.recovery_service import ( + BackupItem, + BackupVault, + ) + from prowler.providers.azure.services.vm.vm_backup_enabled.vm_backup_enabled import ( + vm_backup_enabled, + ) + from prowler.providers.azure.services.vm.vm_service import ( + ManagedDiskParameters, + OSDisk, + StorageProfile, + VirtualMachine, + ) + + vm = VirtualMachine( + resource_id=vm_id, + resource_name=vm_name, + location="eastus", + security_profile=None, + extensions=[], + storage_profile=StorageProfile( + os_disk=OSDisk( + name="os_disk_name", + operating_system_type="Linux", + managed_disk=ManagedDiskParameters(id="managed_disk_id"), + ), + data_disks=[], + ), + ) + backup_item = BackupItem( + id=str(uuid4()), + name="someprefix;VMTEST", + workload_type=DataSourceType.VM, + ) + vault = BackupVault( + id=vault_id, + name=vault_name, + location="eastus", + backup_protected_items={backup_item.id: backup_item}, + ) + mock_vm_client.virtual_machines = {AZURE_SUBSCRIPTION_ID: {vm_id: vm}} + mock_recovery_client.vaults = {AZURE_SUBSCRIPTION_ID: {vault_id: vault}} + check = vm_backup_enabled() + result = check.execute() + assert len(result) == 1 + assert result[0].status == "PASS" + assert result[0].subscription == AZURE_SUBSCRIPTION_ID + assert result[0].resource_name == vm_name + assert result[0].resource_id == vm_id + assert ( + result[0].status_extended + == f"VM {vm_name} in subscription {AZURE_SUBSCRIPTION_ID} is protected by Azure Backup (vault: {vault_name})." + ) + def test_vm_protected_by_backup_non_vm_workload(self): vm_id = str(uuid4()) vm_name = "VMTest" diff --git a/tests/providers/azure/services/vm/vm_sufficient_daily_backup_retention_period/vm_sufficient_daily_backup_retention_period_test.py b/tests/providers/azure/services/vm/vm_sufficient_daily_backup_retention_period/vm_sufficient_daily_backup_retention_period_test.py index b43b75548a..28aab1b38b 100644 --- a/tests/providers/azure/services/vm/vm_sufficient_daily_backup_retention_period/vm_sufficient_daily_backup_retention_period_test.py +++ b/tests/providers/azure/services/vm/vm_sufficient_daily_backup_retention_period/vm_sufficient_daily_backup_retention_period_test.py @@ -156,6 +156,100 @@ class Test_vm_sufficient_daily_backup_retention_period: in result[0].status_extended ) + def test_vm_with_sufficient_retention_case_insensitive(self): + from azure.mgmt.recoveryservicesbackup.activestamp.models import DataSourceType + + from prowler.providers.azure.services.recovery.recovery_service import ( + BackupItem, + BackupPolicy, + BackupVault, + ) + from prowler.providers.azure.services.vm.vm_service import ( + ManagedDiskParameters, + OSDisk, + StorageProfile, + VirtualMachine, + ) + + vm_id = str(uuid4()) + vm_name = "vmtest" + vault_id = str(uuid4()) + policy_id = str(uuid4()) + retention_days = 14 + min_retention_days = 7 + + vm = VirtualMachine( + resource_id=vm_id, + resource_name=vm_name, + location="eastus", + security_profile=None, + extensions=[], + storage_profile=StorageProfile( + os_disk=OSDisk( + name="os_disk_name", + operating_system_type="Linux", + managed_disk=ManagedDiskParameters(id="managed_disk_id"), + ), + data_disks=[], + ), + ) + backup_item = BackupItem( + id=str(uuid4()), + name="someprefix;VMTEST", + workload_type=DataSourceType.VM, + backup_policy_id=policy_id, + ) + backup_policy = BackupPolicy( + id=policy_id, + name="policy1", + retention_days=retention_days, + ) + vault = BackupVault( + id=vault_id, + name="vault1", + location="eastus", + backup_protected_items={backup_item.id: backup_item}, + backup_policies={policy_id: backup_policy}, + ) + vm_client = mock.MagicMock() + recovery_client = mock.MagicMock() + vm_client.virtual_machines = {AZURE_SUBSCRIPTION_ID: {vm_id: vm}} + recovery_client.vaults = {AZURE_SUBSCRIPTION_ID: {vault_id: vault}} + vm_client.audit_config = { + "vm_backup_min_daily_retention_days": min_retention_days + } + with ( + mock.patch( + "prowler.providers.common.provider.Provider.get_global_provider", + return_value=set_mocked_azure_provider( + audit_config=vm_client.audit_config + ), + ), + mock.patch( + "prowler.providers.azure.services.vm.vm_sufficient_daily_backup_retention_period.vm_sufficient_daily_backup_retention_period.vm_client", + new=vm_client, + ), + mock.patch( + "prowler.providers.azure.services.vm.vm_sufficient_daily_backup_retention_period.vm_sufficient_daily_backup_retention_period.recovery_client", + new=recovery_client, + ), + ): + from prowler.providers.azure.services.vm.vm_sufficient_daily_backup_retention_period.vm_sufficient_daily_backup_retention_period import ( + vm_sufficient_daily_backup_retention_period, + ) + + check = vm_sufficient_daily_backup_retention_period() + result = check.execute() + assert len(result) == 1 + assert result[0].status == "PASS" + assert result[0].subscription == AZURE_SUBSCRIPTION_ID + assert result[0].resource_name == vm_name + assert result[0].resource_id == vm_id + assert ( + f"has a daily backup retention period of {retention_days} days" + in result[0].status_extended + ) + def test_vm_with_insufficient_retention(self): from azure.mgmt.recoveryservicesbackup.activestamp.models import DataSourceType From 7df73a9d4fe66e54f1e9377e5279f21dbcb164b3 Mon Sep 17 00:00:00 2001 From: Hugo Pereira Brito <101209179+HugoPBrito@users.noreply.github.com> Date: Mon, 23 Mar 2026 09:59:14 +0000 Subject: [PATCH 02/15] fix(sdk): use case-insensitive comparison for Azure MySQL flexible server checks (#10396) --- prowler/CHANGELOG.md | 3 +- ...e_server_audit_log_connection_activated.py | 4 +- ...mysql_flexible_server_audit_log_enabled.py | 2 +- ..._flexible_server_ssl_connection_enabled.py | 5 +- ...ver_audit_log_connection_activated_test.py | 51 +++++++++++++++++++ ..._flexible_server_audit_log_enabled_test.py | 51 +++++++++++++++++++ ...ible_server_ssl_connection_enabled_test.py | 51 +++++++++++++++++++ 7 files changed, 162 insertions(+), 5 deletions(-) diff --git a/prowler/CHANGELOG.md b/prowler/CHANGELOG.md index a0061fb196..2c8b47daf4 100644 --- a/prowler/CHANGELOG.md +++ b/prowler/CHANGELOG.md @@ -6,7 +6,8 @@ All notable changes to the **Prowler SDK** are documented in this file. ### 🐞 Fixed -- Azure `vm_backup_enabled` and `vm_sufficient_daily_backup_retention_period` checks now compare VM names case-insensitively to avoid false negatives when Azure stores backup item names in a different case [(#10373)](https://github.com/prowler-cloud/prowler/pull/10373) +- Azure MySQL flexible server checks now compare configuration values case-insensitively to avoid false negatives when Azure returns lowercase values [(#10396)](https://github.com/prowler-cloud/prowler/pull/10396) +- Azure `vm_backup_enabled` and `vm_sufficient_daily_backup_retention_period` checks now compare VM names case-insensitively to avoid false negatives when Azure stores backup item names in a different case [(#10395)](https://github.com/prowler-cloud/prowler/pull/10395) --- diff --git a/prowler/providers/azure/services/mysql/mysql_flexible_server_audit_log_connection_activated/mysql_flexible_server_audit_log_connection_activated.py b/prowler/providers/azure/services/mysql/mysql_flexible_server_audit_log_connection_activated/mysql_flexible_server_audit_log_connection_activated.py index 03c94bcfed..5071da4b20 100644 --- a/prowler/providers/azure/services/mysql/mysql_flexible_server_audit_log_connection_activated/mysql_flexible_server_audit_log_connection_activated.py +++ b/prowler/providers/azure/services/mysql/mysql_flexible_server_audit_log_connection_activated/mysql_flexible_server_audit_log_connection_activated.py @@ -21,9 +21,9 @@ class mysql_flexible_server_audit_log_connection_activated(Check): "audit_log_events" ].resource_id - if "CONNECTION" in server.configurations[ + if "connection" in server.configurations[ "audit_log_events" - ].value.split(","): + ].value.lower().split(","): report.status = "PASS" report.status_extended = f"Audit log is enabled for server {server.name} in subscription {subscription_name}." diff --git a/prowler/providers/azure/services/mysql/mysql_flexible_server_audit_log_enabled/mysql_flexible_server_audit_log_enabled.py b/prowler/providers/azure/services/mysql/mysql_flexible_server_audit_log_enabled/mysql_flexible_server_audit_log_enabled.py index c8ae94fb31..81918f7756 100644 --- a/prowler/providers/azure/services/mysql/mysql_flexible_server_audit_log_enabled/mysql_flexible_server_audit_log_enabled.py +++ b/prowler/providers/azure/services/mysql/mysql_flexible_server_audit_log_enabled/mysql_flexible_server_audit_log_enabled.py @@ -21,7 +21,7 @@ class mysql_flexible_server_audit_log_enabled(Check): "audit_log_enabled" ].resource_id - if server.configurations["audit_log_enabled"].value == "ON": + if server.configurations["audit_log_enabled"].value.lower() == "on": report.status = "PASS" report.status_extended = f"Audit log is enabled for server {server.name} in subscription {subscription_name}." diff --git a/prowler/providers/azure/services/mysql/mysql_flexible_server_ssl_connection_enabled/mysql_flexible_server_ssl_connection_enabled.py b/prowler/providers/azure/services/mysql/mysql_flexible_server_ssl_connection_enabled/mysql_flexible_server_ssl_connection_enabled.py index a18a1aba5e..79930de947 100644 --- a/prowler/providers/azure/services/mysql/mysql_flexible_server_ssl_connection_enabled/mysql_flexible_server_ssl_connection_enabled.py +++ b/prowler/providers/azure/services/mysql/mysql_flexible_server_ssl_connection_enabled/mysql_flexible_server_ssl_connection_enabled.py @@ -20,7 +20,10 @@ class mysql_flexible_server_ssl_connection_enabled(Check): report.resource_id = server.configurations[ "require_secure_transport" ].resource_id - if server.configurations["require_secure_transport"].value == "ON": + if ( + server.configurations["require_secure_transport"].value.lower() + == "on" + ): report.status = "PASS" report.status_extended = f"SSL connection is enabled for server {server.name} in subscription {subscription_name}." diff --git a/tests/providers/azure/services/mysql/mysql_flexible_server_audit_log_connection_activated/mysql_flexible_server_audit_log_connection_activated_test.py b/tests/providers/azure/services/mysql/mysql_flexible_server_audit_log_connection_activated/mysql_flexible_server_audit_log_connection_activated_test.py index 84daaa758c..47ef92551b 100644 --- a/tests/providers/azure/services/mysql/mysql_flexible_server_audit_log_connection_activated/mysql_flexible_server_audit_log_connection_activated_test.py +++ b/tests/providers/azure/services/mysql/mysql_flexible_server_audit_log_connection_activated/mysql_flexible_server_audit_log_connection_activated_test.py @@ -56,6 +56,57 @@ class Test_mysql_flexible_server_audit_log_connection_activated: result = check.execute() assert len(result) == 0 + def test_mysql_audit_log_connection_activated_lowercase(self): + server_name = str(uuid4()) + mysql_client = mock.MagicMock + mysql_client.flexible_servers = { + AZURE_SUBSCRIPTION_ID: { + "/subscriptions/resource_id": FlexibleServer( + resource_id="/subscriptions/resource_id", + name=server_name, + location="location", + version="version", + configurations={ + "audit_log_events": Configuration( + resource_id=f"/subscriptions/{server_name}/configurations/audit_log_events", + description="description", + value="connection", + ) + }, + ) + } + } + + with ( + mock.patch( + "prowler.providers.common.provider.Provider.get_global_provider", + return_value=set_mocked_azure_provider(), + ), + mock.patch( + "prowler.providers.azure.services.mysql.mysql_flexible_server_audit_log_connection_activated.mysql_flexible_server_audit_log_connection_activated.mysql_client", + new=mysql_client, + ), + ): + from prowler.providers.azure.services.mysql.mysql_flexible_server_audit_log_connection_activated.mysql_flexible_server_audit_log_connection_activated import ( + mysql_flexible_server_audit_log_connection_activated, + ) + + check = mysql_flexible_server_audit_log_connection_activated() + result = check.execute() + assert len(result) == 1 + assert result[0].status == "PASS" + assert result[0].subscription == AZURE_SUBSCRIPTION_ID + assert result[0].resource_name == server_name + assert result[0].location == "location" + assert ( + result[0].resource_id + == f"/subscriptions/{server_name}/configurations/audit_log_events" + ) + assert ( + result[0].status_extended + == f"Audit log is enabled for server {server_name} in subscription {AZURE_SUBSCRIPTION_ID}." + ) + def test_mysql_audit_log_connection_not_connection(self): server_name = str(uuid4()) mysql_client = mock.MagicMock diff --git a/tests/providers/azure/services/mysql/mysql_flexible_server_audit_log_enabled/mysql_flexible_server_audit_log_enabled_test.py b/tests/providers/azure/services/mysql/mysql_flexible_server_audit_log_enabled/mysql_flexible_server_audit_log_enabled_test.py index ad243c5807..7c32f337fd 100644 --- a/tests/providers/azure/services/mysql/mysql_flexible_server_audit_log_enabled/mysql_flexible_server_audit_log_enabled_test.py +++ b/tests/providers/azure/services/mysql/mysql_flexible_server_audit_log_enabled/mysql_flexible_server_audit_log_enabled_test.py @@ -56,6 +56,57 @@ class Test_mysql_flexible_server_audit_log_enabled: result = check.execute() assert len(result) == 0 + def test_mysql_audit_log_enabled_lowercase(self): + server_name = str(uuid4()) + mysql_client = mock.MagicMock + mysql_client.flexible_servers = { + AZURE_SUBSCRIPTION_ID: { + "/subscriptions/resource_id": FlexibleServer( + resource_id="/subscriptions/resource_id", + name=server_name, + location="location", + version="version", + configurations={ + "audit_log_enabled": Configuration( + resource_id=f"/subscriptions/{server_name}/configurations/audit_log_enabled", + description="description", + value="on", + ) + }, + ) + } + } + + with ( + mock.patch( + "prowler.providers.common.provider.Provider.get_global_provider", + return_value=set_mocked_azure_provider(), + ), + mock.patch( + "prowler.providers.azure.services.mysql.mysql_flexible_server_audit_log_enabled.mysql_flexible_server_audit_log_enabled.mysql_client", + new=mysql_client, + ), + ): + from prowler.providers.azure.services.mysql.mysql_flexible_server_audit_log_enabled.mysql_flexible_server_audit_log_enabled import ( + mysql_flexible_server_audit_log_enabled, + ) + + check = mysql_flexible_server_audit_log_enabled() + result = check.execute() + assert len(result) == 1 + assert result[0].status == "PASS" + assert result[0].subscription == AZURE_SUBSCRIPTION_ID + assert result[0].resource_name == server_name + assert result[0].location == "location" + assert ( + result[0].resource_id + == f"/subscriptions/{server_name}/configurations/audit_log_enabled" + ) + assert ( + result[0].status_extended + == f"Audit log is enabled for server {server_name} in subscription {AZURE_SUBSCRIPTION_ID}." + ) + def test_mysql_audit_log_disabled(self): server_name = str(uuid4()) mysql_client = mock.MagicMock diff --git a/tests/providers/azure/services/mysql/mysql_flexible_server_ssl_connection_enabled/mysql_flexible_server_ssl_connection_enabled_test.py b/tests/providers/azure/services/mysql/mysql_flexible_server_ssl_connection_enabled/mysql_flexible_server_ssl_connection_enabled_test.py index f540fe4865..2b87a28d8f 100644 --- a/tests/providers/azure/services/mysql/mysql_flexible_server_ssl_connection_enabled/mysql_flexible_server_ssl_connection_enabled_test.py +++ b/tests/providers/azure/services/mysql/mysql_flexible_server_ssl_connection_enabled/mysql_flexible_server_ssl_connection_enabled_test.py @@ -107,6 +107,57 @@ class Test_mysql_flexible_server_ssl_connection_enabled: == f"SSL connection is enabled for server {server_name} in subscription {AZURE_SUBSCRIPTION_ID}." ) + def test_mysql_connection_enabled_lowercase(self): + server_name = str(uuid4()) + mysql_client = mock.MagicMock + mysql_client.flexible_servers = { + AZURE_SUBSCRIPTION_ID: { + "/subscriptions/resource_id": FlexibleServer( + resource_id="/subscriptions/resource_id", + name=server_name, + location="location", + version="version", + configurations={ + "require_secure_transport": Configuration( + resource_id=f"/subscriptions/{server_name}/configurations/require_secure_transport", + description="description", + value="on", + ) + }, + ) + } + } + + with ( + mock.patch( + "prowler.providers.common.provider.Provider.get_global_provider", + return_value=set_mocked_azure_provider(), + ), + mock.patch( + "prowler.providers.azure.services.mysql.mysql_flexible_server_ssl_connection_enabled.mysql_flexible_server_ssl_connection_enabled.mysql_client", + new=mysql_client, + ), + ): + from prowler.providers.azure.services.mysql.mysql_flexible_server_ssl_connection_enabled.mysql_flexible_server_ssl_connection_enabled import ( + mysql_flexible_server_ssl_connection_enabled, + ) + + check = mysql_flexible_server_ssl_connection_enabled() + result = check.execute() + assert len(result) == 1 + assert result[0].status == "PASS" + assert result[0].subscription == AZURE_SUBSCRIPTION_ID + assert result[0].resource_name == server_name + assert result[0].location == "location" + assert ( + result[0].resource_id + == f"/subscriptions/{server_name}/configurations/require_secure_transport" + ) + assert ( + result[0].status_extended + == f"SSL connection is enabled for server {server_name} in subscription {AZURE_SUBSCRIPTION_ID}." + ) + def test_mysql_ssl_connection_disabled(self): server_name = str(uuid4()) mysql_client = mock.MagicMock From 93b8a7c74ca2e3ae2ee29c11360a98a55388eda7 Mon Sep 17 00:00:00 2001 From: "mintlify[bot]" <109931778+mintlify[bot]@users.noreply.github.com> Date: Mon, 23 Mar 2026 11:12:26 +0100 Subject: [PATCH 03/15] docs(attack-paths): Lighthouse AI support and supported queries to Attack Paths (#10409) Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com> Co-authored-by: Josema Camacho --- .../tutorials/prowler-app-attack-paths.mdx | 122 +++++++++++++++++- 1 file changed, 121 insertions(+), 1 deletion(-) diff --git a/docs/user-guide/tutorials/prowler-app-attack-paths.mdx b/docs/user-guide/tutorials/prowler-app-attack-paths.mdx index 88d9a3a25d..646ee557de 100644 --- a/docs/user-guide/tutorials/prowler-app-attack-paths.mdx +++ b/docs/user-guide/tutorials/prowler-app-attack-paths.mdx @@ -202,15 +202,135 @@ To expand the graph for detailed exploration, click the fullscreen icon in the g width="700" /> -## Using Attack Paths with the MCP Server +## 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. +[Prowler Lighthouse AI](/getting-started/products/prowler-lighthouse-ai) also supports Attack Paths queries, allowing you to analyze privilege escalation chains and security misconfigurations directly from the chat interface. + 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 + +### Example Questions + +Ask through the MCP Server or Lighthouse AI: + +- "Find EC2 instances exposed to the internet with access to sensitive S3 buckets" +- "Are there any IAM roles that can escalate their own privileges?" +- "Show me all internet-facing resources with open security groups" +- "Which principals can create Lambda functions with privileged roles?" +- "List all RDS instances with storage encryption disabled" +- "Find S3 buckets that allow anonymous access" +- "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 From 591f5a860382cccf7aa03b2b3c40b6f0d765d1af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Pe=C3=B1a?= Date: Mon, 23 Mar 2026 12:43:45 +0100 Subject: [PATCH 04/15] fix(api): align finding-group latest aggregation (#10419) --- api/CHANGELOG.md | 5 ++ api/src/backend/api/tests/test_views.py | 63 +++++++++++++++++++++++-- api/src/backend/api/v1/views.py | 41 +++++++++++----- 3 files changed, 94 insertions(+), 15 deletions(-) diff --git a/api/CHANGELOG.md b/api/CHANGELOG.md index 17acf2155a..e09b601197 100644 --- a/api/CHANGELOG.md +++ b/api/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes to the **Prowler API** are documented in this file. ## [1.23.0] (Prowler UNRELEASED) +### 🐞 Fixed + +- Finding groups latest endpoint now aggregates the latest snapshot per provider before check-level totals, keeping impacted resources aligned across providers [(#10419)](https://github.com/prowler-cloud/prowler/pull/10419) +- Mute rule creation now triggers finding-group summary re-aggregation after historical muting, keeping stats in sync after mute operations [(#10419)](https://github.com/prowler-cloud/prowler/pull/10419) + ### 🔐 Security - Replace stdlib XML parser with `defusedxml` in SAML metadata parsing to prevent XML bomb (billion laughs) DoS attacks [(#10165)](https://github.com/prowler-cloud/prowler/pull/10165) diff --git a/api/src/backend/api/tests/test_views.py b/api/src/backend/api/tests/test_views.py index 7dd14bf420..b2e82d2ea1 100644 --- a/api/src/backend/api/tests/test_views.py +++ b/api/src/backend/api/tests/test_views.py @@ -45,6 +45,7 @@ from api.models import ( ComplianceRequirementOverview, DailySeveritySummary, Finding, + FindingGroupDailySummary, Integration, Invitation, LighthouseProviderConfiguration, @@ -14689,10 +14690,16 @@ class TestMuteRuleViewSet: assert len(data) == 2 assert data[0]["id"] == str(mute_rules_fixture[first_index].id) - @patch("tasks.tasks.mute_historical_findings_task.apply_async") + @patch("api.v1.views.chain") + @patch("api.v1.views.aggregate_finding_group_summaries_task.si") + @patch("api.v1.views.mute_historical_findings_task.si") + @patch("api.v1.views.transaction.on_commit", side_effect=lambda fn: fn()) def test_mute_rules_create_valid( self, - mock_task, + _mock_on_commit, + mock_mute_signature, + mock_aggregate_signature, + mock_chain, authenticated_client, findings_fixture, create_test_user, @@ -14730,8 +14737,14 @@ class TestMuteRuleViewSet: assert finding.muted_at is not None assert finding.muted_reason == "Security exception approved" - # Verify background task was called - mock_task.assert_called_once() + # Verify background task chain was called + mock_mute_signature.assert_called_once() + mock_aggregate_signature.assert_called_once() + mock_chain.assert_called_once_with( + mock_mute_signature.return_value, + mock_aggregate_signature.return_value, + ) + mock_chain.return_value.apply_async.assert_called_once() @patch("tasks.tasks.mute_historical_findings_task.apply_async") def test_mute_rules_create_converts_finding_ids_to_uids( @@ -15840,6 +15853,48 @@ class TestFindingGroupViewSet: assert len(data) == 1 assert data[0]["id"] == "cloudtrail_enabled" + def test_finding_groups_latest_aggregates_latest_per_provider( + self, authenticated_client, providers_fixture + ): + """Test /latest aggregates latest summary from each provider for the same check.""" + provider1 = providers_fixture[0] + provider2 = providers_fixture[1] + + check_id = "cross_provider_latest_resources_total" + now = datetime.now(timezone.utc).replace(minute=0, second=0, microsecond=0) + + FindingGroupDailySummary.objects.create( + tenant_id=provider1.tenant_id, + provider=provider1, + check_id=check_id, + inserted_at=now - timedelta(days=1), + resources_total=20, + resources_fail=20, + fail_count=20, + ) + FindingGroupDailySummary.objects.create( + tenant_id=provider2.tenant_id, + provider=provider2, + check_id=check_id, + inserted_at=now, + resources_total=7, + resources_fail=7, + fail_count=7, + ) + + response = authenticated_client.get( + reverse("finding-group-latest"), + {"filter[check_id]": check_id}, + ) + + assert response.status_code == status.HTTP_200_OK + data = response.json()["data"] + assert len(data) == 1 + attrs = data[0]["attributes"] + assert attrs["resources_total"] == 27 + assert attrs["resources_fail"] == 27 + assert attrs["fail_count"] == 27 + def test_finding_groups_latest_provider_type_filter( self, authenticated_client, finding_groups_fixture ): diff --git a/api/src/backend/api/v1/views.py b/api/src/backend/api/v1/views.py index 7c2de4a41c..85c3062965 100644 --- a/api/src/backend/api/v1/views.py +++ b/api/src/backend/api/v1/views.py @@ -16,6 +16,7 @@ from allauth.socialaccount.providers.github.views import GitHubOAuth2Adapter from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from allauth.socialaccount.providers.saml.views import FinishACSView, LoginView from botocore.exceptions import ClientError, NoCredentialsError, ParamValidationError +from celery import chain from celery.result import AsyncResult from config.custom_logging import BackendLogger from config.env import env @@ -81,6 +82,7 @@ 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 ( + aggregate_finding_group_summaries_task, backfill_compliance_summaries_task, backfill_scan_resource_summaries_task, check_integration_connection_task, @@ -6725,10 +6727,25 @@ class MuteRuleViewSet(BaseRLSViewSet): ) # Launch background task for historical muting - with transaction.atomic(): - mute_historical_findings_task.apply_async( - kwargs={"tenant_id": tenant_id, "mute_rule_id": str(mute_rule.id)} - ) + latest_scan_id = ( + Scan.objects.filter(tenant_id=tenant_id, state=StateChoices.COMPLETED) + .order_by("-completed_at", "-inserted_at") + .values_list("id", flat=True) + .first() + ) + + transaction.on_commit( + lambda: chain( + mute_historical_findings_task.si( + tenant_id=tenant_id, + mute_rule_id=str(mute_rule.id), + ), + aggregate_finding_group_summaries_task.si( + tenant_id=tenant_id, + scan_id=str(latest_scan_id), + ), + ).apply_async() + ) # Return the created mute rule serializer = self.get_serializer(mute_rule) @@ -7210,13 +7227,15 @@ class FindingGroupViewSet(BaseRLSViewSet): raise ValidationError(filterset.errors) filtered_queryset = filterset.qs - # Keep only rows from the latest inserted_at date per check_id - latest_per_check = filtered_queryset.annotate( - latest_inserted_at=Window( - expression=Max("inserted_at"), - partition_by=[F("check_id")], - ) - ).filter(inserted_at=F("latest_inserted_at")) + # Keep only the latest row per (check_id, provider), then aggregate by check_id. + latest_per_check_ids = ( + filtered_queryset.order_by("check_id", "provider_id", "-inserted_at") + .distinct("check_id", "provider_id") + .values("id") + ) + latest_per_check = filtered_queryset.filter( + id__in=Subquery(latest_per_check_ids) + ) # Re-aggregate daily summaries aggregated_queryset = self._aggregate_daily_summaries(latest_per_check) From 14356e31871cc18e258313214064b1c759e8b6dc Mon Sep 17 00:00:00 2001 From: Daniel Barranquero <74871504+danibarranqueroo@users.noreply.github.com> Date: Mon, 23 Mar 2026 13:51:07 +0100 Subject: [PATCH 05/15] docs: add cookbooks section (#10410) Co-authored-by: Andoni A. <14891798+andoniaf@users.noreply.github.com> --- docs/docs.json | 10 +- docs/user-guide/cookbooks/cicd-pipeline.mdx | 243 ++++++++++++++++++ .../cookbooks/kubernetes-in-cluster.mdx | 207 +++++++++++++++ .../kubernetes/getting-started-k8s.mdx | 4 + 4 files changed, 463 insertions(+), 1 deletion(-) create mode 100644 docs/user-guide/cookbooks/cicd-pipeline.mdx create mode 100644 docs/user-guide/cookbooks/kubernetes-in-cluster.mdx diff --git a/docs/docs.json b/docs/docs.json index 3ec056989f..a8fd6dedd6 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -225,7 +225,8 @@ "group": "Kubernetes", "pages": [ "user-guide/providers/kubernetes/getting-started-k8s", - "user-guide/providers/kubernetes/misc" + "user-guide/providers/kubernetes/misc", + "user-guide/cookbooks/kubernetes-in-cluster" ] }, { @@ -304,6 +305,13 @@ "pages": [ "user-guide/compliance/tutorials/threatscore" ] + }, + { + "group": "Cookbooks", + "pages": [ + "user-guide/cookbooks/kubernetes-in-cluster", + "user-guide/cookbooks/cicd-pipeline" + ] } ] }, diff --git a/docs/user-guide/cookbooks/cicd-pipeline.mdx b/docs/user-guide/cookbooks/cicd-pipeline.mdx new file mode 100644 index 0000000000..9dffd5049c --- /dev/null +++ b/docs/user-guide/cookbooks/cicd-pipeline.mdx @@ -0,0 +1,243 @@ +--- +title: 'Run Prowler in CI/CD and Send Findings to Prowler Cloud' +--- + +This cookbook demonstrates how to integrate Prowler into CI/CD pipelines so that security scans run automatically and findings are sent to Prowler Cloud via [Import Findings](/user-guide/tutorials/prowler-app-import-findings). Examples cover GitHub Actions and GitLab CI. + +## Prerequisites + +* A **Prowler Cloud** account with an active subscription (see [Prowler Cloud Pricing](https://prowler.com/pricing)) +* A Prowler Cloud **API key** with the **Manage Ingestions** permission (see [API Keys](/user-guide/tutorials/prowler-app-api-keys)) +* Cloud provider credentials configured in the CI/CD environment (e.g., AWS credentials for scanning AWS accounts) +* Access to configure pipeline workflows and secrets in the CI/CD platform + +## Key Concepts + +Prowler CLI provides the `--push-to-cloud` flag, which uploads scan results directly to Prowler Cloud after a scan completes. Combined with the `PROWLER_CLOUD_API_KEY` environment variable, this enables fully automated ingestion without manual file uploads. + +For full details on the flag and API, refer to the [Import Findings](/user-guide/tutorials/prowler-app-import-findings) documentation. + + +The examples in this guide use AWS as the target provider, but the same approach applies to any provider supported by Prowler (Azure, GCP, Kubernetes, and others). Replace `prowler aws` with the desired provider command (e.g., `prowler gcp`, `prowler azure`) and configure the corresponding credentials in the CI/CD environment. + + +## GitHub Actions + +### Store Secrets + +Before creating the workflow, add the following secrets to the repository (under "Settings" > "Secrets and variables" > "Actions"): + +* `PROWLER_CLOUD_API_KEY` — the Prowler Cloud API key +* Cloud provider credentials (e.g., `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`, or configure OIDC-based role assumption) + +### Workflow: Scheduled AWS Scan + +This workflow runs Prowler against an AWS account on a daily schedule and on every push to the `main` branch: + +```yaml +name: Prowler Security Scan + +on: + schedule: + - cron: "0 3 * * *" # Daily at 03:00 UTC + push: + branches: [main] + workflow_dispatch: # Allow manual triggers + +permissions: + id-token: write # Required for OIDC + contents: read + +jobs: + prowler-scan: + runs-on: ubuntu-latest + steps: + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: arn:aws:iam::123456789012:role/ProwlerScanRole + aws-region: us-east-1 + + - name: Install Prowler + run: pip install prowler + + - name: Run Prowler Scan + env: + PROWLER_CLOUD_API_KEY: ${{ secrets.PROWLER_CLOUD_API_KEY }} + run: | + prowler aws --push-to-cloud +``` + + +Replace `123456789012` with the actual AWS account ID and `ProwlerScanRole` with the IAM role name. For IAM role setup, refer to the [AWS authentication guide](/user-guide/providers/aws/authentication). + + +### Workflow: Scan Specific Services on Pull Request + +To run targeted scans on pull requests without blocking the merge pipeline, use `continue-on-error`: + +```yaml +name: Prowler PR Check + +on: + pull_request: + branches: [main] + +jobs: + prowler-scan: + runs-on: ubuntu-latest + continue-on-error: true + steps: + - name: Configure AWS Credentials + uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: arn:aws:iam::123456789012:role/ProwlerScanRole + aws-region: us-east-1 + + - name: Install Prowler + run: pip install prowler + + - name: Run Prowler Scan + env: + PROWLER_CLOUD_API_KEY: ${{ secrets.PROWLER_CLOUD_API_KEY }} + run: | + prowler aws --services s3,iam,ec2 --push-to-cloud +``` + + +Limiting the scan to specific services with `--services` reduces execution time, making it practical for pull request checks. + + +## GitLab CI + +### Store Variables + +Add the following CI/CD variables in the GitLab project (under "Settings" > "CI/CD" > "Variables"): + +* `PROWLER_CLOUD_API_KEY` — mark as **masked** and **protected** +* Cloud provider credentials as needed + +### Pipeline: Scheduled AWS Scan + +Add the following to `.gitlab-ci.yml`: + +```yaml +prowler-scan: + image: python:3.12-slim + stage: test + script: + - pip install prowler + - prowler aws --push-to-cloud + variables: + PROWLER_CLOUD_API_KEY: $PROWLER_CLOUD_API_KEY + AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY + AWS_DEFAULT_REGION: "us-east-1" + rules: + - if: $CI_PIPELINE_SOURCE == "schedule" + - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH + when: manual +``` + +To run the scan on a schedule, create a **Pipeline Schedule** in GitLab (under "Build" > "Pipeline Schedules") with the desired cron expression. + +### Pipeline: Multi-Provider Scan + +To scan multiple cloud providers in parallel: + +```yaml +stages: + - security + +.prowler-base: + image: python:3.12-slim + stage: security + before_script: + - pip install prowler + rules: + - if: $CI_PIPELINE_SOURCE == "schedule" + +prowler-aws: + extends: .prowler-base + script: + - prowler aws --push-to-cloud + variables: + PROWLER_CLOUD_API_KEY: $PROWLER_CLOUD_API_KEY + AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY + +prowler-gcp: + extends: .prowler-base + script: + - prowler gcp --push-to-cloud + variables: + PROWLER_CLOUD_API_KEY: $PROWLER_CLOUD_API_KEY + GOOGLE_APPLICATION_CREDENTIALS: $GCP_SERVICE_ACCOUNT_KEY +``` + +## Tips and Best Practices + +### When to Run Scans + +* **Scheduled scans** (daily or weekly) provide continuous monitoring and are ideal for baseline security assessments +* **On-merge scans** catch configuration changes introduced by new code +* **Pull request scans** provide early feedback but should target specific services to keep execution times reasonable + +### Handling Scan Failures + +By default, Prowler exits with a non-zero code when it finds failing checks. This causes the CI/CD job to fail. To prevent scan results from blocking the pipeline: + +* **GitHub Actions**: Add `continue-on-error: true` to the job +* **GitLab CI**: Add `allow_failure: true` to the job + + +Ingestion failures (e.g., network issues reaching Prowler Cloud) do not affect the Prowler exit code. The scan completes normally and only a warning is emitted. See [Import Findings troubleshooting](/user-guide/tutorials/prowler-app-import-findings#troubleshooting) for details. + + +### Caching Prowler Installation + +For faster pipeline runs, cache the Prowler installation: + +**GitHub Actions:** +```yaml +- name: Cache pip packages + uses: actions/cache@v4 + with: + path: ~/.cache/pip + key: ${{ runner.os }}-pip-prowler + restore-keys: ${{ runner.os }}-pip- + +- name: Install Prowler + run: pip install prowler +``` + +**GitLab CI:** +```yaml +prowler-scan: + cache: + paths: + - .cache/pip + variables: + PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip" +``` + +### Output Formats + +To generate additional report formats alongside the cloud upload: + +```bash +prowler aws --push-to-cloud -M csv,html -o /tmp/prowler-reports +``` + +This produces CSV and HTML files locally while also pushing OCSF findings to Prowler Cloud. The local files can be stored as CI/CD artifacts for archival purposes. + +### Scanning Multiple AWS Accounts + +To scan multiple accounts sequentially in a single job, use [role assumption](/user-guide/providers/aws/role-assumption): + +```bash +prowler aws -R arn:aws:iam::111111111111:role/ProwlerScanRole --push-to-cloud +prowler aws -R arn:aws:iam::222222222222:role/ProwlerScanRole --push-to-cloud +``` + +Each scan run creates a separate ingestion job in Prowler Cloud. diff --git a/docs/user-guide/cookbooks/kubernetes-in-cluster.mdx b/docs/user-guide/cookbooks/kubernetes-in-cluster.mdx new file mode 100644 index 0000000000..765bcf9313 --- /dev/null +++ b/docs/user-guide/cookbooks/kubernetes-in-cluster.mdx @@ -0,0 +1,207 @@ +--- +title: 'Run Kubernetes In-Cluster and Send Findings to Prowler Cloud' +--- + +This cookbook walks through deploying Prowler inside a Kubernetes cluster on a recurring schedule and automatically sending findings to Prowler Cloud via [Import Findings](/user-guide/tutorials/prowler-app-import-findings). By the end, security scan results from the cluster appear in Prowler Cloud without any manual file uploads. + +## Prerequisites + +* A **Prowler Cloud** account with an active subscription (see [Prowler Cloud Pricing](https://prowler.com/pricing)) +* A Prowler Cloud **API key** with the **Manage Ingestions** permission (see [API Keys](/user-guide/tutorials/prowler-app-api-keys)) +* Access to a Kubernetes cluster with `kubectl` configured +* Permissions to create ServiceAccounts, Roles, RoleBindings, Secrets, and CronJobs in the cluster + +## Step 1: Create the ServiceAccount and RBAC Resources + +Prowler needs a ServiceAccount with read access to cluster resources. Apply the manifests from the [`kubernetes` directory](https://github.com/prowler-cloud/prowler/tree/master/kubernetes) of the Prowler repository: + +```console +kubectl apply -f kubernetes/prowler-sa.yaml +kubectl apply -f kubernetes/prowler-role.yaml +kubectl apply -f kubernetes/prowler-rolebinding.yaml +``` + +This creates: + +* A `prowler-sa` ServiceAccount in the `prowler-ns` namespace +* A ClusterRole with the read permissions Prowler requires +* A ClusterRoleBinding linking the ServiceAccount to the role + +For more details on these resources, refer to [Getting Started with Kubernetes](/user-guide/providers/kubernetes/getting-started-k8s). + +## Step 2: Store the Prowler Cloud API Key as a Secret + +Create a Kubernetes Secret to hold the API key securely: + +```console +kubectl create secret generic prowler-cloud-api-key \ + --from-literal=api-key=pk_your_api_key_here \ + --namespace prowler-ns +``` + +Replace `pk_your_api_key_here` with the actual API key from Prowler Cloud. + + +Avoid embedding the API key directly in the CronJob manifest. Using a Kubernetes Secret keeps credentials out of version control and pod specs. + + +## Step 3: Create the CronJob Manifest + +The CronJob runs Prowler on a schedule, scanning the cluster and pushing findings to Prowler Cloud with the `--push-to-cloud` flag. + +Create a file named `prowler-cronjob.yaml`: + +```yaml +apiVersion: batch/v1 +kind: CronJob +metadata: + name: prowler-k8s-scan + namespace: prowler-ns +spec: + schedule: "0 2 * * *" # Runs daily at 02:00 UTC + concurrencyPolicy: Forbid + jobTemplate: + spec: + backoffLimit: 1 + template: + metadata: + labels: + app: prowler + spec: + serviceAccountName: prowler-sa + containers: + - name: prowler + image: prowlercloud/prowler:stable + args: + - "kubernetes" + - "--push-to-cloud" + env: + - name: PROWLER_CLOUD_API_KEY + valueFrom: + secretKeyRef: + name: prowler-cloud-api-key + key: api-key + - name: CLUSTER_NAME + value: "my-cluster" + imagePullPolicy: Always + volumeMounts: + - name: var-lib-cni + mountPath: /var/lib/cni + readOnly: true + - name: var-lib-etcd + mountPath: /var/lib/etcd + readOnly: true + - name: var-lib-kubelet + mountPath: /var/lib/kubelet + readOnly: true + - name: etc-kubernetes + mountPath: /etc/kubernetes + readOnly: true + hostPID: true + restartPolicy: Never + volumes: + - name: var-lib-cni + hostPath: + path: /var/lib/cni + - name: var-lib-etcd + hostPath: + path: /var/lib/etcd + - name: var-lib-kubelet + hostPath: + path: /var/lib/kubelet + - name: etc-kubernetes + hostPath: + path: /etc/kubernetes +``` + + +Replace `my-cluster` with a meaningful name for the cluster. This value appears in Prowler Cloud reports and helps identify the source of findings. See the `--cluster-name` flag documentation in [Getting Started with Kubernetes](/user-guide/providers/kubernetes/getting-started-k8s) for more details. + + +### Customizing the Schedule + +The `schedule` field uses standard cron syntax. Common examples: + +* `"0 2 * * *"` — daily at 02:00 UTC +* `"0 */6 * * *"` — every 6 hours +* `"0 2 * * 1"` — weekly on Mondays at 02:00 UTC + +### Scanning Specific Namespaces + +To limit the scan to specific namespaces, add the `--namespace` flag to the `args` array: + +```yaml +args: + - "kubernetes" + - "--push-to-cloud" + - "--namespace" + - "production,staging" +``` + +## Step 4: Deploy and Verify + +Apply the CronJob to the cluster: + +```console +kubectl apply -f prowler-cronjob.yaml +``` + +To trigger an immediate test run without waiting for the schedule: + +```console +kubectl create job prowler-test-run --from=cronjob/prowler-k8s-scan -n prowler-ns +``` + +Monitor the job execution: + +```console +kubectl get pods -n prowler-ns -l app=prowler --watch +``` + +Check the logs to confirm findings were pushed successfully: + +```console +kubectl logs -n prowler-ns -l app=prowler --tail=50 +``` + +A successful upload produces output similar to: + +``` +Pushing findings to Prowler Cloud, please wait... + +Findings successfully pushed to Prowler Cloud. Ingestion job: fa8bc8c5-4925-46a0-9fe0-f6575905e094 +See more details here: https://cloud.prowler.com/scans +``` + +## Step 5: View Findings in Prowler Cloud + +Once the job completes and findings are pushed: + +1. Navigate to [Prowler Cloud](https://cloud.prowler.com/) +2. Open the "Scans" section to verify the ingestion job status +3. Browse findings under the Kubernetes provider + +For details on the ingestion workflow and status tracking, refer to the [Import Findings](/user-guide/tutorials/prowler-app-import-findings) documentation. + +## Tips and Troubleshooting + +* **Resource limits**: For large clusters, consider setting `resources.requests` and `resources.limits` on the container to prevent the scan from consuming excessive cluster resources. +* **Network policies**: Ensure the Prowler pod can reach `api.prowler.com` over HTTPS (port 443). Adjust NetworkPolicies or egress rules if needed. +* **Job history**: Kubernetes retains completed and failed jobs by default. Set `successfulJobsHistoryLimit` and `failedJobsHistoryLimit` in the CronJob spec to control cleanup: + + ```yaml + spec: + successfulJobsHistoryLimit: 3 + failedJobsHistoryLimit: 1 + ``` + +* **API key rotation**: When rotating the API key, update the Secret and restart any running jobs: + + ```console + kubectl delete secret prowler-cloud-api-key -n prowler-ns + kubectl create secret generic prowler-cloud-api-key \ + --from-literal=api-key=pk_new_api_key_here \ + --namespace prowler-ns + ``` + +* **Failed uploads**: If the push to Prowler Cloud fails, the scan still completes and findings are saved locally in the container. Check the [Import Findings troubleshooting section](/user-guide/tutorials/prowler-app-import-findings#troubleshooting) for common error messages. diff --git a/docs/user-guide/providers/kubernetes/getting-started-k8s.mdx b/docs/user-guide/providers/kubernetes/getting-started-k8s.mdx index 0ec8215776..c4f4822792 100644 --- a/docs/user-guide/providers/kubernetes/getting-started-k8s.mdx +++ b/docs/user-guide/providers/kubernetes/getting-started-k8s.mdx @@ -164,3 +164,7 @@ env: ``` + + +To set up a production-ready CronJob that runs Prowler on a schedule and sends findings to Prowler Cloud, see the [Run Kubernetes In-Cluster and Send Findings to Prowler Cloud](/user-guide/cookbooks/kubernetes-in-cluster) cookbook. + From c62ac6c71bbf5d3754504e45f8c6d5f858731085 Mon Sep 17 00:00:00 2001 From: Prowler Bot Date: Mon, 23 Mar 2026 15:26:29 +0100 Subject: [PATCH 06/15] feat(aws): Update regions for AWS services (#10076) Co-authored-by: prowler-bot <179230569+prowler-bot@users.noreply.github.com> From 1015f1379fbb4745097129599ae30e8e3090596a Mon Sep 17 00:00:00 2001 From: Prowler Bot Date: Mon, 23 Mar 2026 15:28:51 +0100 Subject: [PATCH 07/15] feat(aws): Update regions for AWS services (#10413) Co-authored-by: prowler-bot <179230569+prowler-bot@users.noreply.github.com> --- .../providers/aws/aws_regions_by_service.json | 22 +++++++------------ 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/prowler/providers/aws/aws_regions_by_service.json b/prowler/providers/aws/aws_regions_by_service.json index 3a414e5f77..297921370d 100644 --- a/prowler/providers/aws/aws_regions_by_service.json +++ b/prowler/providers/aws/aws_regions_by_service.json @@ -1587,6 +1587,7 @@ "ap-northeast-1", "ap-south-1", "ap-southeast-2", + "ca-central-1", "eu-central-1", "eu-west-1", "eu-west-2", @@ -1670,20 +1671,8 @@ "budgets": { "regions": { "aws": [ - "ap-northeast-1", - "ap-northeast-2", - "ap-south-1", - "ap-southeast-1", - "ap-southeast-2", "ca-central-1", - "eu-central-1", - "eu-west-1", - "eu-west-2", - "eu-west-3", - "sa-east-1", "us-east-1", - "us-east-2", - "us-west-1", "us-west-2" ], "aws-cn": [ @@ -3439,7 +3428,6 @@ "datazone": { "regions": { "aws": [ - "af-south-1", "ap-east-1", "ap-northeast-1", "ap-northeast-2", @@ -3452,7 +3440,6 @@ "eu-central-1", "eu-central-2", "eu-north-1", - "eu-south-2", "eu-west-1", "eu-west-2", "eu-west-3", @@ -6998,6 +6985,7 @@ "aws": [ "af-south-1", "ap-east-1", + "ap-east-2", "ap-northeast-1", "ap-northeast-2", "ap-northeast-3", @@ -7022,6 +7010,7 @@ "il-central-1", "me-central-1", "me-south-1", + "mx-central-1", "sa-east-1", "us-east-1", "us-east-2", @@ -7695,6 +7684,7 @@ "ap-southeast-1", "ap-southeast-2", "ap-southeast-4", + "ap-southeast-5", "ca-central-1", "eu-central-1", "eu-north-1", @@ -7932,6 +7922,7 @@ "aws": [ "ap-southeast-2", "eu-west-1", + "eu-west-2", "us-east-1", "us-west-2" ], @@ -8255,6 +8246,7 @@ "ap-east-1", "ap-northeast-1", "ap-northeast-2", + "ap-northeast-3", "ap-south-1", "ap-southeast-1", "ap-southeast-2", @@ -8270,6 +8262,7 @@ "sa-east-1", "us-east-1", "us-east-2", + "us-west-1", "us-west-2" ], "aws-cn": [], @@ -9877,6 +9870,7 @@ "eu-west-1", "eu-west-2", "il-central-1", + "sa-east-1", "us-east-1", "us-east-2", "us-west-1", From 114e86c0dc2f9b301d735a2f5c77d79f6681ec2c Mon Sep 17 00:00:00 2001 From: Hugo Pereira Brito <101209179+HugoPBrito@users.noreply.github.com> Date: Mon, 23 Mar 2026 15:21:31 +0000 Subject: [PATCH 08/15] fix(sdk): ignore disabled users in Entra MFA check (#10426) --- prowler/CHANGELOG.md | 1 + .../entra_non_privileged_user_has_mfa.py | 2 +- .../azure/services/entra/entra_service.py | 15 +++- .../entra_non_privileged_user_has_mfa_test.py | 80 +++++++++++++++++++ .../services/entra/entra_service_test.py | 14 +++- 5 files changed, 108 insertions(+), 4 deletions(-) diff --git a/prowler/CHANGELOG.md b/prowler/CHANGELOG.md index 2c8b47daf4..9582f7123a 100644 --- a/prowler/CHANGELOG.md +++ b/prowler/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to the **Prowler SDK** are documented in this file. - Azure MySQL flexible server checks now compare configuration values case-insensitively to avoid false negatives when Azure returns lowercase values [(#10396)](https://github.com/prowler-cloud/prowler/pull/10396) - Azure `vm_backup_enabled` and `vm_sufficient_daily_backup_retention_period` checks now compare VM names case-insensitively to avoid false negatives when Azure stores backup item names in a different case [(#10395)](https://github.com/prowler-cloud/prowler/pull/10395) +- `entra_non_privileged_user_has_mfa` skips disabled users to avoid false positives [(#10426)](https://github.com/prowler-cloud/prowler/pull/10426) --- diff --git a/prowler/providers/azure/services/entra/entra_non_privileged_user_has_mfa/entra_non_privileged_user_has_mfa.py b/prowler/providers/azure/services/entra/entra_non_privileged_user_has_mfa/entra_non_privileged_user_has_mfa.py index c86fc02da7..d231a7a6b1 100644 --- a/prowler/providers/azure/services/entra/entra_non_privileged_user_has_mfa/entra_non_privileged_user_has_mfa.py +++ b/prowler/providers/azure/services/entra/entra_non_privileged_user_has_mfa/entra_non_privileged_user_has_mfa.py @@ -11,7 +11,7 @@ class entra_non_privileged_user_has_mfa(Check): for tenant_domain, users in entra_client.users.items(): for user in users.values(): - if not is_privileged_user( + if user.account_enabled and not is_privileged_user( user, entra_client.directory_roles[tenant_domain] ): report = Check_Report_Azure(metadata=self.metadata(), resource=user) diff --git a/prowler/providers/azure/services/entra/entra_service.py b/prowler/providers/azure/services/entra/entra_service.py index 011ea675b0..eb1d62ac11 100644 --- a/prowler/providers/azure/services/entra/entra_service.py +++ b/prowler/providers/azure/services/entra/entra_service.py @@ -3,7 +3,9 @@ from asyncio import gather from typing import List, Optional from uuid import UUID +from kiota_abstractions.base_request_configuration import RequestConfiguration from msgraph import GraphServiceClient +from msgraph.generated.users.users_request_builder import UsersRequestBuilder from pydantic.v1 import BaseModel from prowler.lib.logger import logger @@ -65,9 +67,16 @@ class Entra(AzureService): logger.info("Entra - Getting users...") users = {} try: + request_configuration = RequestConfiguration( + query_parameters=UsersRequestBuilder.UsersRequestBuilderGetQueryParameters( + select=["id", "displayName", "accountEnabled"] + ) + ) for tenant, client in self.clients.items(): users.update({tenant: {}}) - users_response = await client.users.get() + users_response = await client.users.get( + request_configuration=request_configuration + ) registration_details = await self._get_user_registration_details(client) try: @@ -81,6 +90,9 @@ class Entra(AzureService): is_mfa_capable=registration_details.get( user.id, False ), + account_enabled=getattr( + user, "account_enabled", True + ), ) } ) @@ -409,6 +421,7 @@ class User(BaseModel): id: str name: str is_mfa_capable: bool = False + account_enabled: bool = True class DefaultUserRolePermissions(BaseModel): diff --git a/tests/providers/azure/services/entra/entra_non_privileged_user_has_mfa/entra_non_privileged_user_has_mfa_test.py b/tests/providers/azure/services/entra/entra_non_privileged_user_has_mfa/entra_non_privileged_user_has_mfa_test.py index 4667b665ed..4d2f289a90 100644 --- a/tests/providers/azure/services/entra/entra_non_privileged_user_has_mfa/entra_non_privileged_user_has_mfa_test.py +++ b/tests/providers/azure/services/entra/entra_non_privileged_user_has_mfa/entra_non_privileged_user_has_mfa_test.py @@ -142,6 +142,86 @@ class Test_entra_non_privileged_user_has_mfa: assert result[0].resource_id == user_id assert result[0].subscription == f"Tenant: {DOMAIN}" + def test_entra_disabled_user_no_privileged_no_mfa(self): + entra_client = mock.MagicMock + user_id = str(uuid4()) + + with ( + mock.patch( + "prowler.providers.common.provider.Provider.get_global_provider", + return_value=set_mocked_azure_provider(), + ), + mock.patch( + "prowler.providers.azure.services.entra.entra_non_privileged_user_has_mfa.entra_non_privileged_user_has_mfa.entra_client", + new=entra_client, + ), + ): + from prowler.providers.azure.services.entra.entra_non_privileged_user_has_mfa.entra_non_privileged_user_has_mfa import ( + entra_non_privileged_user_has_mfa, + ) + from prowler.providers.azure.services.entra.entra_service import ( + DirectoryRole, + User, + ) + + user = User( + id=user_id, + name="foo", + is_mfa_capable=False, + account_enabled=False, + ) + + entra_client.users = {DOMAIN: {f"foo@{DOMAIN}": user}} + entra_client.directory_roles = { + DOMAIN: { + "Global Administrator": DirectoryRole(id=str(uuid4()), members=[]) + } + } + + check = entra_non_privileged_user_has_mfa() + result = check.execute() + assert len(result) == 0 + + def test_entra_disabled_user_no_privileged_mfa(self): + entra_client = mock.MagicMock + user_id = str(uuid4()) + + with ( + mock.patch( + "prowler.providers.common.provider.Provider.get_global_provider", + return_value=set_mocked_azure_provider(), + ), + mock.patch( + "prowler.providers.azure.services.entra.entra_non_privileged_user_has_mfa.entra_non_privileged_user_has_mfa.entra_client", + new=entra_client, + ), + ): + from prowler.providers.azure.services.entra.entra_non_privileged_user_has_mfa.entra_non_privileged_user_has_mfa import ( + entra_non_privileged_user_has_mfa, + ) + from prowler.providers.azure.services.entra.entra_service import ( + DirectoryRole, + User, + ) + + user = User( + id=user_id, + name="foo", + is_mfa_capable=True, + account_enabled=False, + ) + + entra_client.users = {DOMAIN: {f"foo@{DOMAIN}": user}} + entra_client.directory_roles = { + DOMAIN: { + "Global Administrator": DirectoryRole(id=str(uuid4()), members=[]) + } + } + + check = entra_non_privileged_user_has_mfa() + result = check.execute() + assert len(result) == 0 + def test_entra_user_privileged_no_mfa(self): entra_client = mock.MagicMock user_id = str(uuid4()) diff --git a/tests/providers/azure/services/entra/entra_service_test.py b/tests/providers/azure/services/entra/entra_service_test.py index 8e3a25e59f..75ef4f98c4 100644 --- a/tests/providers/azure/services/entra/entra_service_test.py +++ b/tests/providers/azure/services/entra/entra_service_test.py @@ -147,6 +147,7 @@ class Test_Entra_Service: assert entra_client.users[DOMAIN]["user-1@tenant1.es"].id == "id-1" assert entra_client.users[DOMAIN]["user-1@tenant1.es"].name == "User 1" assert entra_client.users[DOMAIN]["user-1@tenant1.es"].is_mfa_capable is False + assert entra_client.users[DOMAIN]["user-1@tenant1.es"].account_enabled is True def test_get_authorization_policy(self): entra_client = Entra(set_mocked_azure_provider()) @@ -229,8 +230,8 @@ def test_azure_entra__get_users_handles_pagination(): entra_service = Entra.__new__(Entra) users_page_one = [ - SimpleNamespace(id="user-1", display_name="User 1"), - SimpleNamespace(id="user-2", display_name="User 2"), + SimpleNamespace(id="user-1", display_name="User 1", account_enabled=False), + SimpleNamespace(id="user-2", display_name="User 2", account_enabled=True), ] users_page_two = [ SimpleNamespace(id="user-3", display_name="User 3"), @@ -288,9 +289,18 @@ def test_azure_entra__get_users_handles_pagination(): assert len(users["tenant-1"]) == 3 assert users_builder.get.await_count == 1 + request_configuration = users_builder.get.await_args.kwargs["request_configuration"] + assert request_configuration.query_parameters.select == [ + "id", + "displayName", + "accountEnabled", + ] with_url_mock.assert_called_once_with("next-link") registration_details_builder.get.assert_awaited() registration_details_builder.with_url.assert_not_called() assert users["tenant-1"]["user-1"].is_mfa_capable is True + assert users["tenant-1"]["user-1"].account_enabled is False assert users["tenant-1"]["user-2"].is_mfa_capable is True + assert users["tenant-1"]["user-2"].account_enabled is True assert users["tenant-1"]["user-3"].is_mfa_capable is False + assert users["tenant-1"]["user-3"].account_enabled is True From 41629137efdec1ade078e4386f738c8e0ffce94b Mon Sep 17 00:00:00 2001 From: Daniel Barranquero <74871504+danibarranqueroo@users.noreply.github.com> Date: Mon, 23 Mar 2026 16:22:54 +0100 Subject: [PATCH 09/15] docs: remove cookbook from k8s section (#10427) --- docs/docs.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/docs.json b/docs/docs.json index a8fd6dedd6..6fcd387a07 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -225,8 +225,7 @@ "group": "Kubernetes", "pages": [ "user-guide/providers/kubernetes/getting-started-k8s", - "user-guide/providers/kubernetes/misc", - "user-guide/cookbooks/kubernetes-in-cluster" + "user-guide/providers/kubernetes/misc" ] }, { From 49ba25ba07e11f84a583a52cd542d915745a1a48 Mon Sep 17 00:00:00 2001 From: Hugo Pereira Brito <101209179+HugoPBrito@users.noreply.github.com> Date: Mon, 23 Mar 2026 15:36:37 +0000 Subject: [PATCH 10/15] feat(ui): add custom attack paths queries (#10397) --- ui/CHANGELOG.md | 8 + .../attack-paths/queries.adapter.test.ts | 54 ++++++ ui/actions/attack-paths/queries.adapter.ts | 52 ++++++ ui/actions/attack-paths/queries.test.ts | 142 ++++++++++++++- ui/actions/attack-paths/queries.ts | 94 ++++++++++ .../query-builder/_components/index.ts | 2 + .../_components/query-description.test.tsx | 76 ++++++++ .../_components/query-description.tsx | 70 ++++++++ .../query-execution-error.test.tsx | 46 +++++ .../_components/query-execution-error.tsx | 30 ++++ .../query-parameters-form.test.tsx | 122 ++++++++++++- .../_components/query-parameters-form.tsx | 166 ++++++++++++------ .../_hooks/use-query-builder.test.tsx | 123 +++++++++++++ .../query-builder/_hooks/use-query-builder.ts | 27 ++- .../query-builder/attack-paths-page.tsx | 90 ++++------ ui/components/shadcn/index.ts | 1 + ui/lib/attack-paths/custom-query.ts | 42 +++++ ui/types/attack-paths.ts | 50 ++++++ 18 files changed, 1086 insertions(+), 109 deletions(-) create mode 100644 ui/actions/attack-paths/queries.adapter.test.ts create mode 100644 ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-description.test.tsx create mode 100644 ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-description.tsx create mode 100644 ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-execution-error.test.tsx create mode 100644 ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-execution-error.tsx create mode 100644 ui/lib/attack-paths/custom-query.ts diff --git a/ui/CHANGELOG.md b/ui/CHANGELOG.md index 2c17bcc5d6..c20aa5bf99 100644 --- a/ui/CHANGELOG.md +++ b/ui/CHANGELOG.md @@ -2,6 +2,14 @@ All notable changes to the **Prowler UI** are documented in this file. +## [1.22.0] (Prowler UNRELEASED) + +### 🚀 Added + +- Attack Paths custom openCypher queries with Cartography schema guidance and clearer execution errors [(#10397)](https://github.com/prowler-cloud/prowler/pull/10397) + +--- + ## [1.21.0] (Prowler v5.21.0) ### 🚀 Added diff --git a/ui/actions/attack-paths/queries.adapter.test.ts b/ui/actions/attack-paths/queries.adapter.test.ts new file mode 100644 index 0000000000..cd6bafd206 --- /dev/null +++ b/ui/actions/attack-paths/queries.adapter.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vitest"; + +import { + ATTACK_PATH_QUERY_IDS, + type AttackPathCartographySchemaAttributes, + type AttackPathQuery, +} from "@/types/attack-paths"; + +import { buildAttackPathQueries } from "./queries.adapter"; + +const presetQuery: AttackPathQuery = { + type: "attack-paths-scans", + id: "preset-query", + attributes: { + name: "Preset Query", + short_description: "Returns privileged attack paths", + description: "Returns privileged attack paths.", + provider: "aws", + attribution: null, + parameters: [], + }, +}; + +describe("buildAttackPathQueries", () => { + it("prepends a custom query with a schema documentation link", () => { + // Given + const schema: AttackPathCartographySchemaAttributes = { + id: "aws-0.129.0", + provider: "aws", + cartography_version: "0.129.0", + schema_url: + "https://github.com/cartography-cncf/cartography/blob/0.129.0/docs/root/modules/aws/schema.md", + raw_schema_url: + "https://raw.githubusercontent.com/cartography-cncf/cartography/refs/tags/0.129.0/docs/root/modules/aws/schema.md", + }; + + // When + const result = buildAttackPathQueries([presetQuery], schema); + + // Then + expect(result[0]).toMatchObject({ + id: ATTACK_PATH_QUERY_IDS.CUSTOM, + attributes: { + name: "Custom openCypher query", + short_description: "Write and run your own read-only query", + documentation_link: { + text: "Cartography schema used by Prowler for AWS graphs", + link: schema.schema_url, + }, + }, + }); + expect(result[1]).toEqual(presetQuery); + }); +}); diff --git a/ui/actions/attack-paths/queries.adapter.ts b/ui/actions/attack-paths/queries.adapter.ts index fd256739e1..016abde60e 100644 --- a/ui/actions/attack-paths/queries.adapter.ts +++ b/ui/actions/attack-paths/queries.adapter.ts @@ -1,7 +1,10 @@ import { MetaDataProps } from "@/types"; import { + ATTACK_PATH_QUERY_IDS, + type AttackPathCartographySchemaAttributes, AttackPathQueriesResponse, AttackPathQuery, + QUERY_PARAMETER_INPUT_TYPES, } from "@/types/attack-paths"; /** @@ -53,3 +56,52 @@ export function adaptAttackPathQueriesResponse( return { data: enrichedData, metadata }; } + +const CUSTOM_QUERY_PLACEHOLDER = `MATCH (n) +RETURN n +LIMIT 25`; + +const formatSchemaDocumentationLinkText = ( + schema: AttackPathCartographySchemaAttributes, +): string => { + return `Cartography schema used by Prowler for ${schema.provider.toUpperCase()} graphs`; +}; + +const createCustomQuery = ( + schema?: AttackPathCartographySchemaAttributes, +): AttackPathQuery => ({ + type: "attack-paths-scans", + id: ATTACK_PATH_QUERY_IDS.CUSTOM, + attributes: { + name: "Custom openCypher query", + short_description: "Write and run your own read-only query", + description: + "Run a read-only openCypher query against the selected Attack Paths scan. Results are automatically scoped to the selected provider.", + provider: "custom", + attribution: null, + documentation_link: schema + ? { + text: formatSchemaDocumentationLinkText(schema), + link: schema.schema_url, + } + : null, + parameters: [ + { + name: "query", + label: "openCypher", + data_type: "string", + description: "", + placeholder: CUSTOM_QUERY_PLACEHOLDER, + required: true, + input_type: QUERY_PARAMETER_INPUT_TYPES.TEXTAREA, + }, + ], + }, +}); + +export const buildAttackPathQueries = ( + queries: AttackPathQuery[], + schema?: AttackPathCartographySchemaAttributes, +): AttackPathQuery[] => { + return [createCustomQuery(schema), ...queries]; +}; diff --git a/ui/actions/attack-paths/queries.test.ts b/ui/actions/attack-paths/queries.test.ts index 6c2be5f15d..ab3afc447f 100644 --- a/ui/actions/attack-paths/queries.test.ts +++ b/ui/actions/attack-paths/queries.test.ts @@ -17,7 +17,11 @@ vi.mock("@/lib/server-actions-helper", () => ({ handleApiResponse: handleApiResponseMock, })); -import { executeQuery } from "./queries"; +import { + executeCustomQuery, + executeQuery, + getCartographySchema, +} from "./queries"; describe("executeQuery", () => { beforeEach(() => { @@ -65,3 +69,139 @@ describe("executeQuery", () => { expect(handleApiResponseMock).not.toHaveBeenCalled(); }); }); + +describe("executeCustomQuery", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.stubGlobal("fetch", fetchMock); + getAuthHeadersMock.mockResolvedValue({ Authorization: "Bearer token" }); + handleApiResponseMock.mockResolvedValue({ + data: { + type: "attack-paths-query-run-requests", + id: null, + attributes: { + nodes: [], + relationships: [], + }, + }, + }); + }); + + it("posts the custom query to the dedicated endpoint", async () => { + // Given + fetchMock.mockResolvedValue(new Response(null, { status: 200 })); + + // When + await executeCustomQuery( + "550e8400-e29b-41d4-a716-446655440000", + "MATCH (n) RETURN n LIMIT 10", + ); + + // Then + expect(fetchMock).toHaveBeenCalledWith( + "https://api.example.com/api/v1/attack-paths-scans/550e8400-e29b-41d4-a716-446655440000/queries/custom", + expect.objectContaining({ + method: "POST", + body: JSON.stringify({ + data: { + type: "attack-paths-custom-query-run-requests", + attributes: { + query: "MATCH (n) RETURN n LIMIT 10", + }, + }, + }), + }), + ); + }); + + it("rejects empty custom queries before calling the API", async () => { + // When + const result = await executeCustomQuery( + "550e8400-e29b-41d4-a716-446655440000", + " ", + ); + + // Then + expect(result).toEqual({ + error: "Custom query cannot be empty", + status: 400, + }); + expect(fetchMock).not.toHaveBeenCalled(); + expect(handleApiResponseMock).not.toHaveBeenCalled(); + }); + + it("rejects custom queries longer than 10000 characters before calling the API", async () => { + // When + const result = await executeCustomQuery( + "550e8400-e29b-41d4-a716-446655440000", + "x".repeat(10001), + ); + + // Then + expect(result).toEqual({ + error: "Custom query must be 10000 characters or fewer", + status: 400, + }); + expect(fetchMock).not.toHaveBeenCalled(); + expect(handleApiResponseMock).not.toHaveBeenCalled(); + }); + + it("rejects custom queries with write operations before calling the API", async () => { + // When + const result = await executeCustomQuery( + "550e8400-e29b-41d4-a716-446655440000", + "MATCH (n) SET n.name = 'updated' RETURN n", + ); + + // Then + expect(result).toEqual({ + error: "Only read-only queries are allowed", + status: 400, + }); + expect(fetchMock).not.toHaveBeenCalled(); + expect(handleApiResponseMock).not.toHaveBeenCalled(); + }); +}); + +describe("getCartographySchema", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.stubGlobal("fetch", fetchMock); + getAuthHeadersMock.mockResolvedValue({ Authorization: "Bearer token" }); + }); + + it("fetches the schema metadata for the selected scan", async () => { + // Given + const apiResponse = { + data: { + type: "attack-paths-cartography-schemas", + id: "aws-0.129.0", + attributes: { + id: "aws-0.129.0", + provider: "aws", + cartography_version: "0.129.0", + schema_url: + "https://github.com/cartography-cncf/cartography/blob/0.129.0/docs/root/modules/aws/schema.md", + raw_schema_url: + "https://raw.githubusercontent.com/cartography-cncf/cartography/refs/tags/0.129.0/docs/root/modules/aws/schema.md", + }, + }, + }; + fetchMock.mockResolvedValue(new Response(null, { status: 200 })); + handleApiResponseMock.mockResolvedValue(apiResponse); + + // When + const result = await getCartographySchema( + "550e8400-e29b-41d4-a716-446655440000", + ); + + // Then + expect(fetchMock).toHaveBeenCalledWith( + "https://api.example.com/api/v1/attack-paths-scans/550e8400-e29b-41d4-a716-446655440000/schema", + expect.objectContaining({ + method: "GET", + }), + ); + expect(result).toEqual(apiResponse); + }); +}); diff --git a/ui/actions/attack-paths/queries.ts b/ui/actions/attack-paths/queries.ts index bc9068d52e..228c1cca0c 100644 --- a/ui/actions/attack-paths/queries.ts +++ b/ui/actions/attack-paths/queries.ts @@ -3,12 +3,16 @@ import { z } from "zod"; import { apiBaseUrl, getAuthHeaders } from "@/lib"; +import { customAttackPathQuerySchema } from "@/lib/attack-paths/custom-query"; import { handleApiResponse } from "@/lib/server-actions-helper"; import { + AttackPathCartographySchema, + AttackPathCartographySchemaResponse, AttackPathQueriesResponse, AttackPathQuery, AttackPathQueryError, AttackPathQueryResult, + ExecuteCustomQueryRequest, ExecuteQueryRequest, } from "@/types/attack-paths"; @@ -102,3 +106,93 @@ export const executeQuery = async ( }; } }; + +/** + * Execute a custom openCypher query on an attack path scan + */ +export const executeCustomQuery = async ( + scanId: string, + query: string, +): Promise => { + const validatedScanId = UUIDSchema.safeParse(scanId); + if (!validatedScanId.success) { + console.error("Invalid scan ID format"); + return undefined; + } + + const validatedQuery = customAttackPathQuerySchema.safeParse(query); + if (!validatedQuery.success) { + return { + error: + validatedQuery.error.issues[0]?.message ?? "Custom query is invalid.", + status: 400, + }; + } + + const headers = await getAuthHeaders({ contentType: true }); + + const requestBody: ExecuteCustomQueryRequest = { + data: { + type: "attack-paths-custom-query-run-requests", + attributes: { + query: validatedQuery.data, + }, + }, + }; + + try { + const response = await fetch( + `${apiBaseUrl}/attack-paths-scans/${validatedScanId.data}/queries/custom`, + { + headers, + method: "POST", + body: JSON.stringify(requestBody), + }, + ); + + return (await handleApiResponse(response)) as + | AttackPathQueryResult + | AttackPathQueryError; + } catch (error) { + console.error("Error executing custom query on scan:", error); + return { + error: + "Server is temporarily unavailable. Please try again in a few minutes.", + status: 503, + }; + } +}; + +/** + * Fetch cartography schema metadata for a specific attack path scan + */ +export const getCartographySchema = async ( + scanId: string, +): Promise<{ data: AttackPathCartographySchema } | undefined> => { + const validatedScanId = UUIDSchema.safeParse(scanId); + if (!validatedScanId.success) { + console.error("Invalid scan ID format"); + return undefined; + } + + const headers = await getAuthHeaders({ contentType: false }); + + try { + const response = await fetch( + `${apiBaseUrl}/attack-paths-scans/${validatedScanId.data}/schema`, + { + headers, + method: "GET", + }, + ); + + const apiResponse = (await handleApiResponse( + response, + )) as AttackPathCartographySchemaResponse; + + return { data: apiResponse.data }; + } catch (error) { + console.error("Error fetching cartography schema for scan:", error); + return undefined; + } +}; diff --git a/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/index.ts b/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/index.ts index eac86fccc7..83161cc4ef 100644 --- a/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/index.ts +++ b/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/index.ts @@ -1,6 +1,8 @@ export { ExecuteButton } from "./execute-button"; export * from "./graph"; export * from "./node-detail"; +export { QueryDescription } from "./query-description"; +export { QueryExecutionError } from "./query-execution-error"; export { QueryParametersForm } from "./query-parameters-form"; export { QuerySelector } from "./query-selector"; export { ScanListTable } from "./scan-list-table"; diff --git a/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-description.test.tsx b/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-description.test.tsx new file mode 100644 index 0000000000..cc61c16a4d --- /dev/null +++ b/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-description.test.tsx @@ -0,0 +1,76 @@ +import { render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; + +import type { AttackPathQuery } from "@/types/attack-paths"; + +import { QueryDescription } from "./query-description"; + +const customQuery: AttackPathQuery = { + type: "attack-paths-scans", + id: "custom-query", + attributes: { + name: "Custom openCypher query", + short_description: "Write your own query", + description: + "Run a read-only openCypher query against the selected Attack Paths scan.", + provider: "aws", + attribution: null, + documentation_link: { + text: "Cartography schema used by Prowler for AWS graphs", + link: "https://example.com/schema", + }, + parameters: [], + }, +}; + +describe("QueryDescription", () => { + it("renders the schema documentation link inside an info alert", () => { + // Given + render(); + + // When + const alert = screen.getByRole("alert"); + const link = screen.getByRole("link", { + name: /cartography schema used by prowler for aws graphs/i, + }); + + // Then + expect(alert).toBeInTheDocument(); + expect(link).toHaveAttribute("href", "https://example.com/schema"); + }); + + it("does not render unsafe documentation or attribution URLs as clickable links", () => { + // Given + const queryWithUnsafeLinks: AttackPathQuery = { + ...customQuery, + attributes: { + ...customQuery.attributes, + documentation_link: { + text: "Cartography schema used by Prowler for AWS graphs", + link: "javascript:alert('xss')", + }, + attribution: { + text: "Unsafe source", + link: "javascript:alert('xss')", + }, + }, + }; + + // When + render(); + + // Then + expect( + screen.queryByRole("link", { + name: /cartography schema used by prowler for aws graphs/i, + }), + ).not.toBeInTheDocument(); + expect( + screen.queryByRole("link", { name: /unsafe source/i }), + ).not.toBeInTheDocument(); + expect( + screen.getByText(/cartography schema used by prowler for aws graphs/i), + ).toBeInTheDocument(); + expect(screen.getByText(/unsafe source/i)).toBeInTheDocument(); + }); +}); diff --git a/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-description.tsx b/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-description.tsx new file mode 100644 index 0000000000..d1cb6e85fe --- /dev/null +++ b/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-description.tsx @@ -0,0 +1,70 @@ +import { Info } from "lucide-react"; + +import { Alert, AlertDescription } from "@/components/shadcn"; +import type { AttackPathQuery } from "@/types/attack-paths"; + +interface QueryDescriptionProps { + query: AttackPathQuery; +} + +const isSafeUrl = (url: string): boolean => { + try { + const parsedUrl = new URL(url); + return parsedUrl.protocol === "https:" || parsedUrl.protocol === "http:"; + } catch { + return false; + } +}; + +export const QueryDescription = ({ query }: QueryDescriptionProps) => { + const documentationLink = query.attributes.documentation_link; + const attribution = query.attributes.attribution; + + return ( + + + +

{query.attributes.description}

+ + {documentationLink && ( +

+ {isSafeUrl(documentationLink.link) ? ( + + {documentationLink.text} + + ) : ( + {documentationLink.text} + )} +

+ )} + + {attribution && ( +

+ {isSafeUrl(attribution.link) ? ( + <> + Source:{" "} + + {attribution.text} + + + ) : ( + <> + Source: {attribution.text} + + )} +

+ )} +
+
+ ); +}; diff --git a/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-execution-error.test.tsx b/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-execution-error.test.tsx new file mode 100644 index 0000000000..1c7fb29712 --- /dev/null +++ b/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-execution-error.test.tsx @@ -0,0 +1,46 @@ +import { render, screen } from "@testing-library/react"; +import { describe, expect, it } from "vitest"; + +import { QueryExecutionError } from "./query-execution-error"; + +describe("QueryExecutionError", () => { + it("renders the default title and the raw query error details without extra copy", () => { + // Given + const error = + "Invalid input 'WHERE': expected 'MATCH' or 'WITH' (line 1, column 1)"; + + // When + render(); + + // Then + expect(screen.getByRole("alert")).toBeInTheDocument(); + expect(screen.getByText(/query execution failed/i)).toBeInTheDocument(); + expect( + screen.queryByText(/the attack paths query could not be executed/i), + ).not.toBeInTheDocument(); + expect(screen.getByText(error)).toBeInTheDocument(); + }); + + it("renders custom title and description when provided", () => { + // Given + const error = "Failed to load available queries"; + + // When + render( + , + ); + + // Then + expect(screen.getByText(/failed to load queries/i)).toBeInTheDocument(); + expect( + screen.getByText( + /available attack paths queries could not be loaded for this scan/i, + ), + ).toBeInTheDocument(); + expect(screen.getByText(error)).toBeInTheDocument(); + }); +}); diff --git a/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-execution-error.tsx b/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-execution-error.tsx new file mode 100644 index 0000000000..084bcf6e16 --- /dev/null +++ b/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-execution-error.tsx @@ -0,0 +1,30 @@ +import { CircleAlert } from "lucide-react"; + +import { Alert, AlertDescription, AlertTitle } from "@/components/shadcn"; + +interface QueryExecutionErrorProps { + error: string; + title?: string; + description?: string; +} + +export const QueryExecutionError = ({ + error, + title = "Query execution failed", + description, +}: QueryExecutionErrorProps) => { + return ( + + + {title} + + {description ?

{description}

: null} +
+
+            {error}
+          
+
+
+
+ ); +}; diff --git a/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-parameters-form.test.tsx b/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-parameters-form.test.tsx index ac2b81be7f..694da8babe 100644 --- a/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-parameters-form.test.tsx +++ b/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-parameters-form.test.tsx @@ -1,8 +1,12 @@ import { render, screen } from "@testing-library/react"; +import { useEffect } from "react"; import { FormProvider, useForm } from "react-hook-form"; import { describe, expect, it } from "vitest"; -import type { AttackPathQuery } from "@/types/attack-paths"; +import { + ATTACK_PATH_QUERY_IDS, + type AttackPathQuery, +} from "@/types/attack-paths"; import { QueryParametersForm } from "./query-parameters-form"; @@ -42,6 +46,64 @@ function TestForm() { ); } +function TestCustomQueryForm() { + const customQuery: AttackPathQuery = { + type: "attack-paths-scans", + id: ATTACK_PATH_QUERY_IDS.CUSTOM, + attributes: { + name: "Custom openCypher query", + short_description: "Write your own query", + description: "Run a custom query against the graph.", + provider: "aws", + attribution: null, + parameters: [ + { + name: "query", + label: "openCypher", + data_type: "string", + input_type: "textarea", + placeholder: "MATCH (n) RETURN n LIMIT 25", + description: "", + required: true, + }, + ], + }, + }; + + const form = useForm({ + defaultValues: { + query: "", + }, + }); + + return ( + + + + ); +} + +function TestFormWithError() { + const form = useForm({ + defaultValues: { + tag_key: "", + }, + }); + + useEffect(() => { + form.setError("tag_key", { + type: "manual", + message: "Tag key is required", + }); + }, [form]); + + return ( + + + + ); +} + describe("QueryParametersForm", () => { it("uses the field description as the placeholder instead of rendering helper text below", () => { // Given @@ -70,4 +132,62 @@ describe("QueryParametersForm", () => { screen.queryByText("Tag key to filter the S3 bucket."), ).not.toBeInTheDocument(); }); + + it("renders a textarea when the parameter input type is textarea", () => { + // Given + render(); + + // When + const input = screen.getByRole("textbox", { name: /opencypher/i }); + const codeEditor = screen.getByTestId("query-code-editor"); + + // Then + expect(input.tagName).toBe("TEXTAREA"); + expect(input).toHaveAttribute("data-slot", "textarea"); + expect(input).toHaveAttribute("placeholder", "MATCH (n) RETURN n LIMIT 25"); + expect(input).toHaveAttribute("spellcheck", "false"); + expect(input).toHaveAttribute("autocomplete", "off"); + expect(input).toHaveAttribute("autocorrect", "off"); + expect(input).toHaveAttribute("autocapitalize", "none"); + expect(input).toHaveClass( + "minimal-scrollbar", + "min-h-[320px]", + "font-mono", + "leading-6", + ); + expect(codeEditor).toHaveClass( + "rounded-xl", + "border", + "bg-bg-neutral-primary", + ); + expect(screen.getByText("Read-only")).toBeInTheDocument(); + }); + + it("uses the design-system error token for field validation messages", async () => { + // Given + render(); + + // When + const errorMessage = await screen.findByText("Tag key is required"); + + // Then + expect(errorMessage).toHaveClass("text-text-error-primary", "text-xs"); + }); + + it("connects field errors to the input for accessibility", async () => { + // Given + render(); + + // When + const input = screen.getByRole("textbox", { name: /tag key/i }); + const errorMessage = await screen.findByText("Tag key is required"); + + // Then + expect(input).toHaveAttribute("aria-invalid", "true"); + expect(errorMessage).toHaveAttribute("id"); + expect(input).toHaveAttribute( + "aria-describedby", + expect.stringContaining(errorMessage.getAttribute("id") ?? ""), + ); + }); }); diff --git a/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-parameters-form.tsx b/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-parameters-form.tsx index 24937c0b7b..6ac5883e66 100644 --- a/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-parameters-form.tsx +++ b/ui/app/(prowler)/attack-paths/(workflow)/query-builder/_components/query-parameters-form.tsx @@ -1,9 +1,21 @@ "use client"; -import { Controller, useFormContext } from "react-hook-form"; +import { useFormContext } from "react-hook-form"; -import { Input } from "@/components/shadcn"; -import type { AttackPathQuery } from "@/types/attack-paths"; +import { Input, Textarea } from "@/components/shadcn"; +import { + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form"; +import { cn } from "@/lib/utils"; +import { + ATTACK_PATH_QUERY_IDS, + type AttackPathQuery, + QUERY_PARAMETER_INPUT_TYPES, +} from "@/types/attack-paths"; interface QueryParametersFormProps { selectedQuery: AttackPathQuery | null | undefined; @@ -16,10 +28,7 @@ interface QueryParametersFormProps { export const QueryParametersForm = ({ selectedQuery, }: QueryParametersFormProps) => { - const { - control, - formState: { errors }, - } = useFormContext(); + const { control } = useFormContext(); if (!selectedQuery || !selectedQuery.attributes.parameters.length) { return null; @@ -36,23 +45,26 @@ export const QueryParametersForm = ({ className="grid grid-cols-1 gap-4 md:grid-cols-2" > {selectedQuery.attributes.parameters.map((param) => ( - { + render={({ field, fieldState }) => { if (param.data_type === "boolean") { return ( -
+ -
+ + ); } - const errorMessage = (() => { - const error = errors[param.name]; - if (error && typeof error.message === "string") { - return error.message; - } - return undefined; - })(); + const placeholder = + param.description || + param.placeholder || + `Enter ${param.label.toLowerCase()}`; + + const isTextarea = + param.input_type === QUERY_PARAMETER_INPUT_TYPES.TEXTAREA; + const isCustomCodeEditor = + selectedQuery.id === ATTACK_PATH_QUERY_IDS.CUSTOM && + param.name === "query" && + isTextarea; return ( -
- - - {errorMessage && ( - {errorMessage} + + > + {!isCustomCodeEditor && ( + + {param.label} + {param.required && ( + * + )} + + )} + {isCustomCodeEditor ? ( +
+
+ + {param.label} + {param.required && ( + * + )} + + + Read-only + +
+ +